blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
6ecdb7ba8838ff92090e88ca84eefa02a42a64fa
Java
ebozkurt93/Favor-App-Backend-API
/src/main/java/com/favorapp/api/config/JwtMyHelper.java
UTF-8
4,096
2.328125
2
[]
no_license
package com.favorapp.api.config; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import javax.servlet.ServletException; import com.favorapp.api.config.key.KeyFactory; import com.favorapp.api.helper.JSONResponse; import com.favorapp.api.user.User; import com.favorapp.api.user.UserService; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; public class JwtMyHelper { private UserService userService; public JwtMyHelper() { } public JwtMyHelper(UserService userService) { this.userService = userService; } public static ArrayList<String> getJWTRoles(String jwt) { if (KeyFactory.checkKeyValidity(jwt)) { jwt = jwt.replace("Bearer ", ""); Claims claims = Jwts.parser().setSigningKey(KeyFactory.jwtKey).parseClaimsJws(jwt).getBody(); @SuppressWarnings(value = {"unchecked"}) ArrayList<String> roles = (ArrayList<String>) claims.get("roles"); return roles; /* if (!(roles.contains("USER") || roles.contains("ADMIN") || roles.contains("BLOCKED"))) { throw new ServletException("testing exception"); } if(roles.isEmpty()) { throw new ServletException("testing is empty exception"); } */ } return null; } public static boolean getIfJWTUser(String jwt) { ArrayList<String> roleList = getJWTRoles(jwt); if (roleList.contains("USER")) { return true; } else { return false; } } public User getUserFromJWT(String jwt) { jwt = jwt.replace("Bearer ", ""); String email = Jwts.parser().setSigningKey(KeyFactory.jwtKey).parseClaimsJws(jwt).getBody().getSubject(); return userService.getUserByEmail(email); } public static boolean getIfJWTAdmin(String jwt) { ArrayList<String> roleList = getJWTRoles(jwt); if (roleList.contains("ADMIN")) { return true; } else { return false; } } public String createAccessToken(User user) { if (user == null) { return ""; } Calendar date = Calendar.getInstance(); long t = date.getTimeInMillis(); // 30 min //todo enable this back //Date endDate = new Date(t + (30 * 60000)); Date endDate = new Date(t + (10000 * 30 * 60000)); String jwtToken = Jwts.builder().setSubject(user.getEmail()).claim("roles", user.getRoles()).setIssuedAt(new Date()) .setExpiration(endDate).signWith(SignatureAlgorithm.HS256, KeyFactory.jwtKey).compact(); KeyFactory.tokenMap.put(user.getId(), jwtToken); System.out.println(KeyFactory.tokenMap); return jwtToken; } /* public String createRefreshToken(User user) { if (user == null) { return ""; } Calendar date = Calendar.getInstance(); long t = date.getTimeInMillis(); //10000 hours todo => find a good value for this Date endDate = new Date(t + (10000 * 60 * 60000)); Claims claims = Jwts.claims().setSubject(user.getEmail()); claims.put("scopes", Arrays.asList(Scopes.REFRESH_TOKEN.authority())); String token = Jwts.builder() .setClaims(Jwts.claims().setSubject(user.getEmail())) .setIssuedAt(new Date()) .setExpiration(endDate) .signWith(SignatureAlgorithm.HS256, KeyFactory.jwtKey) .compact(); return new AccessJwtToken(token, claims); return ""; }*/ /* * public static boolean getJWTAdmin(String jwt) { * * jwt = jwt.replace("Bearer ", ""); Claims claims = * Jwts.parser().setSigningKey("secretkey").parseClaimsJws(jwt).getBody(); * Object role = claims.get("roles"); if (role.equals("ADMIN")) { return * true; } else { return false; } } */ }
true
af8b584bb17133d35799a75764a158fd28929201
Java
Duaff/javaSE
/src/comeon/EnumTest.java
UTF-8
259
2.828125
3
[]
no_license
package comeon; public class EnumTest { public static void main(String[] args) { Dog d = Dog.TOP; System.out.println(d); for(Dog dog : Dog.values()){ System.out.println(dog+" ordinal:"+dog.ordinal()); } } } enum Dog{ SMILE,BIG,TOP,KING,QUEUE }
true
f60b780af019254b83290803c3dd61c602850a4a
Java
eliasah/Transparix
/src/test/MainUI.java
UTF-8
2,849
2.6875
3
[]
no_license
package test; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.JButton; import examples.PanelStation; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class MainUI { ArrayList<String> stations; private JFrame frmTransparix; private PanelStation cbStationDepart; private PanelStation cbStationArrivee; private JPanel pSelection; private JPanel pBouton; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { MainUI window = new MainUI(); window.frmTransparix.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public MainUI() { stations = new ArrayList(); try { BufferedReader bf = new BufferedReader(new FileReader("data/data_v1/stations.txt")); try { String[] line; String str = bf.readLine(); while(str!=null){ line = str.split("#"); // System.out.println(line[1]); stations.add(line[1]); str = bf.readLine(); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } initialize(); } private void initialize() { frmTransparix = new JFrame(); pSelection = new JPanel(); pSelection.setLayout(new BorderLayout()); pBouton = new JPanel(); pBouton.setLayout(new BorderLayout()); frmTransparix.getContentPane().setLayout(new BorderLayout(0, 0)); frmTransparix.setTitle("Transparix"); //frmTransparix.setPreferredSize(new Dimension(500, 320)); frmTransparix.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cbStationDepart = new PanelStation("Depart", stations); cbStationArrivee = new PanelStation("Arrivee", stations); JButton search = new JButton("Chercher"); search.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Reaffect action listener System.exit(0); } }); JButton quit = new JButton("Quitter"); quit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); pSelection.add(cbStationDepart,BorderLayout.NORTH); pSelection.add(cbStationArrivee,BorderLayout.SOUTH); pBouton.add(search,BorderLayout.WEST); pBouton.add(quit,BorderLayout.EAST); frmTransparix.getContentPane().add(pSelection,BorderLayout.NORTH); frmTransparix.getContentPane().add(pBouton,BorderLayout.SOUTH); frmTransparix.pack(); frmTransparix.setVisible(true); } }
true
e538bd2455d34ce4a4a165aee6666dccb21dff8e
Java
IanBravo14/prueba_tecnica_choucair
/src/main/java/co/com/prueba/tecnica/exceptions/registrarcliente/RegistroClienteError.java
UTF-8
321
2.046875
2
[]
no_license
package co.com.prueba.tecnica.exceptions.registrarcliente; public class RegistroClienteError extends AssertionError { public static final String MENSAJE_REGISTRO_FALLIDO = "El cliente no se pudo registrar"; public RegistroClienteError(String mensaje, Throwable causa) { super(mensaje, causa); } }
true
c8eafc20c28016fc03923d47e8d5dc1ea0b3ec7c
Java
NekoQ/oop-labs
/src/com/company/lab5/Main.java
UTF-8
478
2.78125
3
[]
no_license
package com.company.lab5; public class Main { public static void main(String[] args) { A a = new A("x0", "a0"); B b = new B("x1","a1", "b1"); C c = new C("x2","a2", "b2", "c2"); D d = new D("x3","a3", "b3", "c3", "d3"); E e = new E("x4","a4", "b4", "c4", "d4", "e4"); System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); System.out.println(e); } }
true
322cc986b4d6104a79931109636d9bc8a7000834
Java
Rafaty/FinancialAppAPI
/src/main/java/com/example/financialApp/repositories/ClientRepository.java
UTF-8
373
2.109375
2
[]
no_license
package com.example.financialApp.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.financialApp.models.Client; public interface ClientRepository extends JpaRepository<Client, Long> { @Query("SELECT count(c.id) as amt from Client c ") Integer getNumberOfClients(); }
true
119e9ff28facc60a85df18ba0515aa9b6b671797
Java
uu04418/genealogy
/src/main/java/cn/com/gene/mymapper/GeneCustomerMapper.java
UTF-8
3,433
1.835938
2
[]
no_license
package cn.com.gene.mymapper; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.com.gene.comm.PageQuery; import cn.com.gene.pojo.Genemess; import cn.com.gene.pojo.Genemessconn; import cn.com.gene.pojo.Surname; import cn.com.gene.queryvo.GenemessCustomer; import cn.com.gene.queryvo.GenemessVo; import cn.com.gene.queryvo.PosCustomer; import cn.com.gene.queryvo.UserCustomer; public interface GeneCustomerMapper { //查询所有的姓氏 List<Surname> searchsurname(Surname realname); // 更新配偶 void updatewife(@Param("profileid")Long profileid, @Param("spouseid") Long spouseid); // 查询兄弟姐妹的父ID Long getfatheridbybrotherids( @Param ("idsList") String[] brotherids); //同步所有的兄弟姐妹一个父亲 void updatefatherbyuserids( @Param ("idsList") String[] brotherids, @Param ("fatherid") Long fatherid); // 更新父亲 void updatefatherbyuserid(@Param("profileid") Long profileid,@Param("fatherid") Long fatherid); // 查询第一代的数据 List<UserCustomer> firstgene(Long genemessid); List<UserCustomer> searchnextgene( @Param ("idsList") List<Long> array); // 根据userid 查询数据 UserCustomer searchuserbyuserid(Long userid); //根据家族ID 查询家族基本信 GenemessCustomer searchgenemess(GenemessCustomer search); // 查询氏族成员 List<UserCustomer> searchgeneuser(Long genemessid); // 氏族列表页面 List<GenemessCustomer> genearray(GenemessVo genemessVo); int genearrayCount(GenemessVo genemessVo); List<Surname> surnames(GenemessVo genemessVo); int surnamesCount(GenemessVo genemessVo); //我加入的家族列表页面 List<GenemessCustomer> mygenearray(@Param("genemessids") String genemessids ,@Param("pagequery") PageQuery pagequery); int mygenearrayCount( @Param("genemessids") String gennemessids); //校验是否是氏族成员 Genemessconn checkgeneuser(@Param("profileid") Long profileid , @Param("genemessid") Long genemessid ); List<UserCustomer> checkbrother(@Param("userid") String alluserids, @Param("realname")String realname, @Param("rankings") Integer rankings ,@Param("myid") Long userid); List<UserCustomer> searchgenesignuser(GenemessVo genemessVo); int searchgenesignuserCount(GenemessVo genemessVo); // 查询学历的统计 List<PosCustomer> honorpostype(@Param("fatherid")Long fatherid ,@Param("genemessid") Long genemessid); //查询职位的统计 List<PosCustomer> honoredutype(Long genemessid); //改变成员在家族中的地位 void changegeneusersate(Genemessconn checkgene); void synchuserid(@Param("userid")Long userid,@Param("newuserid") Long newuserid); List<String> searchhonorposname(@Param("positionid")Long positionid,@Param("genemessid") Long genemessid); List<String> searchhonoreduname(@Param("educationid")Long educationid, @Param("genemessid") Long genemessid); // 先查首级职称 List<PosCustomer> honorpostfatherype(Long genemessid); // 判断用户是否已经有氏族 Genemess checkaddgene(@Param("profileid") Long profileid,@Param("likenameone") String likenameone, @Param("likenametwo") String likenametwo); // 获取当前用户 的基本信息 UserCustomer searchcheckduser(Long userid); // 地图找 家族成员 List<UserCustomer> searchgeneusermap (Long genemessid); }
true
c283168cb69a4aff771a19ba011f4b0e55d4706a
Java
prodizy69/slots
/src/com/rss/pojo/ForgotPasswordResponse.java
UTF-8
226
1.632813
2
[]
no_license
package com.rss.pojo; import com.rss.common.ErrorObj; public class ForgotPasswordResponse extends BaseResponse { public ForgotPasswordResponse(boolean isSuccess, ErrorObj error) { super(isSuccess, error); } }
true
f63c09cf773a572d7e8dd3325d776e591b8ddaff
Java
mai-mahamed/FCI-CS352-Challenge
/src/com/FCI/SWE/ServicesModels/FriendEntity.java
UTF-8
8,640
2.3125
2
[]
no_license
package com.FCI.SWE.ServicesModels; import java.util.Date; import java.util.List; import java.util.Vector; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; public class FriendEntity { private long UID; private long FuID; private String status; /** * Constructor accepts user data * * @param Funame * friend user name * @param FuID * friend user id */ public FriendEntity(long UID, long FU_ID,String status) { this.UID = UID; this.FuID = FU_ID; this.status=status; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public void setUID(long uID) { UID = uID; } public void setFuID(long fuID) { FuID = fuID; } public long getUID() { return UID; } public long getFuID() { return FuID; } /** * * This static method will form FriendEntity class using json format contains * user data * * @param json * String in json format contains friend user data * @return Constructed friend entity */ /** * * @return Saving friend in data store */ public Boolean saveFriendUser() { DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("FriendsStatus"); PreparedQuery pq = datastore.prepare(gaeQuery); List<Entity> list = pq.asList(FetchOptions.Builder.withDefaults()); Entity employee = new Entity("FriendsStatus", list.size() + 1); employee.setProperty("FriendID", this.FuID); employee.setProperty("UserID", this.UID); employee.setProperty("Status","Send"); datastore.put(employee); return true; } /** * * @param id : friend ID * @return getting friends ID */ public static long getAllFriendsID(long id){ DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("FriendsStatus"); PreparedQuery pq = datastore.prepare(gaeQuery); String newID=String.valueOf(id); for (Entity entity : pq.asIterable()) { <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= <<<<<<< HEAD if (entity.getProperty("FriendID").toString().equals(newID)&& entity.getProperty("Status").toString().equals("Send")) { ======= if (entity.getProperty("FriendID").toString().equals(newID)) { >>>>>>> f361c47c5a73c19bc593b2844bfb444cb0c6be40 >>>>>>> e549c54537cb4d303bcbc0bcd68d25eb677ac60e >>>>>>> e55f3b0c9652a5e4c98922e3768db182dac76a58 >>>>>>> 03152846dbbe0d049207fe46386a2f5da3dd7061 >>>>>>> d293d0515af81388349236d24a3aec7554c709a2 >>>>>>> b4bce9d46968d253f312331916dbea989824bfcd >>>>>>> ed6cdda22f362a9816aed254c00b74fc2be43805 FriendEntity returnedFriend=new FriendEntity((long)entity.getProperty("UserID"), (long)entity.getProperty("FriendID"),entity.getProperty("Status").toString()); return returnedFriend.getUID() ; } } return -1; } <<<<<<< HEAD /** * * @param id : Friend ID * @return getting all ID in list */ ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= <<<<<<< HEAD >>>>>>> e549c54537cb4d303bcbc0bcd68d25eb677ac60e >>>>>>> e55f3b0c9652a5e4c98922e3768db182dac76a58 >>>>>>> 03152846dbbe0d049207fe46386a2f5da3dd7061 >>>>>>> d293d0515af81388349236d24a3aec7554c709a2 >>>>>>> b4bce9d46968d253f312331916dbea989824bfcd >>>>>>> ed6cdda22f362a9816aed254c00b74fc2be43805 public static Vector<Long> getAllFriendsIDList(long id){ DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("FriendsStatus"); PreparedQuery pq = datastore.prepare(gaeQuery); Vector<Long> list=new Vector<Long>(); String newID=String.valueOf(id); for (Entity entity : pq.asIterable()) { if (entity.getProperty("FriendID").toString().equals(newID)) { FriendEntity returnedFriend=new FriendEntity((long)entity.getProperty("UserID"), (long)entity.getProperty("FriendID"),entity.getProperty("Status").toString()); list.add(returnedFriend.getUID()); } } return list; } <<<<<<< HEAD /** * * @param fID : friend ID * @param curID : user ID * Changing status */ public static boolean changeStatus(long fID,long curID){ ======= <<<<<<< HEAD public static boolean changeStatus(long fID,long curID){ ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= <<<<<<< HEAD ======= ======= >>>>>>> f361c47c5a73c19bc593b2844bfb444cb0c6be40 >>>>>>> e549c54537cb4d303bcbc0bcd68d25eb677ac60e >>>>>>> e55f3b0c9652a5e4c98922e3768db182dac76a58 >>>>>>> 03152846dbbe0d049207fe46386a2f5da3dd7061 >>>>>>> d293d0515af81388349236d24a3aec7554c709a2 public static void changeStatus(long fID,long curID){ >>>>>>> b4bce9d46968d253f312331916dbea989824bfcd >>>>>>> ed6cdda22f362a9816aed254c00b74fc2be43805 DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("FriendsStatus"); PreparedQuery pq = datastore.prepare(gaeQuery); List<Entity> list = pq.asList(FetchOptions.Builder.withDefaults()); String newID=String.valueOf(curID); String newID2=String.valueOf(fID); for (Entity entity : pq.asIterable()) { if (entity.getProperty("FriendID").toString().equals(newID)&&entity.getProperty("UserID").toString().equals(newID2)) { long key=entity.getKey().getId(); Entity employee = new Entity("FriendsStatus", key); FriendEntity returnedFriend=new FriendEntity((long)entity.getProperty("UserID"), (long)entity.getProperty("FriendID"),entity.getProperty("Status").toString()); employee.setProperty("FriendID",curID ); employee.setProperty("UserID", fID); employee.setProperty("Status", "Active"); datastore.put(employee); return true; } } return false; } /** * * @param fID : friend ID * @param curID : user ID * @return checking on friend ID & user ID */ public static boolean Check(long fID,long curID){ DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("FriendsStatus"); PreparedQuery pq = datastore.prepare(gaeQuery); List<Entity> list = pq.asList(FetchOptions.Builder.withDefaults()); String newID=String.valueOf(curID); String newID2=String.valueOf(fID); for (Entity entity : pq.asIterable()) { if (entity.getProperty("FriendID").toString().equals(newID)&&entity.getProperty("UserID").toString().equals(newID2)&&entity.getProperty("Status").toString().equals("Active")) { return true; } } return false; } public static boolean Check(long fID,long curID){ DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("FriendsStatus"); PreparedQuery pq = datastore.prepare(gaeQuery); List<Entity> list = pq.asList(FetchOptions.Builder.withDefaults()); String newID=String.valueOf(curID); String newID2=String.valueOf(fID); for (Entity entity : pq.asIterable()) { if (entity.getProperty("FriendID").toString().equals(newID)&&entity.getProperty("UserID").toString().equals(newID2)&&entity.getProperty("Status").toString().equals("Active")) { return true; } } return false; } }
true
cfe30c78ddc76a3962431b30a38473533e3616e1
Java
chromium/chromium
/chrome/browser/download/internal/android/java/src/org/chromium/chrome/browser/download/interstitial/DownloadInterstitialView.java
UTF-8
7,427
1.867188
2
[ "BSD-3-Clause" ]
permissive
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.download.interstitial; import static org.chromium.chrome.browser.download.interstitial.DownloadInterstitialProperties.STATE; import static org.chromium.chrome.browser.download.interstitial.DownloadInterstitialProperties.State.CANCELLED; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; import org.chromium.chrome.browser.download.home.list.ListItem; import org.chromium.chrome.browser.download.home.list.ListProperties; import org.chromium.chrome.browser.download.home.list.holder.GenericViewHolder; import org.chromium.chrome.browser.download.home.list.holder.InProgressGenericViewHolder; import org.chromium.chrome.browser.download.internal.R; import org.chromium.components.browser_ui.widget.DualControlLayout; import org.chromium.components.offline_items_collection.OfflineItem; import org.chromium.components.offline_items_collection.OfflineItemState; import org.chromium.ui.modelutil.PropertyModel; /** Class for a download interstitial which handles all interaction with the view. */ class DownloadInterstitialView { private final View mView; private final TextView mTitle; private final TextView mLoadingMessage; private final GenericViewHolder mGenericViewHolder; private final InProgressGenericViewHolder mInProgressGenericViewHolder; private final Button mPrimaryButton; private final Button mSecondaryButton; /** * @param context The context of the tab to contain the download interstitial. * @return A new DownloadInterstitialView instance. */ public static DownloadInterstitialView create(Context context) { View view = LayoutInflater.from(context).inflate(R.layout.download_interstitial, null); return new DownloadInterstitialView(view, context); } private DownloadInterstitialView(View view, Context context) { mView = view; mTitle = mView.findViewById(R.id.heading); mLoadingMessage = mView.findViewById(R.id.loading_message); FrameLayout fileInfo = mView.findViewById(R.id.file_info); mGenericViewHolder = GenericViewHolder.create(fileInfo); mInProgressGenericViewHolder = InProgressGenericViewHolder.create(fileInfo); mGenericViewHolder.itemView.setVisibility(View.GONE); mInProgressGenericViewHolder.itemView.setVisibility(View.INVISIBLE); fileInfo.addView(mGenericViewHolder.itemView); fileInfo.addView(mInProgressGenericViewHolder.itemView); mPrimaryButton = DualControlLayout.createButtonForLayout(context, true, "", null); mPrimaryButton.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mPrimaryButton.setVisibility(View.INVISIBLE); mSecondaryButton = DualControlLayout.createButtonForLayout( context, false, mView.getResources().getString(R.string.cancel), null); mSecondaryButton.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mSecondaryButton.setVisibility(View.INVISIBLE); DualControlLayout buttonBar = mView.findViewById(R.id.button_bar); buttonBar.addView(mPrimaryButton); buttonBar.addView(mSecondaryButton); } /** @return The parent view containing the download interstitial. */ public View getView() { return mView; } /** * Updates the file info section when the attached download's progress or state is updated. * @param item The offline item attached to the UI. * @param model The property model of the DownloadInterstitial. */ void updateFileInfo(OfflineItem item, PropertyModel model) { if (item == null) return; if (item.state == OfflineItemState.COMPLETE && model.get(STATE) == CANCELLED) { model.get(ListProperties.CALLBACK_REMOVE).onResult(item); return; } if (item.state == OfflineItemState.COMPLETE) { mInProgressGenericViewHolder.itemView.setVisibility(View.GONE); mGenericViewHolder.itemView.setVisibility(View.VISIBLE); mGenericViewHolder.bind(model, new ListItem.OfflineItemListItem(item)); } else { mGenericViewHolder.itemView.setVisibility(View.GONE); mInProgressGenericViewHolder.itemView.setVisibility(View.VISIBLE); mInProgressGenericViewHolder.bind(model, new ListItem.OfflineItemListItem(item)); } } /** * Sets the text shown as the title. * @param text The new text for the title to display. */ void setTitleText(String text) { mTitle.setText(text); } /** * Sets whether the primary button should be shown. * @param visible Whether the primary button should be visible. */ void setPrimaryButtonVisibility(boolean visible) { mPrimaryButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } /** * Sets the text shown on the primary button. * @param text The new text for the primary button to display. */ void setPrimaryButtonText(String text) { mPrimaryButton.setText(text); } /** * Sets the callback which is run when the primary button is clicked. * @param callback The callback to run. */ void setPrimaryButtonCallback(Runnable callback) { mPrimaryButton.setOnClickListener(v -> callback.run()); } /** * Sets whether the secondary button should be shown. * @param visible Whether the secondary button should be visible. */ void setSecondaryButtonVisibility(boolean visible) { mSecondaryButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } /** * Sets the text shown on the secondary button. * @param text The new text for the secondary button to display. */ void setSecondaryButtonText(String text) { mSecondaryButton.setText(text); } /** * Sets the callback which is run when the secondary button is clicked. * @param callback The callback to run. */ void setSecondaryButtonCallback(Runnable callback) { mSecondaryButton.setOnClickListener(v -> callback.run()); } void setPendingMessageIsVisible(boolean isVisible) { if (isVisible) { mLoadingMessage.setVisibility(View.VISIBLE); mInProgressGenericViewHolder.itemView.setVisibility(View.INVISIBLE); mGenericViewHolder.itemView.setVisibility(View.INVISIBLE); mPrimaryButton.setVisibility(View.GONE); mSecondaryButton.setVisibility(View.GONE); } else { mLoadingMessage.setVisibility(View.GONE); } } void switchToCancelledViewHolder(OfflineItem item, PropertyModel model) { mGenericViewHolder.itemView.setVisibility(View.GONE); item.state = OfflineItemState.CANCELLED; mInProgressGenericViewHolder.bind(model, new ListItem.OfflineItemListItem(item)); mInProgressGenericViewHolder.itemView.setVisibility(View.VISIBLE); } }
true
fdc6cc1db40fc5499aa565b082399d74bab4ffb8
Java
Ljy2016/JardinSecret
/app/src/main/java/com/azadljy/jardinsecret/adapter/JardinAdapter.java
UTF-8
2,218
2.234375
2
[]
no_license
package com.azadljy.jardinsecret.adapter; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import androidx.annotation.Nullable; import com.azadljy.jardinsecret.R; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import java.util.List; public class JardinAdapter extends BaseQuickAdapter<JardinAdapter.JardinModel, BaseViewHolder> { public JardinAdapter(int layoutResId, @Nullable List<JardinModel> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, JardinModel item) { helper.setText(R.id.tv_project_name, item.getProjectName()); // int colors[] = {0xff255779, 0xff3e7492, 0xffa6c0cd};//分别为开始颜色,中间夜色,结束颜色 GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, item.getColors()); // helper.setBackgroundColor(R.id.item_content, item.getBackGround()); helper.getView(R.id.item_content).setBackground(gradientDrawable); } public static class JardinModel { private String projectName; private int icon; private int backGround; private int[] colors; public JardinModel(String projectName, int backGround, int[] colors) { this.projectName = projectName; this.backGround = backGround; this.colors = colors; } public JardinModel() { } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public int getBackGround() { return backGround; } public void setBackGround(int backGround) { this.backGround = backGround; } public int[] getColors() { return colors; } public void setColors(int[] colors) { this.colors = colors; } } }
true
12fb4d67367ab3019dc1a12a8dad43598d77e0db
Java
Chetanr/Multiset
/implementation/ArrayMultiset.java
UTF-8
9,046
3.671875
4
[]
no_license
package implementation; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Array implementation of a multiset. See comments in RmitMultiset to * understand what each overriden method is meant to do. * * @author Jeffrey Chan & Yongli Ren, RMIT 2020 */ public class ArrayMultiset extends RmitMultiset { /* Memory allocation for Dynamic Array*/ String[] elements; int[] frequency; int count=0; public ArrayMultiset() { elements = new String[3000]; frequency = new int[3000]; } /* Adding elements to Array */ @Override public void add(String elem) { count++; if(count == elements.length ) { String[] elementsTemp = new String[elements.length * 2]; int[] frequencyTemp = new int[frequency.length * 2]; for(int i=0;i<elements.length;i++) { elementsTemp[i] = elements[i]; frequencyTemp[i] = frequency[i]; } elements = elementsTemp; frequency = frequencyTemp; } if (elements[0] == null) { elements[0] = elem; frequency[0] = 1; } else { boolean found = false; int i = 0; while (elements[i] != null) { if (elements[i].equals(elem)) { frequency[i] += 1; found = true; break; } i++; } if (!found) { elements[i] = elem; frequency[i] = 1; } } } /* Search an element in Array */ @Override public int search(String elem) { int i = 0; boolean found = false; while (elements[i] != null) { if (elements[i].equals(elem)) { i = frequency[i]; found = true; break; } i++; } if (found) { return i; } return searchFailed; } // end of search() /* Search the elements by Instances in Array */ @Override public List<String> searchByInstance(int instanceCount) { List<String> found = new ArrayList<String>(); int i = 0; boolean foundFrequncy = false; while (frequency[i] != 0) { if (frequency[i] == instanceCount) { found.add(elements[i]); foundFrequncy = true; } i++; } if (foundFrequncy) { return found; } return null; } // end of searchByInstance /* Check whether the element is contained in the array */ @Override public boolean contains(String elem) { int i = 0; while (elements[i] != null) { if (elements[i].equals(elem)) { return true; } i++; } return false; } // end of contains() /* Remove a element from array */ @Override public void removeOne(String elem) { int i = 0; while (elements[i] != null) { if (elements[i].equals(elem)) { if (frequency[i] > 1) { frequency[i] -= 1; } else { frequency[i] = 0; elements[i] = null; } break; } i++; } } // end of removeOne() /* print the elements added in the array */ @Override public String print() { Set<String> outPut=new TreeSet<>(); String outPutString = ""; for (int j = 0; j < elements.length; j++) { if (elements[j] != null) { outPut.add(elements[j] + " : " + String.valueOf(frequency[j])); } } for(String out:outPut) { outPutString+=out+"\n"; } return outPutString; } // end of OrderedPrint /* Print range : lower to high range of elements in array multisets */ @Override public String printRange(String lower, String upper) { String elems = ""; int i = 0; while (elements[i] != null) { if (elements[i].compareTo(lower) >= 0 && elements[i].compareTo(upper) <= 0) { elems += elements[i] + " : "+ frequency[i] + "\n"; } i++; } return elems; } // end of printRange() /* Union of different array multisets */ @Override public RmitMultiset union(RmitMultiset other) { int endPoint = 0; boolean matchFound = false; ArrayMultiset otherMultiSet = (ArrayMultiset) other; ArrayMultiset union = new ArrayMultiset(); for (int i = 0; i < elements.length; i++) { if (frequency[i] != 0 && elements[i] != null) { union.elements[i] = elements[i]; union.frequency[i] = frequency[i]; endPoint++; } } for (int i = 0; i < otherMultiSet.elements.length; i++) { if (otherMultiSet.frequency[i] != 0 && otherMultiSet.elements[i] != null) { matchFound = false; for (int j = 0; j < union.elements.length; j++) { if (union.frequency[j] != 0 && union.elements[j] != null && union.elements[j].equals(otherMultiSet.elements[i])) { union.frequency[j] += otherMultiSet.frequency[i]; matchFound = true; break; } } if (!matchFound) { union.elements[endPoint] = otherMultiSet.elements[i]; union.frequency[endPoint] = otherMultiSet.frequency[i]; endPoint++; } } } return union; } // end of union() /* Intersection of different array multisets */ @Override public RmitMultiset intersect(RmitMultiset other) { int count=0; ArrayMultiset otherMultiSet = (ArrayMultiset) other; ArrayMultiset intersect = new ArrayMultiset(); for (int i = 0; i <elements.length; i++) { if (frequency[i] != 0 && elements[i] != null) { for (int j = 0; j < otherMultiSet.elements.length; j++) { if (otherMultiSet.frequency[j] != 0 && otherMultiSet.elements[j] != null && elements[i].equals(otherMultiSet.elements[j])) { intersect.elements[count]=elements[i]; intersect.frequency[count]=otherMultiSet.frequency[i]>frequency[j]?frequency[j]:otherMultiSet.frequency[i]; count++; } } } } return intersect; } // end of intersect() /* Difference between different array multisets */ @Override public RmitMultiset difference(RmitMultiset other) { boolean found=false; boolean eliminated=false; int count=0; ArrayMultiset otherMultiSet = (ArrayMultiset) other; ArrayMultiset difference = new ArrayMultiset(); for (int i = 0; i < elements.length; i++) { found=false; eliminated=false; if (frequency[i] != 0 && elements[i] != null) { for (int j = 0; j < otherMultiSet.elements.length; j++) { if (otherMultiSet.frequency[j] != 0 && otherMultiSet.elements[j] != null && elements[i].equals(otherMultiSet.elements[j]) && (frequency[i]-otherMultiSet.frequency[j])>0) { found=true; difference.elements[count]=elements[i]; difference.frequency[count]=frequency[i]-otherMultiSet.frequency[j]; count++; break; } else if(otherMultiSet.frequency[j] != 0 && otherMultiSet.elements[j] != null && elements[i].equals(otherMultiSet.elements[j]) && (frequency[i]-otherMultiSet.frequency[j] ==0 || frequency[i]-otherMultiSet.frequency[j]<0) ) { eliminated=true; break; } } if(!found && !eliminated) { difference.elements[count]=elements[i]; difference.frequency[count]=frequency[i]; count++; } } } return difference; } // end of difference() } // end of class ArrayMultiset
true
6f1f83aec3e521b7a87c29c314f9530a5861b957
Java
SerkanGitRepo/CC_BDD_TNG
/src/test/java/parallel/AccountPageSteps.java
UTF-8
2,579
2.296875
2
[]
no_license
package parallel; import java.util.List; import java.util.Map; import com.aventstack.extentreports.GherkinKeyword; import com.pages.AccountPage; import com.pages.LoginPage; import io.cucumber.datatable.DataTable; import io.cucumber.java.Before; import io.cucumber.java.en.*; import utilities.DriverFactory; //import utilities.baseUtil; import org.junit.Assert; public class AccountPageSteps { private LoginPage loginPage=new LoginPage(DriverFactory.getDriver()); private AccountPage accountPage; // private baseUtil base; // public AccountPageSteps(baseUtil base) { // this.base=base; // } // @Before @Given("user has already logged in to application") public void user_has_already_logged_in_to_application(DataTable dataTable) throws InterruptedException, Throwable { // scenarioDef.createNode(new GherkinKeyword("Given"), "user has already logged in to application"); List<Map<String,String>> credList=dataTable.asMaps(); String userName=credList.get(0).get("username"); String password=credList.get(0).get("password"); DriverFactory.getDriver().get("http://automationpractice.com/index.php?controller=authentication&back=my-account"); Thread.sleep(1000); accountPage=loginPage.doLogin(userName, password); } @Given("user is on Account page") public void user_is_on_account_page() throws Throwable{ // scenarioDef.createNode(new GherkinKeyword("Given"), "user is on Account page"); String title = accountPage.getsAccountPageTitle(); System.out.println("Account page title is: " + title); System.out.println("Thread Id: " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName()); } @Then("user gets account section") public void user_gets_account_section(DataTable sectionsTable) throws Throwable{ // scenarioDef.createNode(new GherkinKeyword("Then"), "user gets account section"); List<String> expAccountSectionslist=sectionsTable.asList(); System.out.println("Expected account section lists: " + expAccountSectionslist); List<String> actAccountSectionslist=accountPage.getAccountSectionsList(); System.out.println("Actual account section lists: " + actAccountSectionslist); Assert.assertTrue(expAccountSectionslist.containsAll(actAccountSectionslist)); } @Then("accounts section count should be {int}") public void accounts_section_count_should_be(Integer expectedSectionCount) throws Throwable{ // scenarioDef.createNode(new GherkinKeyword("Then"), "accounts section count should be 6"); Assert.assertTrue(accountPage.getAccountsSectionCount()==expectedSectionCount); } }
true
656b57ac6a98418a34dc72023ce1abd8d1ade1ee
Java
ucomignani/SATMiner
/java-generator/SATMining/satmining-utils/src/main/java/dag/satmining/utils/MatrixCollection.java
UTF-8
3,095
2.21875
2
[]
no_license
/* ./satmining-utils/src/main/java/dag/satmining/utils/MatrixCollection.java Copyright (C) 2013, 2014 Emmanuel Coquery. This file is part of SATMiner SATMiner 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, or (at your option) any later version. SATMiner 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 SATMiner; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package dag.satmining.utils; import java.util.AbstractCollection; import java.util.Iterator; import java.util.NoSuchElementException; public class MatrixCollection<E> extends AbstractCollection<E> { /** * The underlying matrix. */ private E[][] _matrix; /** * The size of the collection */ private int _size = -1; /** * Constructs a collection wrapper around the given matrix. * @param matrix the matrix to use. */ public MatrixCollection(E[][] matrix) { this._matrix = matrix; } @Override public final Iterator<E> iterator() { return new Iterator<E>() { private int _lineIdx = 0; private int _columnIdx = 0; public boolean hasNext() { return _lineIdx < _matrix.length && _columnIdx < _matrix[_lineIdx].length; } public E next() { if (hasNext()) { E result = _matrix[_lineIdx][_columnIdx]; _columnIdx ++; while (_lineIdx < _matrix.length && _columnIdx == _matrix[_lineIdx].length) { _lineIdx ++; _columnIdx = 0; } return result; } else { throw new NoSuchElementException(); } } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public final int size() { if (_size == -1) { _size = 0; for (E[] line : _matrix) { _size += line.length; } } return _size; } }
true
0410c3e27c082a400c64d68fedefa4326b535062
Java
ankit249/Algorithms
/src/com/ds/basic/LoveLetterMystery.java
UTF-8
732
3.625
4
[]
no_license
package com.ds.basic; import java.util.Scanner; public class LoveLetterMystery { public static void findDecrementCount(String string) { int count = 0; int n = string.length(); for (int i = 0; i < n / 2; i++) { if (string.charAt(i) != string.charAt(n - i - 1)) { count = count + (Math.abs(string.charAt(i) - string.charAt(n - i - 1))); } } System.out.println(count); } public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); String[] strArray = new String[t]; for (int i = 0; i < t; i++) { strArray[i] = input.next(); } for (int i = 0; i < strArray.length; i++) { String string = strArray[i]; findDecrementCount(string); } } }
true
0768abf48ce4bd38e7908a16b02825b6445d9370
Java
google-code/anttesttools
/CodeExamples/Java/anttesttools/tools/CacheUtils.java
UTF-8
1,974
2.765625
3
[]
no_license
/* * http://code.google.com/p/anttesttools/ * ehcache 使用 * site: * jar: ehcache-core-*.jar */ package anttesttools.tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * @author anttesttools * */ public class CacheUtils { private static Logger log = LoggerFactory.getLogger(CacheUtils.class); public static final String CONFIG_CACHE = "configCache"; /** * 增加或更新 * * @param cacheName * @param key * @param value */ public static void put(String cacheName, Object key, Object value) { Cache cache = CacheManager.getInstance().getCache(cacheName); cache.put(new Element(key, value)); } /** * 获得 * * @param cacheName * @param key * @return */ public static Object getObject(String cacheName, Object key) { Cache cache = CacheManager.getInstance().getCache(cacheName); return cache.get(key).getObjectValue(); } /** * 删除 * * @param cacheName * @param key */ public static void remove(String cacheName, Object key) { Cache cache = CacheManager.getInstance().getCache(cacheName); cache.remove(key); } /** * 增加新的缓存 * * @param cacheName */ public static void addCache(String cacheName) { Cache cache = new Cache(cacheName, 10000, false, true, 0, 0); CacheManager.getInstance().addCache(cache); log.debug("addCache = {}", cacheName); } public static void main(String[] args) { // 创建ehcache的CacheManager CacheManager.create(); CacheUtils.addCache(CacheUtils.CONFIG_CACHE); //put--增加、更新 //get-- //remove-- } }
true
735cde354b62b1e3b0ca26627a4359bcbe0129f3
Java
Vladry/HW12-File-system
/src/hw12/family/Main.java
UTF-8
642
2.25
2
[]
no_license
package hw12.family; import hw12.family.Controller.FamilyController; import hw12.family.Controller.Menu; import hw12.family.FamilyDAO.CollectionFamilyDao; import hw12.family.service.FamilyService; public class Main { public static void main(String[] args) { //создание сервиса DAO: CollectionFamilyDao familyMemStorage = new CollectionFamilyDao();//создаём хранилище1 FamilyService service = new FamilyService(familyMemStorage); Menu menu = new Menu(); FamilyController controller = new FamilyController(service, menu); controller.doControl(); } }
true
1abed2ca4e73a293af94a6b06eac9499a83dc58f
Java
marooter/tester
/src/main/java/com/example/demo/MusicCouse.java
UTF-8
615
2.40625
2
[]
no_license
package com.example.demo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Data; @Data @Entity public class MusicCouse { private @Id @GeneratedValue Long id; private String MusicCouseID; private String price; private String date; private String time; private MusicCouse() {} public MusicCouse(String MusicCouseID,String price, String date,String time) { this.MusicCouseID = MusicCouseID; this.price = price; this.date = date; this.time = time; } }
true
ce811a3dc5996c38df4d7500964b881f7b46d79e
Java
mohamedaiche/Savers-Team
/Mobile Application/Source/com/google/appinventor/components/runtime/ImagePicker.java
UTF-8
6,588
1.984375
2
[]
no_license
package com.google.appinventor.components.runtime; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore.Images.Media; import android.util.Log; import android.webkit.MimeTypeMap; import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.runtime.util.MediaUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Comparator; @DesignerComponent(category=ComponentCategory.MEDIA, description="A special-purpose button. When the user taps an image picker, the device's image gallery appears, and the user can choose an image. After an image is picked, it is saved, and the <code>Selected</code> property will be the name of the file where the image is stored. In order to not fill up storage, a maximum of 10 images will be stored. Picking more images will delete previous images, in order from oldest to newest.", version=5) @SimpleObject @UsesPermissions(permissionNames="android.permission.WRITE_EXTERNAL_STORAGE") public class ImagePicker extends Picker implements ActivityResultListener { private static final String FILE_PREFIX = "picked_image"; private static final String LOG_TAG = "ImagePicker"; private static final String imagePickerDirectoryName = "/Pictures/_app_inventor_image_picker"; private static int maxSavedFiles = 10; private String selectionSavedImage = ""; private String selectionURI; public ImagePicker(ComponentContainer paramComponentContainer) { super(paramComponentContainer); } private void copyToExternalStorageAndDeleteSource(File paramFile, String paramString) { localFile1 = null; File localFile2 = new File(Environment.getExternalStorageDirectory() + "/Pictures/_app_inventor_image_picker"); localObject = localFile1; for (;;) { try { localFile2.mkdirs(); localObject = localFile1; localFile1 = File.createTempFile("picked_image", paramString, localFile2); localObject = localFile1; this.selectionSavedImage = localFile1.getPath(); localObject = localFile1; Log.i("ImagePicker", "saved file path is: " + this.selectionSavedImage); localObject = localFile1; paramString = new FileInputStream(paramFile); } catch (IOException paramString) { continue; } try { localObject = new FileOutputStream(localFile1); try { byte[] arrayOfByte = new byte['Ѐ']; int i = paramString.read(arrayOfByte); if (i <= 0) { continue; } ((OutputStream)localObject).write(arrayOfByte, 0, i); continue; paramString = "destination is " + this.selectionSavedImage + ": " + "error is " + paramString.getMessage(); } catch (IOException paramString) { localObject = localFile1; } } catch (IOException paramString) { localObject = localFile1; } } Log.i("ImagePicker", "copyFile failed. " + paramString); this.container.$form().dispatchErrorOccurredEvent(this, "SaveImage", 1601, new Object[] { paramString }); this.selectionSavedImage = ""; ((File)localObject).delete(); for (;;) { paramFile.delete(); trimDirectory(maxSavedFiles, localFile2); return; paramString.close(); ((OutputStream)localObject).close(); Log.i("ImagePicker", "Image was copied to " + this.selectionSavedImage); } } private void saveSelectedImageToExternalStorage(String paramString) { this.selectionSavedImage = ""; try { File localFile = MediaUtil.copyMediaToTempFile(this.container.$form(), this.selectionURI); Log.i("ImagePicker", "temp file path is: " + localFile.getPath()); copyToExternalStorageAndDeleteSource(localFile, paramString); return; } catch (IOException paramString) { Log.i("ImagePicker", "copyMediaToTempFile failed: " + paramString.getMessage()); this.container.$form().dispatchErrorOccurredEvent(this, "ImagePicker", 1602, new Object[] { paramString.getMessage() }); } } private void trimDirectory(int paramInt, File paramFile) { paramFile = paramFile.listFiles(); Arrays.sort(paramFile, new Comparator() { public int compare(File paramAnonymousFile1, File paramAnonymousFile2) { return Long.valueOf(paramAnonymousFile1.lastModified()).compareTo(Long.valueOf(paramAnonymousFile2.lastModified())); } }); int j = paramFile.length; int i = 0; while (i < j - paramInt) { paramFile[i].delete(); i += 1; } } @SimpleProperty(category=PropertyCategory.BEHAVIOR, description="Path to the file containing the image that was selected.") public String Selection() { return this.selectionSavedImage; } protected Intent getIntent() { return new Intent("android.intent.action.PICK", MediaStore.Images.Media.INTERNAL_CONTENT_URI); } public void resultReturned(int paramInt1, int paramInt2, Intent paramIntent) { if ((paramInt1 == this.requestCode) && (paramInt2 == -1)) { paramIntent = paramIntent.getData(); this.selectionURI = paramIntent.toString(); Log.i("ImagePicker", "selectionURI = " + this.selectionURI); ContentResolver localContentResolver = this.container.$context().getContentResolver(); MimeTypeMap localMimeTypeMap = MimeTypeMap.getSingleton(); paramIntent = "." + localMimeTypeMap.getExtensionFromMimeType(localContentResolver.getType(paramIntent)); Log.i("ImagePicker", "extension = " + paramIntent); saveSelectedImageToExternalStorage(paramIntent); AfterPicking(); } } } /* Location: C:\Users\Mohamed\Downloads\dex2jar-2.0\dex2jar-2.0\classes-dex2jar.jar!\com\google\appinventor\components\runtime\ImagePicker.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
2702a3744ba29787dfe18f5a0b931ab7ce38626e
Java
ramadannasr/Hospital-Management-System
/Fcih_Hospital/src/GUI/MenuPharmacist.java
UTF-8
749
2.640625
3
[]
no_license
package GUI; import java.awt.event.ActionEvent; import javax.swing.JButton; import GUI.*; public class MenuPharmacist extends MYFrameTitle { JButton medicineButton; public MenuPharmacist(String s) { super(s); this.medicineButton=new JButton("Medicine"); add(medicineButton); medicineButton.addActionListener(this); TitleLable.setBounds(120, 90, 200, 40); medicineButton.setBounds(TitleLable.getBounds().x + 100, TitleLable.getBounds().y + 50, 150, 150); } public void actionPerformed(ActionEvent e){ if(e.getSource()==medicineButton){ this.setVisible(false); new MenuPharmacist2("Patient Medicine").setVisible(true); } } }
true
68221b49a8226e96b1b90c37137034957a9a2142
Java
xiaotou745/et-rrt
/renrencore/src/main/java/com/renrentui/renrencore/enums/TaskDetailCode.java
UTF-8
631
2.5
2
[]
no_license
package com.renrentui.renrencore.enums; public enum TaskDetailCode { /** * 成功 */ Success(200, "success"), UserIdErr(1102, "用户ID错误"), TaskIdErr(1103, "任务ID错误"), Fail(1101, "系统错误"); private int value = 0; private String desc; private TaskDetailCode(int value, String desc) { this.value = value; this.desc = desc; } public int value() { return this.value; } public String desc() { return this.desc; } public static TaskDetailCode getEnum(int index) { for (TaskDetailCode c : TaskDetailCode.values()) { if (c.value() == index) { return c; } } return null; } }
true
750b131ce2fb56d456bc1e5b8afdda6e83ff418c
Java
manoranjan99/Student-Diary
/app/src/main/java/com/manoranjank/studentdiary/attendance.java
UTF-8
570
2.515625
3
[]
no_license
package com.manoranjank.studentdiary; /** * Created by Manoranjan K on 03-06-2019. */ public class attendance { private String subjectname; private int attended; private int bunked; public attendance(String subjectname,int attended,int bunked) { this.subjectname=subjectname; this.attended=attended; this.bunked=bunked; } public String getSubjectname() { return subjectname; } public int getAttended() { return attended; } public int getBunked() { return bunked; } }
true
69836a37327953c16387183263b2833f22e7e0e3
Java
cherkavi/java-code-example
/XML_Editor/src/bc/data_terminal/editor/database/Connector.java
UTF-8
833
2.25
2
[]
no_license
package bc.data_terminal.editor.database; import java.sql.*; import bc.data_terminal.editor.database.oracle.HibernateOracleConnect; /** Singelton for HibernateOracleConnect*/ public class Connector { private static HibernateOracleConnect field_hibernate=null; private static void getHibernateOracleConnect(){ if(field_hibernate==null){ field_hibernate=new HibernateOracleConnect("jdbc:oracle:thin:@192.168.15.254:1521:demo", "bc_reports", "bc_reports", 1); } } public static Connection getConnection(){ if(field_hibernate==null){ getHibernateOracleConnect(); } return field_hibernate.getConnection(); } public static void closeConnection(Connection connection){ if(field_hibernate!=null){ field_hibernate.closeConnection(connection); } } }
true
12256a4935b20d341c58bf09e07b0c0790ec5ba2
Java
nmundhra/CompSci
/PinLockout.java
UTF-8
1,114
3.921875
4
[]
no_license
/* * Assignments turned in without these things will receive no credit. * Change the code so that it locks them out after 4 tries instead of 3. Make sure to change the message at the bottom, too. * Move the "maximum tries" value into a variable, and use that variable everywhere instead of just the number. * */ import java.util.Scanner; public class PinLockout { public static void main( String[] args ) { Scanner keyboard = new Scanner(System.in); int pin = 12345; int tries = 0; int MAX_TRIES = 5; System.out.println("WELCOME TO THE BANK OF MITCHELL."); System.out.print("ENTER YOUR PIN: "); int entry = keyboard.nextInt(); tries++; while ( entry != pin && tries < MAX_TRIES ) { System.out.println("\nINCORRECT PIN. TRY AGAIN."); System.out.print("ENTER YOUR PIN: "); entry = keyboard.nextInt(); tries++; } if ( entry == pin ) System.out.println("\nPIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT."); else if ( tries >= MAX_TRIES ) System.out.println("\nYOU HAVE RUN OUT OF "+ tries + " TRIES. ACCOUNT LOCKED."); } }
true
381a07347b06b1cc9bfd0ffc5073b2e413d3d594
Java
DenShlk/Sticky
/app/src/main/java/com/hypersphere/sticky/StickerAdapter.java
UTF-8
2,692
2.53125
3
[]
no_license
package com.hypersphere.sticky; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class StickerAdapter extends RecyclerView.Adapter<StickerAdapter.StickerHolder> { private final List<Sticker> stickers = new ArrayList<>(); public void addSticker(@NonNull Sticker sticker) { stickers.add(sticker); notifyItemInserted(stickers.size() - 1); } @NonNull @Override public StickerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { int layoutId = viewType == 0 ? R.layout.sticker_element_layout_right : R.layout.sticker_element_layout_left; View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false); return new StickerHolder(view); } @Override public void onBindViewHolder(@NonNull StickerHolder holder, int position) { holder.bind(stickers.get(position)); } @Override public int getItemViewType(int position) { return position % 2; } @Override public int getItemCount() { return stickers.size(); } static class StickerHolder extends RecyclerView.ViewHolder { private final TextView emojiText; private final ImageView image; private final View foreground; private final ImageView editIc; public StickerHolder(@NonNull View itemView) { super(itemView); emojiText = itemView.findViewById(R.id.sticker_emoji_text); image = itemView.findViewById(R.id.sticker_image); foreground = itemView.findViewById(R.id.sticker_foreground); editIc = itemView.findViewById(R.id.sticker_edit_ic); } public Sticker sticker; public void bind(@NonNull Sticker sticker) { this.sticker = sticker; emojiText.setText(sticker.emoji); image.setImageBitmap(sticker.image); } public View getForeground() { return foreground; } public void onSwipe(float t, boolean toRight) { t = (float) Math.pow(t, 0.3f); editIc.setScaleX(t); editIc.setScaleY(t); if (toRight) { editIc.setImageResource(R.drawable.ic_baseline_edit_24); }else { editIc.setImageResource(R.drawable.ic_baseline_delete_24); } } public void onSwipeFinished(boolean toRight) { } } }
true
10ae4b8152a8d2072fc8cbdf352088dbffb2a306
Java
andrei-safronov/SkiingInSingapore
/src/main/java/com/wishmaster/singapore/skiing/MapFileLinesReader.java
UTF-8
899
2.640625
3
[]
no_license
package com.wishmaster.singapore.skiing; import java.io.*; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; /** * Simple utility-class to get data from map file. * It is acceptable for this task purposes. * * @author Andrew */ public class MapFileLinesReader { private final String mapFileResource; public MapFileLinesReader(String mapFileResource) { this.mapFileResource = mapFileResource; } public List<String> getMapFileLines() throws IOException { return Files.readAllLines(getMapFilePath()); } private Path getMapFilePath() throws IOException { try { return Paths.get(MapFileLinesReader.class.getResource(mapFileResource).toURI()); } catch (URISyntaxException e) { throw new IOException(e); } } }
true
7934a8e2a8f4a0a13832444aab499fb27da01a95
Java
goinggoing/test
/JavaBasic/src/java05_array/array2D/Array2D_05.java
UHC
1,102
3.890625
4
[]
no_license
package java05_array.array2D; import java.util.Scanner; public class Array2D_05 { public static void main(String[] args) { //new // Ҵ //Ҵ //Ҵ // Ҵ : ( ) // : , Compile-time // : , , Run-time int num; //int -> Ҵ int[] arr; //int 迭 -> Ҵ arr = new int[5]; //int[5] 迭 -> Ҵ //----------------------------------------- // int[] arr2 = new int[-5]; // 迭 ÿ ϴ ڵ // 迭 ѹ ۼ // ϴ ٸ(Ҵ, Ҵ) //----------------------------------------- int[][] arr3 = new int[3][]; Scanner sc = new Scanner(System.in); for(int i=0; i<arr3.length; i++) { System.out.print(i+" 迭 ũ? "); int len = sc.nextInt(); arr3[i] = new int[len]; } } }
true
60266fe7eec737cda4e83cefc4cb230b01290486
Java
mrudat/skyproc
/src/main/java/skyproc/AVIF.java
UTF-8
4,537
2.5
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package skyproc; import java.util.ArrayList; /** * Actor value records and perk trees. * * @author Justin Swanson */ @SuppressWarnings("serial") public class AVIF extends MajorRecordDescription { // Static prototypes and definitions static final SubPrototype AVIFproto = new SubPrototype( MajorRecordDescription.descProto) { @Override protected void addRecords() { add(SubString.getNew("ANAM", true)); add(new SubData("CNAM")); add(new SubData("AVSK")); add(new SubList<>(new PerkReference(new SubPrototype() { @Override protected void addRecords() { add(new SubForm("PNAM")); forceExport("PNAM"); add(new SubInt("FNAM")); add(new SubInt("XNAM")); add(new SubInt("YNAM")); add(new SubFloat("HNAM")); add(new SubFloat("VNAM")); add(new SubForm("SNAM")); add(new SubList<>(new SubInt("CNAM"))); add(new SubInt("INAM")); } }))); } }; /** * A structure that represents a perk in a perktree */ public static final class PerkReference extends SubShellBulkType { PerkReference(SubPrototype proto) { super(proto, false); } @Override boolean isValid() { return true; } @Override PerkReference getNew(String type) { return new PerkReference(getPrototype()); } @Override PerkReference getNew() { return new PerkReference(getPrototype()); } /** * * @param id */ public void setPerk(FormID id) { subRecords.setSubForm("PNAM", id); } /** * * @return */ public FormID getPerk() { return subRecords.getSubForm("PNAM").getForm(); } /** * * @param x */ public void setX(int x) { subRecords.setSubInt("XNAM", x); } /** * * @return */ public int getX() { return subRecords.getSubInt("XNAM").get(); } /** * * @param y */ public void setY(int y) { subRecords.setSubInt("YNAM", y); } /** * * @return */ public int getY() { return subRecords.getSubInt("YNAM").get(); } /** * * @param horiz */ public void setHorizontalPos(float horiz) { subRecords.setSubFloat("HNAM", horiz); } /** * * @return */ public float getHorizontalPos() { return subRecords.getSubFloat("HNAM").get(); } /** * * @param vert */ public void setVerticalPos(float vert) { subRecords.setSubFloat("VNAM", vert); } /** * * @return */ public float getVerticalPos() { return subRecords.getSubFloat("VNAM").get(); } /** * * @param skill */ public void setSkill(FormID skill) { subRecords.setSubForm("SNAM", skill); } /** * * @return */ public FormID getSkill() { return subRecords.getSubForm("SNAM").getForm(); } /** * * @return */ public ArrayList<Integer> getPointers() { return subRecords.getSubList("CNAM").toPublic(); } /** * @deprecated modifying the ArrayList will now directly affect the * record. */ public void clearPointers() { subRecords.getSubList("CNAM").clear(); } /** * @deprecated modifying the ArrayList will now directly affect the * record. * @param index */ public void addPointer(int index) { subRecords.getSubList("CNAM").add(index); } /** * @param ref */ public void addPointer(PerkReference ref) { addPointer(ref.getIndex()); } /** * * @param index */ public void setIndex(int index) { subRecords.setSubInt("INAM", index); } /** * * @return */ public int getIndex() { return subRecords.getSubInt("INAM").get(); } } // Common Functions AVIF() { super(); subRecords.setPrototype(AVIFproto); } @Override ArrayList<String> getTypes() { return Record.getTypeList("AVIF"); } @Override AVIF getNew() { return new AVIF(); } // Get/Set /** * * @param abbr */ public void setAbbreviation(String abbr) { subRecords.setSubString("ANAM", abbr); } /** * * @return */ public String getAbbreviation() { return subRecords.getSubString("ANAM").print(); } /** * * @return */ public ArrayList<PerkReference> getPerkReferences() { return subRecords.getSubList("PNAM").toPublic(); } }
true
3063e054bf3042f72f593715bce7c75a3ab57e4d
Java
shashaaankk/Playground
/Operation Choices/Main.java
UTF-8
249
2.90625
3
[]
no_license
def operatorChoices(a,b,c): if c==1: return a+b elif c==2: return a-b elif c==3: return a*b elif c==4: return int(a/b) c=int(input()) a=int(input()) b=int(input()) op=operatorChoices(a,b,c) print(op)
true
69e343b63f40447c2272fb6789df1ac6b1d4215a
Java
yzuzhang/socket-agent
/src/main/java/com/feicent/agent/SocketApplication.java
UTF-8
2,229
2.921875
3
[]
no_license
package com.feicent.agent; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feicent.agent.thread.ServerThread; import com.feicent.agent.util.CloseUtil; import com.feicent.agent.util.Constants; import com.feicent.agent.util.MyUtil; /** * 代理服务器启动类 * @author yzuzhang * @date 2017年11月3日 */ public class SocketApplication { public static Logger logger = LoggerFactory.getLogger("log"); public static ServerSocket server = null; public static ExecutorService threadPool = null; public static void main(String[] args) { try { threadPool = Executors.newCachedThreadPool(); server = new ServerSocket(Constants.SOCKET_PORT); logger.info(MyUtil.getNow() +" creates a server socket successfully!"); addShutdownHook(); while (true) { Socket socket = server.accept(); socket.setTcpNoDelay(true); //当有请求时,线程池处理 ServerThread thread = new ServerThread(socket); threadPool.execute(thread); } } catch (IOException e) { logger.error(e.getMessage()); } finally { CloseUtil.close(server); if (threadPool != null) { threadPool.shutdown(); } } } /** * 在关闭JVM前, 关闭资源 */ private static void addShutdownHook() { Thread hookThread = new Thread(){ @Override public void run() { try { logger.info("开始停止接收消息, 关闭socket连接....."); IOUtils.closeQuietly(server); if(threadPool != null){ threadPool.shutdown(); } logger.info("ShutdownHook: 线程池已经关闭!!!"); } catch(Exception e) { logger.error("addShutdownHook Exception: {}", e.getMessage(), e); } } }; Runtime.getRuntime().addShutdownHook(hookThread); } }
true
25474fa73ac3a6f148535073352696772f6b5bbf
Java
ericschaal/booker
/src/main/java/common/resource/Resource.java
UTF-8
83
1.78125
2
[]
no_license
package common.resource; public enum Resource { CAR, ROOM, FLIGHT, CUSTOMER }
true
18b70cce78ec8b450d7e951c3ca2bd472d9e89de
Java
averbeir/tp3
/src/main/java/tp3.java
UTF-8
1,925
3.359375
3
[]
no_license
/** * Created by averbeir on 14/04/18. */ public class tp3 { public static void main(String[] args){ System.out.println(pgcd(4997,1)); int[] tab = {0,1,2,3,4,5,6,7,8,9}; System.out.println(maxTab(tab)); System.out.println(sum(tab)); System.out.println(isEven(-5)); System.out.println(isPrime(2)); combine(tab,tab); } /** * * @param d * @param n * @return */ private static int pgcd(int d,int n){ if(d < 0 || n < 0){ throw new IllegalArgumentException(); } int r=0; while(n!=0) { r=d%n; d=n; n=r; } return d; } /** * * @param tab * @return */ private static int maxTab(int[] tab){ if(tab == null){ throw new IllegalArgumentException(); } int max = tab[0]; for(int i=1;tab.length>i;i++){ if(tab[i] > max ){ max = tab[i]; } } return max; } /** * * @param tab * @return */ private static int sum(int[] tab){ if(tab == null){ throw new IllegalArgumentException(); } int sum = tab[0]; for (int i = 1;i<tab.length;i++){ sum += tab[i]; } return sum; } /** * * @param p * @return */ private static boolean isEven(int p){ return p%2 == 0; } /** * * @param n * @return */ private static boolean isPrime(int n){ for(int d=2;d<n; d++) { if(n%d==0) { return false; } } return true; } private static void combine(int[] a, int[] b){ int sum = sum(b); for(int i = 0;i<a.length;i++){ a[i] = a[i]*sum; } } }
true
91872fd76c942cc210cac742cac2fd51a929eb62
Java
luanch/Ploximo
/src/ploximo/controle/Motivo.java
UTF-8
982
2.40625
2
[]
no_license
/* * 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 ploximo.controle; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * * @author Bianca */ public class Motivo { private static Map<Integer,String> motivos; public static void setMotivos() throws IOException { motivos = hashMapMotivos(); } private static HashMap hashMapMotivos() throws IOException{ ConversorDeTxtParaMatriz conversor = new ConversorDeTxtParaMatriz(); HashMap<Integer, String> c = conversor.converter("src/ploximo/basesDeDados/motivos.txt"); return c; } public static String gerar() throws IOException{ setMotivos(); Randomizador r = new Randomizador(); int posicao = r.gerarInt(motivos.size()); return motivos.get(posicao); } }
true
5607c6d69d41bdc85bed00b4f7ec731eea21aede
Java
iissky/LZ
/src/com/controller/GameRoundController.java
UTF-8
2,954
2.046875
2
[]
no_license
package com.controller; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.pojo.LzGameround; import com.pojo.LzUserinfo; import com.pojo.PageBean; import com.service.IGameRoundService; @Controller @RequestMapping("/game") public class GameRoundController { @Autowired IGameRoundService gameSer; public void setGameSer(IGameRoundService gameSer) { this.gameSer = gameSer; } @RequestMapping("/gameListPage") public String gameListPage(Map model, String pageIndex){ int index = 1; if(pageIndex!=null){ index = Integer.valueOf(pageIndex); } PageBean<LzGameround> pb = gameSer.findGameRoundByPage(index, 20, "select * from lz_gameround where 1=1 order by createtime desc"); model.put("pb", pb); return "gameRoundList"; } @RequestMapping(value="/gameLimit") public String gameLimit(Map model){ try { String path = this.getClass().getResource("/").getPath(); InputStream in = new FileInputStream(path+"/gameset.properties"); Properties p = new Properties(); p.load(in); String gameLimit = p.getProperty("gameLimit"); model.put("limit", gameLimit); in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "gameLimit"; } @RequestMapping("/gameLimitSet") public String gameLimitSet(Map model,String limit){ try { String path = this.getClass().getResource("/").getPath(); InputStream in = new FileInputStream(path+"/gameset.properties"); Properties p = new Properties(); p.load(in); in.close(); FileOutputStream fot = new FileOutputStream(path+"/gameset.properties"); p.setProperty("gameLimit", limit); String gameLimit = p.getProperty("gameLimit"); model.put("limit", gameLimit); p.store(fot, ""); fot.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "gameLimit"; } @RequestMapping("/startGame") public String startGame(ModelMap model){ gameSer.createGameRound(); try { String path = this.getClass().getResource("/").getPath(); InputStream in = new FileInputStream(path+"/gameset.properties"); Properties p = new Properties(); p.load(in); String gameLimit = p.getProperty("gameLimit"); model.put("limit", gameLimit); in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } model.addAttribute("mess", "<script>alert('启动成功')</script>"); return "gameLimit"; } }
true
f7d8ee96095fb59eff6607a6a0cd2d7d988db454
Java
qiaoenyin/test
/src/main/java/Test/idCardTest.java
UTF-8
1,365
2.921875
3
[]
no_license
package main.java.Test; public class idCardTest { private static final int IDCARD_LEN = 18; private static final int[] INTARR = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; private static final int[] INTARR2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; private static final int[] INTARR3 = { 1, 0, 88, 9, 8, 7, 6, 5, 4, 3, 2 }; public static boolean validator(Object input) { if (input == null) { return false; } String idCard = (String) input; if ((idCard == "") || (idCard.length() != 18)) { return false; } idCard = idCard.toUpperCase(); int sum = 0; for (int i = 0; i < INTARR.length; ++i) { //{ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9,10, 5, 8, 4, 2 } //34030219980718182X System.out.println(idCard.charAt(i)); System.out.println(Character.digit(idCard.charAt(i), 10)); sum += Character.digit(idCard.charAt(i), 10) * INTARR[i]; } int mod = sum % 11; String matchDigit = ""; for (int i = 0; i < INTARR2.length; ++i) { int j = INTARR2[i]; if (j == mod) { matchDigit = String.valueOf(INTARR3[i]); if (INTARR3[i] > 57) { matchDigit = String.valueOf((char) INTARR3[i]); } } } return matchDigit.equals(idCard.substring(idCard.length() - 1)); } public static void main(String args[]){ String idCard = "34122519900301727X"; System.out.println(validator(idCard)); } }
true
72a7fd47b4ba1083f7e276f037e4a63a05d0f3c3
Java
ydch10086/ane-inf
/src/main/java/com/ane/mq/kafka/consumer/split_pack/SplitPackConsumer.java
UTF-8
11,880
1.929688
2
[]
no_license
/** * @Title: SplitPackConsumer.java * @Package com.ane.mq.kafka.consumer.split_pack * @Description: TODO * Copyright: Copyright (c) 2011 * Company:*****信息技术有限责任公司 * * @author Comsys-xuanning * @date 2016年5月14日 上午10:58:05 * @version V1.0 */ package com.ane.mq.kafka.consumer.split_pack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Properties; import java.util.concurrent.Executors; import kafka.consumer.Consumer; import kafka.consumer.ConsumerConfig; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ane.common.service.IRedisCommandService; import com.ane.entity.PackageEwbsVO; import com.ane.inf.common.util.Constant; import com.ane.inf.split_pack.dao.IContrastWithSplitPackMapper; import com.ane.inf.split_pack.entity.ContrastWithSplitPack; import com.ane.inf.split_pack.entity.SplitPack; import com.ane.inf.split_pack.entity.SplitPackSubItem; import com.ane.mq.kafka.consumer.BaseConsumer; import com.ane.util.CommonGsonHandler; import com.google.gson.reflect.TypeToken; /** * @ClassName: SplitPackConsumer * @Description: 拆包对比数据的消费者 * @author Comsys-xuanning * @date 2016年5月14日 上午10:58:05 */ public class SplitPackConsumer extends BaseConsumer implements Observer { private final static Logger _LOGGER = LoggerFactory.getLogger(SplitPackConsumer.class); private IContrastWithSplitPackMapper contrastSplitPackRepo; private IRedisCommandService redisService; /** * @ClassName: SplitPackConsumerFactory * @Description: 静态内部类来构建单例对象 * @author Comsys-xuanning * @date 2016年5月14日 下午3:05:25 */ private static class SplitPackConsumerFactory{ private final static SplitPackConsumer INSTANCE = new SplitPackConsumer(); } /** * getInstance * * @Title: getInstance * @Description: 单例对象对外提供数据的方法 * @author Comsys-xuanning * @return 设定文件 * @throws */ public static SplitPackConsumer getInstance(){ return SplitPackConsumerFactory.INSTANCE; } private SplitPackConsumer(){ } /** * <p>Title: createConsumer</p> * <p>Description: </p> * @return * @see com.ane.mq.kafka.consumer.BaseConsumer#createConsumer() */ @Override protected ConsumerConnector createConsumer() { if (this.producerProps == null) { this.producerProps = new Properties(); } this.consumer = Consumer.createJavaConsumerConnector(new ConsumerConfig(producerProps)); return this.consumer; } /** * <p>Title: executor</p> * <p>Description: </p> * @see com.ane.mq.kafka.consumer.BaseConsumer#executor() */ @Override public void executor() { pool = Executors.newFixedThreadPool(poolsize); Bee bee = null; for (int i = 0; i < poolsize; i++) { bee = new Bee(); // bee.addObserver(this); pool.execute(bee); } } /** * @ClassName: Bee * @Description: 消费处理的线程 * @author Comsys-xuanning * @date 2016年5月14日 上午11:52:39 */ private class Bee extends Thread{ @Override public void run() { try { _LOGGER.info("小蜜蜂开始运行..."); Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(topic, 1); // 一次从主题中获取一个数据 Map<String, List<KafkaStream<byte[], byte[]>>> messageStreams = consumer.createMessageStreams(topicCountMap); KafkaStream<byte[], byte[]> stream = messageStreams.get(topic).get(0);// 获取每次接收到的这个数据 ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); String message = ""; List<SplitPack> splitPackLst = null; SplitPack splitPack = null; List<SplitPackSubItem> itemLst = null; Map<String, List<SplitPackSubItem>> subItemMap = new HashMap<String, List<SplitPackSubItem>>(); List<SplitPackSubItem> tempSubItemLst = null; String ewbNo = ""; String packBarCode = ""; int shouldNum = 0; int realNum = 0; List<ContrastWithSplitPack> diffLst = null;; ContrastWithSplitPack diffPack = null; PackageEwbsVO groupPack = null; Map<String, List<String>> splitItemMap = null; List<String> ewbLst = null; List<String> ewbLstByPackCode = null; SplitPackSubItem item = null; Map<Integer, List<String>> diffNoteMap = null; while(true){ _LOGGER.info("小蜜蜂运行中..."); while(iterator.hasNext()){ message = new String(iterator.next().message(),"UTF-8"); _LOGGER.info("接收到:{} ", message); if (CommonGsonHandler.isGoodJson(message)) { try { splitPackLst = Constant.GSON.fromJson(message, new TypeToken<List<SplitPack>>(){}.getType()); if (splitPackLst != null && !splitPackLst.isEmpty()) { splitPack = splitPackLst.get(0); itemLst = splitPack.getSubItemLst(); if (itemLst != null && !itemLst.isEmpty()) { diffLst = new ArrayList<ContrastWithSplitPack>(); subItemMap = new HashMap<String, List<SplitPackSubItem>>(); splitItemMap = new HashMap<String, List<String>>(); for (SplitPackSubItem subItem : itemLst) { /** * 获取到扫描的运单号 */ ewbNo = subItem.getEwbNo(); /** * 查询出本运单在本网点的包条码 */ packBarCode = contrastSplitPackRepo.getSplitPackWithCondition(ewbNo, subItem.getScanSiteId()); if (StringUtils.isBlank(packBarCode)) { packBarCode = "0000000000000"; } /** * 当子表map已经存在数据时,取出map的value进行添加后再放入 */ if (subItemMap.containsKey(packBarCode)) { tempSubItemLst = subItemMap.get(packBarCode); tempSubItemLst.add(subItem); subItemMap.put(packBarCode, tempSubItemLst); ewbLst = splitItemMap.get(packBarCode); ewbLst.add(subItem.getEwbNo()); splitItemMap.put(packBarCode, ewbLst); }else { /** * 当子表map不存在数据时,先申请一个list对象再放入 */ tempSubItemLst = new ArrayList<SplitPackSubItem>(); tempSubItemLst.add(subItem); subItemMap.put(packBarCode, tempSubItemLst); ewbLst = new ArrayList<String>(); ewbLst.add(subItem.getEwbNo()); splitItemMap.put(packBarCode, ewbLst); } } for (String key : subItemMap.keySet()) { item = subItemMap.get(key).get(0); diffPack = new ContrastWithSplitPack(); if ("0000000000000".equals(key)) { realNum = subItemMap.get(key).size(); diffPack.setShouldScanNum(0); /** * 实扫 */ diffPack.setRealScanNum(realNum); /** * 有效 */ diffPack.setEffectiveScanNum(0); diffPack.setInvalidScanNum(realNum); diffNoteMap = new HashMap<Integer, List<String>>(); ewbLst = splitItemMap.get(key); diffNoteMap.put(20, ewbLst); diffPack.setDiffType(20); diffPack.setDiffNum(shouldNum - realNum); diffPack.setDiffNote(Constant.GSON.toJson(diffNoteMap)); }else { groupPack = contrastSplitPackRepo.getGroupPackWithPackBarCode(key); if (groupPack != null) { /** * 根据包条码来查询出信息,查询集包数量、拆包主键、集包主键、集包site */ diffPack.setGroupPackId(groupPack.getPackageId()); diffPack.setLeaveSiteId(groupPack.getScanSiteId()); diffPack.setLeaveSiteName(groupPack.getScanSite()); /** * 应扫 */ shouldNum = groupPack.getNum(); realNum = subItemMap.get(key).size(); diffPack.setShouldScanNum(shouldNum); /** * 查询出明细进行对比 */ ewbLstByPackCode = contrastSplitPackRepo.getGroupEwbByPackBarCode(key, item.getScanSiteId()); ewbLst = splitItemMap.get(key); /** * 10 */ ewbLstByPackCode.removeAll(ewbLst); if (!ewbLstByPackCode.isEmpty()) { diffNoteMap = new HashMap<Integer, List<String>>(); diffNoteMap.put(10, ewbLstByPackCode); diffPack.setDiffType(10); diffPack.setDiffNum(shouldNum - realNum); diffPack.setDiffNote(Constant.GSON.toJson(diffNoteMap)); } /** * 实扫 */ diffPack.setRealScanNum(realNum); /** * 有效 */ diffPack.setEffectiveScanNum(realNum); diffPack.setInvalidScanNum(0); } } diffPack.setPackBarCode(key); diffPack.setDeviceCode(item.getDeviceCode()); diffPack.setScanMan(item.getScanMan()); diffPack.setScanManId(item.getScanManId()); diffPack.setScanSite(item.getScanSite()); diffPack.setScanSiteId(item.getScanSiteId()); diffPack.setScanSourceId(item.getScanSiteId()); diffPack.setScanTime(item.getScanTime()); if (StringUtils.isNotBlank(key)) { String jsonStr = redisService.get("ANE_EX:CONSTRASTEWB:"+key, String.class); Map<String, String> map = Constant.GSON.fromJson(jsonStr, new TypeToken<Map<String, String>>(){}.getType()); if (map!=null && !map.isEmpty()) { diffPack.setGroupPackId(map.get("groupPackId")); diffPack.setSplitPackId(Long.valueOf(map.get("splitPackId"))); } redisService.remove("ANE_EX:CONSTRASTEWB:"+key); } diffLst.add(diffPack); } } } if (diffLst!= null && !diffLst.isEmpty()) { contrastSplitPackRepo.batchSave(diffLst); } } catch (Exception e) { // TODO Auto-generated catch block _LOGGER.info("处理报错:{}",e); } } } _LOGGER.info("小蜜蜂勤劳累了,休息会儿..."); Thread.sleep(5000); } } catch (InterruptedException e) { // TODO Auto-generated catch block _LOGGER.error("处理线程报错,{}",e); }catch (Exception e) { // TODO: handle exception _LOGGER.error("处理线程报错,{}",e); }finally{ consumer.commitOffsets(); consumer.shutdown(); } } } /** * <p>Title: update</p> * <p>Description: </p> * @param o * @param arg * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ @Override public void update(Observable o, Object arg) { _LOGGER.info("观察者开始处理信息"); try { pool.execute(new Bee()); } catch (Exception e) { // TODO Auto-generated catch block _LOGGER.error("{}",e); } _LOGGER.info("观察者处理信息完成"); } public IContrastWithSplitPackMapper getContrastSplitPackRepo() { return contrastSplitPackRepo; } public void setContrastSplitPackRepo( IContrastWithSplitPackMapper contrastSplitPackRepo) { this.contrastSplitPackRepo = contrastSplitPackRepo; } public IRedisCommandService getRedisService() { return redisService; } public void setRedisService(IRedisCommandService redisService) { this.redisService = redisService; } }
true
898f1b3b173ecd6de7a92e1beba025d85249dcc2
Java
Featherlet/Algorithm_and_Leetcode
/LeetcodeSolution_Java/Solution347.java
UTF-8
1,061
2.96875
3
[]
no_license
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; public class Solution347 { public List<Integer> topKFrequent(int[] nums, int k) { //using hashmap and buscket HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int n : nums) map.put(n, map.getOrDefault(n, 0) + 1); ArrayList<Integer>[] bucket = new ArrayList[nums.length + 1]; for(int n : map.keySet()){ int count = map.get(n); if(bucket[count] == null){ bucket[count] = new ArrayList<Integer>(); bucket[count].add(n); } else bucket[count].add(n); } List<Integer> res = new ArrayList<Integer>(); int counter = 0; for(int i = bucket.length - 1; i >= 0 && counter < k; i--){ if(bucket[i] != null){ for(int j = 0; j < bucket[i].size(); j++){ res.add(bucket[i].get(j)); counter++; if(counter == k) break; } } } return res; } }
true
d8386b87dd4c0b3325e88e03b5e3728703c07cd7
Java
hohler/scg-bico
/src/main/java/tool/bico/mvc/StringUtils.java
UTF-8
174
1.585938
2
[]
no_license
package tool.bico.mvc; public class StringUtils { public static final String LF = "\n"; public static final String CR = "\r"; public static final String CRLF = "\r\n"; }
true
d4ddebb24d28a37e13e5a1e20633cb68bdbb999b
Java
mstepan/app-java13-template
/src/main/java/com/max/app/concurrency/model/EvenImpl.java
UTF-8
424
2.71875
3
[ "MIT" ]
permissive
package com.max.app.concurrency.model; public class EvenImpl implements Even { private int value; private final Object mutex = new Object(); @Override public int next() { synchronized (mutex) { ++value; ++value; return value; } } @Override public int getValue() { synchronized (mutex) { return value; } } }
true
5692d274296a261834b4cc14973a034fad17444e
Java
chivas-yin/RentHouse
/src/main/java/com/rent/model/RentPerson.java
UTF-8
1,968
2.203125
2
[]
no_license
package com.rent.model; import java.util.Date; /** * 租客信息 * @author chivas * */ public class RentPerson { /**租客信息主键**/ private Long rpKey; /**租客姓名**/ private String rpName; /**租客电话**/ private String rpPhone; /**租客身份证**/ private String rpId; /**租客身份证地址**/ private String rpDistrict; /**租客银行卡**/ private String rpCard; /**银行卡银行**/ private String rpCardBank; /**租客所租房间号码**/ private Integer rhId; private Integer status; private Date createDate; private Date lastUpdateDate; public Long getRpKey() { return rpKey; } public void setRpKey(Long rpKey) { this.rpKey = rpKey; } public String getRpName() { return rpName; } public void setRpName(String rpName) { this.rpName = rpName; } public String getRpPhone() { return rpPhone; } public void setRpPhone(String rpPhone) { this.rpPhone = rpPhone; } public String getRpId() { return rpId; } public void setRpId(String rpId) { this.rpId = rpId; } public String getRpDistrict() { return rpDistrict; } public void setRpDistrict(String rpDistrict) { this.rpDistrict = rpDistrict; } public String getRpCard() { return rpCard; } public void setRpCard(String rpCard) { this.rpCard = rpCard; } public String getRpCardBank() { return rpCardBank; } public void setRpCardBank(String rpCardBank) { this.rpCardBank = rpCardBank; } public Integer getRhId() { return rhId; } public void setRhId(Integer rhId) { this.rhId = rhId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getLastUpdateDate() { return lastUpdateDate; } public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } }
true
2db42677c46f61660f7e3f13801ca480a628135a
Java
zekai-li/SpringLearnProject
/SpringLearn4/src/main/java/com/learn/xml/calculator/Calculator.java
UTF-8
212
2.40625
2
[]
no_license
package com.learn.xml.calculator; public interface Calculator { public int add(int i,int j); public int decr(int i,int j); public int multi(int i,int j); public int div(int i,int j); }
true
0b9776a15b1ae7491a621b2fc6d8e50074189596
Java
wjf8882300/ck
/src/main/java/com/tonggu/repository/custom/impl/UserRepositoryImpl.java
UTF-8
1,623
2.015625
2
[]
no_license
package com.tonggu.repository.custom.impl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Repository; import com.tonggu.repository.custom.UserRepositoryCustom; import com.tonggu.util.RepositoryUtil; import com.tonggu.util.SqlCondition; @Repository public class UserRepositoryImpl implements UserRepositoryCustom { @Autowired private RepositoryUtil repositoryUtil; @Override public Page<Map<String, Object>> queryAll(Map<String, Object> params) { StringBuilder sql = new StringBuilder() .append(" SELECT id \"id\",login_name \"loginName\",login_password \"loginPassword\", ") .append(" cust_name \"custName\",credentials_code \"credentialsCode\",mobile \"mobile\", ") .append(" email \"email\",record_status \"recordStatus\",create_user \"createUser\", ") .append(" create_date \"createDate\",last_update_user \"lastUpdateUser\",last_update_date \"lastUpdateDate\", ") .append(" VERSION \"version\",memo \"memo\" ") .append(" FROM ck_t_user ") .append(" WHERE 1 = 1 "); SqlCondition condition = new SqlCondition(sql, params); condition.addString("loginName", "login_name") .addString("custName", "cust_name") .addString("credentialsCode", "credentials_code") .addString("mobile", "mobile") .addSql(" order by create_date desc"); return repositoryUtil.queryForPageMap(condition.toString(), condition.toArray(), Integer.valueOf(params.get("start").toString()), Integer.valueOf(params.get("length").toString())); } }
true
e98a240d1b21027b6cac246941c92a56943995fd
Java
allords/CSE360_FinalProjecr
/Final Project/src/CSE_360_Final_Project.java
UTF-8
6,960
3.109375
3
[]
no_license
import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class CSE_360_Final_Project { //This method displays the main menu public CSE_360_Final_Project(){ //Creating tabs in menu JMenu file = new JMenu("File"); JMenu about = new JMenu("About"); //creating JFrame JFrame frame = new JFrame("CSE360 Final Project"); //creating JMenuBar JMenuBar bar = new JMenuBar(); JMenuItem roaster = new JMenuItem("Load a Roster"); JMenuItem attendance = new JMenuItem("Add Attendance"); JMenuItem save = new JMenuItem("Save"); JMenuItem plot = new JMenuItem("Plot Data"); JMenuItem studentInformation = new JMenuItem("Student Info"); //Creating textArea JTextArea text = new JTextArea(); //creating object for Information Information in = new Information(); //add items onto its corresponding item file.add(roaster); file.add(attendance); file.add(save); file.add(plot); about.add(studentInformation); //adding file and about to JMenuBar bar.add(file); bar.add(about); //adding text into frame frame.add(text); //action event for when you click on about and studentInfo studentInformation.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Creating JFrame JFrame frame2 = new JFrame("Student Information"); //creating JPanel JPanel panel = new JPanel(); //creating JLabel with student info JLabel student1 = new JLabel("Name: Luis Vazquez" + " ID: 1214868824" + " Email: lovazque@asu.edu"); //JLabel student2 = new JLabel(" Name: " + " ID: " + " Email: "); //JLabel student3 = new JLabel(" Name: " + " ID: " + " Email: "); //adding Label into panel panel.add(student1); //panel.add(student2); //panel.add(student3); //add panel into frame frame2.add(panel); //set frame2 visible,location, and its size frame2.setVisible(true); frame2.setSize(600,200); frame2.setLocation(500, 125); } }); //action event when you want to load Attendance roaster roaster.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //creating JfileChooser object JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); File selectedFile = chooser.getSelectedFile(); String file = selectedFile.getAbsolutePath(); try { //creating a FileReader and BUfferedReader FileReader reader = new FileReader(file); BufferedReader buffer = new BufferedReader(reader); FileReader reader2 = new FileReader(file); BufferedReader buffer2 = new BufferedReader(reader2); //Prints Name of columns String[] columns = in.getColumnInfo(); //Initialized variables int index = 0; int count = 0; String line = " "; while((buffer.readLine()) != null) { count++; } //keep the number of rows in.setRoasterRow(count); //creating data Array String[][] roaster = new String[count][6]; //parse through file and save in array while((line = buffer2.readLine()) != null) { //saves info in data2 roaster[index] = line.split(","); index++; } //save data in.setRoaster(roaster); //create table with data JTable table = new JTable(roaster, columns); frame.add(new JScrollPane(table)); //make text area not visible text.setVisible(false); //close BufferedReader text.read(buffer, null); buffer.close(); buffer2.close(); text.requestFocus(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }//end of actionPerformed() }); //action event when you want to load attendnace attendance.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //creating JfileChooser object JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); File selectedFile = chooser.getSelectedFile(); String file = selectedFile.getAbsolutePath(); try { //creating a FileReader and BUfferedReader FileReader read = new FileReader(file); BufferedReader buffer = new BufferedReader(read); FileReader reader2 = new FileReader(file); BufferedReader buffer2 = new BufferedReader(reader2); String date = "Date"; //date picker goes here //add another column for date String[] column = in.addColumn(date); //Initialized index and line int index = 0; int count = 0; String line = " "; //parse through file and count number of rows while((buffer.readLine()) != null) { count++; } //creating data Array String[][] attendance = new String[count][2]; String[][] roaster = in.getRoaster(); //parse through file and save in array while((line = buffer2.readLine()) != null) { //saves info in data2 attendance[index] = line.split(","); index++; } //setting number of rows in.setAttendnanceRow(count); //combines duplicates asurite attendance = in.compareEmails(attendance); in.setAttendance(attendance); roaster = in.increaseSize(roaster); roaster = in.combine(roaster, attendance); in.setRoaster(roaster); //create table with data JTable table = new JTable(roaster, column); frame.add(new JScrollPane(table)); //make text area not visible text.setVisible(false); //close BufferedReader text.read(buffer, null); buffer.close(); buffer2.close(); text.requestFocus(); }catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); //action event when you want to save save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); //action event when you want to plot plot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //code in here } }); //set frame visible, location, and its size frame.setLocation(300, 50); frame.setSize(1000, 700); frame.setVisible(true); //will terminate program when window is closed frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(bar); } public static void main(String[] args) { new CSE_360_Final_Project(); }//end of main }
true
68b3d5ab56502e570a6b0294f9bce3745315a590
Java
PrasanthLevelUp/FullStackTestingBatch1
/TestDemoSelenium/src/com/levelup/JSDemo1.java
UTF-8
1,465
2.28125
2
[]
no_license
package com.levelup; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class JSDemo1 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://demoqa.com/automation-practice-form"); driver.manage().window().maximize(); WebElement gender = driver.findElement(By.xpath("//label[contains(text(),'Male')]")); WebElement fn = driver.findElement(By.xpath("//input[@id='firstName']")); WebElement address = driver.findElement(By.xpath("//*[@id='currentAddress']")); JavascriptExecutor ex = (JavascriptExecutor) driver; ex.executeScript("arguments[0].click();", gender); ex.executeScript("arguments[0].value='Malathi'", fn); ex.executeScript("document.getElementById('lastName').value='Shaymala'"); ex.executeScript("arguments[0].scrollIntoView(true);", address); //ex.executeScript("window.scrollBy(0,400)"); String title = driver.getTitle(); System.out.println(title); String url = driver.getCurrentUrl(); System.out.println(url); String jstitle = ex.executeScript("return document.title").toString(); System.out.println(jstitle); String jsurl = ex.executeScript("return document.URL").toString(); System.out.println(jsurl); } }
true
1077ca57517887729c8485daf41ffb4c166fe51f
Java
TH1284/Java
/중간고사/src/중간고사/StudentMain.java
UTF-8
1,556
3.65625
4
[]
no_license
package 중간고사; import java.util.Arrays; public class StudentMain { public static void main(String[] args) { System.out.println("중간고사 성적"); Student[] student1 = new Student[100]; Student[] student2 = new Student[100]; for (int i = 0; i < student1.length; i++) { student1[i] = new Student(); } Random2 rand = new Random2(); for (int i = 0; i < student1.length; i++) { student1[i].name = (i + 1) + "번 학생"; student1[i] = rand.randomStudent(student1[i]); } for (int i = 0; i < student1.length; i++) { student1[i].total = student1[i].kor + student1[i].eng + student1[i].math; } Arrays.sort(student1); for (int i = 0; i < student1.length; i++) { System.out.println(student1[i].print()); } System.out.println(); System.out.println("기말고사 성적"); for (int i = 0; i < student2.length; i++) { student2[i] = new Student(); } for (int i = 0; i < student2.length; i++) { student2[i].name = (i + 1) + "번 학생"; student2[i] = rand.randomStudent(student2[i]); } for (int i = 0; i < student2.length; i++) { student2[i].total = student2[i].kor + student2[i].eng + student2[i].math; } Arrays.sort(student2); for (int i = 0; i < student2.length; i++) { System.out.println(student2[i].print()); } System.out.println(); System.out.println("성적이 올라간 학생은"); for (int i = 0; i < student2.length; i++) { if(student1[i].total < student2[i].total) { System.out.println(student2[i].print()); } } } }
true
0b0c0a52756023fbe0a5cf23f4079c1503d4aae2
Java
SahilMarkanday/FaceRecognitionKairosDemo
/app/src/main/java/com/facerecognitionkairosdemo/marka/facerecognitionkairosdemo/AdminActivity.java
UTF-8
10,432
2.0625
2
[]
no_license
package com.facerecognitionkairosdemo.marka.facerecognitionkairosdemo; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.view.View; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.kairos.Kairos; import com.kairos.KairosListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; public class AdminActivity extends AppCompatActivity { Button reg; Button remove; Button adminlogout; ListView userList; Kairos myKairos; KairosListener listener; JSONObject jo; JSONArray ja; String[] listItems; int counter; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin); reg = (Button)findViewById(R.id.reg); remove = (Button)findViewById(R.id.remove); adminlogout = (Button)findViewById(R.id.adminlogout); userList = (ListView)findViewById(R.id.userList); myKairos = new Kairos(); String app_id = "793a284b"; String api_key = "d1ad8c7199a0ab9f700146b1065bbe95"; myKairos.setAuthentication(AdminActivity.this, app_id, api_key); listener = new KairosListener() { @Override public void onSuccess(String s) { Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show(); } @Override public void onFail(String s) { } }; reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(AdminActivity.this, RegisterActivity.class); startActivity(i); } }); remove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { // Reading a file that already exists File f = new File(getFilesDir(), "file.ser"); FileInputStream fi = new FileInputStream(f); ObjectInputStream o = new ObjectInputStream(fi); // Notice here that we are de-serializing a String object (instead of // a JSONObject object) and passing the String to the JSONObject’s // constructor. That’s because String is serializable and // JSONObject is not. To convert a JSONObject back to a String, simply // call the JSONObject’s toString method. String j = null; try { j = (String) o.readObject(); } catch (ClassNotFoundException c) { c.printStackTrace(); } try { jo = new JSONObject(j); ja = jo.getJSONArray("data"); } catch (JSONException e) { e.printStackTrace(); } }catch(IOException e){ // There's no JSON file that exists, so don't // show the list. But also don't worry about creating // the file just yet, that takes place in AddText. //Here, disable the list view userList.setEnabled(false); userList.setVisibility(View.INVISIBLE); } showEnterLabelDialog(); /*JSONArray list = new JSONArray(); int len = ja.length(); if (ja != null) { for (int i=0;i<len;i++) { //Excluding the item at position if (i != counter) { try { list.put(ja.get(i)); } catch (JSONException e) { e.printStackTrace(); } } } }*/ } }); adminlogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(AdminActivity.this, MainActivity.class); startActivity(i); } }); try { myKairos.listSubjectsForGallery("Company", listener); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); jo = null; try { // Reading a file that already exists File f = new File(getFilesDir(), "file.ser"); FileInputStream fi = new FileInputStream(f); ObjectInputStream o = new ObjectInputStream(fi); // Notice here that we are de-serializing a String object (instead of // a JSONObject object) and passing the String to the JSONObject’s // constructor. That’s because String is serializable and // JSONObject is not. To convert a JSONObject back to a String, simply // call the JSONObject’s toString method. String j = null; try { j = (String) o.readObject(); } catch (ClassNotFoundException c) { c.printStackTrace(); } try { jo = new JSONObject(j); ja = jo.getJSONArray("data"); } catch (JSONException e) { e.printStackTrace(); } if(ja.length() == 0){ userList.setEnabled(false); userList.setVisibility(View.INVISIBLE); } final ArrayList<String> aList = new ArrayList<String>(); for(int i = 0; i < ja.length(); i++){ String temp = ""; try{ temp = ja.getJSONObject(i).getString("name"); } catch (JSONException e) { e.printStackTrace(); } aList.add(temp); } listItems = new String[aList.size()]; for(int i = 0; i < aList.size(); i++){ String listD = aList.get(i); listItems[i] = listD; } ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems); userList.setAdapter(adapter); }catch(IOException e){ // There's no JSON file that exists, so don't // show the list. But also don't worry about creating // the file just yet, that takes place in AddText. //Here, disable the list view userList.setEnabled(false); userList.setVisibility(View.INVISIBLE); } } private void showEnterLabelDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this); builder.setTitle("Please enter your name:"); final EditText input = new EditText(AdminActivity.this); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setPositiveButton("Submit", null); // Set up positive button, but do not provide a listener, so we can check the string before dismissing the dialog builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setCancelable(false); // User has to input a name AlertDialog dialog = builder.create(); // Source: http://stackoverflow.com/a/7636468/2175837 dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button mButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String string = input.getText().toString().trim(); if (!string.isEmpty()) { // Make sure the input is valid // If input is valid, dismiss the dialog and add the label to the array /*counter = 0; for(int i = 0; i < listItems.length; i++){ if(listItems[i].equals(string)){ counter = i; break; } }*/ try { myKairos.deleteSubject(string, "Company", listener); //Toast.makeText(getBaseContext(),"User deleted",Toast.LENGTH_LONG).show(); }catch(JSONException e1){ e1.printStackTrace(); }catch(UnsupportedEncodingException e2){ e2.printStackTrace(); } dialog.dismiss(); //addLabel(string); } } }); } }); // Show keyboard, so the user can start typing straight away dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); } }
true
6663ea1f5ff05b7b238c38a9c4e28c25510c79e1
Java
younggeun0/SSangYoung
/dev/workspace/spring_di/src/date0423/RunAnnotation.java
UHC
510
2.125
2
[]
no_license
package date0423; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class RunAnnotation { public static void main(String[] args) { // Spring Container ApplicationContext ac = new ClassPathXmlApplicationContext("date0423/applicationContext2.xml"); TestService3 ts3 = ac.getBean(TestService3.class); System.out.println(ts3); System.out.println(ts3.getTestDAO3()); // autowired } }
true
49f4f14eb6cec2cf44dd3dd56d7e056fc0a7af80
Java
jinss06/MobileShops
/app/src/main/java/mobileshop/edu/huatec/com/mobileshop2/http/presenter/CategoryPresenter.java
UTF-8
952
2.015625
2
[]
no_license
package mobileshop.edu.huatec.com.mobileshop2.http.presenter; import java.util.List; import mobileshop.edu.huatec.com.mobileshop2.http.HttpMethods; import mobileshop.edu.huatec.com.mobileshop2.http.entity.CategoryEntity; import rx.Observable; import rx.Subscriber; public class CategoryPresenter extends HttpMethods { //一级分类 public static void getTopList(Subscriber<List<CategoryEntity>> subscriber) { Observable<List<CategoryEntity>> observable = categoryService.getTopList() .map(new HttpResultFunc<List<CategoryEntity>>()); toSubscribe(observable, subscriber); } //二级分类 public static void getSecondList(Subscriber<List<CategoryEntity>> subscriber, int parentId) { Observable<List<CategoryEntity>> observable = categoryService.getSecondList(parentId) .map(new HttpResultFunc<List<CategoryEntity>>()); toSubscribe(observable, subscriber); } }
true
ac8d8e5d4242ebc00d44dbc1aa982f520a19c5a7
Java
jiangrf/WeixinMultiPlatform
/src/main/java/org/hamster/weixinmp/dao/entity/auth/WxAuth.java
UTF-8
3,634
2.1875
2
[ "Apache-2.0" ]
permissive
/** * */ package org.hamster.weixinmp.dao.entity.auth; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hamster.weixinmp.dao.entity.base.WxBaseEntity; import com.google.gson.annotations.SerializedName; /** * * * @author honey.zhao@aliyun.com * @version Aug 3, 2013 * */ @Entity @Table(name = "wx_auth") public class WxAuth extends WxBaseEntity { @Column(name = "grant_type", length = 50, nullable = false) private String grantType; @Column(name = "appid", length = 100, nullable = false) private String appid; @Column(name = "secret", length = 100, nullable = false) private String secret; @SerializedName("access_token") @Column(name = "access_token", length = 200, nullable = false) private String accessToken; @SerializedName("expires_in") @Column(name = "expires_in", nullable = false) private Long expiresIn; public String getGrantType() { return grantType; } public void setGrantType(String grantType) { this.grantType = grantType; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public Long getExpiresIn() { return expiresIn; } public void setExpiresIn(Long expiresIn) { this.expiresIn = expiresIn; } public WxAuth() { super(); // TODO Auto-generated constructor stub } public WxAuth(Long id, Date createdDate) { super(id, createdDate); // TODO Auto-generated constructor stub } public WxAuth(String grantType, String appid, String secret, String accessToken, Long expiresIn) { super(); this.grantType = grantType; this.appid = appid; this.secret = secret; this.accessToken = accessToken; this.expiresIn = expiresIn; } @Override public String toString() { return "WxAuth [grantType=" + grantType + ", appid=" + appid + ", secret=" + secret + ", accessToken=" + accessToken + ", expiresIn=" + expiresIn + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((accessToken == null) ? 0 : accessToken.hashCode()); result = prime * result + ((appid == null) ? 0 : appid.hashCode()); result = prime * result + ((expiresIn == null) ? 0 : expiresIn.hashCode()); result = prime * result + ((grantType == null) ? 0 : grantType.hashCode()); result = prime * result + ((secret == null) ? 0 : secret.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; WxAuth other = (WxAuth) obj; if (accessToken == null) { if (other.accessToken != null) return false; } else if (!accessToken.equals(other.accessToken)) return false; if (appid == null) { if (other.appid != null) return false; } else if (!appid.equals(other.appid)) return false; if (expiresIn == null) { if (other.expiresIn != null) return false; } else if (!expiresIn.equals(other.expiresIn)) return false; if (grantType == null) { if (other.grantType != null) return false; } else if (!grantType.equals(other.grantType)) return false; if (secret == null) { if (other.secret != null) return false; } else if (!secret.equals(other.secret)) return false; return true; } }
true
64258f295486243d9beb8825ce77ce5a6bbe835c
Java
pandakill/weclubs-server
/src/main/java/com/weclubs/api/WCIMAPI.java
UTF-8
3,771
2.09375
2
[]
no_license
package com.weclubs.api; import com.weclubs.application.rongcloud.WCIRongCloudService; import com.weclubs.application.security.WCISecurityService; import com.weclubs.model.request.WCRequestModel; import com.weclubs.model.response.WCResultData; import com.weclubs.util.WCCommonUtil; import com.weclubs.util.WCHttpStatus; import com.weclubs.util.WCRequestParamsUtil; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; /** * IM 相关的 API 接口 * * Created by fangzanpan on 2017/6/22. */ @RestController @RequestMapping(value = "/im") class WCIMAPI { private static Logger log = Logger.getLogger(WCIMAPI.class); @Autowired private WCISecurityService mSecurityService; @Autowired private WCIRongCloudService mRongCloudService; @RequestMapping(value = "/get_token", method = RequestMethod.POST) public WCResultData getClubActivities(@RequestBody WCRequestModel requestModel) { WCHttpStatus check = mSecurityService.checkRequestParams(requestModel); if (check != WCHttpStatus.SUCCESS) { return WCResultData.getHttpStatusData(check, null); } check = mSecurityService.checkTokenAvailable(requestModel); if (check != WCHttpStatus.SUCCESS) { return WCResultData.getHttpStatusData(check, null); } HashMap requestData = WCRequestParamsUtil.getRequestParams(requestModel, HashMap.class); if (requestData == null || requestData.size() == 0) { check = WCHttpStatus.FAIL_REQUEST_NULL_PARAMS; return WCResultData.getHttpStatusData(check, null); } String token = mRongCloudService.getUserToken(WCCommonUtil.getLongData(requestData.get("user_id"))); if (StringUtils.isEmpty(token)) { check = WCHttpStatus.FAIL_REQUEST; check.msg = "获取token失败,请检查后重试"; return WCResultData.getHttpStatusData(check, null); } HashMap<String, Object> result = new HashMap<String, Object>(); result.put("im_token", token); return WCResultData.getSuccessData(result); } @RequestMapping(value = "/get_group_chat_list", method = RequestMethod.POST) public WCResultData getGroupChatList(@RequestBody WCRequestModel requestModel) { WCHttpStatus check = mSecurityService.checkRequestParams(requestModel); if (check != WCHttpStatus.SUCCESS) { return WCResultData.getHttpStatusData(check, null); } check = mSecurityService.checkTokenAvailable(requestModel); if (check != WCHttpStatus.SUCCESS) { return WCResultData.getHttpStatusData(check, null); } HashMap requestData = WCRequestParamsUtil.getRequestParams(requestModel, HashMap.class); if (requestData == null || requestData.size() == 0) { check = WCHttpStatus.FAIL_REQUEST_NULL_PARAMS; return WCResultData.getHttpStatusData(check, null); } long userId = WCCommonUtil.getLongData(requestData.get("user_id")); List<HashMap<String, Object>> groupChatList = mRongCloudService.getMyClubChatListForMap(userId); HashMap<String, Object> result = new HashMap<String, Object>(); result.put("group_chat_list", (groupChatList == null || groupChatList.size() == 0) ? null : groupChatList); return WCResultData.getSuccessData(result); } }
true
7e6f095b60045dc5dbdd879782bd1342ea3d88e1
Java
skyjacker/Meganekko
/sample-component/src/main/java/org/meganekkovr/sample_component/RotatorControllerComponent.java
UTF-8
625
2.4375
2
[ "Apache-2.0" ]
permissive
package org.meganekkovr.sample_component; import android.support.annotation.NonNull; import org.meganekkovr.Component; import org.meganekkovr.FrameInput; import org.meganekkovr.JoyButton; public class RotatorControllerComponent extends Component { @Override public void update(@NonNull FrameInput frame) { // Detect single tap event if (JoyButton.contains(frame.getButtonPressed(), JoyButton.BUTTON_TOUCH_SINGLE)) { // Get component RotatorComponent c1 = getComponent(RotatorComponent.class); c1.togglePause(); } super.update(frame); } }
true
beabaacdfe7af16720e69a84c9ec3320f30dc3a0
Java
flowable/flowable-engine
/modules/flowable-cmmn-api/src/main/java/org/flowable/cmmn/api/CmmnManagementService.java
UTF-8
14,680
1.828125
2
[ "Apache-2.0" ]
permissive
/* 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.flowable.cmmn.api; import java.util.Collection; import java.util.Map; import org.flowable.batch.api.Batch; import org.flowable.batch.api.BatchBuilder; import org.flowable.batch.api.BatchPartBuilder; import org.flowable.batch.api.BatchPartQuery; import org.flowable.batch.api.BatchQuery; import org.flowable.cmmn.api.runtime.CmmnExternalWorkerTransitionBuilder; import org.flowable.common.engine.api.FlowableObjectNotFoundException; import org.flowable.common.engine.api.tenant.ChangeTenantIdBuilder; import org.flowable.job.api.DeadLetterJobQuery; import org.flowable.job.api.ExternalWorkerJobAcquireBuilder; import org.flowable.job.api.ExternalWorkerJobFailureBuilder; import org.flowable.job.api.ExternalWorkerJobQuery; import org.flowable.job.api.HistoryJob; import org.flowable.job.api.HistoryJobQuery; import org.flowable.job.api.Job; import org.flowable.job.api.JobQuery; import org.flowable.job.api.SuspendedJobQuery; import org.flowable.job.api.TimerJobQuery; /** * @author Joram Barrez */ public interface CmmnManagementService { /** * Returns a map containing {tableName, rowCount} values. */ Map<String, Long> getTableCounts(); /** * Returns all relational database tables of the engine. */ Collection<String> getTableNames(); /** * Returns a new JobQuery implementation, that can be used to query the jobs. */ JobQuery createJobQuery(); /** * Returns a new ExternalWorkerJobQuery implementation, that can be used to dynamically query the external worker jobs. */ ExternalWorkerJobQuery createExternalWorkerJobQuery(); /** * Returns a new TimerJobQuery implementation, that can be used to query the timer jobs. */ TimerJobQuery createTimerJobQuery(); /** * Returns a new SuspendedJobQuery implementation, that can be used to query the suspended jobs. */ SuspendedJobQuery createSuspendedJobQuery(); /** * Returns a new DeadLetterJobQuery implementation, that can be used to query the dead letter jobs. */ DeadLetterJobQuery createDeadLetterJobQuery(); /** * Forced synchronous execution of a job (eg. for administration or testing). * The job will be executed, even if the case instance is suspended. * * @param jobId * id of the job to execute, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ void executeJob(String jobId); /** * Moves a timer job to the executable job table (eg. for administration or testing). * The timer job will be moved, even if the case instance is suspended. * * @param jobId * id of the timer job to move, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ Job moveTimerToExecutableJob(String jobId); /** * Moves a job to the dead letter job table (eg. for administration or testing). * The job will be moved, even if the case instance is suspended or there are retries left. * * @param jobId * id of the job to move, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ Job moveJobToDeadLetterJob(String jobId); /** * Moves a bulk of jobs that are in the dead letter job table back to the executable job table, * and resets the retries (as the retries was 0 when it was put into the dead letter job table). * * @param jobIds ids of the jobs to move, cannot be null. * @param retries the number of retries (value greater than 0) which will be set on the jobs. * @throws FlowableObjectNotFoundException when there is no job with any of the given ids. */ void bulkMoveDeadLetterJobs(Collection<String> jobIds, int retries); /** * Moves a bulk of jobs that are in the dead letter job table back to be history jobs, * and resets the retries (as the retries was 0 when it was put into the dead letter job table). * * @param jobIds ids of the jobs to move, cannot be null. * @param retries the number of retries (value greater than 0) which will be set on the jobs. * @throws FlowableObjectNotFoundException when one job with of the given ids is not found. */ void bulkMoveDeadLetterJobsToHistoryJobs(Collection<String> jobIds, int retries); /** * Moves a job that is in the dead letter job table back to be an executable job, * and resetting the retries (as the retries were probably 0 when it was put into the dead letter job table). * * @param jobId * id of the job to move, cannot be null. * @param retries * the number of retries (value greater than 0) which will be set on the job. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ Job moveDeadLetterJobToExecutableJob(String jobId, int retries); /** * Moves a job that is in the dead letter job table back to be a history job, * and resetting the retries (as the retries was 0 when it was put into the dead letter job table). * * @param jobId * id of the job to move, cannot be null. * @param retries * the number of retries (value greater than 0) which will be set on the job. * @throws FlowableObjectNotFoundException * when there is no job with the given id. * @throws org.flowable.common.engine.api.FlowableIllegalArgumentException * when the job cannot be moved to be a history job (e.g. because it's not history job) */ HistoryJob moveDeadLetterJobToHistoryJob(String jobId, int retries); /** * Moves a suspended job from the suspended letter job table back to be an executable job. The retries are untouched. * * @param jobId * id of the job to move, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ Job moveSuspendedJobToExecutableJob(String jobId); /** * Delete the job with the provided id. * * @param jobId * id of the job to delete, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ void deleteJob(String jobId); /** * Delete the timer job with the provided id. * * @param jobId * id of the timer job to delete, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ void deleteTimerJob(String jobId); /** * Delete the suspended job with the provided id. * * @param jobId * id of the suspended job to delete, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ void deleteSuspendedJob(String jobId); /** * Delete the dead letter job with the provided id. * * @param jobId * id of the dead letter job to delete, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ void deleteDeadLetterJob(String jobId); /** * Sets the number of retries that a job has left. * * Whenever the JobExecutor fails to execute a job, this value is decremented. * When it hits zero, the job is supposed to be dead and not retried again. * In that case, this method can be used to increase the number of retries. * * @param jobId * id of the job to modify, cannot be null. * @param retries * number of retries. */ void setJobRetries(String jobId, int retries); /** * Sets the number of retries that a timer job has left. * * Whenever the JobExecutor fails to execute a timer job, this value is decremented. * When it hits zero, the job is supposed to be dead and not retried again. * In that case, this method can be used to increase the number of retries. * * @param jobId * id of the timer job to modify, cannot be null. * @param retries * number of retries. */ void setTimerJobRetries(String jobId, int retries); /** * Returns the full stacktrace of the exception that occurs when the job with the given id was last executed. * Returns null when the job has no exception stacktrace. * * @param jobId * id of the job, cannot be null. * @throws FlowableObjectNotFoundException * when no job exists with the given id. */ String getJobExceptionStacktrace(String jobId); /** * Returns the full stacktrace of the exception that occurs when the timer job with the given id was last executed. * Returns null when the job has no exception stacktrace. * * @param jobId * id of the job, cannot be null. * @throws FlowableObjectNotFoundException * when no job exists with the given id. */ String getTimerJobExceptionStacktrace(String jobId); /** * Returns the full stacktrace of the exception that occurs when the suspended with the given id was last executed. * Returns null when the job has no exception stacktrace. * * @param jobId * id of the job, cannot be null. * @throws FlowableObjectNotFoundException * when no job exists with the given id. */ String getSuspendedJobExceptionStacktrace(String jobId); /** * Returns the full stacktrace of the exception that occurs when the deadletter job with the given id was last executed. * Returns null when the job has no exception stacktrace. * * @param jobId * id of the job, cannot be null. * @throws FlowableObjectNotFoundException * when no job exists with the given id. */ String getDeadLetterJobExceptionStacktrace(String jobId); /** * Returns the full error details that were passed to the External worker {@link Job} when the job was last failed. * Returns null when the job has no error details. * * @param jobId id of the job, cannot be null. * @throws FlowableObjectNotFoundException when no job exists with the given id. */ String getExternalWorkerJobErrorDetails(String jobId); void handleHistoryCleanupTimerJob(); /** * Returns a new BatchQuery implementation, that can be used to dynamically query the batches. */ BatchQuery createBatchQuery(); BatchBuilder createBatchBuilder(); /** * Returns a new BatchPartQuery implementation, that can be used to dynamically query the batch parts. */ BatchPartQuery createBatchPartQuery(); BatchPartBuilder createBatchPartBuilder(Batch batch); void deleteBatch(String batchId); /** * Returns a new HistoryJobQuery implementation, that can be used to dynamically query the history jobs. */ HistoryJobQuery createHistoryJobQuery(); /** * Forced synchronous execution of a historyJob (eg. for administration or testing). * * @param historyJobId * id of the historyjob to execute, cannot be null. * @throws FlowableObjectNotFoundException * when there is no historyJob with the given id. */ void executeHistoryJob(String historyJobId); /** * Get the advanced configuration (storing the history json data) of a {@link HistoryJob}. * * @param historyJobId * id of the history job to execute, cannot be null. * @throws FlowableObjectNotFoundException * when there is no historyJob with the given id. * */ String getHistoryJobHistoryJson(String historyJobId); /** * Delete the history job with the provided id. * * @param jobId * id of the history job to delete, cannot be null. * @throws FlowableObjectNotFoundException * when there is no job with the given id. */ void deleteHistoryJob(String jobId); // External Worker /** * Create an {@link ExternalWorkerJobAcquireBuilder} that can be used to acquire jobs for an external worker. */ ExternalWorkerJobAcquireBuilder createExternalWorkerJobAcquireBuilder(); /** * Create an {@link ExternalWorkerJobFailureBuilder} that can be used to fail an external worker job. * * @param externalJobId the id of the external worker job * @param workerId the id of the worker doing the action */ ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String externalJobId, String workerId); /** * Create a {@link CmmnExternalWorkerTransitionBuilder} that can be used to transition the status of the external worker job. */ CmmnExternalWorkerTransitionBuilder createCmmnExternalWorkerTransitionBuilder(String externalJobId, String workerId); /** * Unaquire a locked external worker job. */ void unacquireExternalWorkerJob(String jobId, String workerId); /** * Unaquire all locked external worker jobs for worker. */ void unacquireAllExternalWorkerJobsForWorker(String workerId); /** * Create a {@link ChangeTenantIdBuilder} that can be used to change the tenant id of the case instances * and all the related instances. See {@link CmmnChangeTenantIdEntityTypes} for related instances. * <p> * You must provide the source tenant id and the destination tenant id. All instances from the source tenant id in the CMMN scope * will be changed to the target tenant id. */ ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId); }
true
c4d92215fa3e46a7532663f004b4747d22384c50
Java
Bedework/bw-event-registration
/bw-event-registration-common/src/main/java/org/bedework/eventreg/common/BwConnector.java
UTF-8
7,663
1.757813
2
[]
no_license
/* ******************************************************************** Licensed to Jasig under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Jasig licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.bedework.eventreg.common; import org.bedework.eventreg.db.Event; import org.bedework.util.calendar.XcalUtil.TzGetter; import org.bedework.util.logging.BwLogger; import org.bedework.util.logging.Logged; import ietf.params.xml.ns.icalendar_2.ArrayOfComponents; import ietf.params.xml.ns.icalendar_2.BaseComponentType; import org.oasis_open.docs.ws_calendar.ns.soap.CalWsService; import org.oasis_open.docs.ws_calendar.ns.soap.CalWsServicePortType; import org.oasis_open.docs.ws_calendar.ns.soap.FetchItemResponseType; import org.oasis_open.docs.ws_calendar.ns.soap.FetchItemType; import org.oasis_open.docs.ws_calendar.ns.soap.ObjectFactory; import org.w3c.dom.Document; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPMessage; /** Implements the client end of a SOAP connection for a single eventreg session. * */ public class BwConnector implements Logged { private final TzGetter tzs; private final static ietf.params.xml.ns.icalendar_2.ObjectFactory icalOf = new ietf.params.xml.ns.icalendar_2.ObjectFactory(); private final String wsdlUri; private final Map<String, Event> events = new HashMap<>(); protected ObjectFactory of = new ObjectFactory(); protected MessageFactory soapMsgFactory; protected JAXBContext jc; /** * @param wsdlUri for SOAP * @param tzs getter for timezones */ public BwConnector(final String wsdlUri, final TzGetter tzs) { this.wsdlUri = wsdlUri; this.tzs = tzs; } /** Flush any trace of events. * */ public void flush() { events.clear(); } /** * @param href of event * @return cached event or event retrieved from service */ public Event getEvent(final String href) { Event ev = events.get(href); if (ev != null) { return ev; } /* XXX If the href is terminated with an anchor - e.g. #2012... * we're referring to an instance rather than the entire event. We have to * pull the whole event so we should cache that. We need to create a cached * instance as well. * * That calls for 2 caches. The returned icalendar and the converted event info. */ // Pull from server. final FetchItemResponseType fir = fetchItem(href); if ((fir == null) || (fir.getIcalendar() == null) || (fir.getIcalendar().getVcalendar().size() != 1) || (fir.getIcalendar().getVcalendar().get(0).getComponents() == null)) { return null; } final ArrayOfComponents aoc = fir.getIcalendar().getVcalendar().get(0).getComponents(); final List<BaseComponentType> comps = new ArrayList<>(); for (final JAXBElement<? extends BaseComponentType> comp: aoc.getBaseComponent()) { comps.add(comp.getValue()); } if (comps.size() != 1) { // XXX Fix this stuff return null; } ev = new Event(comps.get(0), href, tzs); events.put(href, ev); return ev; } /** * @param href of item to fetch * @return FetchItemResponseType */ public FetchItemResponseType fetchItem(final String href) { //ObjectFactory of = getIcalObjectFactory(); final FetchItemType fi = new FetchItemType(); fi.setHref(href); return getPort().fetchItem(fi); } protected ietf.params.xml.ns.icalendar_2.ObjectFactory getIcalObjectFactory() { return icalOf; } protected CalWsServicePortType getPort() { return getPort(wsdlUri); } protected CalWsServicePortType getPort(final String uri) { final URL wsURL; try { wsURL = new URL(uri); } catch (final MalformedURLException e) { throw new RuntimeException(e); } final CalWsService svc = new CalWsService(wsURL, new QName("http://docs.oasis-open.org/ws-calendar/ns/soap", "CalWsService")); final CalWsServicePortType port = svc.getCalWsPort(); // Map requestContext = ((BindingProvider)port).getRequestContext(); // requestContext.put(BindingProvider.USERNAME_PROPERTY, userName); // requestContext.put(BindingProvider.PASSWORD_PROPERTY, password); return port; } @SuppressWarnings("rawtypes") protected Object unmarshalBody(final HttpServletRequest req) throws Throwable { final SOAPMessage msg = getSoapMsgFactory() .createMessage(null,// headers req.getInputStream()); final SOAPBody body = msg.getSOAPBody(); final Unmarshaller u = getSynchJAXBContext().createUnmarshaller(); Object o = u.unmarshal(body.getFirstChild()); if (o instanceof JAXBElement) { // Some of them get wrapped. o = ((JAXBElement)o).getValue(); } return o; } protected void marshal(final Object o, final OutputStream out) throws Throwable { final Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final Document doc = dbf.newDocumentBuilder().newDocument(); final SOAPMessage msg = soapMsgFactory.createMessage(); msg.getSOAPBody().addDocument(doc); marshaller.marshal(o, msg.getSOAPBody()); msg.writeTo(out); } protected MessageFactory getSoapMsgFactory() throws Throwable { if (soapMsgFactory == null) { soapMsgFactory = MessageFactory.newInstance(); } return soapMsgFactory; } /* ==================================================================== * Package methods * ==================================================================== */ JAXBContext getSynchJAXBContext() throws Throwable { if (jc == null) { jc = JAXBContext.newInstance("org.bedework.synch.wsmessages:" + "ietf.params.xml.ns.icalendar_2"); } return jc; } /* ==================================================================== * Logged methods * ==================================================================== */ private final BwLogger logger = new BwLogger(); @Override public BwLogger getLogger() { if ((logger.getLoggedClass() == null) && (logger.getLoggedName() == null)) { logger.setLoggedClass(getClass()); } return logger; } }
true
88d068946e3e87f594eb1606dfece19a193b9006
Java
diosvo/LTDD_TH109-C91A_VoThiMyNhung
/app/src/main/java/com/dv/grocery/activities/DetailsActivity.java
UTF-8
4,101
2.390625
2
[]
no_license
package com.dv.grocery.activities; import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.bumptech.glide.Glide; import com.dv.grocery.R; import com.dv.grocery.models.ProductModel; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; public class DetailsActivity extends AppCompatActivity { ImageView detail_img; TextView name, desc, price, quantity; int totalQty = 1; int totalPrice = 0; Button plus, minus, add_to_cart; ProductModel productModel = null; FirebaseFirestore db; FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); db = FirebaseFirestore.getInstance(); auth = FirebaseAuth.getInstance(); final Object object = getIntent().getSerializableExtra("details"); if (object instanceof ProductModel) { productModel = (ProductModel) object; } init(); updateQty(); addToCart(); if (productModel != null) { Glide.with(getApplicationContext()).load(productModel.getImage()).into(detail_img); name.setText(productModel.getName()); desc.setText(productModel.getDescription()); price.setText(productModel.getPrice()); totalPrice = Integer.parseInt(productModel.getPrice()) * totalQty; } } private void init() { detail_img = findViewById(R.id.detail_img); name = findViewById(R.id.detail_name); desc = findViewById(R.id.detail_desc); price = findViewById(R.id.detail_price); quantity = findViewById(R.id.detail_qty); plus = findViewById(R.id.detail_plus); minus = findViewById(R.id.detail_minus); add_to_cart = findViewById(R.id.detail_add_to_cart); } private void updateQty() { plus.setOnClickListener(view -> { if (totalQty < 10) { totalQty++; quantity.setText(String.valueOf(totalQty)); totalPrice = Integer.parseInt(productModel.getPrice()) * totalQty; } }); minus.setOnClickListener(view -> { if (totalQty > 1) { totalQty--; quantity.setText(String.valueOf(totalQty)); totalPrice = Integer.parseInt(productModel.getPrice()) * totalQty; } }); } private void addToCart() { add_to_cart.setOnClickListener(view -> { String saveCurrentDate, saveCurrentTime; Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy"); saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss"); saveCurrentTime = currentTime.format(calendar.getTime()); final HashMap<String, Object> cartMap = new HashMap<>(); cartMap.put("productName", productModel.getName()); cartMap.put("productPrice", productModel.getPrice()); cartMap.put("currentDate", saveCurrentDate); cartMap.put("currentTime", saveCurrentTime); cartMap.put("totalQuantity", quantity.getText().toString()); cartMap.put("totalPrice", totalPrice); cartMap.put("productImage", productModel.getImage()); db.collection("CurrentUser") .document(auth.getCurrentUser().getUid()) .collection("AddToCart") .add(cartMap) .addOnCompleteListener(task -> { Toast.makeText(DetailsActivity.this, "Đã thêm vào giỏ hàng", Toast.LENGTH_SHORT).show(); }); }); } }
true
e7eb6f43d90244588fc1f70da7c7c06a4278323f
Java
ObvilionNetwork/launcher-v1
/src/main/java/ru/obvilion/launcher/utils/FileUtil.java
UTF-8
4,677
2.734375
3
[]
no_license
package ru.obvilion.launcher.utils; import javafx.application.Platform; import ru.obvilion.launcher.config.Vars; import java.io.*; import java.net.URL; import java.nio.file.*; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class FileUtil { public static void downloadFromURL(String url, Path target) { try { URL website = new URL(url); try (InputStream in = website.openStream()) { System.out.println("Downloading file: " + url); Platform.runLater(() -> { Vars.loadingController.now.setText(Lang.get("loading") + Lang.get("downloading").replace("{0}", url)); }); Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { e.printStackTrace(); } } public static void downloadFromURL2(String url, Path target) { try { URL website = new URL(url); try (InputStream in = website.openStream()) { System.out.println("Downloading file: " + url); Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { e.printStackTrace(); } } public static long folderSize(File directory) { long length = 0; for (File file : directory.listFiles()) { if (file.isFile()) length += file.length(); else length += folderSize(file); } return length; } public static void downloadAndUnpackFromURL(String url, Path target) { try { URL website = new URL(url); try (InputStream in = website.openStream()) { System.out.println("Downloading file: " + url); Platform.runLater(() -> { Vars.loadingController.now.setText(Lang.get("loading") + Lang.get("downloading").replace("{0}", url)); }); Files.copy(in, new File(target.toFile(), "temp.zip").toPath(), StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Unzip file: " + url); Platform.runLater(() -> { Vars.loadingController.now.setText(Lang.get("loading") + Lang.get("unzip").replace("{0}", url)); }); unzip(new File(target.toFile(), "temp.zip"), target.toFile()); } } public static void unzip(File zip, File dest) { ZipFile zipFile = null; try { zipFile = new ZipFile(zip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationPath = new File(dest, entry.getName()); destinationPath.getParentFile().mkdirs(); if (!entry.isDirectory()) { System.out.println("Extracting file: " + destinationPath); Platform.runLater(() -> { Vars.loadingController.now.setText(Lang.get("loading") + Lang.get("unzipFile").replace("{0}", destinationPath.getAbsolutePath())); }); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; byte buffer[] = new byte[8192]; FileOutputStream fos = new FileOutputStream(destinationPath); BufferedOutputStream bos = new BufferedOutputStream(fos, 8192); while ((b = bis.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, b); } bos.close(); bis.close(); } } } catch (IOException ioe) { System.out.println("Error opening zip file" + ioe); } finally { try { if (zipFile != null) { zipFile.close(); } } catch (IOException ioe) { System.out.println("Error while closing zip file" + ioe); } } } public static void deleteDirectory(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { File f = new File(dir, children[i]); deleteDirectory(f); } dir.delete(); } else dir.delete(); } }
true
6d1052515688c1ec6cb4a5fa6c289cd7e2633039
Java
Xun6/learning_notes
/java_study/src/MySuperMarketForStudy/interfaces/Merchandise.java
UTF-8
445
2.421875
2
[]
no_license
package MySuperMarketForStudy.interfaces; /** * 商品接口 */ public interface Merchandise { String getName(); //获取商品名称 double getSoldPrice(); //获取商品的销售价格 double getPurchasePrice(); //获取商品的进货价格 int buy(int count); //购买商品 void putBack(int count); //放回商品 int getCount(); //获取商品库存 Category getGategory(); //获取商品的类别 }
true
b6f3d965cbe83a99092c200dc0b1f30909a7294c
Java
ilywka/movie-analytics
/src/main/java/by/sashnikov/jfuture/imdb/ParseUtil.java
UTF-8
1,786
2.59375
3
[]
no_license
package by.sashnikov.jfuture.imdb; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; /** * @author Ilya_Sashnikau */ public class ParseUtil { public static final String IMDB_URL = "https://www.imdb.com"; private static final String DIRECTOR_URL_BASE = "https://www.imdb.com/name/"; public static Document getDocumentQuietly(String url) { int i = 0; while (true) { try { return Jsoup.connect(url) .get(); } catch (IOException e) { i++; if (i == 5) { throw new RuntimeException(e); } } } } public static String extractPath(String hrefDirtyValue) { int redundantParamsStart = hrefDirtyValue.lastIndexOf('?'); if (redundantParamsStart == -1) { return hrefDirtyValue; } else { return hrefDirtyValue.substring(0, redundantParamsStart); } } public static URIBuilder createRequestUrl(String baseUrl, NameValuePair[] parameters) throws URISyntaxException { URIBuilder uriBuilder = new URIBuilder(baseUrl); uriBuilder.addParameters(Arrays.asList(parameters)); return uriBuilder; } public static String directorPageUrl(String directorId) { return DIRECTOR_URL_BASE.concat(directorId); } public static Integer getFirstGroupNumericValue(Pattern pattern, String value) { Matcher singlePagePatternMatcher = pattern.matcher(value); if (singlePagePatternMatcher.find()) { return Integer.valueOf(singlePagePatternMatcher.group(1).replace(",", "")); } return null; } }
true
bbe2c8754f6c02d6a2ba8f42702a6bf89f27cfbc
Java
mountrivers/OverlayMemo
/app/src/main/java/com/sanha/overlaymemo/Services/S1.java
UTF-8
1,532
2.015625
2
[]
no_license
package com.sanha.overlaymemo.Services; import android.content.ClipboardManager; import androidx.room.Room; import com.sanha.overlaymemo.DB.AppDatabase; import com.sanha.overlaymemo.DB.Memo; import com.sanha.overlaymemo.R; public class S1 extends MyService { public static S1 s1 ; // 정의 추가 private int serviceId = 1; @Override public void setBasic() { s1 = this; clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); } @Override protected void setDB() { db = Room.databaseBuilder(this, AppDatabase.class, "memo-db") .allowMainThreadQueries() .build(); while(db.todoDao().getC() <= 3) { db.todoDao().insert(new Memo("")); } memo = db.todoDao().getA(serviceId); spPref = getSharedPreferences("spPref", MODE_PRIVATE); spEditor = spPref.edit(); textSize = spPref.getInt("size"+ serviceId, 14); textWidth = spPref.getInt("width"+ serviceId, 150); backColor = spPref.getInt("color"+ serviceId, 0xFFFFFFFF); } @Override protected void alterSize() { changeSize(textSize); changeWidth(getPixel()); changeColor(backColor); } @Override protected void attachView(){ mView = inflate.inflate(R.layout.view_in_service, null); } @Override protected void setXY(){ params.x = -100; params.y = -20; wm.updateViewLayout(mView,params); } }
true
802eb898df793109e1e80ad546924fc4ea49fe9d
Java
facebook/fresco
/memory-types/ashmem/src/main/java/com/facebook/imagepipeline/memory/AshmemMemoryChunk.java
UTF-8
6,263
2.125
2
[ "MIT" ]
permissive
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.memory; import android.annotation.TargetApi; import android.os.SharedMemory; import android.system.ErrnoException; import android.util.Log; import androidx.annotation.VisibleForTesting; import com.facebook.common.internal.Preconditions; import com.facebook.infer.annotation.Nullsafe; import java.io.Closeable; import java.nio.ByteBuffer; import javax.annotation.Nullable; /** Wrapper around chunk of ashmem memory. */ @TargetApi(27) @Nullsafe(Nullsafe.Mode.LOCAL) public class AshmemMemoryChunk implements MemoryChunk, Closeable { private static final String TAG = "AshmemMemoryChunk"; private @Nullable SharedMemory mSharedMemory; private @Nullable ByteBuffer mByteBuffer; /** Unique identifier of the chunk */ private final long mId; public AshmemMemoryChunk(final int size) { Preconditions.checkArgument(size > 0); try { mSharedMemory = SharedMemory.create(TAG, size); mByteBuffer = mSharedMemory.mapReadWrite(); } catch (ErrnoException e) { throw new RuntimeException("Fail to create AshmemMemory", e); } mId = System.identityHashCode(this); } @VisibleForTesting public AshmemMemoryChunk() { mSharedMemory = null; mByteBuffer = null; mId = System.identityHashCode(this); } @Override public synchronized void close() { if (!isClosed()) { if (mSharedMemory != null) { mSharedMemory.close(); } if (mByteBuffer != null) { SharedMemory.unmap(mByteBuffer); } mByteBuffer = null; mSharedMemory = null; } } @Override public synchronized boolean isClosed() { return mByteBuffer == null || mSharedMemory == null; } @Override public int getSize() { Preconditions.checkNotNull(mSharedMemory); return mSharedMemory.getSize(); } @Override public synchronized int write( final int memoryOffset, final byte[] byteArray, final int byteArrayOffset, final int count) { Preconditions.checkNotNull(byteArray); Preconditions.checkNotNull(mByteBuffer); final int actualCount = MemoryChunkUtil.adjustByteCount(memoryOffset, count, getSize()); MemoryChunkUtil.checkBounds( memoryOffset, byteArray.length, byteArrayOffset, actualCount, getSize()); mByteBuffer.position(memoryOffset); mByteBuffer.put(byteArray, byteArrayOffset, actualCount); return actualCount; } @Override public synchronized int read( final int memoryOffset, final byte[] byteArray, final int byteArrayOffset, final int count) { Preconditions.checkNotNull(byteArray); Preconditions.checkNotNull(mByteBuffer); final int actualCount = MemoryChunkUtil.adjustByteCount(memoryOffset, count, getSize()); MemoryChunkUtil.checkBounds( memoryOffset, byteArray.length, byteArrayOffset, actualCount, getSize()); mByteBuffer.position(memoryOffset); mByteBuffer.get(byteArray, byteArrayOffset, actualCount); return actualCount; } @Override public synchronized byte read(final int offset) { Preconditions.checkState(!isClosed()); Preconditions.checkArgument(offset >= 0); Preconditions.checkArgument(offset < getSize()); Preconditions.checkNotNull(mByteBuffer); return mByteBuffer.get(offset); } @Override public long getNativePtr() { throw new UnsupportedOperationException("Cannot get the pointer of an AshmemMemoryChunk"); } @Override @Nullable public ByteBuffer getByteBuffer() { return mByteBuffer; } @Override public long getUniqueId() { return mId; } @Override public void copy( final int offset, final MemoryChunk other, final int otherOffset, final int count) { Preconditions.checkNotNull(other); // This implementation acquires locks on this and other objects and then delegates to // doCopy which does actual copy. In order to avoid deadlocks we have to establish some linear // order on all AshmemMemoryChunks and acquire locks according to this order. In order // to do that, we use unique ids. // So we have to address 3 cases: // Case 1: other buffer equals this buffer, id comparison if (other.getUniqueId() == getUniqueId()) { // we do not allow copying to the same address // lets log warning and not copy Log.w( TAG, "Copying from AshmemMemoryChunk " + Long.toHexString(getUniqueId()) + " to AshmemMemoryChunk " + Long.toHexString(other.getUniqueId()) + " which are the same "); Preconditions.checkArgument(false); } // Case 2: Other memory chunk id < this memory chunk id if (other.getUniqueId() < getUniqueId()) { synchronized (other) { synchronized (this) { doCopy(offset, other, otherOffset, count); } } return; } // Case 3: Other memory chunk id > this memory chunk id synchronized (this) { synchronized (other) { doCopy(offset, other, otherOffset, count); } } } /** * This does actual copy. It should be called only when we hold locks on both this and other * objects */ private void doCopy( final int offset, final MemoryChunk other, final int otherOffset, final int count) { if (!(other instanceof AshmemMemoryChunk)) { throw new IllegalArgumentException("Cannot copy two incompatible MemoryChunks"); } Preconditions.checkState(!isClosed()); Preconditions.checkState(!other.isClosed()); Preconditions.checkNotNull(mByteBuffer); Preconditions.checkNotNull(other.getByteBuffer()); MemoryChunkUtil.checkBounds(offset, other.getSize(), otherOffset, count, getSize()); mByteBuffer.position(offset); // ByteBuffer can't be null at this point other.getByteBuffer().position(otherOffset); // Recover the necessary part to be copied as a byte array. // This requires a copy, for now there is not a more efficient alternative. byte[] b = new byte[count]; mByteBuffer.get(b, 0, count); other.getByteBuffer().put(b, 0, count); } }
true
07f840d5f71065a0666ba575f54c1428d56de8c1
Java
mayankit/Algorithm1
/src/main/java/com/mayank/algorithm1/week1/QuickUnion.java
UTF-8
892
3.265625
3
[]
no_license
package com.mayank.algorithm1.week1; public class QuickUnion { private int[] id; public QuickUnion(int N){ id = new int[N]; for(int i=0;i < N; i++){ id[i] = i; } } public boolean isConnected(int p, int q){ return root(p) == root(q); } private int root(int p) { while(p != id[p]){ p = id[p]; } return p; } public void union(int p, int q){ int i = root(p); int j = root(q); id[i] = j; } public static void main(String[] args) { QuickUnion qu = new QuickUnion(10); qu.union(4,3); qu.union(3,8); qu.union(6,5); qu.union(9,4); qu.union(2,1); qu.union(5,0); qu.union(7,2); qu.union(6,1); qu.union(7,3); System.out.println(qu.isConnected(4,8)); } }
true
974337e2daeccd3fff917390d75d782bc886b0f2
Java
Janggol/pet
/Workspace/wsJava/PetLocal/src/main/java/com/pet/ctrl/CtrlBBS.java
UTF-8
2,503
1.679688
2
[]
no_license
package com.pet.ctrl; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import com.pet.dto.DtoBBS; import com.pet.dto.DtoEvl; @ Controller public class CtrlBBS{ Map<String, Object> map; public String sltDetail(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltList(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltSubject(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltWriter(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltNewest(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltEvl(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltClick(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltLocation(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltBsnTime(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String sltMyEntrprs(Model model, DtoBBS dto){ // TODO Auto-generated method stub return null; } public String insert(DtoBBS dto){ // TODO Auto-generated method stub return null; } public String insertReply(DtoBBS dto){ // TODO Auto-generated method stub return null; } public String insert(DtoEvl dto){ // TODO Auto-generated method stub return null; } public String update(DtoBBS dto){ // TODO Auto-generated method stub return null; } public String updateReply(DtoBBS dto){ // TODO Auto-generated method stub return null; } public String update(DtoEvl dto){ // TODO Auto-generated method stub return null; } public String delUpdate(DtoBBS dto){ // TODO Auto-generated method stub return null; } public String deleteReply(DtoBBS dto){ // TODO Auto-generated method stub return null; } public String delete(DtoEvl dto){ // TODO Auto-generated method stub return null; } public String onLike(DtoEvl dto){ // TODO Auto-generated method stub return null; } public String offLike(DtoEvl dto){ // TODO Auto-generated method stub return null; } }
true
460b1588be212aee5b55f0b24846f325ebb1dd8d
Java
benravago/TodoMVC.fx
/src/ToDo-jbmlc/todo/vc/jbml/App.java
UTF-8
406
2.234375
2
[]
no_license
package todo.vc.jbml; import fx.mvc.runtime.Runtime; public class App { public static void main(String... args) throws Throwable { var name = "todo.vc.jbml.app.MainController"; var rc = Runtime.getRuntime().launch(name); System.out.println("app " + name + " started"); var e = rc.get(); if (e != null) { throw e; } System.out.println("" + App.class + " done"); } }
true
dd69b9a8b0b8ef18d007ce887631447b162af76a
Java
AnushaPavanKumar/Worldapp
/app/src/main/java/com/pavanusha/worldapp/ViewPagerAdapter.java
UTF-8
1,871
2.453125
2
[]
no_license
package com.pavanusha.worldapp; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class ViewPagerAdapter extends PagerAdapter { // Declare Variables Context context; String[] category; int[] flag; LayoutInflater inflater; public ViewPagerAdapter(Context context, String[] category, int[] flag) { this.context = context; this.category = category; this.flag = flag; } @Override public int getCount() { return category.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((RelativeLayout) object); } @Override public Object instantiateItem(ViewGroup container, int position) { // Declare Variables TextView txt; ImageView imgflag; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.m_content, container, false); // Locate the TextViews in viewpager_item.xml txt = (TextView) itemView.findViewById(R.id.txt); // Capture position and set to the TextViews txt.setText(category[position]); // Locate the ImageView in viewpager_item.xml imgflag = (ImageView) itemView.findViewById(R.id.img); // Capture position and set to the ImageView imgflag.setImageResource(flag[position]); // Add viewpager_item.xml to ViewPager ((ViewPager) container).addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // Remove viewpager_item.xml from ViewPager ((ViewPager) container).removeView((RelativeLayout) object); } }
true
8ea5709e41470b2e09bcd4b21249d57c3bf6d378
Java
liuyong240/SortAlgorithm
/com/newtalent/www/hfmtree/HFMEncode.java
GB18030
2,733
3.046875
3
[]
no_license
package com.newtalent.www.hfmtree; import java.util.Comparator; import java.util.PriorityQueue; import java.util.concurrent.CancellationException; import javax.xml.soap.Node; import com.newtalent.www.bstree.Tree; public class HFMEncode { public static void main(String[] args) { String text = "Welcome"; int[] counts = getCharsFrequence(text); System.out.printf("%-15s%-15s%-15s%-15s\n","ASCII Code","Character","Frequence","HFMCode"); HFMTree hfmTree = createHfmTree(counts); String[] codes = getCode(hfmTree.root); for (int i = 0; i < codes.length; i++) { if (counts[i] != 0) { System.out.printf("%-15s%-15s%-15s%-15s\n",i,(char)i + "",counts[i],codes[i] ); } } } /** * ȡַպշ * @param root * @return */ public static String[] getCode(HFMTree.HFMNode root) { if (root == null) { return null; } String[] codes = new String[2 * 128]; encode(root, codes); return codes; } /** * * ʼ룬ݹʸڵ * ʵҶӽڵʱı븳code[] * * @param root * @param codes */ public static void encode(HFMTree.HFMNode root , String[] codes) { if (root.left != null) { root.left.hfmcode = root.hfmcode + "0"; encode(root.left, codes); root.right.hfmcode = root.hfmcode + "1"; encode(root.right, codes); } else { codes[(int) root.element] = root.hfmcode; } } /** * ͳıַijִ * @param text * @return */ public static int[] getCharsFrequence(String text) { //256ASCIIļ int[] charCount = new int[256]; for (int i = 0; i < text.length(); i++) { charCount[(int)text.charAt(i)]++; } return charCount; } /** * յһźշͨȶУάշɭ֣ * @param counts ַƵ * @return */ public static HFMTree createHfmTree(int[] counts) { //ȶĬǽ PriorityQueue<HFMTree> hfmTreesHeap = new PriorityQueue<>(); //ַƵ г˵ַ Ƶ շɭ ÿúշֻеڵ㣩 for (int i = 0; i < counts.length; i++) { if (counts[i] > 0) { hfmTreesHeap.offer(new HFMTree(counts[i], (char) i)); } } while (hfmTreesHeap.size() > 1) { //ȡɭȨС HFMTree tree1 = hfmTreesHeap.poll(); HFMTree tree2 = hfmTreesHeap.poll(); HFMTree conbinedTree = new HFMTree(tree1, tree2); hfmTreesHeap.add(conbinedTree); } //ȡ󽨳ɵһúշ return hfmTreesHeap.poll(); } }
true
352de7c410013fcdd83bec1029dbac64f0879aad
Java
johnworth/ui
/de-lib/src/test/java/org/iplantc/de/admin/desktop/client/workshopAdmin/view/WorkshopAdminViewImplTest.java
UTF-8
2,077
1.882813
2
[]
no_license
package org.iplantc.de.admin.desktop.client.workshopAdmin.view; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.iplantc.de.admin.desktop.client.workshopAdmin.WorkshopAdminView; import org.iplantc.de.admin.desktop.client.workshopAdmin.model.MemberProperties; import org.iplantc.de.client.models.groups.Member; import org.iplantc.de.collaborators.client.util.UserSearchField; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwtmockito.GxtMockitoTestRunner; import com.google.gwtmockito.WithClassesToStub; import com.sencha.gxt.data.shared.ListStore; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import java.util.ArrayList; import java.util.Iterator; /** * @author aramseyds */ @RunWith(GxtMockitoTestRunner.class) @WithClassesToStub(UserSearchField.class) public class WorkshopAdminViewImplTest { @Mock WorkshopAdminView.WorkshopAdminViewAppearance appearanceMock; @Mock MemberProperties propertiesMock; @Mock ListStore<Member> listStoreMock; @Mock ArrayList<HandlerRegistration> globalRegistrationMock; @Mock Iterator<HandlerRegistration> registrationIteratorMock; @Mock HandlerRegistration handlerMock; private WorkshopAdminViewImpl uut; @Before public void setUp() { when(globalRegistrationMock.size()).thenReturn(2); when(globalRegistrationMock.iterator()).thenReturn(registrationIteratorMock); when(registrationIteratorMock.hasNext()).thenReturn(true, true, false); when(registrationIteratorMock.next()).thenReturn(handlerMock, handlerMock); uut = new WorkshopAdminViewImpl(appearanceMock, propertiesMock, listStoreMock); uut.globalHandlerRegistrations = globalRegistrationMock; } @Test public void testOnUnload() { /** CALL METHOD UNDER TEST **/ uut.onUnload(); verify(handlerMock, times(2)).removeHandler(); verify(globalRegistrationMock).clear(); } }
true
3ec168b0d6fd842c5c42c81c342a246e352148f8
Java
michael-simons/neo4j-migrations
/neo4j-migrations-core/src/test/java/ac/simons/neo4j/migrations/core/EnterpriseRequiredDetectionIT.java
UTF-8
3,697
1.679688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ac.simons.neo4j.migrations.core; import static org.assertj.core.api.Assertions.assertThat; import ac.simons.neo4j.migrations.core.catalog.Constraint; import ac.simons.neo4j.migrations.core.catalog.RenderConfig; import ac.simons.neo4j.migrations.core.catalog.Renderer; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Session; import org.neo4j.driver.exceptions.Neo4jException; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.junit.jupiter.Testcontainers; /** * Very specific tests for detecting capabilities and error conditions. */ @Testcontainers(disabledWithoutDocker = true) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SkipArm64IncompatibleConfiguration.class) class EnterpriseRequiredDetectionIT { @ParameterizedTest // GH-647 @ArgumentsSource(SkipArm64IncompatibleConfiguration.VersionProvider.class) void shouldFailAsGracefullyAsItGetsWhenEditionMismatch( SkipArm64IncompatibleConfiguration.VersionUnderTest version) { Neo4jContainer<?> neo4j = new Neo4jContainer<>(String.format("neo4j:%s", version.value.toString())) .withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes") .withReuse(true); neo4j.start(); Constraint[] exists = new Constraint[] { Constraint.forNode("Book") .named("x") .exists("isbn"), Constraint.forNode("Book") .named("y") .key("title"), Constraint.forRelationship("PUBLISHED") .named("z") .exists("on") }; Renderer<Constraint> renderer = Renderer.get(Renderer.Format.CYPHER, Constraint.class); // Force the renderer to enterprise RenderConfig cfg = RenderConfig.create().forVersionAndEdition(version.value, Neo4jEdition.ENTERPRISE).ignoreName(); try (Driver driver = GraphDatabase.driver(neo4j.getBoltUrl(), AuthTokens.basic("neo4j", neo4j.getAdminPassword()))) { MigrationsConfig configuration = MigrationsConfig.builder() .withLocationsToScan("classpath:ee") .withAutocrlf(true) .build(); Migrations migrations = new Migrations(configuration, driver); ConnectionDetails connectionDetails = migrations.getConnectionDetails(); for (Constraint constraint : exists) { String statement = renderer.render(constraint, cfg); try (Session session = driver.session()) { session.run(statement); Assertions.fail("An exception was expected"); } catch (Neo4jException e) { assertThat(HBD.constraintProbablyRequiredEnterpriseEdition(e, connectionDetails)).isTrue(); } } try (Session session = driver.session()) { session.run("CREATE CONSTRAINT"); Assertions.fail("An exception was expected"); } catch (Neo4jException e) { assertThat(HBD.constraintProbablyRequiredEnterpriseEdition(e, connectionDetails)).isFalse(); } } } }
true
e7c2be4be98ee088be7145ff1e1bfe4004ae4510
Java
ngmartinezs/GestionLog
/src/main/java/com/gestionLogsPortales/LogEvento/api/LogEventoApi.java
UTF-8
2,089
2.28125
2
[]
no_license
package com.gestionLogsPortales.LogEvento.api; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.gestionLogsPortales.LogEvento.dto.LogEvento; import com.gestionLogsPortales.LogEvento.dto.LogEventoRequest; import com.gestionLogsPortales.LogEvento.dto.RespuestaGestionLog; import com.gestionLogsPortales.LogEvento.service.LogEventoServices; @RestController public class LogEventoApi { @Autowired LogEventoServices lLogEventoServices; @Autowired DozerMapper lDozerMapper; @RequestMapping(value="/evento", method =RequestMethod.POST) public RespuestaGestionLog registrarEventoLog( @RequestBody @Valid LogEventoRequest pLogEventoRequest ) { LogEvento lLogEvento = null; RespuestaGestionLog lRespuestaGestionLog = new RespuestaGestionLog(); lRespuestaGestionLog.setCodigoError("0"); lRespuestaGestionLog.setMensajeError("OK"); System.out.println(" RespuestaGestionLog registrarEventoLog 1"); try { /** * Se realiza el registro sobre la tabla de LogEvento **/ lLogEvento = lLogEventoServices.registrarEvento(pLogEventoRequest); System.out.println(" RespuestaGestionLog registrarEventoLog 2"); if(lLogEvento != null /*&& lLogEvento.getlogEventoId() > 0*/) { lRespuestaGestionLog.setMensajeError("Registrado lLogEvento =>"+lLogEvento.toString()); } else { lRespuestaGestionLog.setCodigoError("998"); lRespuestaGestionLog.setMensajeError("No se logro registrar la informacion del log del evento."); } } catch(Exception pException) { lRespuestaGestionLog.setCodigoError("999"); lRespuestaGestionLog.setMensajeError("Error al registrar Evento => "+pException.getMessage()); } return lRespuestaGestionLog; } }
true
6bac7c8227f26663d4e1b0d7e1669d7581b02d64
Java
bincip/weatherservice
/src/test/java/com/web/weatherservice/service/impl/WeatherInfoServiceImplTest.java
UTF-8
1,729
2.046875
2
[]
no_license
package com.web.weatherservice.service.impl; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.atMostOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import com.web.weatherservice.client.OpenWeatherMapFeignClient; import com.web.weatherservice.dto.WeatherResponse; @ExtendWith(MockitoExtension.class) public class WeatherInfoServiceImplTest { @InjectMocks private WeatherInfoServiceImpl weatherInfoService; @Mock OpenWeatherMapFeignClient openWeatherMapClient; @BeforeEach public void setUp() { ReflectionTestUtils.setField(weatherInfoService, "applicationKey", "ffa6f13ea40a22452bba3be726315d3f"); } @Test public void weatherInfoByCityTest() { when(openWeatherMapClient.getWeatherByCity("London","ffa6f13ea40a22452bba3be726315d3f")).thenReturn(getWeatherResponse()); WeatherResponse response = weatherInfoService.weatherInfoByCity("London"); assertNotNull(response); } @Test public void weatherInfoByLocationTest() { when(openWeatherMapClient.getWeatherByLocation("35", "139", "ffa6f13ea40a22452bba3be726315d3f")).thenReturn(getWeatherResponse()); WeatherResponse response = weatherInfoService.weatherInfoByLocation("35", "139"); assertNotNull(response); } private WeatherResponse getWeatherResponse() { WeatherResponse response = new WeatherResponse(); return response; } }
true
891e02bab7178690f3acb264b5027a82f66d85fe
Java
sony93/practice
/src/LC/no234.java
UTF-8
1,698
3.375
3
[]
no_license
package LC; /** * Created by Administrator on 2017/8/3. */ public class no234 { public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public static boolean isPalindrome(ListNode head) { if(head == null || head.next == null) return true; ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; } if(fast != null){ slow = slow.next; } slow = reverse(slow); fast = head; while (slow != null){ if(slow.val != fast.val) return false; slow = slow.next; fast = fast.next; } return true; } public static ListNode reverse(ListNode head) { ListNode prev = null; while (head != null) { ListNode next = head.next; head.next = prev; prev = head; head = next; } return prev; } public static void main(String[] args){ ListNode head = null; head = new ListNode(1); ListNode temp = head; for (int i = 2; i < 5; i++){ temp.next = new ListNode(i); temp = temp.next; } for (int l = 4; l > 0; l--){ temp.next = new ListNode(l); temp = temp.next; } // ListNode test = head; // while (test != null){ // System.out.println(test.val); // test = test.next; // } System.out.println(isPalindrome(head)); } }
true
cf5daedcf2c322d00d5b11f20e00ed827c98f608
Java
LiMouo/SmartTraffic
/app/src/main/java/com/lenovo/smarttraffic/ETC_HOME_1/ETCActivity.java
UTF-8
1,415
1.820313
2
[]
no_license
package com.lenovo.smarttraffic.ETC_HOME_1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TextView; import com.lenovo.smarttraffic.R; import com.lenovo.smarttraffic.TolssHome.ToolbarMaster; import org.w3c.dom.Text; public class ETCActivity extends AppCompatActivity implements View.OnClickListener{ private ImageButton mMenu; private TextView mShow_money; private Spinner mSpinner; private EditText mIn_money; private Button mBtn_query,mBtn_inmoney; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_e_t_c); InitView(); } private void InitView() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); ToolbarMaster.MenuCreate(); ToolbarMaster.setTitle("我的账户"); mShow_money = findViewById(R.id.show_money); mSpinner = findViewById(R.id.spinner); mIn_money = findViewById(R.id.in_money); mBtn_query = findViewById(R.id.btn_query); mBtn_inmoney = findViewById(R.id.btn_inmoney); } @Override public void onClick(View v) { } }
true
39c0d6fabc7b7b8a18a2e5c438db571f9c79ce57
Java
jordi0907/ProyectoDSABackend
/src/main/java/edu/upc/dsa/SessionImpl.java
UTF-8
8,561
2.921875
3
[]
no_license
package edu.upc.dsa; import edu.upc.dsa.util.ObjectHelper; import edu.upc.dsa.util.QueryHelper; import org.apache.log4j.Logger; import java.lang.reflect.InvocationTargetException; import java.sql.*; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class SessionImpl implements Session { private final Connection conn; final static Logger logger = Logger.getLogger(SessionImpl.class); public SessionImpl(Connection conn) { this.conn = conn; } @Override public String save(Object entity) throws Exception { String insertQuery = QueryHelper.createQueryINSERT(entity); PreparedStatement pstm = null; String ID = ""; try { pstm = conn.prepareStatement(insertQuery); // He añadido el valor de ID al usuario, y ahora recorro todos los valores desde el principio porque quiero poner el ID int i = 1; // recorro la lista de nombres de los atributos de la clase for (String field: ObjectHelper.getStrFields(entity)) { pstm.setObject(i++, ObjectHelper.getter(entity, field)); } pstm.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return (String) ObjectHelper.getter(entity, "id"); } @Override public void close() { } @Override public Object get(Class theClass, String ID) { Object obj = null; PreparedStatement pstm = null; //Instantiating a object of type class for the getters try { String selectQuery = QueryHelper.createQuerySELECT(theClass.newInstance()); obj = theClass.newInstance(); pstm = conn.prepareStatement(selectQuery); pstm.setObject(1, ID); ResultSet resultSet = pstm.executeQuery(); int i = 0; while (resultSet.next()){ ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for(i=1;i<=resultSetMetaData.getColumnCount();i++){ String name = resultSetMetaData.getColumnName(i); ObjectHelper.setter(obj,name, resultSet.getObject(i)); } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } logger.info("el objeto es " +obj ); return obj; } @Override public List<Object> query(String query, Class theClass, List params) { PreparedStatement pstm = null; List<Object> objResultado = new LinkedList<>(); try{ pstm = conn.prepareStatement(query); int i = 1; for(Object obj: params){ pstm.setObject(i, params.get(i-1)); logger.info("EL PARAMETRO ES " +params.get(i-1) ); i++; } ResultSet resultSet = pstm.executeQuery(); logger.info("ELRESULTADO DE LA QUERY OBJETOS " +resultSet ); while(resultSet.next()) { ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for(int j=1;j<=resultSetMetaData.getColumnCount();j++){ objResultado.add(resultSet.getObject(j)); } } } catch(Exception e){ e.printStackTrace(); } return objResultado; } @Override public List<Object> queryObjects(String query, Class theClass, List params) { PreparedStatement pstm = null; List<Object> objResultado = new LinkedList<>(); Object obj = null; try{ obj = theClass.newInstance(); pstm = conn.prepareStatement(query); int i = 1; for(Object o: params){ pstm.setObject(i, params.get(i-1)); i++; } ResultSet resultSet = pstm.executeQuery(); while(resultSet.next()) { ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for(int j=1;j<=resultSetMetaData.getColumnCount();j++){ String name = resultSetMetaData.getColumnName(j); ObjectHelper.setter(obj,name, resultSet.getObject(j)); } logger.info("objeto añadido " +obj); objResultado.add(obj); obj = theClass.newInstance(); } } catch(Exception e){ e.printStackTrace(); } return objResultado; } public int update(Object entity) { String[] updateSentenciaCampos = QueryHelper.createQueryUPDATE(entity); String updateQuery = updateSentenciaCampos[0]; String[] fieldsOrdenados = Arrays.copyOfRange(updateSentenciaCampos,1,(updateSentenciaCampos.length)); PreparedStatement preparedStatement;int affectedRows = 0; try { preparedStatement = conn.prepareStatement(updateQuery); int i = 1; for (String field: fieldsOrdenados) { Object objt = ObjectHelper.getter(entity, field); preparedStatement.setObject(i, objt); i++; } affectedRows = preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return affectedRows; } @Override public int delete(Object object) { String delete = QueryHelper.createQueryDELETE(object); int affectedRows = 0; PreparedStatement pstm = null; try { pstm=conn.prepareStatement(delete); for(String field: ObjectHelper.getStrFields(object)){ if(field.equals("id")) { pstm.setObject(1, ObjectHelper.getter(object, field)); } if(field.equals("ID")) { pstm.setObject(1, ObjectHelper.getter(object, field)); } } affectedRows = pstm.executeUpdate(); } catch (Exception e){ e.printStackTrace(); } return affectedRows; } @Override public List<Object> findAll(Class theClass) { PreparedStatement pstm = null; //Instantiating a object of type class for the getters List<Object> objList = new LinkedList<>(); try { String selectQuery = QueryHelper.createQuerySELECTALL(theClass.newInstance()); pstm = conn.prepareStatement(selectQuery); ResultSet resultSet = pstm.executeQuery(); while(resultSet.next()) { Object obj = theClass.newInstance(); ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for(int i=1;i<=resultSetMetaData.getColumnCount();i++){ String name = resultSetMetaData.getColumnName(i); obj = ObjectHelper.setter(obj,name, resultSet.getObject(i)); } objList.add(obj); } }catch (Exception e){ e.printStackTrace(); } return objList; } @Override public int updatePassword(Object entity) { String[] updateSentenciaCampos = QueryHelper.createQueryPasswordUPDATE(entity); String updateQuery = updateSentenciaCampos[0]; String[] fieldsOrdenados = Arrays.copyOfRange(updateSentenciaCampos,1,(updateSentenciaCampos.length)); PreparedStatement preparedStatement;int affectedRows = 0; try { preparedStatement = conn.prepareStatement(updateQuery); int i = 1; for (String field: fieldsOrdenados) { Object objt = ObjectHelper.getter(entity, field); preparedStatement.setObject(i, objt); i++; } affectedRows = preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } return affectedRows; } }
true
2cbbd4f885354047d5bfad78a1e28e519d6b228f
Java
deckersmichael/test
/UserManagementApp/UserManagementApp-ejb/src/main/java/ua/group06/logic/UserSettingsServiceLocal.java
UTF-8
592
1.898438
2
[]
no_license
/* * 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 ua.group06.logic; import javax.ejb.Local; import ua.group06.persistence.AbstractUser; import ua.group06.persistence.User; /** * * @author Yves Maris */ @Local public interface UserSettingsServiceLocal { AbstractUser edit(AbstractUser user); User editPassword(User user); boolean checkPassword(String cleartext, String encrypted); public boolean checkEmailAvailible(String email); }
true
a48cacd797e54b44bc3bcc2fd2c28753f673a2f8
Java
AlbertoGarcia2034/Listas-Enlazadas
/src/MainClass.java
ISO-8859-1
3,922
3.578125
4
[]
no_license
import java.util.Scanner; /** * */ /** * @author Eduardo * */ public class MainClass { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SimpleList lista = new SimpleList(); Nodo nodo = new Nodo(lista); Scanner sc = new Scanner(System.in); int opcion; boolean detener=true; while(detener !=false ) { //Impresion de nuestro mun System.out.println("\n<<Men>>"); System.out.println("1: Insertar."); System.out.println("2: Mostrar."); System.out.println("3: Buscar."); System.out.println("4: Eliminar."); System.out.println("5: Contar."); System.out.println("6: Terminar."); System.out.println(""); System.out.println("Cul es tu opcin?: "); opcion = sc.nextInt(); Scanner cs = new Scanner(System.in); switch (opcion) { //en este caso mandara a que el usuario inserte la cantidad de elementos para la lista case 1: System.out.println("Insertar"); System.out.println("Ingrese la cantidad de elementos para la lista:"); //int c = 0; //lista.ValidarNumeros(c); int c = cs.nextInt(); for(int i = 0; i<c; i++) { System.out.println("Ingrese el valor para el elemento " + "["+i+"]"); int obj = cs.nextInt(); lista.addFirst(obj); } break; //Si el usuario Selecciona la opcin 2 mandara a mostrar los datos ingresados en la lista case 2: System.out.println("Mostrar"); lista.mostrar(); break; case 3: //Si selleciona la opcin 3 el nmero que el usuario ingrese lo buscara /*System.out.println("Buscar"); System.out.println("Por ndice"); System.out.println("Ingrese una posicin"); int b = sc.nextInt(); lista.search(b); System.out.println("");*/ System.out.println("Por valor"); //System.out.println("Introduce un valor"); int v = cs.nextInt(); //lista.ValidarNumeros(v); lista.searchValue(v); break; //En esta opcin podra eliminar un valor que desea case 4: System.out.println("Eliminar"); //System.out.println("Por ndice"); //System.out.println("Ingrese una posicin"); System.out.println("Ingrese un valor"); int e = sc.nextInt(); lista.deleteValue(e); //System.out.println("Por valor"); // break; //En esta opcin contara el tamao de la lista que ingreso el usuario case 5: System.out.println("Contar"); System.out.println("El tamao de la lista es " + lista.size()); break; //Si selecciona esta obcion terminara la ejecucion de la aplicacin case 6: detener = false; System.out.println("Vuelva pronto"); break; default: System.out.println("Opcin incorrecta"); break; } } } }
true
01ab2d4a4a904d42830a2bcc2b992126ed9a6ae1
Java
SeanTAllen/nate
/java/src/main/java/org/nate/internal/transformer/NateTransformers.java
UTF-8
654
2.03125
2
[ "MIT" ]
permissive
package org.nate.internal.transformer; import java.util.Map; import org.nate.internal.NateDocumentBackedEngine; public class NateTransformers { @SuppressWarnings("unchecked") public static NateTransformer from(Object data) { if (data instanceof Iterable) { return TransformationSequence.fromObjectSequence((Iterable) data); } if (data instanceof Map) { return TransformationMap.fromObjectMap((Map) data); } if (data instanceof NateDocumentBackedEngine) { return new EngineInjector((NateDocumentBackedEngine) data); } if (data == null) { return new NullDataInjector(); } return new TextInjector(data.toString()); } }
true
ca88aa376a48b517ec45fe698304409d654aadd0
Java
liuyibin23/iovVis
/dao/src/main/java/org/thingsboard/server/dao/vdeviceattrkv/DeviceAttrKVService.java
UTF-8
535
1.648438
2
[ "Apache-2.0", "MIT" ]
permissive
package org.thingsboard.server.dao.vdeviceattrkv; import org.thingsboard.server.dao.model.sql.DeviceAttrKV; import java.util.List; public interface DeviceAttrKVService { List<DeviceAttrKV> getDeviceAttrKV(); List<DeviceAttrKV> findbytenantId(String tenandId); List<DeviceAttrKV> findbyAttributeKey(String attributeKey, String tenantId); List<DeviceAttrKV> findbyAttributeKeyAndValueLike(String attributeKey, String tenantId, String strV); List<DeviceAttrKV> findbyAttributeValueLike(String tenantId, String strV); }
true
18e63d475e54b6072bdeb89becb0114ca43102e0
Java
domiiii11/SpringHomeWorkStore
/src/main/java/lt/sda/demo/configure/ProductQuantity.java
UTF-8
430
1.617188
2
[]
no_license
package lt.sda.demo.configure; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @ConfigurationProperties(prefix = "lv.sda.store.quantities") @Component public class ProductQuantity { private Double appleQuantity; private Double orangeQuantity; private Double carrotQuantity; private Double potatoQuantity; }
true
91ead1c935a92fdffcd8ff3862907f84f654cb46
Java
Gwisdomm/springcloud
/tx_springcloud_02/cloud-provider-payment8002/src/main/java/com/gao/controller/PaymentController.java
UTF-8
1,347
2.171875
2
[]
no_license
package com.gao.controller; import com.gao.domain.CommonResult; import com.gao.domain.Payment; import com.gao.service.impl.PaymentServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @program: tx_springcloud_02 * @description: 支付的控制层 * @author: gaowz * @create: 2020-11-13 15:47 **/ @RestController @RequestMapping("/payment") public class PaymentController { //获取yml中的端口号 @Value("${server.port}") private String serverPort; @Autowired private PaymentServiceImpl paymentService; @GetMapping("/get/{id}") public CommonResult getPaymentById(@PathVariable(value = "id") Long id) { Payment payment = paymentService.getPaymentById(id); if (StringUtils.isEmpty(payment)) { return new CommonResult(404, "查无数据,serverPort "+serverPort, null); } else { return new CommonResult(200, "查询成功,serverPort "+serverPort, payment); } } }
true
2aeb31c93a93e382d0ab21aaf8e86640d292dcd7
Java
moha1818/2019demo
/src/main/java/com/sunland/pojo/json/InvoiceDetailItem.java
UTF-8
1,059
1.898438
2
[]
no_license
package com.sunland.pojo.json; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.Date; public class InvoiceDetailItem { @ApiModelProperty(value="停车点名称") private String parkname; @ApiModelProperty(value="金额") private BigDecimal parkmoney; @ApiModelProperty(value="停车时间") private Date parktime; @ApiModelProperty(value="号码牌") private String hphm; public String getParkname() { return parkname; } public void setParkname(String parkname) { this.parkname = parkname; } public BigDecimal getParkmoney() { return parkmoney; } public void setParkmoney(BigDecimal parkmoney) { this.parkmoney = parkmoney; } public Date getParktime() { return parktime; } public void setParktime(Date parktime) { this.parktime = parktime; } public String getHphm() { return hphm; } public void setHphm(String hphm) { this.hphm = hphm; } }
true
00326acaeda9f8ad0c06ac9d385b9f9c11052b22
Java
G4meM0ment/RPGEssentials
/src/me/G4meM0ment/DeathAndRebirth/Framework/Shrine.java
UTF-8
1,104
2.671875
3
[]
no_license
package me.G4meM0ment.DeathAndRebirth.Framework; import org.bukkit.Location; public class Shrine { private Location max, min, spawn; private boolean binding; private String name; /** * Contains all information needed for a shrine * @param name * @param max * @param min * @param spawn * @param binding */ public Shrine(String name, Location max, Location min, Location spawn, boolean binding) { this.name = name; this.max = max; this.min = min; this.spawn = spawn; this.binding = binding; } public Location getMax() { return max; } public void setMax(Location max) { this.max = max; } public Location getMin() { return min; } public void setMin(Location min) { this.min = min; } public Location getSpawn() { return spawn; } public void setSpawn(Location spawn) { this.spawn = spawn; } public boolean hasBinding() { return binding; } public void setBinding(boolean binding) { this.binding = binding; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
f0f7738f42e36d36ec9b4cd092bb3e3339bbb8de
Java
saatvikj/ConferenceApp
/MobileApp/app/src/main/java/com/example/conferenceapp/adapters/MyDayPagerAdapter.java
UTF-8
1,333
2.53125
3
[]
no_license
package com.example.conferenceapp.adapters; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.example.conferenceapp.fragments.FragmentMyDaySchedule; import com.example.conferenceapp.models.Conference; import com.example.conferenceapp.utils.ConferenceCSVParser; public class MyDayPagerAdapter extends FragmentPagerAdapter { Context context; public MyDayPagerAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; } @Override public int getCount() { Conference conference = null; try { conference = ConferenceCSVParser.parseCSV(context); } catch (Exception e) { } int start_date = Integer.parseInt(conference.getConference_start_day().split("-")[2]); int end_date = Integer.parseInt(conference.getConference_end_day().split("-")[2]); return end_date - start_date + 1; } @Override public Fragment getItem(int position) { return FragmentMyDaySchedule.newInstance(position); } @Override public CharSequence getPageTitle(int position) { // Generate title based on item position return "Day " + (position + 1); } }
true
ec7923c8e5404faf3838eb87628022e9770acdb8
Java
lexuanzhou/leetcode
/src/com/java/medium/ArrayandStrings/LongestSubstringWithoutRepeatingCharacters.java
UTF-8
1,791
3.734375
4
[]
no_license
//Given a string, find the length of the longest substring without repeating characters. // // Example 1: // // Input: "abcabcbb" // Output: 3 // Explanation: The answer is "abc", with the length of 3. // Example 2: // // Input: "bbbbb" // Output: 1 // Explanation: The answer is "b", with the length of 1. // Example 3: // // Input: "pwwkew" // Output: 3 // Explanation: The answer is "wke", with the length of 3. // Note that the answer must be a substring, "pwke" is a subsequence and not a substring. package com.java.medium.ArrayandStrings; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class LongestSubstringWithoutRepeatingCharacters { public LongestSubstringWithoutRepeatingCharacters(){} public int lengthOfLongestSubstring(String s) { Set<Character> set = new HashSet<>(); int result = 0, i = 0, j = 0; while (i < s.length() && j < s.length()) { // try to extend the range [i, j] if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); result = Math.max(result, j - i); } else { set.remove(s.charAt(i++)); } } return result; } public int lengthOfLongestSubstring_optimized(String s) { int result = 0; HashMap<Character, Integer> hashMap = new HashMap<>(); for(int i = 0, j = 0; j < s.length(); j++){ if (hashMap.containsKey(s.charAt(j))){ i = Math.max(hashMap.get(s.charAt(j)), i); } result = Math.max(result, j - i + 1); hashMap.put(s.charAt(j), j + 1); } return result; } }
true
08059a92f1863f7750aa546ea0686f0dac390098
Java
artyaban/AplicacionNomina3
/app/src/main/java/com/example/artyaban/aplicacionnomina/inicio2.java
UTF-8
1,811
2.390625
2
[]
no_license
package com.example.artyaban.aplicacionnomina; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class inicio2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inicio2); } public void escaner(View view) { IntentIntegrator scanIntegrator = new IntentIntegrator(this); scanIntegrator.initiateScan(); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { //Se obtiene el resultado del proceso de scaneo y se parsea IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanningResult != null) { //Quiere decir que se obtuvo resultado pro lo tanto: //Desplegamos en pantalla el contenido del código de barra scaneado String scanContent = scanningResult.getContents(); //Desplegamos en pantalla el nombre del formato del código de barra scaneado String scanFormat = scanningResult.getFormatName(); Intent intent2 = new Intent(inicio2.this,asistencia1.class); intent2.putExtra("numEmpleado",scanContent); startActivity(intent2); }else{ //Quiere decir que NO se obtuvo resultado Toast toast = Toast.makeText(getApplicationContext(), "No se ha recibido datos del scaneo!", Toast.LENGTH_SHORT); toast.show(); } } }
true
13754bc6f10dcdc3e156ce9e144989ce7901087b
Java
zj83142/storemanage
/src/com/zj/storemanag/activity/RFIDQueryActivity.java
UTF-8
18,035
1.515625
2
[]
no_license
package com.zj.storemanag.activity; import java.io.File; import java.util.List; import log.Log; import android.annotation.TargetApi; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.NfcA; import android.os.Bundle; import android.os.Handler; import android.provider.MediaStore; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.zj.storemanag.R; import com.zj.storemanag.bean.ImgBean; import com.zj.storemanag.bean.RFIDinfo; import com.zj.storemanag.bean.StoreBean; import com.zj.storemanag.commen.BaseActivity; import com.zj.storemanag.commen.ParamsUtil; import com.zj.storemanag.dao.ImgDao; import com.zj.storemanag.service.AsyncService; import com.zj.storemanag.util.MyTip; import com.zj.storemanag.util.NfcTools; import com.zj.storemanag.util.StrUtil; import com.zj.storemanag.util.Utils; import com.zj.storemanag.view.NetImageView; public class RFIDQueryActivity extends BaseActivity { private EditText rfidEt; private String rfidStr; private RFIDinfo rfidInfo; private TextView materialEt; private TextView factoryEt; private TextView storeEt; private TextView despEt;// 物料描述 private TextView unitEt;// 单位 private TextView fxgfkcEt;// 非限估计库存 private TextView xzjskcEt;// 限制寄售库存 private TextView totalStoreEt;// 总计库存 private TextView fxjskcEt;// 非限寄售库存 private TextView cwEt;// 库位 private TextView xmcwEt;// 项目库存 private boolean skip = false; private TextView titleTv; private StoreBean storeBean; private LinearLayout rfidQueryLayout; private NetImageView netImageView; NfcAdapter mAdapter; PendingIntent mPendingIntent; boolean writeMode; Tag mytag; private IntentFilter[] mFilters; private String[][] mTechLists; private boolean isWrite = false; private Button photoBtn; private Activity context; private String pathStr; private String urlStr; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.rfid_query); Log.i("zj", "----------onCreate----------"); context = this; initView(); } private void initView() { titleTv = (TextView) findViewById(R.id.top_title_tv); titleTv.setText("标签查询"); photoBtn = (Button) findViewById(R.id.top_right_btn); photoBtn.setText("拍照"); photoBtn.setVisibility(View.VISIBLE); photoBtn.setOnClickListener(this); rfidEt = (EditText) findViewById(R.id.rfid_query_et); rfidQueryLayout = (LinearLayout) findViewById(R.id.rfid_query_layout); materialEt = (TextView) findViewById(R.id.rfid_query_material_et); factoryEt = (TextView) findViewById(R.id.rfid_query_factory_et); storeEt = (TextView) findViewById(R.id.rfid_query_store_location_et); despEt = (TextView) findViewById(R.id.rfid_query_material_desp_et); unitEt = (TextView) findViewById(R.id.rfid_query_store_unit_et); fxgfkcEt = (TextView) findViewById(R.id.rfid_query_fxgjkc_et); xzjskcEt = (TextView) findViewById(R.id.rfid_query_xzjskc_et); totalStoreEt = (TextView) findViewById(R.id.rfid_query_total_store_et); fxjskcEt = (TextView) findViewById(R.id.rfid_query_fxjskc_et); cwEt = (TextView) findViewById(R.id.rfid_query_cw_et); xmcwEt = (TextView) findViewById(R.id.rfid_query_xmcw_et); netImageView = (NetImageView) findViewById(R.id.material_img); netImageView.setOnClickListener(this); skip = getIntent().getBooleanExtra("skip", false); if (skip) { // 从物料号查询界面跳转进来的 storeBean = (StoreBean) getIntent() .getSerializableExtra("material"); if (storeBean != null) { setViewData(); } } try { mAdapter = NfcAdapter.getDefaultAdapter(this); mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); // Setup an intent filter for all MIME based dispatches IntentFilter ndef = new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED); mFilters = new IntentFilter[] { ndef, }; // Setup a tech list for all NfcF tags mTechLists = new String[][] { new String[] { NfcA.class.getName() } }; } catch (Exception e) { Log.i("zj", "onCreate " + e.getMessage()); } rfidEt.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if (skip) { // 采购订单入库不需要扫描rfid return; } String rfid = rfidEt.getText().toString(); if (StrUtil.isNotEmpty(rfid) && rfid.length() == 32) { MyTip.showProgress(context, "查询", "正在查询数据,请稍候……"); AsyncService.GetRFIDInfo getRFIDInfo = AsyncService.getInstance().new GetRFIDInfo(); getRFIDInfo.execute(handler, ParamsUtil.GETRFIDINFO, getPreference("url"), getUser().getUserId(), rfid, context); } } }); } @Override public void onNewIntent(Intent intent) { Log.i("zj", "----------onNewIntent----------"); try { mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); Log.i("zj", "onNewIntent"); setIntent(intent); new NfcTools().readInfo(intent, mytag, rfidEt, isWrite, context); } catch (Exception e) { Log.i("zj", "Exception onNewIntent " + e.getMessage()); } } @TargetApi(10) @Override public void onPause() { super.onPause(); Log.d("zj", "onPause() called"); if (mAdapter != null) mAdapter.disableForegroundDispatch(this); } @TargetApi(10) @Override public void onResume() { super.onResume(); Log.d("zj", "onResume() called"); if (mAdapter != null) mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists); if(out != null && out.length() > 0){ netImageView.setVisibility(View.VISIBLE); netImageView.setImagePath(out); String material = StrUtil.filterStr(materialEt.getText().toString()); String factoryStr = StrUtil.slipValue(factoryEt.getText().toString()); String storeStr = StrUtil.slipValue(storeEt.getText().toString()); ImgDao.getInstance(context).updateImgState(material, factoryStr, storeStr); } } String photoPath; File out; public final static int REQUEST_CODE_PHOTO = 1002; // 拍照返回的时候 修改那个指标值 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // log.i("zj","返回的请求标志:" + requestCode); switch (requestCode) { case REQUEST_CODE_PHOTO: // 拍照返回 try { photoPath = getPreference("photoPath"); Log.i("zj", "PHOTO:" + photoPath); File file = new File(photoPath); if (file.exists()) { pathStr = photoPath; Log.i("zj", "保存照片:" + photoPath); // _id, material, factory, store, path, userId, state ImgBean bean = new ImgBean(); bean.setMaterial(materialEt.getText().toString()); bean.setFactory(StrUtil.slipValue(factoryEt.getText().toString())); bean.setStore(StrUtil.slipValue(storeEt.getText().toString())); bean.setPath(photoPath); bean.setUserId(getUser().getUserId()); bean.setState("0"); bean.setDesp(StrUtil.filterStr(despEt.getText().toString())); bean.setUnit(StrUtil.filterStr(unitEt.getText().toString())); bean.setCw(StrUtil.filterStr(cwEt.getText().toString())); // 保存图片到表中 boolean isResult = ImgDao.getInstance( context).save(bean); if (isResult) { // MyTip.showToast(AddEquipInfoActivity.this, "图片保存成功"); } else { MyTip.showToast(context, "图片保存失败"); } } else { MyTip.showToast(context, "保存照片错误,文件不存在!"); } } catch (Exception e) { e.printStackTrace(); Log.e("zj", "保存照片报错:" + e.getMessage()); } break; default: break; } super.onActivityResult(requestCode, resultCode, data); } @Override public void onClick(View v) { // TODO Auto-generated method stub super.onClick(v); switch (v.getId()) { case R.id.top_back_btn: finish(); break; // case R.id.rfid_query_scan_btn: // // 扫描 // rfidEt.setText("123456789"); // break; case R.id.top_right_btn: if (!judgeMaterial()) { // 请先输入 MyTip.showToast(context, "请查询完整物料信息再拍照!"); return; } // 拍照 try { out = Utils.createFile(Utils.EQPICTUREPATH, ".jpg"); if (out.exists() && out != null) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoPath = out.getAbsolutePath(); savePreferences("photoPath", photoPath); Log.i("zj", "拍照,保存照片路径:" + photoPath); Uri uri = Uri.fromFile(out); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, REQUEST_CODE_PHOTO); } } catch (Exception e) { e.printStackTrace(); Log.i("zj", "拍照报错:" + e.getMessage()); } break; case R.id.rfid_query_find_btn: // 查询RFIDInfo rfidStr = rfidEt.getText().toString(); if (!StrUtil.isNotEmpty(rfidStr)) { MyTip.showToast(context, "请输入标签信息!"); return; } MyTip.showProgress(context, "查询", "正在查询数据,请稍候……"); AsyncService.GetRFIDInfo getRFIDInfo = AsyncService.getInstance().new GetRFIDInfo(); getRFIDInfo.execute(handler, ParamsUtil.GETRFIDINFO, getPreference("url"), getUser().getUserId(), rfidStr, context); break; case R.id.material_img: Intent it = new Intent(context, PhotoScanActivity.class); it.putExtra("path", pathStr); it.putExtra("url", urlStr); startActivity(it); break; default: break; } } private boolean judgeMaterial() { String material = StrUtil.filterStr(materialEt.getText().toString()); String factoryStr = StrUtil.slipValue(factoryEt.getText().toString()); String storeStr = StrUtil.slipValue(storeEt.getText().toString()); String unit = StrUtil.filterStr(unitEt.getText().toString()); if (StrUtil.isNotEmpty(material) && StrUtil.isNotEmpty(factoryStr) && StrUtil.isNotEmpty(storeStr) && StrUtil.isNotEmpty(unit)) { return true; } return false; } private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case ParamsUtil.GETRFIDINFO: // 获取RFIDInfo setRfidInfoResult(msg.obj); break; case ParamsUtil.GETKC: setKCResult(msg.obj); break; case ParamsUtil.GETKC2: setKC2Result(msg.obj); break; case ParamsUtil.load_img: if (msg.obj != null) { netImageView.setVisibility(View.VISIBLE); String imgPath = (String) msg.obj; if (imgPath.startsWith("../")) { imgPath = imgPath.replace("../", ""); } imgPath = "http://" + getApp().getUrl() + "/" + imgPath; Log.i("zj", "加载图片路径:" + imgPath); // String url = // "http://pic23.nipic.com/20120909/5907156_101905268000_2.jpg"; urlStr = imgPath; netImageView.setImageUrl(imgPath); } else { netImageView.setVisibility(View.GONE); } break; default: break; } } }; private List<StoreBean> list; /** 设置库存查询结果 */ protected void setKCResult(Object obj) { if (obj != null) { Object[] result = (Object[]) obj; String info = (String) result[0]; if (info.equalsIgnoreCase("ok")) { list = (List<StoreBean>) result[1]; setViewsData(); // 调用项目库存接口 AsyncService.GetKC2 getKc = AsyncService.getInstance().new GetKC2(); getKc.execute(handler, ParamsUtil.GETKC2, getApp().getUrl(), materialStr, factoryStr, storeStr, context); } else { MyTip.showToast(context, "数据已变更,没有查询到数据!"); } } else { clearViewDate(); } MyTip.cancelProgress(); } protected void setKC2Result(Object obj) { if (obj != null) { Object[] result = (Object[]) obj; String info = (String) result[0]; if (info.equalsIgnoreCase("ok")) { List<StoreBean> tempLs = (List<StoreBean>) result[1]; if (tempLs != null && tempLs.size() > 0) { xmcwEt.setText(tempLs.get(0).getLABST()); } else { xmcwEt.setText(""); } } else { xmcwEt.setText(""); } } else { xmcwEt.setText(""); } } private void clearViewDate() { materialEt.setText(""); factoryEt.setText(""); storeEt.setText(""); despEt.setText(""); unitEt.setText(""); fxgfkcEt.setText(""); xzjskcEt.setText(""); totalStoreEt.setText(""); fxjskcEt.setText(""); cwEt.setText(""); xmcwEt.setText(""); } private void setViewsData() { if (rfidInfo == null) { rfidEt.setText(""); MyTip.showToast(context, "没有查询到物料信息!"); return; } materialEt.setText(StrUtil.filterStr(rfidInfo.getPR_MATERIAL())); despEt.setText(StrUtil.filterStr(rfidInfo.getPR_MESSAGE())); if (list != null && list.size() > 0) { StoreBean storeBean = list.get(0); factoryEt.setText(StrUtil.filterStr(storeBean.getFactory())); storeEt.setText(StrUtil.filterStr(storeBean.getStore())); unit = StrUtil.filterStr(storeBean.getUnit()); unitEt.setText(StrUtil.slipName(unit)); fxgfkcEt.setText(StrUtil.filterStr(storeBean.getLABST())); xzjskcEt.setText(StrUtil.filterStr(storeBean.getKLABS())); totalStoreEt.setText(StrUtil.filterStr(storeBean.getEINME())); fxjskcEt.setText(StrUtil.filterStr(storeBean.getKEINM())); cwEt.setText(StrUtil.filterStr(storeBean.getLGPBE())); setMaterialImg(); getProjectKc(); } } private void getProjectKc() { // 调用项目库存接口 AsyncService.GetKC2 getKc = AsyncService.getInstance().new GetKC2(); getKc.execute(handler, ParamsUtil.GETKC2, getApp().getUrl(), materialStr, factoryStr, storeStr, context); } private String unit; /** 物料查询界面跳转过来的 */ private void setViewData() { titleTv.setText("物料详情"); rfidQueryLayout.setVisibility(View.GONE); materialStr = StrUtil.filterStr(storeBean.getMATNR()); factoryStr = StrUtil.filterStr(storeBean.getFactory()); storeStr = StrUtil.filterStr(storeBean.getStore()); materialEt.setText(materialStr); factoryEt.setText(StrUtil.filterStr(storeBean.getFactory())); storeEt.setText(StrUtil.filterStr(storeBean.getStore())); despEt.setText(StrUtil.filterStr(storeBean.getMAKTX())); unit = StrUtil.filterStr(storeBean.getUnit()); unitEt.setText(StrUtil.slipName(storeBean.getUnit())); fxgfkcEt.setText(StrUtil.filterStr(storeBean.getLABST())); xzjskcEt.setText(StrUtil.filterStr(storeBean.getKLABS())); totalStoreEt.setText(StrUtil.filterStr(storeBean.getEINME())); fxjskcEt.setText(StrUtil.filterStr(storeBean.getKEINM())); cwEt.setText(StrUtil.filterStr(storeBean.getLGPBE())); //查询数据库中是否有匹配的图片,如果没有查询接口是否有图片 setMaterialImg(); getProjectKc(); } private void setMaterialImg() { // TODO Auto-generated method stub String materialStr = StrUtil.filterStr(materialEt.getText().toString()); String factoryStr = StrUtil.slipValue(factoryEt.getText().toString()); String storeStr = StrUtil.slipValue(storeEt.getText().toString()); String path = ImgDao.getInstance(context).getMaterialImgPath(materialStr, factoryStr, storeStr); File file = new File(path); if(file.exists()){ pathStr = path; netImageView.setVisibility(View.VISIBLE); netImageView.setImagePath(file); ImgDao.getInstance(context).updateImgState(materialStr, factoryStr, storeStr); }else{ AsyncService.GetMaterialImg getMaterialImg = AsyncService.getInstance().new GetMaterialImg(); getMaterialImg.execute(handler, ParamsUtil.load_img, getApp().getUrl(), getUser().getUserId(), materialStr, factoryStr, StrUtil.slipValue(storeStr)); } } String materialStr; String factoryStr; String storeStr; private void setRfidInfoResult(Object obj) { if (obj != null) { Object[] result = (Object[]) obj; String info = (String) result[0]; if (info.equalsIgnoreCase("ok")) { rfidInfo = (RFIDinfo) result[1]; materialStr = rfidInfo.getPR_MATERIAL(); factoryStr = StrUtil.slipValue(rfidInfo.getFactory()); storeStr = StrUtil.slipValue(rfidInfo.getStore()); if (StrUtil.isNotEmpty(materialStr) && StrUtil.isNotEmpty(factoryStr) && StrUtil.isNotEmpty(storeStr)) { // 根据RFID、工厂、库位获取库存信息 AsyncService.GetKC getKc = AsyncService.getInstance().new GetKC(); getKc.execute(handler, ParamsUtil.GETKC, getApp().getUrl(), materialStr, factoryStr, storeStr, context); } else { MyTip.cancelProgress(); MyTip.showToast(context, "没有查询到数据"); } } else { MyTip.cancelProgress(); MyTip.showToast(context, (String) result[1]); } } else { MyTip.showToast(context, "没有查询到物料信息!"); MyTip.cancelProgress(); } }; }
true
c1dc12ba5102bcb4f7c0d693110ce831059d1f92
Java
Serhiy200/test_task
/src/Main.java
UTF-8
325
2.015625
2
[]
no_license
import file.Rand; import file.mainForm; import javax.swing.*; public class Main extends JFrame { public static void main(String[] args) { JFrame jf = new mainForm("My form"); jf.setVisible(true); System.out.println(Rand.number(10)); Rand rand = new Rand(); rand.array(); } }
true
ef59e0f434e152636048ecfedbadf7a576e7fd05
Java
NeonNeon/ircSEX-Messenger
/ircSEXMessenger/src/main/java/se/chalmers/dat255/ircsex/ui/SettingsActivity.java
UTF-8
1,130
2.046875
2
[ "Beerware" ]
permissive
package se.chalmers.dat255.ircsex.ui; import android.app.Activity; import android.os.Bundle; import android.view.MenuItem; import se.chalmers.dat255.ircsex.R; /** * @author Johan Magnusson * Date: 2013-10-10 */ public class SettingsActivity extends Activity { public static final String PREF_SHOW_JOIN_LEAVE = "pref_show_join_leave"; public static final String PREF_MESSAGE_FONT_SIZE = "pref_message_font_size"; public static final String PREF_HIGHLIGHT = "pref_highlight"; public static final String PREF_NICKNAME = "pref_nickname"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.action_settings); getActionBar().setDisplayHomeAsUpEnabled(true); getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } }
true
38241bd0d55bc45929ec9f4e53131a38d054713b
Java
beezerbt/Spock
/complete/src/main/java/hello/ContractUploadConfig.java
UTF-8
1,583
2.015625
2
[]
no_license
package hello; import com.carslon.contractupload.model.BusinessDivisions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.AbstractRequestLoggingFilter; import org.springframework.web.filter.CommonsRequestLoggingFilter; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; @Configuration public class ContractUploadConfig { private static Logger LOG = LoggerFactory.getLogger(ContractUploadConfig.class); //TODO::KS::Once the debugging is sorted this should be removed...or set to log at debug. @Bean public Filter loggingFilter(){ AbstractRequestLoggingFilter f = new AbstractRequestLoggingFilter() { @Override protected void beforeRequest(HttpServletRequest request, String message) { LOG.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>beforeRequest: " +message); } @Override protected void afterRequest(HttpServletRequest request, String message) { LOG.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>afterRequest: " +message); } }; f.setMaxPayloadLength(9000); f.setIncludeClientInfo(true); f.setIncludePayload(true); f.setIncludeQueryString(true); f.setBeforeMessagePrefix("BEFORE REQUEST ["); f.setAfterMessagePrefix("AFTER REQUEST ["); f.setAfterMessageSuffix("]\n"); return f; } @Bean @Autowired public BusinessDivisions createBusinessDivisions(){ return new BusinessDivisions(); } }
true
f3dd2e64faaf4a02c850f39a5840a2c3a21d3f6c
Java
morristech/PrimeNumbers
/app/src/main/java/info/dvkr/primenumbers/PrimeNumbersApp.java
UTF-8
953
2.171875
2
[]
no_license
package info.dvkr.primenumbers; import android.app.Application; import info.dvkr.primenumbers.background.BackgroundService; import info.dvkr.primenumbers.dagger.component.AppComponent; import info.dvkr.primenumbers.dagger.component.DaggerAppComponent; import info.dvkr.primenumbers.dagger.module.AppModule; import info.dvkr.primenumbers.dagger.module.DataModule; import info.dvkr.primenumbers.dagger.module.DomainModule; public class PrimeNumbersApp extends Application { protected AppComponent component; @Override public void onCreate() { super.onCreate(); component = DaggerAppComponent.builder() .appModule(new AppModule(this)) .dataModule(new DataModule()) .domainModule(new DomainModule()) .build(); startService(BackgroundService.getStartIntent(this)); } public AppComponent getAppComponent() { return component; } }
true
433f38c870a652e598ad09b4087b6b2d1d531c72
Java
Sierou-Java/Spring-Family
/Spring-Family-Security/src/main/java/org/sierou/user/User.java
UTF-8
1,886
2.578125
3
[]
no_license
package org.sierou.user; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.security.core.GrantedAuthority; import java.util.Collection; /** * 此 User 类不是我们的数据库里的用户类,是用来安全服务的. * @Author 王洪悦.{javayue@yeah.net} * @Create 2017-08-15 下午2:58 */ public class User implements UserDetails{ private final String id; //帐号,这里是我数据库里的字段 private final String account; //密码 private final String password; //角色集合 private final Collection<? extends GrantedAuthority> authorities; User(String id, String account, String password, Collection<? extends GrantedAuthority> authorities) { this.id = id; this.account = account; this.password = password; this.authorities = authorities; } //返回分配给用户的角色列表 @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @JsonIgnore public String getId() { return id; } @JsonIgnore @Override public String getPassword() { return password; } //虽然我数据库里的字段是 `account` ,这里还是要写成 `getUsername()`,因为是继承的接口 @Override public String getUsername() { return account; } // 账户是否未过期 @JsonIgnore @Override public boolean isAccountNonExpired() { return true; } // 账户是否未锁定 @JsonIgnore @Override public boolean isAccountNonLocked() { return true; } // 密码是否未过期 @JsonIgnore @Override public boolean isCredentialsNonExpired() { return true; } // 账户是否激活 @JsonIgnore @Override public boolean isEnabled() { return true; } }
true
63d79f9ea3be0e7692c58e9a2b93ab516b211347
Java
4thcalabash/popbattle2
/src/ui/specialParent/NormalParent.java
GB18030
2,500
2.53125
3
[]
no_license
package ui.specialParent; import ui.Main; import java.util.concurrent.CountDownLatch; import bll.platform.Battle; import po.*; import util.Audio; public class NormalParent extends GenerateParent { // scene public NormalParent(int missionID, Main main) { super(main, new Battle(missionID), " "); addPool(false); normal = true; myself.start(); // missionPoһNormalplatform } // NORMAL @Override public void run() { // TODO Auto-generated method stub battleAudio = Audio.normal; battleAudio.play(); platform.getPlayer2().getPlayer().setAILevel(2); BattlePo result = this.platform.check(); System.out.println("Start"); round = 2; changeRound(); while (!result.isBattleIsEnd()) { if (round == 1) { while (true) { if (new1 && new2) { new1 = new2 = false; // ƶʾ boolean flag = moveFlash(); if (flag) { System.out.println("OK AT HERE"); // ʾ abcd = new CountDownLatch(1); popFlash(); try { abcd.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } renewBoard(); // System.out.println(dot1.getX() + "," + dot1.getY() + " " + dot2.getX() + "," + dot2.getY()); result = platform.check(); if (!result.isBattleIsEnd()) { changeRound(); } break; } } else { // ÿ10msһû try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } } } } else { AIStrategyPo temp = platform.getAIStrategy(); if (temp.isMoveStrategy()) { this.setDot1(temp.getDot1().getX(), temp.getDot1().getY()); this.setDot2(temp.getDot2().getX(), temp.getDot2().getY()); new1 = new2 = false; moveFlash(); abcd = new CountDownLatch(1); popFlash(); try { abcd.await(); } catch (InterruptedException e) { e.printStackTrace(); } renewBoard(); result = platform.check(); if (!result.isBattleIsEnd()) { changeRound(); } } } if (result.isBattleIsEnd()) { if (result.getFinalWinnerID() == 1) { showWinFlash(" "); } else { showLoseFlash(" "); } } } System.out.println("End"); } }
true
5493ae3d40efebd79310b4ffacb6d31ae4d2a8b7
Java
Paul-Warren/shopping-list
/src/main/java/edu/depaul/cdm/se/shoppinglist/model/Status.java
UTF-8
99
1.609375
2
[]
no_license
package edu.depaul.cdm.se.shoppinglist.model; public enum Status { COMPLETE, INCOMPLETE }
true
5c06f411e0e86e1e18c39b7653598dca19bf48fa
Java
anuchandy/azure-sdk-for-java
/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java
UTF-8
121,967
1.539063
2
[ "MIT" ]
permissive
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.hdinsight.v2018_06_01_preview.implementation; import com.microsoft.azure.arm.collection.InnerSupportsGet; import com.microsoft.azure.arm.collection.InnerSupportsDelete; import com.microsoft.azure.arm.collection.InnerSupportsListing; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.ClusterCreateParametersExtended; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.ClusterDiskEncryptionParameters; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.ClusterPatchParameters; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.ClusterResizeParameters; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.ErrorResponseException; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.ExecuteScriptActionParameters; import com.microsoft.azure.management.hdinsight.v2018_06_01_preview.UpdateGatewaySettingsParameters; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.PATCH; import retrofit2.http.Path; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in Clusters. */ public class ClustersInner implements InnerSupportsGet<ClusterInner>, InnerSupportsDelete<Void>, InnerSupportsListing<ClusterInner> { /** The Retrofit service to perform REST calls. */ private ClustersService service; /** The service client containing this operation class. */ private HDInsightManagementClientImpl client; /** * Initializes an instance of ClustersInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public ClustersInner(Retrofit retrofit, HDInsightManagementClientImpl client) { this.service = retrofit.create(ClustersService.class); this.client = client; } /** * The interface defining all the services for Clusters to be * used by Retrofit to perform actually REST calls. */ interface ClustersService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters create" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}") Observable<Response<ResponseBody>> create(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body ClusterCreateParametersExtended parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters beginCreate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}") Observable<Response<ResponseBody>> beginCreate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body ClusterCreateParametersExtended parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters update" }) @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}") Observable<Response<ResponseBody>> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ClusterPatchParameters parameters, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters delete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters beginDelete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters getByResourceGroup" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}") Observable<Response<ResponseBody>> getByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters listByResourceGroup" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters") Observable<Response<ResponseBody>> listByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters resize" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/roles/{roleName}/resize") Observable<Response<ResponseBody>> resize(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Path("roleName") String roleName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ClusterResizeParameters parameters, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters beginResize" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/roles/{roleName}/resize") Observable<Response<ResponseBody>> beginResize(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Path("roleName") String roleName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ClusterResizeParameters parameters, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters list" }) @GET("subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/clusters") Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters rotateDiskEncryptionKey" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/rotatediskencryptionkey") Observable<Response<ResponseBody>> rotateDiskEncryptionKey(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body ClusterDiskEncryptionParameters parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters beginRotateDiskEncryptionKey" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/rotatediskencryptionkey") Observable<Response<ResponseBody>> beginRotateDiskEncryptionKey(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body ClusterDiskEncryptionParameters parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters getGatewaySettings" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/getGatewaySettings") Observable<Response<ResponseBody>> getGatewaySettings(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters updateGatewaySettings" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/updateGatewaySettings") Observable<Response<ResponseBody>> updateGatewaySettings(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body UpdateGatewaySettingsParameters parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters beginUpdateGatewaySettings" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/updateGatewaySettings") Observable<Response<ResponseBody>> beginUpdateGatewaySettings(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body UpdateGatewaySettingsParameters parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters executeScriptActions" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/executeScriptActions") Observable<Response<ResponseBody>> executeScriptActions(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body ExecuteScriptActionParameters parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters beginExecuteScriptActions" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/executeScriptActions") Observable<Response<ResponseBody>> beginExecuteScriptActions(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("clusterName") String clusterName, @Query("api-version") String apiVersion, @Body ExecuteScriptActionParameters parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters listByResourceGroupNext" }) @GET Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hdinsight.v2018_06_01_preview.Clusters listNext" }) @GET Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ClusterInner object if successful. */ public ClusterInner create(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters) { return createWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ClusterInner> createAsync(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters, final ServiceCallback<ClusterInner> serviceCallback) { return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ClusterInner> createAsync(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters) { return createWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<ClusterInner>> createWithServiceResponseAsync(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); Observable<Response<ResponseBody>> observable = service.create(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<ClusterInner>() { }.getType()); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ClusterInner object if successful. */ public ClusterInner beginCreate(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body(); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ClusterInner> beginCreateAsync(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters, final ServiceCallback<ClusterInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ClusterInner> beginCreateAsync(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); } /** * Creates a new HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster create request. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ServiceResponse<ClusterInner>> beginCreateWithServiceResponseAsync(String resourceGroupName, String clusterName, ClusterCreateParametersExtended parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.beginCreate(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ClusterInner>>>() { @Override public Observable<ServiceResponse<ClusterInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ClusterInner> clientResponse = beginCreateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ClusterInner> beginCreateDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ClusterInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ClusterInner>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ClusterInner object if successful. */ public ClusterInner update(String resourceGroupName, String clusterName) { return updateWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body(); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ClusterInner> updateAsync(String resourceGroupName, String clusterName, final ServiceCallback<ClusterInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ClusterInner> updateAsync(String resourceGroupName, String clusterName) { return updateWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ServiceResponse<ClusterInner>> updateWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final Map<String, String> tags = null; ClusterPatchParameters parameters = new ClusterPatchParameters(); parameters.withTags(null); return service.update(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ClusterInner>>>() { @Override public Observable<ServiceResponse<ClusterInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ClusterInner> clientResponse = updateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param tags The resource tags. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ClusterInner object if successful. */ public ClusterInner update(String resourceGroupName, String clusterName, Map<String, String> tags) { return updateWithServiceResponseAsync(resourceGroupName, clusterName, tags).toBlocking().single().body(); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param tags The resource tags. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ClusterInner> updateAsync(String resourceGroupName, String clusterName, Map<String, String> tags, final ServiceCallback<ClusterInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, clusterName, tags), serviceCallback); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param tags The resource tags. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ClusterInner> updateAsync(String resourceGroupName, String clusterName, Map<String, String> tags) { return updateWithServiceResponseAsync(resourceGroupName, clusterName, tags).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); } /** * Patch HDInsight cluster with the specified parameters. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param tags The resource tags. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ServiceResponse<ClusterInner>> updateWithServiceResponseAsync(String resourceGroupName, String clusterName, Map<String, String> tags) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } Validator.validate(tags); ClusterPatchParameters parameters = new ClusterPatchParameters(); parameters.withTags(tags); return service.update(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ClusterInner>>>() { @Override public Observable<ServiceResponse<ClusterInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ClusterInner> clientResponse = updateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ClusterInner> updateDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ClusterInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ClusterInner>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void delete(String resourceGroupName, String clusterName) { deleteWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().last().body(); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> deleteAsync(String resourceGroupName, String clusterName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> deleteAsync(String resourceGroupName, String clusterName) { return deleteWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } Observable<Response<ResponseBody>> observable = service.delete(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginDelete(String resourceGroupName, String clusterName) { beginDeleteWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body(); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String clusterName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginDeleteAsync(String resourceGroupName, String clusterName) { return beginDeleteWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.beginDelete(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginDeleteDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Gets the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ClusterInner object if successful. */ public ClusterInner getByResourceGroup(String resourceGroupName, String clusterName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body(); } /** * Gets the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ClusterInner> getByResourceGroupAsync(String resourceGroupName, String clusterName, final ServiceCallback<ClusterInner> serviceCallback) { return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Gets the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ClusterInner> getByResourceGroupAsync(String resourceGroupName, String clusterName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<ClusterInner>, ClusterInner>() { @Override public ClusterInner call(ServiceResponse<ClusterInner> response) { return response.body(); } }); } /** * Gets the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ClusterInner object */ public Observable<ServiceResponse<ClusterInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.getByResourceGroup(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ClusterInner>>>() { @Override public Observable<ServiceResponse<ClusterInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ClusterInner> clientResponse = getByResourceGroupDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ClusterInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ClusterInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ClusterInner>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Lists the HDInsight clusters in a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ClusterInner&gt; object if successful. */ public PagedList<ClusterInner> listByResourceGroup(final String resourceGroupName) { ServiceResponse<Page<ClusterInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single(); return new PagedList<ClusterInner>(response.body()) { @Override public Page<ClusterInner> nextPage(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Lists the HDInsight clusters in a resource group. * * @param resourceGroupName The name of the resource group. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ClusterInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<ClusterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByResourceGroupSinglePageAsync(resourceGroupName), new Func1<String, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Lists the HDInsight clusters in a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<Page<ClusterInner>> listByResourceGroupAsync(final String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName) .map(new Func1<ServiceResponse<Page<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResponse<Page<ClusterInner>> response) { return response.body(); } }); } /** * Lists the HDInsight clusters in a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<ServiceResponse<Page<ClusterInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) { return listByResourceGroupSinglePageAsync(resourceGroupName) .concatMap(new Func1<ServiceResponse<Page<ClusterInner>>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(ServiceResponse<Page<ClusterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Lists the HDInsight clusters in a resource group. * ServiceResponse<PageImpl<ClusterInner>> * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ClusterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ClusterInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.listByResourceGroup(this.client.subscriptionId(), resourceGroupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ClusterInner>> result = listByResourceGroupDelegate(response); return Observable.just(new ServiceResponse<Page<ClusterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ClusterInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ClusterInner>, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ClusterInner>>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void resize(String resourceGroupName, String clusterName) { resizeWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().last().body(); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> resizeAsync(String resourceGroupName, String clusterName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(resizeWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> resizeAsync(String resourceGroupName, String clusterName) { return resizeWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> resizeWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String roleName = "workernode"; final Integer targetInstanceCount = null; ClusterResizeParameters parameters = new ClusterResizeParameters(); parameters.withTargetInstanceCount(null); Observable<Response<ResponseBody>> observable = service.resize(this.client.subscriptionId(), resourceGroupName, clusterName, roleName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void resize(String resourceGroupName, String clusterName, Integer targetInstanceCount) { resizeWithServiceResponseAsync(resourceGroupName, clusterName, targetInstanceCount).toBlocking().last().body(); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> resizeAsync(String resourceGroupName, String clusterName, Integer targetInstanceCount, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(resizeWithServiceResponseAsync(resourceGroupName, clusterName, targetInstanceCount), serviceCallback); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> resizeAsync(String resourceGroupName, String clusterName, Integer targetInstanceCount) { return resizeWithServiceResponseAsync(resourceGroupName, clusterName, targetInstanceCount).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> resizeWithServiceResponseAsync(String resourceGroupName, String clusterName, Integer targetInstanceCount) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String roleName = "workernode"; ClusterResizeParameters parameters = new ClusterResizeParameters(); parameters.withTargetInstanceCount(targetInstanceCount); Observable<Response<ResponseBody>> observable = service.resize(this.client.subscriptionId(), resourceGroupName, clusterName, roleName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginResize(String resourceGroupName, String clusterName) { beginResizeWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body(); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginResizeAsync(String resourceGroupName, String clusterName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginResizeWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginResizeAsync(String resourceGroupName, String clusterName) { return beginResizeWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginResizeWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String roleName = "workernode"; final Integer targetInstanceCount = null; ClusterResizeParameters parameters = new ClusterResizeParameters(); parameters.withTargetInstanceCount(null); return service.beginResize(this.client.subscriptionId(), resourceGroupName, clusterName, roleName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginResizeDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginResize(String resourceGroupName, String clusterName, Integer targetInstanceCount) { beginResizeWithServiceResponseAsync(resourceGroupName, clusterName, targetInstanceCount).toBlocking().single().body(); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginResizeAsync(String resourceGroupName, String clusterName, Integer targetInstanceCount, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginResizeWithServiceResponseAsync(resourceGroupName, clusterName, targetInstanceCount), serviceCallback); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginResizeAsync(String resourceGroupName, String clusterName, Integer targetInstanceCount) { return beginResizeWithServiceResponseAsync(resourceGroupName, clusterName, targetInstanceCount).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Resizes the specified HDInsight cluster to the specified size. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param targetInstanceCount The target instance count for the operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginResizeWithServiceResponseAsync(String resourceGroupName, String clusterName, Integer targetInstanceCount) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String roleName = "workernode"; ClusterResizeParameters parameters = new ClusterResizeParameters(); parameters.withTargetInstanceCount(targetInstanceCount); return service.beginResize(this.client.subscriptionId(), resourceGroupName, clusterName, roleName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginResizeDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginResizeDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Lists all the HDInsight clusters under the subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ClusterInner&gt; object if successful. */ public PagedList<ClusterInner> list() { ServiceResponse<Page<ClusterInner>> response = listSinglePageAsync().toBlocking().single(); return new PagedList<ClusterInner>(response.body()) { @Override public Page<ClusterInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Lists all the HDInsight clusters under the subscription. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ClusterInner>> listAsync(final ListOperationCallback<ClusterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(), new Func1<String, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Lists all the HDInsight clusters under the subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<Page<ClusterInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResponse<Page<ClusterInner>> response) { return response.body(); } }); } /** * Lists all the HDInsight clusters under the subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<ServiceResponse<Page<ClusterInner>>> listWithServiceResponseAsync() { return listSinglePageAsync() .concatMap(new Func1<ServiceResponse<Page<ClusterInner>>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(ServiceResponse<Page<ClusterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Lists all the HDInsight clusters under the subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ClusterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ClusterInner>>> listSinglePageAsync() { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ClusterInner>> result = listDelegate(response); return Observable.just(new ServiceResponse<Page<ClusterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ClusterInner>> listDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ClusterInner>, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ClusterInner>>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void rotateDiskEncryptionKey(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> rotateDiskEncryptionKeyAsync(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> rotateDiskEncryptionKeyAsync(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { return rotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> rotateDiskEncryptionKeyWithServiceResponseAsync(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); Observable<Response<ResponseBody>> observable = service.rotateDiskEncryptionKey(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginRotateDiskEncryptionKey(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { beginRotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body(); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginRotateDiskEncryptionKeyAsync(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginRotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginRotateDiskEncryptionKeyAsync(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { return beginRotateDiskEncryptionKeyWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Rotate disk encryption key of the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for the disk encryption operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginRotateDiskEncryptionKeyWithServiceResponseAsync(String resourceGroupName, String clusterName, ClusterDiskEncryptionParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.beginRotateDiskEncryptionKey(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginRotateDiskEncryptionKeyDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginRotateDiskEncryptionKeyDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Gets the gateway settings for the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the GatewaySettingsInner object if successful. */ public GatewaySettingsInner getGatewaySettings(String resourceGroupName, String clusterName) { return getGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body(); } /** * Gets the gateway settings for the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<GatewaySettingsInner> getGatewaySettingsAsync(String resourceGroupName, String clusterName, final ServiceCallback<GatewaySettingsInner> serviceCallback) { return ServiceFuture.fromResponse(getGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName), serviceCallback); } /** * Gets the gateway settings for the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the GatewaySettingsInner object */ public Observable<GatewaySettingsInner> getGatewaySettingsAsync(String resourceGroupName, String clusterName) { return getGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<GatewaySettingsInner>, GatewaySettingsInner>() { @Override public GatewaySettingsInner call(ServiceResponse<GatewaySettingsInner> response) { return response.body(); } }); } /** * Gets the gateway settings for the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the GatewaySettingsInner object */ public Observable<ServiceResponse<GatewaySettingsInner>> getGatewaySettingsWithServiceResponseAsync(String resourceGroupName, String clusterName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.getGatewaySettings(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<GatewaySettingsInner>>>() { @Override public Observable<ServiceResponse<GatewaySettingsInner>> call(Response<ResponseBody> response) { try { ServiceResponse<GatewaySettingsInner> clientResponse = getGatewaySettingsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<GatewaySettingsInner> getGatewaySettingsDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<GatewaySettingsInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<GatewaySettingsInner>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void updateGatewaySettings(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { updateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> updateGatewaySettingsAsync(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(updateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> updateGatewaySettingsAsync(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { return updateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> updateGatewaySettingsWithServiceResponseAsync(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); Observable<Response<ResponseBody>> observable = service.updateGatewaySettings(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginUpdateGatewaySettings(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { beginUpdateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body(); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginUpdateGatewaySettingsAsync(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginUpdateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginUpdateGatewaySettingsAsync(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { return beginUpdateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Configures the gateway settings on the specified cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The cluster configurations. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginUpdateGatewaySettingsWithServiceResponseAsync(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.beginUpdateGatewaySettings(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginUpdateGatewaySettingsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginUpdateGatewaySettingsDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void executeScriptActions(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters) { executeScriptActionsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body(); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> executeScriptActionsAsync(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(executeScriptActionsWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> executeScriptActionsAsync(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters) { return executeScriptActionsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> executeScriptActionsWithServiceResponseAsync(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); Observable<Response<ResponseBody>> observable = service.executeScriptActions(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginExecuteScriptActions(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters) { beginExecuteScriptActionsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body(); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginExecuteScriptActionsAsync(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginExecuteScriptActionsWithServiceResponseAsync(resourceGroupName, clusterName, parameters), serviceCallback); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginExecuteScriptActionsAsync(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters) { return beginExecuteScriptActionsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Executes script actions on the specified HDInsight cluster. * * @param resourceGroupName The name of the resource group. * @param clusterName The name of the cluster. * @param parameters The parameters for executing script actions. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginExecuteScriptActionsWithServiceResponseAsync(String resourceGroupName, String clusterName, ExecuteScriptActionParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (clusterName == null) { throw new IllegalArgumentException("Parameter clusterName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.beginExecuteScriptActions(this.client.subscriptionId(), resourceGroupName, clusterName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginExecuteScriptActionsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginExecuteScriptActionsDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Lists the HDInsight clusters in a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ClusterInner&gt; object if successful. */ public PagedList<ClusterInner> listByResourceGroupNext(final String nextPageLink) { ServiceResponse<Page<ClusterInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<ClusterInner>(response.body()) { @Override public Page<ClusterInner> nextPage(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Lists the HDInsight clusters in a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ClusterInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<ClusterInner>> serviceFuture, final ListOperationCallback<ClusterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByResourceGroupNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Lists the HDInsight clusters in a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<Page<ClusterInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResponse<Page<ClusterInner>> response) { return response.body(); } }); } /** * Lists the HDInsight clusters in a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<ServiceResponse<Page<ClusterInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<ClusterInner>>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(ServiceResponse<Page<ClusterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Lists the HDInsight clusters in a resource group. * ServiceResponse<PageImpl<ClusterInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ClusterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ClusterInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ClusterInner>> result = listByResourceGroupNextDelegate(response); return Observable.just(new ServiceResponse<Page<ClusterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ClusterInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ClusterInner>, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ClusterInner>>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Lists all the HDInsight clusters under the subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ClusterInner&gt; object if successful. */ public PagedList<ClusterInner> listNext(final String nextPageLink) { ServiceResponse<Page<ClusterInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<ClusterInner>(response.body()) { @Override public Page<ClusterInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Lists all the HDInsight clusters under the subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ClusterInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<ClusterInner>> serviceFuture, final ListOperationCallback<ClusterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Lists all the HDInsight clusters under the subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<Page<ClusterInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResponse<Page<ClusterInner>> response) { return response.body(); } }); } /** * Lists all the HDInsight clusters under the subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ClusterInner&gt; object */ public Observable<ServiceResponse<Page<ClusterInner>>> listNextWithServiceResponseAsync(final String nextPageLink) { return listNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<ClusterInner>>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(ServiceResponse<Page<ClusterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Lists all the HDInsight clusters under the subscription. * ServiceResponse<PageImpl<ClusterInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ClusterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ClusterInner>>> listNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ClusterInner>>>>() { @Override public Observable<ServiceResponse<Page<ClusterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ClusterInner>> result = listNextDelegate(response); return Observable.just(new ServiceResponse<Page<ClusterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ClusterInner>> listNextDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ClusterInner>, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ClusterInner>>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } }
true
d03f15b4cff98750c0673be4669507e8f7236b5f
Java
prakashsharma91/hazelcast
/src/main/java/com/besidescollege/hazelcast/controller/HazelcastExecutorController.java
UTF-8
898
1.976563
2
[]
no_license
package com.besidescollege.hazelcast.controller; import com.besidescollege.hazelcast.service.HazelcastExecutorService; import com.besidescollege.hazelcast.service.HazelcastNearCacheService; import com.besidescollege.hazelcast.service.HazelcastService; import com.hazelcast.map.IMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class HazelcastExecutorController { private static final Logger LOGGER = LogManager.getLogger(HazelcastExecutorController.class); @Autowired private HazelcastExecutorService hazelcastExecutorService; @PostMapping(value = "/task") public String createData(@RequestParam String task) { hazelcastExecutorService.submitTask(task); return "Success"; } }
true
6b4615647ea2164c72f8c42904ba957e1e8ec38f
Java
orzhtml/react-native-blog-examples
/Chapter10-RNInteractionWithNative/NativeJumpToRN/android/app/src/main/java/com/nativejumptorn/OpenNativeModule.java
UTF-8
902
1.984375
2
[ "MIT" ]
permissive
package com.nativejumptorn; import android.content.Intent; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; /** * Created by arronzhu on 2018/5/3. */ public class OpenNativeModule extends ReactContextBaseJavaModule { private ReactContext mReactContext; public OpenNativeModule(ReactApplicationContext context) { super(context); this.mReactContext = context; } @Override public String getName() { return "OpenNativeModule"; } @ReactMethod public void openNativeVC() { Intent intent = new Intent(); intent.setClass(mReactContext, TestActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mReactContext.startActivity(intent); } }
true
dc45b1252817eb73d0375b6f90699220751b88a2
Java
MohseN16/Social-College
/src/main/java/app/helpers/AuthenticateHelper.java
UTF-8
398
2.34375
2
[]
no_license
package app.helpers; import app.models.Student; public class AuthenticateHelper { public static Student current; public static void isValid() { } public static boolean Authenticated() { if (current == null) { return false; } else { return true; } } public static Student getCurrent() { return current; } }
true
5bbe19232064374343401496e1c1ec34a358456d
Java
adirasmadins/router
/app/src/main/java/asliborneo/router/HistoryRecyclerView/HistoryAdapter.java
UTF-8
1,625
2.265625
2
[]
no_license
//package asliborneo.router.HistoryRecyclerView; // //import android.content.Context; //import android.support.v7.widget.RecyclerView; //import android.view.LayoutInflater; //import android.view.View; //import android.view.ViewGroup; // //import asliborneo.router.R; // // //import java.util.List; // // //public class HistoryAdapter extends RecyclerView.Adapter<asliborneo.router.HistoryRecyclerView.HistoryViewHolders> { // // private List<asliborneo.router.HistoryRecyclerView.HistoryObject> itemList; // private Context context; // // public HistoryAdapter(List<HistoryObject> itemList, Context context) { // this.itemList = itemList; // this.context = context; // } // // @Override // public HistoryViewHolders onCreateViewHolder(ViewGroup parent, int viewType) { // // View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false); // RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); // layoutView.setLayoutParams(lp); // HistoryViewHolders rcv = new HistoryViewHolders(layoutView); // return rcv; // } // // @Override // public void onBindViewHolder(HistoryViewHolders holder, final int position) { // holder.rideId.setText(itemList.get(position).getRideId()); // if(itemList.get(position).getTime()!=null){ // holder.time.setText(itemList.get(position).getTime()); // } // } // @Override // public int getItemCount() { // return this.itemList.size(); // } // //}
true
a52406c50053a42ee6759601727be491f790117f
Java
shuping2wang/springboot
/springboot-api/src/main/java/com/wsp/springboot/api/service/IUserService.java
UTF-8
256
1.859375
2
[]
no_license
package com.wsp.springboot.api.service; import com.wsp.springboot.bean.User; import java.util.List; public interface IUserService { int insetUser(User user); int delUser(String id); int updateUser(User user); List<User> getUserList(); }
true
e8e011602e9ca0493c1c8bc884429a7e06950782
Java
isoundy000/OtherProject
/kj/src/cn/sinobest/framework/service/longtran/ILongProcessCallBack.java
UTF-8
377
1.945313
2
[]
no_license
package cn.sinobest.framework.service.longtran; import cn.sinobest.framework.comm.exception.AppException; import cn.sinobest.framework.comm.iface.IDTO; import java.sql.Connection; import java.sql.SQLException; public abstract interface ILongProcessCallBack<T> { public abstract T doAction(Connection paramConnection, IDTO paramIDTO) throws AppException, SQLException; }
true
5666272e48ff4d01b85710442a28568c9dd4e6b6
Java
JCarballi/ProyectoDPJulio
/ProyectoDPJulio/src/ComparadorPilotoProyectoDestreza.java
ISO-8859-1
539
3.21875
3
[]
no_license
import java.util.*; /** * Clase ComparadorPilotoProyectoDestreza * Comparador para ordenar los pilotos por valor de destreza. * @author Javier Santamara Caballero * @author Juan Jos Carballo Pacheco */ public class ComparadorPilotoProyectoDestreza implements Comparator<Piloto> { @Override public int compare(Piloto p1,Piloto p2) { if(p1.calcularDestrezaPiloto()==p2.calcularDestrezaPiloto()) return 0; else if(p1.calcularDestrezaPiloto()>p2.calcularDestrezaPiloto()) return 1; else return -1; } }
true
63cb61d33278cb36ff143def45a45ad2cd551e0c
Java
liuguofeng719/Community
/app/src/main/java/com/joinsmile/community/bean/OpenDoor.java
UTF-8
460
1.890625
2
[]
no_license
package com.joinsmile.community.bean; import com.google.gson.annotations.SerializedName; /** * Created by lgfcxx on 2017/2/4. */ public class OpenDoor extends BaseInfoVo { @SerializedName("CanBeOpenTheDoor") public boolean canBeOpenTheDoor; public boolean isCanBeOpenTheDoor() { return canBeOpenTheDoor; } public void setCanBeOpenTheDoor(boolean canBeOpenTheDoor) { this.canBeOpenTheDoor = canBeOpenTheDoor; } }
true
e6755f7740f07d587ea163b2650506cda0a1120b
Java
i077/CWRUMapper
/app/src/main/java/edu/cwru/students/cwrumapper/user/DaoLocations.java
UTF-8
562
2.125
2
[]
no_license
package edu.cwru.students.cwrumapper.user; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import java.util.List; import static android.arch.persistence.room.OnConflictStrategy.REPLACE; @Dao public interface DaoLocations { @Query("SELECT * FROM Location") List<Location> getAll(); @Query("SELECT * FROM Location WHERE LocationName = :name") Location getLocation(String name); @Insert(onConflict = REPLACE) void insertAll(Location... locations); }
true