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
14e7692a3826be37f5a83df5ac8b82610e192698
Java
mickaelvy/ENI-encheres
/src/fr/eni/projet1/dal/dao/RetraitDAO.java
UTF-8
287
1.6875
2
[]
no_license
package fr.eni.projet1.dal.dao; import fr.eni.projet1.bo.Retrait; import fr.eni.projet1.dal.DALException; public interface RetraitDAO { public void insertAdresseRetrait(Retrait retrait) throws DALException; public Retrait getRetraitById(int idArticle) throws DALException; }
true
71ea4f79c43ebf4f8cb8a4870aae57633d1cab14
Java
Phantoms007/zhihuAPK
/src/main/java/com/zhihu/android/vessay/read_setting/ReadSettingsCache.java
UTF-8
1,474
1.757813
2
[]
no_license
package com.zhihu.android.vessay.read_setting; import com.secneo.apkwrapper.C6969H; import com.zhihu.android.base.util.p1395a.JsonCache; import com.zhihu.android.vessay.models.TimbreInfo; import java.io.File; import kotlin.Metadata; import kotlin.p2243e.p2245b.C32569u; @Metadata /* renamed from: com.zhihu.android.vessay.read_setting.b */ /* compiled from: ReadSettingsCache.kt */ public final class ReadSettingsCache extends JsonCache<TimbreInfo> { /* renamed from: d */ public static final ReadSettingsCache f92452d = new ReadSettingsCache(); @Override // com.zhihu.android.base.util.p1395a.FusionCache /* renamed from: b */ public int mo71654b() { return 1; } private ReadSettingsCache() { } /* access modifiers changed from: protected */ @Override // com.zhihu.android.base.util.p1395a.FusionCache /* renamed from: a */ public File mo71652a() { return new File(mo84386e(), C6969H.m41409d("G7F86C609BE29942AE70D984DCDF1CADA6B91D0")); } /* renamed from: a */ public final void mo112451a(TimbreInfo timbreInfo) { C32569u.m150519b(timbreInfo, C6969H.m41409d("G7D8AD818AD358227E001")); mo84380a(C6969H.m41409d("G7F86C609BE29942DE308915DFEF1FCC3608ED708BA0FA227E001"), timbreInfo); } /* renamed from: g */ public final TimbreInfo mo112452g() { return (TimbreInfo) mo84384c(C6969H.m41409d("G7F86C609BE29942DE308915DFEF1FCC3608ED708BA0FA227E001")); } }
true
acd4a2ada8a78f84e1cd0643e7f34b067d1dc6a2
Java
INNNOVACIS/SRI-Unsa
/SRIUnsa-web/src/main/java/com/innnovacis/unsa/rest/FondoConsursableRestService.java
UTF-8
2,455
2.1875
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 com.innnovacis.unsa.rest; import com.innnovacis.unsa.business.IFondoConcursableBusiness; import com.innnovacis.unsa.model.SRIFondoConcursable; import com.innnovacis.unsa.util.SRIPaginacionObject; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * * @author innnovacis */ @Path("/fondo") @RequestScoped public class FondoConsursableRestService { @Inject private IFondoConcursableBusiness fondoBusiness; @GET @Path("/listarFondos") @Produces(MediaType.APPLICATION_JSON) public List<SRIFondoConcursable> GetAll(){ return fondoBusiness.GetAll(); } @POST @Path("/paginacionFondoConcursable") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response paginacionFondo(SRIPaginacionObject object) { int total = fondoBusiness.GetTotalPaginacion(object); List<SRIFondoConcursable> lista = fondoBusiness.GetPagina(object); Map<String, Object> responseObj = new HashMap<>(); responseObj.put("total", total); responseObj.put("lista", lista); Response.ResponseBuilder builder = Response.status(Response.Status.OK).entity(responseObj); return builder.build(); } @POST @Path("/registrarFondos") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public int SaveFondo(SRIFondoConcursable fondo){ return fondoBusiness.Insertar(fondo); } @PUT @Path("/updateFondos") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public boolean UpdateFondo(SRIFondoConcursable fondo){ return fondoBusiness.Update(fondo); } @PUT @Path("/deleteFondos") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public boolean DeleteFondo(SRIFondoConcursable fondo){ return fondoBusiness.Delete(fondo); } }
true
b3858ecb0beda8cd0e160614b6a65ac1508a885d
Java
Antonromanovcom/arNote
/src/main/java/com/antonromanov/arnote/bot/BotHandler/EditWishHandler.java
UTF-8
5,912
2.453125
2
[]
no_license
package com.antonromanov.arnote.bot.BotHandler; import com.antonromanov.arnote.bot.userdata.UserData; import com.antonromanov.arnote.bot.userdata.UserGlobalStateafdvsfdcvsedf; import com.antonromanov.arnote.model.ArNoteUser; import com.antonromanov.arnote.services.MainService; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.antonromanov.arnote.bot.Bot.createMessageTemplate; public class EditWishHandler implements BotHandler { private final UserGlobalStateafdvsfdcvsedf MESSAGE_HANDLER_STATE = UserGlobalStateafdvsfdcvsedf.WISH_EDIT; @Override //todo: когда пользак вводит id желания для редактирования нужно проверять что такое желание вообще есть и в случае если нет - выкидывать на начало с соответствующим сообщением public List<PartialBotApiMethod<? extends Serializable>> handleMessage(Update update, MainService dataService, ArNoteUser user) { UserData userData = UserData.getInstance(); Message msg = update.getMessage(); // todo: нужно вынести поиск по введенному тексту в зависимости от статуса в отдельный хендлер if (userData.getState() == UserGlobalStateafdvsfdcvsedf.WISH_EDIT) { //todo: весь этот блок подумать как отрефакторить. Может паттерн какой применить userData.setState(UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRICE); int wishId = Integer.parseInt(msg.getText()); userData.setWishToEdit(dataService.getWishById(wishId).get()); // todo: обработать этот кейс. Если не найдено - то стоп и выходим на /start return printMessage(msg.getChatId().toString(), UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRICE.getReplyMessageText() + " [" + userData.getWishToEdit().getPrice() + "]"); // заменить на formatString %s } else if (userData.getState() == UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRICE) { userData.setState(UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRIOR); userData.getWishToEdit().setPrice(Integer.parseInt(msg.getText())); //todo: проверка что не пустое??? А проверка на число? return printMessage(msg.getChatId().toString(), UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRIOR.getReplyMessageText()); } else if (userData.getState() == UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRIOR) { userData.getWishToEdit().setPriority(Integer.parseInt(msg.getText())); //todo: проверка что не пустое??? А проверка на число? userData.setState(UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DELETE); return printMessage(msg.getChatId().toString(), UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DELETE.getReplyMessageText()); } else if (userData.getState() == UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DELETE) { userData.getWishToEdit().setAc("Y".equals(msg.getText())); userData.setState(UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DONE); return printMessage(msg.getChatId().toString(), UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DONE.getReplyMessageText()); // } else if (userData.getState() == UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DONE) { // return printMessage(msg.getChatId().toString(), UserGlobalStateafdvsfdcvsedf.STOP.getReplyMessageText()); } else { userData.getWishToEdit().setRealized("Y".equals(msg.getText())); userData.setState(UserGlobalStateafdvsfdcvsedf.STOP); //todo: поменять название UserGlobalStateafdvsfdcvsedf dataService.saveWish(userData.getWishToEdit()); userData.clear(); String chatId = msg.getChatId().toString(); Long wishId = userData.getWishToEdit().getId(); String text = "Изменили и сохранили желание с ID " + wishId.toString(); return printMessage(chatId, text ); } } @Override public List<PartialBotApiMethod<? extends Serializable>> handleCallback(Update update, MainService dataService, ArNoteUser user) { UserData userData = UserData.getInstance(); userData.setState(UserGlobalStateafdvsfdcvsedf.WISH_EDIT); return printMessage(update.getCallbackQuery().getMessage().getChatId().toString(), MESSAGE_HANDLER_STATE.getReplyMessageText()); } private List<PartialBotApiMethod<? extends Serializable>> printMessage(String chatId, String text) { SendMessage messageToSend = createMessageTemplate(chatId); messageToSend.setText(text); return Collections.singletonList(messageToSend); } @Override public List<UserGlobalStateafdvsfdcvsedf> operatedBotState() { return Arrays.asList(UserGlobalStateafdvsfdcvsedf.WISH_EDIT, UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DONE, UserGlobalStateafdvsfdcvsedf.WISH_EDIT_DELETE, UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRICE, UserGlobalStateafdvsfdcvsedf.WISH_EDIT_PRIOR); } @Override public List<UserGlobalStateafdvsfdcvsedf> operatedCallBackQuery() { return Collections.singletonList(MESSAGE_HANDLER_STATE); } }
true
3ec775b41e8f9c3770febe4bbabd0ae68c0191af
Java
HamidurRahman1/Generic-Data-Structures
/src/stack/Stack.java
UTF-8
259
2.859375
3
[]
no_license
package stack; import java.util.EmptyStackException; public interface Stack<T> { void push(T element) throws NullPointerException; T pop() throws EmptyStackException; T top() throws EmptyStackException; int size(); boolean isEmpty(); }
true
ca2470e789645d3a9b67343773fd2f746d5c43e7
Java
mycmac/SynUrbApp
/src/java/Tools/DateMethods.java
UTF-8
440
2.875
3
[]
no_license
/** * Classe DataMethod * ---------------------------------------------------------- * Classe pour récupérer la date actuelle */ package Tools; import java.sql.Timestamp; import java.util.Date; public class DateMethods { /** * Renvoi de la data actuelle * * @return Date */ public static Timestamp getCurrentDate() { Date date = new Date(); return new Timestamp(date.getTime()); } }
true
ccb085ca4711a500777ff445f12f5471f50703aa
Java
DeB1998/Security-2---Challenge-3
/src/test/java/it/debsite/rr/test/previous/OldForwardSlicing.java
UTF-8
3,613
2.4375
2
[]
no_license
package it.debsite.rr.test.previous; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Description. * * @author DeB * @version 1.0 2021-04-11 * @since version date */ public class OldForwardSlicing { public static boolean applyForwardSlicing( final List<? extends OldUserToRoleAssignment> userToRoleAssignments, final List<OldCanAssignRule> canAssignRules, final List<? extends OldCanRevokeRule> canRevokeRules, final Set<OldRole> roles ) { final Set<OldRole> fixpoint = OldForwardSlicing.compute( userToRoleAssignments, canAssignRules, roles ); // delete the roles R \ S final Set<OldRole> rMinusS = new HashSet<>(roles); rMinusS.removeAll(fixpoint); boolean changed = roles.retainAll(fixpoint); // R- (R-S) // remove from CA: // - all the rules that include any role in R \ S* in: // - the positive preconditions // - in the target final Iterator<OldCanAssignRule> iterator = canAssignRules.iterator(); while (iterator.hasNext()) { final OldCanAssignRule rule = iterator.next(); boolean toRemove = false; for (final OldRole role : rule.getPreconditions()) { if (rMinusS.contains(role)) { toRemove = true; break; } } toRemove = toRemove || rMinusS.contains(rule.getRoleToAssign()); if (toRemove) { iterator.remove(); changed = true; } else { // remove the roles R \ S* from the negative preconditions of all rules changed |= rule.getNegativePreconditions().removeIf(rMinusS::contains); } } // remove from CR all the rules that mention any role in R \ S* changed |= canRevokeRules.removeIf(role -> rMinusS.contains(role.getRoleToRevoke())); return changed; } private static Set<OldRole> compute( final List<? extends OldUserToRoleAssignment> userToRoleAssignments, final List<OldCanAssignRule> canAssignRules, final Set<OldRole> roles ) { final Set<OldRole> initialSet = new HashSet<>(); for (final OldUserToRoleAssignment u : userToRoleAssignments) { initialSet.addAll(u.getRoles()); } return OldForwardSlicing.fixpoint(initialSet, canAssignRules, roles); } private static Set<OldRole> fixpoint( final Set<OldRole> previous, final List<OldCanAssignRule> canAssignRules, final Set<OldRole> roles ) { final Set<OldRole> newRoles = new HashSet<>(); for (final OldRole role : roles) { if ( // {rt ∈ R | (ra, Rp, Rn,rt) ∈ CA ∧ Rp ∪ {ra} ⊆ Si−1} canAssignRules .stream() .anyMatch( value -> value.getRoleToAssign().equals(role) && previous.containsAll(value.getPreconditions()) && previous.contains(value.getAdministrativeRole()) ) ) { newRoles.add(role); } } if (!previous.addAll(newRoles)) { return previous; } return OldForwardSlicing.fixpoint(previous, canAssignRules, roles); } }
true
2ea794e5e7a7d72e2c2b36d49e491b4c933f9299
Java
pengzhengfa/mitbook-web-flux
/src/main/java/com/mitbook/router/MitbookRouter.java
UTF-8
892
2.03125
2
[]
no_license
package com.mitbook.router; import com.mitbook.controller.MitbookHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; /** * @author pengzhengfa */ @Configuration public class MitbookRouter { @Bean public RouterFunction<ServerResponse> route(MitbookHandler mitbookHandler) { return RouterFunctions .route(RequestPredicates.GET("/getUser").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), mitbookHandler::selectUser); } }
true
9a7b8263a3e337d7694469b9d93551958742b884
Java
GEDS1990/GOM
/src/main/java/com/sqe/gom/web/core/TrainingController.java
UTF-8
9,227
1.945313
2
[]
no_license
/** * SQE SERVICE INC. All right reserved. */ package com.sqe.gom.web.core; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.google.gson.reflect.TypeToken; import com.sqe.gom.app.TrainingService; import com.sqe.gom.constant.HandlerState; import com.sqe.gom.constant.SessionAttr; import com.sqe.gom.model.Experience; import com.sqe.gom.model.Training; import com.sqe.gom.util.JsonUtils; import com.sqe.gom.util.ManagerWord; import com.sqe.gom.util.Page; import com.sqe.gom.util.PageTag; import com.sqe.gom.util.RegexUtil; import com.sqe.gom.vo.JGridBase; import com.sqe.gom.vo.UserGroup; import com.sqe.gom.web.core.expand.JGridHelper; import com.sqe.gom.web.validation.TrainingValidator; /** * @description Training entry report to submit information. * @author <a href="mailto:sqe_ole@126.com">OLE</a> * @date Aug 7, 2011 11:04:25 PM * @version 3.0 */ @Controller public class TrainingController { private Log log = LogFactory.getLog(TrainingController.class); private PrintWriter out; private Map<String, Object> m = new HashMap<String, Object>(); private HandlerState str = HandlerState.FAILED; private TrainingService trainingService; @Autowired public void setTrainingService(TrainingService trainingService) { this.trainingService = trainingService; } @InitBinder protected void initBinder(WebDataBinder binder) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(df,false)); } //培训主页面 @RequestMapping(method = RequestMethod.GET, value = "/app/training.htm") public String trainingPage() { return "app/training"; } /** * 前台培训展现方法 * @param req * @param res */ @RequestMapping(method = RequestMethod.GET, value = "/app/get_trainings.htm") public void getTrainings(HttpServletRequest req, HttpServletResponse res) { JGridHelper<Training> grid = new JGridHelper<Training>(); grid.jgridHandler(req, res, "t."); try { out = res.getWriter(); out.write(JsonUtils.toJson(trainingService.getTrainings(grid), new TypeToken<JGridBase<Training>>() {}.getType(),JsonUtils.SHORT_DATE_PATTERN,true)); } catch (Exception e) { log.error("/app/get_trainings.htm have a error!", e); } finally { if (out != null) {out.flush();out.close();} grid = null; } } /** * 心得体会汇总<分页显示> * @param req * @param res */ @RequestMapping(method = RequestMethod.GET, value = "/app/harvest.htm") public String getExperiences(HttpServletRequest req, HttpServletResponse res, Model model) { Integer pageId = 1; String pid = req.getParameter("pageId"); UserGroup ug = (UserGroup)req.getSession().getAttribute(SessionAttr.USER_TAKEN.name()); if(!RegexUtil.notEmpty(ug)) return "app/list_experience"; if(RegexUtil.notEmpty(pid)) pageId = Integer.parseInt(pid); Page page = new Page(pageId,5); model.addAttribute("list", trainingService.getTrainingAndExperience(ug.getEname(), page)); model.addAttribute("page", PageTag.getPageTag(page, pageId, req.getRequestURL()+"?pageId=")); return "app/list_experience"; } /** * 下载心得成word格式文件 * @param startDate * @param endDate * @param req * @param res * @throws IOException */ @RequestMapping(method = RequestMethod.POST, value = "/app/down_gain.htm") public void downloadGain(@RequestParam("sDate")String startDate,@RequestParam("eDate")String endDate,HttpServletRequest req, HttpServletResponse res) { UserGroup ug = (UserGroup)req.getSession().getAttribute(SessionAttr.USER_TAKEN.name()); String path = req.getSession().getServletContext().getRealPath("/uploads/doc/"); try { List<Experience> list = trainingService.getGain(ug.getEname(), startDate, endDate); if(list.size() > 0) { String str = ""; for(Experience ex : list) { str += ex.getGain()+"\n\n"; } if(RegexUtil.notEmpty(str)) { res.setContentType("application/msword"); res.setHeader("Content-Disposition","attachment;filename = " + ug.getEname()+"心得.doc"); String text = ManagerWord.formatText(req.getSession().getServletContext().getRealPath("/images/browse.jpg"), ug.getEname()+"心得", str, "V-1.0", new Date(), new Date(), ug.getEmail()); String fileName = "/"+UUID.randomUUID().toString().replaceAll("-", "")+ ".doc"; //先把数据写成一个word存起来 ManagerWord.writerWord(path+fileName, text); //下载 ManagerWord.downloadWrod(req, res, fileName); //下载后删除在/doc的临时文件 ManagerWord.deleteWord(path+fileName); } else { res.setContentType("text/html;charset=UTF-8"); res.setHeader("Cache-Control", "no-cache"); } } } catch (Exception e) { log.error("down_gain.htm have a error!", e); } } /** * 前台培训<添加,编辑> * @param training * @param result * @param req * @param res * @param model */ @RequestMapping(method=RequestMethod.POST, value="/app/save_training.htm") public void saveTraining(@ModelAttribute("training") Training training, BindingResult result, HttpServletRequest req, HttpServletResponse res){ res.setContentType("text/html;charset=UTF-8"); res.setHeader("Cache-Control", "no-cache"); UserGroup ug = (UserGroup)req.getSession().getAttribute(SessionAttr.USER_TAKEN.name()); try { out = res.getWriter(); if(RegexUtil.isEmpty(training.getId())) { training.setLecturer(ug.getEname()); } new TrainingValidator().validate(training, result); if(result.hasErrors()) { str = HandlerState.PARAM_EMPTY; } else { trainingService.saveTraining(training); str = HandlerState.SUCCESS; m.put("training", training); } m.put("result", str); out.write(JsonUtils.toJson(m, new TypeToken<Map<String,Object>>() {}.getType())); } catch (IOException e) { m.put("result", HandlerState.ERROR); out.write(JsonUtils.toJson(m, new TypeToken<Map<String,Object>>() {}.getType())); log.error("save_training.htm have a error!", e); }finally { m.clear(); if (out != null) { out.flush(); out.close(); } } } /** * 心得<添加,编辑> * @param training * @param result * @param req * @param res * @param model */ @RequestMapping(method=RequestMethod.POST, value="/app/save_experience.htm") public void saveExperince(@ModelAttribute("experience") Experience experience, BindingResult result, HttpServletRequest req, HttpServletResponse res){ res.setContentType("text/html;charset=UTF-8"); res.setHeader("Cache-Control", "no-cache"); UserGroup ug = (UserGroup)req.getSession().getAttribute(SessionAttr.USER_TAKEN.name()); try { out = res.getWriter(); experience.setStudent(ug.getEname()); trainingService.saveExperienceAndToResource(experience, req.getSession().getServletContext().getRealPath("/images/browse.jpg"), req.getSession().getServletContext().getRealPath("/uploads/doc//")); m.put("g", experience.getGain()); m.put("result", HandlerState.SUCCESS); out.write(JsonUtils.toJson(m, new TypeToken<Map<String,Object>>() {}.getType())); } catch (Exception e) { m.put("result", HandlerState.ERROR); out.write(JsonUtils.toJson(m, new TypeToken<Map<String,Object>>() {}.getType())); log.error("save_experience.htm is error!", e); log.warn("心得:" + experience.getStudent() + " 的心得提交失败!", e); }finally { m.clear(); if (out != null) {out.flush();out.close();} } } /** * 删除培训记录 * @param req * @param res */ @RequestMapping(method = RequestMethod.POST, value = "/app/del_training.htm") public void delTrainings(@RequestParam("id")Integer id, HttpServletResponse res) { try { out = res.getWriter(); trainingService.removeTraining(id); m.put("result", HandlerState.SUCCESS); out.write(JsonUtils.toJson(m, new TypeToken<Map<String,Object>>() {}.getType())); log.debug("删除培训记录:培训记录号" + id + "删除成功!"); } catch (Exception e) { m.put("result", HandlerState.ERROR); out.write(JsonUtils.toJson(m, new TypeToken<Map<String,Object>>() {}.getType())); log.warn("删除培训记录:删除ID号为:" + id + "的操作失败了!", e); } finally { if (out != null) {out.flush();out.close();} } } }
true
cbb52d52e1523758a32c78c749e599cc28a2c6f2
Java
axel-n/testing-cqengine
/src/main/java/com/example/testing_cqengine/RunMockProcessing.java
UTF-8
2,324
2.375
2
[]
no_license
package com.example.testing_cqengine; import com.example.testing_cqengine.data.ExchangeOrder; import com.example.testing_cqengine.data.Status; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; @Slf4j @Component public class RunMockProcessing { @Bean public CommandLineRunner run(SaveOrdersService saveOrdersService) { return (args) -> { List<ExchangeOrder> loadedOrders = emulateLoadOrders(); log.info("loadedOrders size {}", loadedOrders.size()); loadedOrders.forEach(saveOrdersService::save); log.info("data saved"); // IndexedCollection<Order> cachedOrders = new ConcurrentIndexedCollection<>(WrappingPersistence.aroundCollection(loadedOrders)); // cachedOrders.addIndex(UniqueIndex.onAttribute(Order.INTERNAL_ID)); }; } private List<ExchangeOrder> emulateLoadOrders() { List<ExchangeOrder> orders = new ArrayList<>(); for (int i = 0; i < 10_000; i++) { ExchangeOrder order = createNewOrder(); orders.add(order); order.setId(UUID.randomUUID().toString()); order.setUpdatedAt(System.currentTimeMillis()); order.setStatus(Status.PART_FILLED); orders.add(order); order.setId(UUID.randomUUID().toString()); order.setUpdatedAt(System.currentTimeMillis()); order.setStatus(Status.FULL_FILLED); orders.add(order); } return orders; } private ExchangeOrder createNewOrder() { ExchangeOrder order = new ExchangeOrder(); order.setId(UUID.randomUUID().toString()); order.setInternalId(UUID.randomUUID().toString()); order.setExternalId(UUID.randomUUID().toString()); order.setCreateAt(System.currentTimeMillis()); order.setAmount(generateRandomInRange(100, 10_000)); order.setStatus(Status.ACCEPTED); return order; } private double generateRandomInRange(int min, int max) { return new Random().nextDouble() * (max - min) + min; } }
true
05790e426589514223a596c4117ca2d6b9b25605
Java
HiroForYou/archived
/android-v1/app/src/main/java/io/github/prabhuomkar/flare/ui/playground/customviews/DrawingCanvasView.java
UTF-8
1,694
2.59375
3
[ "Apache-2.0" ]
permissive
package io.github.prabhuomkar.flare.ui.playground.customviews; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawingCanvasView extends View { private int mPaintColor = Color.WHITE; private Paint mPaint; private Path mPath = new Path(); public DrawingCanvasView(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); setFocusableInTouchMode(true); setPaint(); } private void setPaint() { mPaint = new Paint(); mPaint.setColor(mPaintColor); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(16); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); } public void resetCanvas() { mPath = new Path(); postInvalidate(); } @Override protected void onDraw(Canvas canvas) { canvas.drawPath(mPath, mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { float pointX = event.getX(); float pointY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mPath.moveTo(pointX, pointY); return true; case MotionEvent.ACTION_MOVE: mPath.lineTo(pointX, pointY); break; default: return false; } postInvalidate(); return true; } }
true
2343fde89d0e2d482425b21850dd343bc39452bf
Java
stofly/taojin
/src/main/java/cn/wmyskxz/service/CarouselImgService.java
UTF-8
315
1.8125
2
[]
no_license
package cn.wmyskxz.service; import cn.wmyskxz.pojo.Carousel; import cn.wmyskxz.pojo.ProductImage; import java.util.List; import org.apache.ibatis.annotations.Param; public interface CarouselImgService { List<Carousel> list(); void save(Carousel carousel); int del(@Param("id")int id); }
true
e54f755d7c68e925dd52b57a507ded862e73d550
Java
KingJoker/HackerRankSolutions
/java/Interview Prep Kit/Graphs/Hard/BFSShortestReachInGraph.java
UTF-8
4,561
4.03125
4
[]
no_license
/* Consider an undirected graph consisting of n nodes where each node is labeled from 1 to n and the edge between any two nodes is always of length 6. We define node s to be the starting position for a BFS. Given a graph, determine the distances from the start node to each of its descendants and return the list in node number order, ascending. If a node is disconnected, it's distance should be -1. For example, there are n=6 nodes in the graph with a starting node s=1. The list of edges=[[1,2],[2,3],[3,4][1,5]], and each has a weight of 6. 6 2 - 3 - 4 / 1 \ 5 Starting from node 1 and creating a list of distances, for nodes 2 through 6 we have distances=[6,12,18,6,-1]. *Function Description Define a Graph class with the required methods to return a list of distances. *Input Format The first line contains an integer, q, the number of queries. Each of the following q sets of lines is as follows: The first line contains two space-separated integers, n and m, the number of nodes and the number of edges. Each of the next m lines contains two space-separated integers, u and v, describing an edge connecting node u to node v. The last line contains a single integer, s, the index of the starting node. *Constraints 1<=q<=10 2<=n<=1000 1<=m<=(n*(n-1))/2 1<=u,v,s<=n *Output Format For each of the q queries, print a single line of n-1 space-separated integers denoting the shortest distances to each of the n-1 other nodes from starting position s. These distances should be listed sequentially by node number (i.e., 1,2,...,n), but should not include node s. If some node is unreachable from , print -1 as the distance to that node. *Sample Input 2 4 2 1 2 1 3 1 3 1 2 3 2 *Sample Output 6 6 -1 -1 6 *Explanation We perform the following two queries: 1.The given graph can be represented as: 1 4 / \ 2 3 where our start node, s, is node 1. The shortest distances from s to the other nodes are one edge to node 2, one edge to node 3, and there is no connection to node 4. 2.The given graph can be represented as: 1 2 | 3 where our start node, s, is node 2. There is only one edge here, so node 1 is unreachable from node2 and node 3 has one edge connecting it to node 2. We then print node 2's distance to nodes 1 and 3 (respectively) as a single line of space-separated integers: -1 6. Note: Recall that the actual length of each edge is 6, and we print -1 as the distance to any node that's unreachable from s. */ package Graphs.Hard; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; public class BFSShortestReachInGraph { private static class Node{ int index; int distance; boolean visited; ArrayList<Node> children; public Node(int index){ this.index = index; distance = -1; visited = false; children = new ArrayList<>(); } } public static void BFS(ArrayList<Node> nodes, int startNode){ Node current = nodes.get(startNode); current.distance = 0; current.visited = true; LinkedList<Node> queue = new LinkedList<>(); queue.offer(current); do{ current = queue.poll(); for(Node child : current.children){ if(!child.visited){ queue.offer(child); child.distance = current.distance + 6; child.visited = true; } } }while(queue.size() != 0); for(int i = 0; i < nodes.size(); i++){ if(i != startNode){ System.out.print(nodes.get(i).distance + " "); } } System.out.println(); } public static void main(String[] args){ Scanner input = new Scanner(System.in); int q = input.nextInt(); for(int i = 0; i < q; i++){ int numNodes = input.nextInt(); ArrayList<Node> nodes = new ArrayList<>(); for(int n = 0; n < numNodes; n++){ nodes.add(new Node(n)); } int numEdges = input.nextInt(); for(int e = 0; e < numEdges; e++){ int index1 = input.nextInt() - 1; int index2 = input.nextInt() - 1; Node node1 = nodes.get(index1); Node node2 = nodes.get(index2); node1.children.add(node2); node2.children.add(node1); } int start = input.nextInt() - 1; BFS(nodes,start); } } }
true
f78af141c5ae45c7ed8f00f0085e6c570f6e1ff0
Java
ATPod/nc-training
/SO-WebApp-shop/src/main/java/by/training/nc/dev5/entity/Product.java
UTF-8
1,695
2.734375
3
[]
no_license
package by.training.nc.dev5.entity; import javax.persistence.*; import java.util.List; @NamedQueries( {@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")} ) @Entity public class Product extends AbstractEntity{ private String title; private int price; private List <Ordering> orderings; @Basic @Column(name = "title", nullable = false, length = 50) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Basic @Column(name = "price", nullable = false) public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @ManyToMany @JoinTable(name="ordering_product", joinColumns=@JoinColumn(name="idProduct", referencedColumnName="ID"), inverseJoinColumns=@JoinColumn(name="idOrdering", referencedColumnName="ID")) public List <Ordering> getOrderings() { return orderings; } public void setOrderings(List <Ordering> orderings) { this.orderings = orderings; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Product product = (Product) o; if (getPrice() != product.getPrice()) return false; return getTitle().equals(product.getTitle()); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + getTitle().hashCode(); result = 31 * result + getPrice(); return result; } }
true
acc6c65f31603ecae49385c7882cb908ac36f3c5
Java
KedoKudo/ISAW
/EventTools/ShowEventsApp/Command/IndexedPeaksFilterCmd.java
UTF-8
796
2.703125
3
[]
no_license
package EventTools.ShowEventsApp.Command; public class IndexedPeaksFilterCmd { private String IndexedPeakFile; private boolean FilterNonIndexedPeaks; public IndexedPeaksFilterCmd(String IndexedPeakFile, boolean FilterNonIndexedPeaks) { this.IndexedPeakFile = IndexedPeakFile; this.FilterNonIndexedPeaks = FilterNonIndexedPeaks; } public String getIndexedPeakFile() { return IndexedPeakFile; } public boolean isFilterNonIndexedPeaks() { return FilterNonIndexedPeaks; } public String toString() { return "\nIndex Peak File : " + getIndexedPeakFile() + "\nFilter Non Indexed Peaks : " + isFilterNonIndexedPeaks(); } }
true
781f8ae4139d0b7a1fccec25985ca65d9b4c80aa
Java
pandruszewski/epc
/epubChecker/src/com/adobe/epubcheck/ocf/OCFChecker.java
UTF-8
8,209
1.554688
2
[]
no_license
/* * Copyright (c) 2007 Adobe Systems Incorporated * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.adobe.epubcheck.ocf; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import com.adobe.epubcheck.api.Report; import com.adobe.epubcheck.opf.OPFChecker; import com.adobe.epubcheck.opf.OPFChecker30; import com.adobe.epubcheck.opf.OPFData; import com.adobe.epubcheck.util.CheckUtil; import com.adobe.epubcheck.util.EPUBVersion; import com.adobe.epubcheck.util.InvalidVersionException; import com.adobe.epubcheck.util.OPSType; import com.adobe.epubcheck.xml.XMLHandler; import com.adobe.epubcheck.xml.XMLParser; import com.adobe.epubcheck.xml.XMLValidator; import com.adobe.epubcheck.util.DefaultReportImpl; public class OCFChecker { OCFPackage ocf; Report report; // Hashtable encryptedItems; // private EPUBVersion version = EPUBVersion.VERSION_3; static XMLValidator containerValidator = new XMLValidator( "schema/20/rng/container.rng"); static XMLValidator encryptionValidator = new XMLValidator( "schema/20/rng/encryption.rng"); static XMLValidator signatureValidator = new XMLValidator( "schema/20/rng/signatures.rng"); static XMLValidator containerValidator30 = new XMLValidator( "schema/30/ocf-container-30.rnc"); static XMLValidator encryptionValidator30 = new XMLValidator( "schema/30/ocf-encryption-30.rnc"); static XMLValidator signatureValidator30 = new XMLValidator( "schema/30/ocf-signatures-30.rnc"); private static HashMap<OPSType, XMLValidator> xmlValidatorMap; static { HashMap<OPSType, XMLValidator> map = new HashMap<OPSType, XMLValidator>(); map.put(new OPSType(OCFData.containerEntry, EPUBVersion.VERSION_2), containerValidator); map.put(new OPSType(OCFData.containerEntry, EPUBVersion.VERSION_3), containerValidator30); map.put(new OPSType(OCFData.encryptionEntry, EPUBVersion.VERSION_2), encryptionValidator); map.put(new OPSType(OCFData.encryptionEntry, EPUBVersion.VERSION_3), encryptionValidator30); map.put(new OPSType(OCFData.signatureEntry, EPUBVersion.VERSION_2), signatureValidator); map.put(new OPSType(OCFData.signatureEntry, EPUBVersion.VERSION_3), signatureValidator30); xmlValidatorMap = map; } public OCFChecker(OCFPackage ocf, Report report) { this.ocf = ocf; this.report = report; } public void runChecks() { String rootPath; if (!ocf.hasEntry(OCFData.containerEntry)) { report.error(null, 0, 0, "Required META-INF/container.xml resource is missing"); return; } OCFData containerHandler = ocf.getOcfData(report); // retrieve rootpath rootPath = containerHandler.getRootPath(); if (rootPath != null) { if (ocf.hasEntry(rootPath)) { InputStream mimetype = null; try { OPFData opfHandler = ocf.getOpfData(containerHandler, report); System.out.println("Validating against EPUB version " + opfHandler.getVersion()); DefaultReportImpl.ePubVersion = opfHandler.getVersion().toString(); // checking mimeType file for trailing spaces mimetype = ocf.getInputStream("mimetype"); if (ocf.hasEntry("mimetype") && !CheckUtil.checkTrailingSpaces(mimetype, opfHandler.getVersion())) report.error("mimetype", 0, 0, "Mimetype file should contain only the string \"application/epub+zip\"."); // validate ocf files against the schema definitions validate(opfHandler.getVersion()); // check the root file itself. OPFChecker opfChecker; if (opfHandler.getVersion() == EPUBVersion.VERSION_2) { opfChecker = new OPFChecker(ocf, report, rootPath, containerHandler.getContainerEntries(), opfHandler.getVersion()); } else opfChecker = new OPFChecker30(ocf, report, rootPath, containerHandler.getContainerEntries(), opfHandler.getVersion()); opfChecker.runChecks(); } catch (InvalidVersionException e) { report.error(rootPath, -1, -1, e.getMessage()); } catch (IOException ignore) { // missing file will be reported in OPFChecker } finally { try { mimetype.close(); } catch (Exception e) { // TODO: handle exception } } } else { // ocf.hasEntry(rootPath) report.error(OCFData.containerEntry, -1, -1, "entry " + rootPath + " not found in zip file"); } } else { report.error(OCFData.containerEntry, -1, -1, "No rootfiles with media type 'application/oebps-package+xml'"); } } public boolean validate(EPUBVersion version) { XMLParser parser = null; InputStream in = null; try { // validate container in = ocf.getInputStream(OCFData.containerEntry); parser = new XMLParser(in, OCFData.containerEntry, "xml", report, version); XMLHandler handler = new OCFHandler(parser); parser.addXMLHandler(handler); parser.addValidator(xmlValidatorMap.get(new OPSType( OCFData.containerEntry, version))); parser.process(); try { in.close(); } catch (Exception e) { } // Validate encryption.xml if (ocf.hasEntry(OCFData.encryptionEntry)) { in = ocf.getInputStream(OCFData.encryptionEntry); parser = new XMLParser(in, OCFData.encryptionEntry, "xml", report, version); handler = new EncryptionHandler(ocf, parser); parser.addXMLHandler(handler); parser.addValidator(xmlValidatorMap.get(new OPSType( OCFData.encryptionEntry, version))); parser.process(); try { in.close(); } catch (Exception e) { } } // validate signatures.xml if (ocf.hasEntry(OCFData.signatureEntry)) { in = ocf.getInputStream(OCFData.signatureEntry); parser = new XMLParser(in, OCFData.signatureEntry, "xml", report, version); handler = new OCFHandler(parser); parser.addXMLHandler(handler); parser.addValidator(xmlValidatorMap.get(new OPSType( OCFData.signatureEntry, version))); parser.process(); try { in.close(); } catch (Exception e) { } } } catch (Exception ignore) { } finally { try { in.close(); } catch (Exception e) { } } return false; } /** * This method processes the rootPath String and returns the base path to * the directory that contains the OPF content file. * * @param rootPath * path+name of OPF content file * @return String containing path to OPF content file's directory inside ZIP */ public String processRootPath(String rootPath) { String rootBase = rootPath; if (rootPath.endsWith(".opf")) { int slash = rootPath.lastIndexOf("/"); if (slash < rootPath.lastIndexOf("\\")) slash = rootPath.lastIndexOf("\\"); if (slash >= 0 && (slash + 1) < rootPath.length()) rootBase = rootPath.substring(0, slash + 1); else rootBase = rootPath; return rootBase; } else { System.out.println("RootPath is not an OPF file"); return null; } } }
true
89b4423b235e3a612c146f131d2f902e2d11cba9
Java
intel-secl/key-broker-service
/features/kms-user-api/src/test/java/com/intel/kms/user/jaxrs2/CreateUserRequest.java
UTF-8
432
1.671875
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2019 Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ package com.intel.kms.user.jaxrs2; import com.intel.kms.user.User; /** * * @author jbuhacoff */ public class CreateUserRequest extends AbstractRequest { private User create; public CreateUserRequest() { super(); } public CreateUserRequest(User create) { super(); this.create = create; } }
true
01834e8394646bf39feb9e45cee3b8519eb3cf61
Java
batmaninlondon/MoneyBuddy
/MoneyBuddy/src/com/myMoneyBuddy/ModelClasses/DbfStatusDataModel.java
UTF-8
878
2.34375
2
[]
no_license
package com.myMoneyBuddy.ModelClasses; import java.io.Serializable; public class DbfStatusDataModel implements Serializable{ private String dbfDataDate; private String rta; private String dbfFileType; public DbfStatusDataModel() { } public DbfStatusDataModel(String dbfDataDate, String rta, String dbfFileType) { super(); this.dbfDataDate = dbfDataDate; this.rta = rta; this.dbfFileType = dbfFileType; } public String getDbfDataDate() { return dbfDataDate; } public void setDbfDataDate(String dbfDataDate) { this.dbfDataDate = dbfDataDate; } public String getRta() { return rta; } public void setRta(String rta) { this.rta = rta; } public String getDbfFileType() { return dbfFileType; } public void setDbfFileType(String dbfFileType) { this.dbfFileType = dbfFileType; } }
true
0e53e4b4842c8712f9406cf505bff66ffbc1a857
Java
ybak/kickass
/kickass-lordofpomelo-web/src/main/java/org/kickass/web/vo/HomeResponse.java
UTF-8
1,093
2.328125
2
[]
no_license
package org.kickass.web.vo; import com.google.gson.Gson; public class HomeResponse { private static final Gson gson = new Gson(); public static final String ERROR_500 = new HomeResponse(500).toString(); public static final String ERROR_501 = new HomeResponse(501).toString(); private int code; private String token; private Long uid; public HomeResponse() { } public HomeResponse(int code) { this.code = code; } public HomeResponse(int code, String token, Long uid) { this.code = code; this.token = token; this.uid = uid; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Long getUid() { return uid; } public void setUid(Long uid) { this.uid = uid; } @Override public String toString() { return gson.toJson(this); } }
true
b5096b8a14dbfaadf9c92a12515d01d1c785d4e7
Java
xijunli824/mediacorp_spelling_game_android
/MediaCorpSpellingGame/app/src/main/java/com/media2359/mediacorpspellinggame/game/typeE/TypeEGameFragment.java
UTF-8
8,928
2.125
2
[]
no_license
package com.media2359.mediacorpspellinggame.game.typeE; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.media2359.mediacorpspellinggame.R; import com.media2359.mediacorpspellinggame.factory.GameProgressManager; import com.media2359.mediacorpspellinggame.game.GameActivity; import com.media2359.mediacorpspellinggame.utils.CommonUtils; import com.media2359.mediacorpspellinggame.widget.PasswordDialogFragment; import com.media2359.mediacorpspellinggame.widget.SecondsClockView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by xijunli on 13/2/17. */ public class TypeEGameFragment extends Fragment { private static final int QUESTION_SCORE = 10; @BindView(R.id.tvQuestionCount) TextView tvQuestionCount; @BindView(R.id.tvCurrentScore) TextView tvCurrentScore; @BindView(R.id.tvCurrentScoreText) TextView tvCurrentScoreText; @BindView(R.id.clockView) SecondsClockView clockView; @BindView(R.id.tvResultInstruction) TextView tvResultInstruction; @BindView(R.id.etAnswer) EditText etAnswer; @BindView(R.id.btnNext) Button btnNext; @BindView(R.id.flScoreCard) FrameLayout flScoreCard; @BindView(R.id.tvCardScore) TextView tvCardScore; @BindView(R.id.tvCardTime) TextView tvCardTime; @BindView(R.id.tvSectionScoreText) TextView tvSectionScoreText; @BindView(R.id.tvSectionTimeText) TextView tvSectionTimeText; @BindView(R.id.btnSubmit) Button btnSubmit; @BindView(R.id.logo) ImageView logo; @BindView(R.id.btnEdit) Button btnEdit; @BindView(R.id.btnCorrect) Button btnCorrect; @BindView(R.id.btnWrong) Button btnWrong; private boolean gameHasEnded = false; int timeTaken; int MAX_TIME; int sectionScore; public static TypeEGameFragment newInstance() { Bundle args = new Bundle(); TypeEGameFragment fragment = new TypeEGameFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MAX_TIME = ((GameActivity) getActivity()).getCurrentSectionTime(); timeTaken = MAX_TIME; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_game_5, container, false); ButterKnife.bind(this, root); return root; } private void initViews() { clockView.setTimeListener(new SecondsClockView.TimeListener() { @Override public void onSecond(long seconds) { if (seconds == MAX_TIME - 8) clockView.showAlertClock(); if (seconds >= MAX_TIME) { onTimeExpired(); } } }); tvResultInstruction.setVisibility(View.INVISIBLE); tvCurrentScore.setText(String.valueOf(GameProgressManager.getInstance().getTotalScore())); int qid = GameProgressManager.getInstance().getLastAttemptedQuestionPos() + 1; String questionCount = CommonUtils.getQuestionCountString(getActivity(), qid, ((GameActivity) getActivity()).getCurrentGame().getQuestionCount()); tvQuestionCount.setText(questionCount); String gameType = ((GameActivity) getActivity()).getCurrentGame().getType(); String sectionScoreText = "அங்கம் " + gameType + " - புள்ளிகள்"; String sectionTimeText = "அங்கம் " + gameType + " - நேரம்"; tvSectionScoreText.setText(sectionScoreText); tvSectionTimeText.setText(sectionTimeText); showPlayView(); } private void onTimeExpired() { clockView.pause(); onErrorClick(); gameHasEnded = true; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); etAnswer.requestFocus(); InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(etAnswer, InputMethodManager.SHOW_IMPLICIT); initViews(); } @Override public void onResume() { super.onResume(); if (!gameHasEnded) clockView.resume(); } private void showJudgeView() { btnSubmit.setVisibility(View.GONE); btnNext.setVisibility(View.GONE); btnCorrect.setClickable(true); btnWrong.setClickable(true); btnCorrect.setVisibility(View.VISIBLE); btnWrong.setVisibility(View.VISIBLE); btnEdit.setVisibility(View.GONE); clockView.setVisibility(View.VISIBLE); flScoreCard.setVisibility(View.GONE); tvCurrentScore.setVisibility(View.VISIBLE); tvCurrentScoreText.setVisibility(View.VISIBLE); logo.setVisibility(View.VISIBLE); } private void showPlayView() { btnSubmit.setVisibility(View.VISIBLE); btnNext.setVisibility(View.GONE); btnCorrect.setVisibility(View.GONE); btnWrong.setVisibility(View.GONE); btnCorrect.setClickable(false); btnWrong.setClickable(false); btnEdit.setVisibility(View.GONE); clockView.setVisibility(View.VISIBLE); flScoreCard.setVisibility(View.GONE); tvCurrentScore.setVisibility(View.VISIBLE); tvCurrentScoreText.setVisibility(View.VISIBLE); logo.setVisibility(View.VISIBLE); } private void showScoreView() { btnCorrect.setClickable(false); btnWrong.setClickable(false); clockView.setVisibility(View.GONE); flScoreCard.setVisibility(View.VISIBLE); tvCurrentScore.setVisibility(View.GONE); tvCurrentScoreText.setVisibility(View.GONE); int gameId = ((GameActivity) getActivity()).getCurrentGame().getGameId(); String sectionScoreText = String.valueOf(GameProgressManager.getInstance().getSectionScore(gameId) + sectionScore); String sectionTimeText = String.valueOf(GameProgressManager.getInstance().getSectionTime(gameId) + timeTaken); tvCardScore.setText(sectionScoreText); tvCardTime.setText(sectionTimeText); btnSubmit.setVisibility(View.GONE); btnNext.setVisibility(View.VISIBLE); btnEdit.setVisibility(View.VISIBLE); logo.setVisibility(View.INVISIBLE); } @OnClick(R.id.btnWrong) public void onErrorClick() { btnCorrect.setClickable(false); btnWrong.setClickable(false); tvResultInstruction.setVisibility(View.VISIBLE); tvResultInstruction.setText(getString(R.string.game_a_error)); sectionScore = 0; showScoreView(); } @OnClick(R.id.btnCorrect) public void onCorrect() { btnCorrect.setClickable(false); btnWrong.setClickable(false); tvResultInstruction.setVisibility(View.VISIBLE); tvResultInstruction.setText(getString(R.string.game_a_correct)); sectionScore = QUESTION_SCORE; showScoreView(); } @OnClick(R.id.btnNext) public void onNextClick() { // update the section score/time GameProgressManager.getInstance().increaseSectionScore(getActivity(), sectionScore); GameProgressManager.getInstance().increaseSectionTime(getActivity(), timeTaken); ((GameActivity) getActivity()).showNextQuestion(); } @OnClick(R.id.btnSubmit) public void onSubmitClick() { timeTaken = (int) clockView.getElapsedTime(); clockView.pauseAnimationOnly(); btnSubmit.setEnabled(false); etAnswer.setEnabled(false); gameHasEnded = true; showJudgeView(); } @OnClick(R.id.btnEdit) public void onEditClick() { showPasswordDialog(); } private void showPasswordDialog() { CommonUtils.showPasswordDialogFragment(getChildFragmentManager(), new PasswordDialogFragment.PasswordListener() { @Override public void onPasswordMatch() { showJudgeView(); } }); } @Override public void onPause() { super.onPause(); if (!gameHasEnded) clockView.pauseAndSync(); } @Override public void onDestroyView() { super.onDestroyView(); clockView.pause(); } }
true
33db4a9ba37c8b82ac420046a11e763d1137e7f0
Java
yixuan163/springbootdemo
/progress/src/main/java/com/huawei/progress/mapper/UserMapper.java
UTF-8
178
1.898438
2
[]
no_license
package com.huawei.springbootdemo.mapper; import com.huawei.springbootdemo.bean.UserBean; public interface UserMapper { UserBean getInfo(String name, String password); }
true
d68b063eaedc16ce7b0eb93093d973b9470d2718
Java
daniel-gheorghian/survive
/src/main/java/fp_prez/fp_principles/ImmutableDemo.java
UTF-8
869
3.46875
3
[]
no_license
package fp_prez.fp_principles; public class ImmutableDemo { public class Person { //immutable - use final! private final int cnp; //mandatory private final String name; //optional on build //mutable state private int age = 0; public Person( int cnp, int age ) { this( cnp, "unknown", age ); } public Person( int cnp, String name, int age ) { this.cnp = cnp; this.name = name; this.age = age; } public int getCnp( ) { return cnp; } public String getName( ) { return name; } public int getAge( ) { return age; } public void setAge( int age ) { this.age = age; } } }
true
d6bd8a0a0628a8862ef2f702fbe46f345ebdf2b8
Java
gokter/Java8
/src/test/java/com/flyingh/demo/PCDemo.java
UTF-8
1,755
3.359375
3
[]
no_license
package com.flyingh.demo; import java.util.Random; import java.util.stream.IntStream; public class PCDemo { private static final int COUNT = 10; public static void main(String[] args) { final Data data = new Data(); new Thread(new Producer(data)).start(); new Thread(new Consumer(data)).start(); } static class Producer implements Runnable { private final Data data; public Producer(Data data) { super(); this.data = data; } @Override public void run() { IntStream.range(0, COUNT).forEach(i -> data.put(Math.round(Math.random() * 100))); } } static class Consumer implements Runnable { private final Data data; public Consumer(Data data) { super(); this.data = data; } @Override public void run() { IntStream.range(0, COUNT).forEach(i -> data.take()); } } static class Data { private boolean empty = true; private Object value; synchronized void put(long value) { while (!empty) { System.out.println("waiting to put..."); try { Thread.sleep(new Random().nextInt(5000)); wait(); } catch (final InterruptedException e) { e.printStackTrace(); } } this.value = value; System.out.println("put the data :" + value); empty = false; notifyAll(); } synchronized Object take() { while (empty) { System.out.println("waiting to take..."); try { Thread.sleep(new Random().nextInt(3000)); wait(); } catch (final InterruptedException e) { e.printStackTrace(); } } final Object result = value; System.out.println("take the data :" + value); value = null; empty = true; notifyAll(); return result; } } }
true
69547441b0db8d4c572d916dcb3156c70a24430e
Java
philipparndt/jsolid
/src/test/java/org/testory/TestoryAssertionError.java
UTF-8
317
2.078125
2
[ "Apache-2.0" ]
permissive
package org.testory; public class TestoryAssertionError extends AssertionError { public TestoryAssertionError() {} public TestoryAssertionError(String message) { super(message); } public static TestoryAssertionError assertionError(String message) { return new TestoryAssertionError(message); } }
true
262653641ac93dcd83f8830218ccc0b047bf948b
Java
RamiRozenblium/WaterManagerModule
/src/main/java/com/domain/Tank.java
UTF-8
957
2.828125
3
[]
no_license
package com.domain; import java.math.BigDecimal; import java.math.RoundingMode; public class Tank { int id; BigDecimal currentVolume; BigDecimal maxVolume; public int getId() { return id; } public void setId(int id) { this.id = id; } public BigDecimal getCurrentVolume() { return currentVolume; } public void setCurrentVolume(BigDecimal currentVolume) { this.currentVolume = currentVolume; } public BigDecimal getMaxVolume() { return maxVolume; } public void setMaxVolume(BigDecimal maxVolume) { this.maxVolume = maxVolume; } public Tank(int id, BigDecimal maxVolume) { this.id = id; this.currentVolume = BigDecimal.ZERO; this.maxVolume = maxVolume; } public void leak() { if (BigDecimal.ZERO.compareTo(currentVolume) > -1) { currentVolume = BigDecimal.ZERO; } else { currentVolume = currentVolume .subtract(BigDecimal.ONE.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP)); } } }
true
5367e4c07231732a26ed6ba42ff24a45d2cd5487
Java
jorge190588/springBase
/student_web/src/com/student/tools/DataResponse.java
UTF-8
861
2.28125
2
[]
no_license
package com.student.tools; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import org.codehaus.jackson.map.ObjectMapper; import com.student.entities.ListStudent; import com.student.entities.Student; /** * @author jorge * */ @SuppressWarnings({"rawtypes","unchecked"}) public class DataResponse<T>{ private T data; private T pagination; public DataResponse(Object object){ LinkedHashMap objectMap = (LinkedHashMap)object; this.data = (T) objectMap.get("data"); this.pagination = (T) objectMap.get("pagination"); } public T getData() { return this.data; } public void setData(T _data) { this.data=_data; } public Object getPagination() { return this.pagination; } public void setPagination(T _pagination) { this.pagination=_pagination; } }
true
748127c1487a0e2caa9bcce880ffe5631ad3a8ba
Java
bc5g15/Space05_BoneIDLE2
/src/instructions/Instruction.java
UTF-8
1,716
3.25
3
[]
no_license
package instructions; import bonereader.UIHandler; import java.util.ArrayList; import bonereader.Reader; /* * My abstract parent Instruction class * Holds all the commands I think every instruction will need */ public abstract class Instruction { protected int instNum; protected String instruction; private ArrayList<String> args; public Instruction(int instNum, String instruction) { this.instNum = instNum; this.instruction = instruction.trim(); this.args = new ArrayList<String>(); populateArgs(); Reader.addInstruction(this); } private void populateArgs() { String[] temp = instruction.split(" "); for(int i = 1; i<temp.length; i++) { args.add(temp[i]); } } /* * Returns arguments if they exist. * Remember, each class is going to have to error check for null arguments. */ protected String getArg(int num) { if(args.size() > num) { return args.get(num); } else { UIHandler.highlightError(instNum); return null; } } protected String[] getArgs() { String[] temp = instruction.split(" "); //The output array is always going to have 1 less value. String[] output = new String[temp.length-1]; for(int x = 1; x<temp.length; x++) { output[x-1] = temp[x]; } return output; } //Each instruction is responsible for highlighting itself. //Sort of. It just hands it off to the HighlightHandler public void highlightInst() { UIHandler.highlightInstruction(instNum); } //If there is a problem, highlight the bad code public void highlightError() { UIHandler.highlightError(instNum); } abstract public void execute(); }
true
fc0ac7d512e3e93a8a9957a111ace07d3e6cc57a
Java
hillionlane/buy
/src/main/java/com/my/buy/dao/ProductCategoryDao.java
UTF-8
1,959
2.28125
2
[]
no_license
package com.my.buy.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.my.buy.entity.ProductCategory; public interface ProductCategoryDao { /** * F1:根据查询条件查找商品类别 * 参数为一个商品类,根据这个类的父类有无来进行相应条件的查找 * @param productCategoryCondition * @return */ public List<ProductCategory> queryProductCategoryList(@Param("productCategoryCondition")ProductCategory productCategoryCondition,@Param("rowIndex")int rowIndex,@Param("pageSize") int pageSize); public int queryproductCategoryCount(@Param("productCategoryCondition")ProductCategory productCategoryCondition); /** * F1:查询全部的商品类别 */ public List<ProductCategory> queryAllProductCategoryList(@Param("rowIndex")int rowIndex,@Param("pageSize") int pageSize); public int queryAllProductCategoryCount(); /** * F2:根据商品类别Id查询商品 * @param ProductCategory * @return */ ProductCategory queryProductCategoryById(long productCategoryId); /** * F3:根据商品类别Id列表查询list * @param productCategoryIdList * @return */ List<ProductCategory> queryProductCategoryByIds(List<Long> productCategoryIdList); int queryProductCategoryListCount(List<Long> productCategoryIdList); /** * F4:插入商品类别 * @param productCategory * @return */ int insertProductCategory(ProductCategory productCategory); /** * F5:修改商品类别 * @param productCategory * @return */ int updateProductCategory(ProductCategory productCategory); /** * F6:删除商品类别 * @param productCategoryId * @return */ int deleteProductCategory(long productCategoryId); /** * F7:批量删除商品类别 * @param productCategoryIdList * @return */ int batchDeleteProductCategory(List<Long> productCategoryIdList); }
true
c5154b0605dadc3ba640823d6e38835331795124
Java
Prince-Shaikh/Inventario
/Inventory Management System/src/com/inventoryManagementSystem/ProductScreen.java
UTF-8
11,069
2.375
2
[]
no_license
package com.inventoryManagementSystem; import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import java.awt.Color; import java.awt.Dimension; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.JTextArea; import java.awt.Component; import javax.swing.JScrollPane; import javax.swing.JTable; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ArrayList; public class ProductScreen extends JFrame implements ActionListener{ /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField textFieldId; private JTextField textFieldName; private JTextField textFieldPrice; private JTextArea textAreaDiscription; private JTable table; private JTextField textFieldSearch; /** * Create the frame. */ public ProductScreen() { setTitle("Product"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 1280, 720); this.setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBackground(new Color(255, 140, 0)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); JPanel panel = new JPanel(); panel.setBackground(new Color(255, 140, 0)); panel.setPreferredSize(new Dimension(450,720)); contentPane.add(panel, BorderLayout.WEST); panel.setLayout(null); JLabel lblProducts = new JLabel("Products"); lblProducts.setBounds(148, 58, 153, 31); lblProducts.setAlignmentX(Component.CENTER_ALIGNMENT); lblProducts.setForeground(Color.WHITE); lblProducts.setFont(new Font("Montserrat", Font.BOLD, 30)); panel.add(lblProducts); textFieldSearch = new JTextField(); textFieldSearch.setToolTipText("Search By Name"); textFieldSearch.setFont(new Font("Lato", Font.PLAIN, 16)); textFieldSearch.setColumns(10); textFieldSearch.setBounds(126, 122, 165, 34); panel.add(textFieldSearch); JLabel lblSearch = new JLabel("Search"); lblSearch.setForeground(Color.WHITE); lblSearch.setFont(new Font("Montserrat", Font.BOLD, 16)); lblSearch.setBounds(32, 122, 76, 16); panel.add(lblSearch); JLabel lblId = new JLabel("ID"); lblId.setForeground(Color.WHITE); lblId.setFont(new Font("Montserrat", Font.BOLD, 16)); lblId.setBounds(32, 185, 56, 16); panel.add(lblId); textFieldId = new JTextField(); textFieldId.setEditable(false); textFieldId.setFont(new Font("Lato", Font.PLAIN, 16)); textFieldId.setBounds(126, 176, 116, 34); panel.add(textFieldId); textFieldId.setColumns(10); JLabel lblName = new JLabel("Name"); lblName.setForeground(Color.WHITE); lblName.setFont(new Font("Montserrat", Font.BOLD, 16)); lblName.setBounds(32, 241, 56, 16); panel.add(lblName); textFieldName = new JTextField(); textFieldName.setFont(new Font("Lato", Font.PLAIN, 16)); textFieldName.setBounds(126, 232, 260, 34); textFieldName.requestFocusInWindow(); panel.add(textFieldName); textFieldName.setColumns(10); JLabel lblPhone = new JLabel("Price"); lblPhone.setForeground(Color.WHITE); lblPhone.setFont(new Font("Montserrat", Font.BOLD, 16)); lblPhone.setBounds(32, 296, 56, 16); panel.add(lblPhone); textFieldPrice = new JTextField(); textFieldPrice.setFont(new Font("Lato", Font.PLAIN, 16)); textFieldPrice.setBounds(126, 287, 260, 34); panel.add(textFieldPrice); textFieldPrice.setColumns(10); JLabel lblAddress = new JLabel("Discription"); lblAddress.setForeground(Color.WHITE); lblAddress.setFont(new Font("Montserrat", Font.BOLD, 14)); lblAddress.setBounds(32, 348, 88, 16); panel.add(lblAddress); textAreaDiscription = new JTextArea(); textAreaDiscription.setFont(new Font("Lato", Font.PLAIN, 16)); textAreaDiscription.setBounds(126, 348, 260, 168); panel.add(textAreaDiscription); JButton btnNew = new JButton("New"); btnNew.addActionListener(this); btnNew.setActionCommand("New"); btnNew.setBackground(new Color(70, 130, 180)); btnNew.setForeground(SystemColor.text); btnNew.setBounds(49, 557, 97, 50); panel.add(btnNew); JButton btnEdit = new JButton("Update"); btnEdit.setActionCommand("Update"); btnEdit.addActionListener(this); btnEdit.setBackground(new Color(70, 130, 180)); btnEdit.setForeground(SystemColor.text); btnEdit.setBounds(172, 557, 97, 50); panel.add(btnEdit); JButton btnDelete = new JButton("Delete"); btnDelete.setActionCommand("Delete"); btnDelete.addActionListener(this); btnDelete.setBackground(new Color(70, 130, 180)); btnDelete.setForeground(SystemColor.text); btnDelete.setBounds(289, 557, 97, 50); panel.add(btnDelete); JButton btnSearch = new JButton("Search"); btnSearch.setToolTipText("Search By Name"); btnSearch.setForeground(Color.WHITE); btnSearch.setBackground(new Color(70, 130, 180)); btnSearch.setActionCommand("New"); btnSearch.setBounds(289, 122, 97, 34); btnSearch.addActionListener(this); btnSearch.setActionCommand("Search"); panel.add(btnSearch); JLabel lblbyName = new JLabel("(By NAME)"); lblbyName.setForeground(Color.WHITE); lblbyName.setFont(new Font("Montserrat", Font.PLAIN, 12)); lblbyName.setBounds(32, 140, 76, 16); panel.add(lblbyName); JPanel panel_1 = new JPanel(); contentPane.add(panel_1, BorderLayout.CENTER); panel_1.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); panel_1.add(scrollPane, BorderLayout.CENTER); table = new JTable(); table.setFont(new Font("Lato", Font.PLAIN, 18)); table.setColumnSelectionAllowed(false); scrollPane.setViewportView(table); addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) { textFieldName.requestFocus(); } }); ListSelectionModel selectionModel = table.getSelectionModel(); selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selectionModel.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { try { DefaultTableModel model = (DefaultTableModel) table.getModel(); int id = (int) model.getValueAt(table.getSelectedRow(), 0); fillData(id); }catch(ArrayIndexOutOfBoundsException ex) { // System.out.println("Exception was Cought!"); } } }); refreshTable(App.products); } @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command.equals("New")) { NewProductDialog screen = new NewProductDialog(); WindowListener exitListener = new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { refreshTable(App.products); } }; screen.addWindowListener(exitListener); }else if(command.equals("Update")) { try { int id = Integer.parseInt(textFieldId.getText()); int index = searchProductById(id); String name,discription; double price; name = textFieldName.getText(); try { price = Double.parseDouble(textFieldPrice.getText()); }catch(NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Price Must be a NUMBER!!"); return; } discription = textAreaDiscription.getText(); if(index != -1) { App.products.get(index).setName(name); App.products.get(index).setPrice(price); App.products.get(index).setDiscription(discription); refreshTable(App.products); emptyFields(); } }catch(NumberFormatException exception) { } }else if(command.equals("Delete")) { try { int id = Integer.parseInt(textFieldId.getText()); int index = searchProductById(id); if(index != -1) { App.products.remove(index); JOptionPane.showMessageDialog(null, "Product Details Deleted!"); refreshTable(App.products); emptyFields(); } }catch(NumberFormatException exception) { } }else if(command.equals("Search")) { String searchStr = ""; searchStr = textFieldSearch.getText(); if(searchStr.length() != 0) { ArrayList<Product> products = new ArrayList<>(); for(Product p : App.products) { if(p.getName().toUpperCase().contains(searchStr.toUpperCase())) { products.add(p); } } refreshTable(products); }else { refreshTable(App.products); } } } public void refreshTable(ArrayList<Product> data) { DefaultTableModel model = new DefaultTableModel() { private static final long serialVersionUID = 1L; public boolean isCellEditable(int row, int column) { return false;//This causes all cells to be not editable } }; String[] colNames = {"ID","Name","Price","Discription"}; model.setColumnIdentifiers(colNames); model.setRowCount(0); for(Product p : data) { model.addRow(new Object[] {p.getID(),p.getName(),p.getPrice(),p.getDiscription()}); } table.setModel(model); table.setRowHeight(50); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(0).setMaxWidth(50);; table.getColumnModel().getColumn(1).setPreferredWidth(100); table.getColumnModel().getColumn(2).setPreferredWidth(180); table.getColumnModel().getColumn(2).setMaxWidth(200); table.getColumnModel().getColumn(3).setPreferredWidth(200); } private void emptyFields() { textFieldId.setText(""); textFieldName.setText(""); textFieldPrice.setText(""); textFieldSearch.setText(""); textAreaDiscription.setText(""); } private int searchProductById(int id) { for(Product product : App.products) { if(product.getID() == id) { return App.products.indexOf(product); } } return -1; } private void fillData(int id) { int index = searchProductById(id); try { textFieldId.setText(App.products.get(index).getID()+""); textFieldName.setText(App.products.get(index).getName()); textFieldPrice.setText(App.products.get(index).getPrice()+""); textAreaDiscription.setText(App.products.get(index).getDiscription()); }catch(ArrayIndexOutOfBoundsException ex) { // System.out.println("Array OUT OF BOund"); } } }
true
ca07adb7c41ff21298c9750de601f70b9c20ee03
Java
git-developers/koketa-android
/app/src/main/java/com/tianos/koketa/entity/Product.java
UTF-8
3,527
2.21875
2
[]
no_license
package com.tianos.koketa.entity; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import io.realm.RealmObject; public class Product extends RealmObject implements Serializable { public static final String TABLE_NAME = "t_product"; public static final String COLUMN_ID_INCR = "ID_INCR"; public static final String COLUMN_ID = "ID"; public static final String COLUMN_CODE = "CODE"; public static final String COLUMN_NAME = "NAME"; public static final String COLUMN_STOCK = "STOCK"; public static final String COLUMN_FAMILY = "FAMILY"; public static final String COLUMN_PRICE = "PRICE"; public static final String COLUMN_CATEGORY_ID = "CATEGORY_ID"; public static final String COLUMN_USERNAME = "USERNAME"; public static final String COLUMN_TIMESTAMP = "TIMESTAMP"; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID_INCR + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_ID + " INTEGER(11)," + COLUMN_CODE + " VARCHAR(45)," + COLUMN_NAME + " VARCHAR(45) DEFAULT NULL," + COLUMN_FAMILY + " VARCHAR(11) DEFAULT NULL," + COLUMN_STOCK + " INTEGER(11) DEFAULT NULL," + COLUMN_PRICE + " DECIMAL(8,2) DEFAULT NULL," + COLUMN_USERNAME + " VARCHAR(45)," + COLUMN_CATEGORY_ID + " INTEGER(11) DEFAULT NULL," + COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP" + ")"; @SerializedName("id") private Integer id; @SerializedName("code") private String code; @SerializedName("username") private String username; @SerializedName("name") private String name; @SerializedName("family") private String family; @SerializedName("stock") private Integer stock; @SerializedName("price") private float price; @SerializedName("category") private Category category; public Product() { } public Product(Integer id, String code, String name, String family, Integer stock, float price) { this.id = id; this.code = code; this.name = name; this.family = family; this.stock = stock; this.price = price; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
true
395f64d179911da795b4b5df9488d228084dd413
Java
Nineodes19/happy-end
/test_12.20/src/code1/Bird.java
UTF-8
358
2.984375
3
[]
no_license
package code1; /** * @program:test_12.20 * @author: Nine_odes * @description: * @create:2019-12-20 14:28 */ public class Bird extends Animal{ public Bird(String name){ super(name); } public void eat(String food){ System.out.println("我是一只小鸟"); System.out.println(this.name + "正在吃" + food); } }
true
994fa18ef5cecf4e682addc3a097f0247559a85a
Java
jasmineconseil/applicationBlanche
/gainde-demo/gainde-integral-ejb/gainde-integral-data-layer/src/main/java/sn/com/douane/ejb/declaration/model/keys/AttestationVerifKey.java
UTF-8
1,647
2.265625
2
[]
no_license
package sn.com.douane.ejb.declaration.model.keys; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Id; public class AttestationVerifKey implements Serializable{ /** * */ private static final long serialVersionUID = -3223726086839269277L; @Id @Column(name="DOUAVSR" , length=6 , nullable=false) private String douAVsr; @Id @Column(name="DOUAVPAY" , length=3 , nullable=false) private String douAVPay; public AttestationVerifKey(){ } public AttestationVerifKey(String douAVsr, String douAVPay){ this.douAVsr=douAVsr; this.douAVPay=douAVPay; } /** * @return the douAVsr */ public String getDouAVsr() { return douAVsr; } /** * @param douAVsr the douAVsr to set */ public void setDouAVsr(String douAVsr) { this.douAVsr = douAVsr; } /** * @return the douAVPay */ public String getDouAVPay() { return douAVPay; } /** * @param douAVPay the douAVPay to set */ public void setDouAVPay(String douAVPay) { this.douAVPay = douAVPay; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((douAVsr == null) ? 0 : douAVsr.hashCode()); result = prime * result + ((douAVPay == null) ? 0 : douAVPay.hashCode()); return result; } @Override public boolean equals(Object obj) { if (obj instanceof AttestationVerifKey) { AttestationVerifKey o = (AttestationVerifKey) obj; return ((this.douAVsr.equals(o.douAVsr)) && (this.douAVPay.equals(o.douAVPay))); } return false; } }
true
3aa5ae2c62be18df11217ba5a46ddf1f16733275
Java
KaroDarbinyan/films
/src/main/java/am/imdb/films/persistence/repository/CountryRepository.java
UTF-8
877
2.046875
2
[]
no_license
package am.imdb.films.persistence.repository; import am.imdb.films.persistence.entity.CountryEntity; import am.imdb.films.persistence.entity.GenreEntity; import am.imdb.films.service.dto.CountryDto; import am.imdb.films.service.dto.GenreDto; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; @Repository public interface CountryRepository extends JpaRepository<CountryEntity, Long> { Optional<CountryEntity> findByName(String name); List<CountryEntity> findByNameIn(Collection<String> names); }
true
2777f7cabee8aa4247018b491cca78882bbad554
Java
zeus7777777/VISHelper
/app/src/main/java/com/mixerbox/hackathon/vis/Player.java
UTF-8
588
2.640625
3
[]
no_license
package com.mixerbox.hackathon.vis; public class Player { String name, number, nickName; Position position; public Player(String _name, String _nickName, Position _position, String _number) { name = _name; nickName = _nickName; position = _position; number = _number; } public void editPlayer(String _nickName, Position _position, String _number) { nickName = _nickName; position = _position; number = _number; } public String toString() { return number + " " +nickName; } }
true
c59f3f9067eec3df8e132e524a63d7e380c0bd13
Java
PietrygaM/JavaTasks
/src/DesignPatterns/Creational/FactoryPattern/Example2/Computer.java
UTF-8
605
3.6875
4
[]
no_license
package DesignPatterns.Creational.FactoryPattern.Example2; public class Computer { private String serialNumber; private Processor processor; private Cooler cooler; public Computer(String serialNumber, ProcessorFactory processorFactory) { this.serialNumber = serialNumber; this.processor = processorFactory.createProcessor(); this.cooler = processorFactory.createCooler(); process(); } private void process() { System.out.println("Preparing computer with serial number: "+serialNumber); processor.process(); cooler.process(); System.out.println("Computer was build"); } }
true
21e5562d1daadc8bc124c9d56a0ef0024169bc0a
Java
jcm951301435/petition-manage-back
/src/main/java/com/ssy/petition/config/handler/ResultAuthenticationEntryPoint.java
UTF-8
1,044
2.078125
2
[ "Apache-2.0" ]
permissive
package com.ssy.petition.config.handler; import com.ssy.petition.common.CommonResult; import com.ssy.petition.util.JsonUtils; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * 未登录 * * @author jcm */ @Component public class ResultAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(JsonUtils.objectToJson(CommonResult.unauthorized(exception.getMessage()))); out.flush(); } }
true
3858c1b7b8406a266d77e18a16bbf913cf02313c
Java
nmeo7/BK-DF-Exercise
/FilmFan/app/src/main/java/com/example/filmfan/ListFragment.java
UTF-8
2,309
2.203125
2
[]
no_license
package com.example.filmfan; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import static com.example.filmfan.DetailsActivity.MOVIE_ID_TOKEN; public class ListFragment extends Fragment { final static private String TAG = "HOME_FRAGMENT"; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_list, container, false); ListView listView = root.findViewById(R.id.list); ProgressBar progressBar = root.findViewById(R.id.loadingList); TextView nothingToShow = root.findViewById(R.id.nothingToShow); Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences( getString(R.string.user_configurations), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(getString(R.string.tmdb_api_key), "API KEY"); editor.apply(); String api_key= sharedPref.getString(getString(R.string.tmdb_api_key), ""); Log.i(TAG, "onCreateView: " + api_key); Log.i(TAG, "onCreateView: " + getArguments().getInt("myArg")); Movie m = Movie.getInstance(getActivity()); // new Movie( getActivity() ); m.setViews (listView, progressBar, nothingToShow); Intent intent = getActivity().getIntent(); int movieId = intent.getIntExtra(MOVIE_ID_TOKEN, 0); switch (getArguments().getInt("myArg")) { case 0: m.retrieveNowPlaying (); break; case 1: m.retrieveFavorites (); break; case 2: m.retrieveVotedMovies (); break; case 3: m.retrieveSimilarMovies (movieId); break; case 4: m.retrieveRecommendedMovies (movieId); break; case 5: m.retrieveCast (movieId); break; } return root; } }
true
2c13b670d6884561008db127308b70eef0e39462
Java
leiwingqueen/anti-spider
/anti-spider-common/src/main/java/com/elend/spider/common/mapper/AntiSpiderBlackListMapper.java
UTF-8
1,145
2.015625
2
[]
no_license
package com.elend.spider.common.mapper; import java.util.List; import com.elend.p2p.mapper.SqlMapper; import com.elend.spider.common.vo.AntiSpiderBlackListSearchVO; import com.elend.spider.common.model.AntiSpiderBlackListPO; public interface AntiSpiderBlackListMapper extends SqlMapper { /** * 根据搜索条件返回列表 * * @param svo * @return */ List<AntiSpiderBlackListPO> list(AntiSpiderBlackListSearchVO svo); /** * 根据搜索条件返回列表总数 * * @param svo * @return */ int count(AntiSpiderBlackListSearchVO svo); /** * 根据主键id获取单条记录 * * @param id * @return */ AntiSpiderBlackListPO get(int id); /** * 插入记录 * * @param vo */ void insert(AntiSpiderBlackListPO po); /** * 更新记录 * * @param vo */ void update(AntiSpiderBlackListPO po); /** * 根据主键id删除记录 * * @param id */ void delete(int id); /** * 根据ip删除 * @param ip */ int deleteByIp(String ip); }
true
38e71f37ef5f41c030b33f4b0ffc4247e5644542
Java
ReyhanPatria/OpenMetadata
/catalog-rest-service/src/main/java/org/openmetadata/catalog/jdbi3/FeedRepository.java
UTF-8
7,134
1.859375
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmetadata.catalog.jdbi3; import org.jdbi.v3.sqlobject.transaction.Transaction; import org.openmetadata.catalog.Entity; import org.openmetadata.catalog.entity.feed.Thread; import org.openmetadata.catalog.resources.feeds.FeedUtil; import org.openmetadata.catalog.resources.feeds.MessageParser; import org.openmetadata.catalog.resources.feeds.MessageParser.EntityLink; import org.openmetadata.catalog.resources.feeds.MessageParser.EntityLink.LinkType; import org.openmetadata.catalog.type.EntityReference; import org.openmetadata.catalog.type.Post; import org.openmetadata.catalog.util.EntityUtil; import org.openmetadata.catalog.util.JsonUtils; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; public class FeedRepository { private final CollectionDAO dao; public FeedRepository(CollectionDAO dao) { this.dao = dao; } @Transaction public Thread create(Thread thread) throws IOException { // Validate user creating thread UUID fromUser = thread.getPosts().get(0).getFrom(); dao.userDAO().findEntityById(fromUser); // Validate about data entity is valid EntityLink about = EntityLink.parse(thread.getAbout()); EntityReference aboutRef = EntityUtil.validateEntityLink(about, dao); // Get owner for the addressed to Entity EntityReference owner = EntityUtil.populateOwner(aboutRef.getId(), dao.relationshipDAO(), dao.userDAO(), dao.teamDAO()); // Insert a new thread dao.feedDAO().insert(JsonUtils.pojoToJson(thread)); // Add relationship User -- created --> Thread relationship dao.relationshipDAO().insert(fromUser.toString(), thread.getId().toString(), "user", "thread", Relationship.CREATED.ordinal()); // Add field relationship data asset Thread -- isAbout ---> entity/entityField // relationship dao.fieldRelationshipDAO().insert(thread.getId().toString(), about.getFullyQualifiedFieldValue(), "thread", about.getFullyQualifiedFieldType(), Relationship.IS_ABOUT.ordinal()); // Add the owner also as addressedTo as the entity he owns when addressed, the owner is actually being addressed if (owner != null) { dao.relationshipDAO().insert(thread.getId().toString(), owner.getId().toString(), "thread", owner.getType(), Relationship.ADDRESSED_TO.ordinal()); } // Create relationship for users, teams, and other entities that are mentioned in the post // Multiple mentions of the same entity is handled by taking distinct mentions List<EntityLink> mentions = MessageParser.getEntityLinks(thread.getPosts().get(0).getMessage()); mentions.stream().distinct().forEach(mention -> dao.fieldRelationshipDAO().insert(mention.getFullyQualifiedFieldValue(), thread.getId().toString(), mention.getFullyQualifiedFieldType(), "thread", Relationship.MENTIONED_IN.ordinal())); return thread; } public Thread get(String id) throws IOException { return EntityUtil.validate(id, dao.feedDAO().findById(id), Thread.class); } @Transaction public Thread addPostToThread(String id, Post post) throws IOException { // Query 1 - validate user creating thread UUID fromUser = post.getFrom(); dao.userDAO().findEntityById(fromUser); // Query 2 - Find the thread Thread thread = EntityUtil.validate(id, dao.feedDAO().findById(id), Thread.class); FeedUtil.addPost(thread, post); // TODO is rewriting entire json okay? // Query 3 - update the JSON document for the feed dao.feedDAO().update(id, JsonUtils.pojoToJson(thread)); // Query 4 - Add relation User -- repliedTo --> Thread // Add relationship from thread to the from entity that is posting a reply boolean relationAlreadyExists = false; for (Post p : thread.getPosts()) { if (p.getFrom().equals(post.getFrom())) { relationAlreadyExists = true; break; } } if (!relationAlreadyExists) { dao.relationshipDAO().insert(post.getFrom().toString(), thread.getId().toString(), "user", "thread", Relationship.REPLIED_TO.ordinal()); } return thread; } @Transaction public List<Thread> listThreads(String link) throws IOException { if (link == null) { // Not listing thread by data asset or user return JsonUtils.readObjects(dao.feedDAO().list(), Thread.class); } EntityLink entityLink = EntityLink.parse(link); if (entityLink.getLinkType() != LinkType.ENTITY) { throw new IllegalArgumentException("Only entity links of type <E#/{entityType}/{entityName}> is allowed"); } EntityReference reference = EntityUtil.validateEntityLink(entityLink, dao); List<String> threadIds = new ArrayList<>(); List<List<String>> result = dao.fieldRelationshipDAO().listToByPrefix(entityLink.getFullyQualifiedFieldValue(), entityLink.getFullyQualifiedFieldType(), "thread", Relationship.MENTIONED_IN.ordinal()); result.forEach(l -> threadIds.add(l.get(1))); // TODO remove hardcoding of thread // For a user entitylink get created or replied relationships to the thread if (reference.getType().equals(Entity.USER)) { threadIds.addAll(dao.relationshipDAO().findTo(reference.getId().toString(), Relationship.CREATED.ordinal(), "thread")); threadIds.addAll(dao.relationshipDAO().findTo(reference.getId().toString(), Relationship.REPLIED_TO.ordinal(), "thread")); } else { // Only data assets are added as about result = dao.fieldRelationshipDAO().listToByPrefix(entityLink.getFullyQualifiedFieldValue(), entityLink.getFullyQualifiedFieldType(), "thread", Relationship.IS_ABOUT.ordinal()); result.forEach(l -> threadIds.add(l.get(1))); } List<Thread> threads = new ArrayList<>(); Set<String> uniqueValues = new HashSet<>(); for (String t : threadIds) { // If an entity has multiple relationships (created, mentioned, repliedTo etc.) to the same thread // Don't sent duplicated copies of the thread in response if (uniqueValues.add(t)) { threads.add(EntityUtil.validate(t, dao.feedDAO().findById(t), Thread.class)); } } return threads; } }
true
955904c89e279193a0b2f38ceb2a3d0ae79157ce
Java
dnosauro/singcie
/base_source_from_JADX/sources/com/google/android/gms/internal/ads/zzakw.java
UTF-8
364
1.75
2
[]
no_license
package com.google.android.gms.internal.ads; final class zzakw implements Runnable { private final /* synthetic */ zzakq zzdim; private final /* synthetic */ String zzdio; zzakw(zzakq zzakq, String str) { this.zzdim = zzakq; this.zzdio = str; } public final void run() { this.zzdim.zzdii.loadUrl(this.zzdio); } }
true
5cb7b725e3b33548fc46f3f787ad095936f9031a
Java
ralenmandao/dhvtsu-careers
/Desktop/WORKSPACE/CareersCCS/src/main/java/com/careers/ccs/data/entities/Candidate.java
UTF-8
1,058
2.828125
3
[]
no_license
package com.careers.ccs.data.entities; import javax.validation.constraints.*; public class Candidate extends User{ private long candidate_id; @NotNull private String first_name; @NotNull private String last_name; public Candidate(){ System.out.println("Im instantiated"); } public Candidate(String first_name, String last_name) { super(); this.first_name = first_name; this.last_name = last_name; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name.toLowerCase(); } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name.toLowerCase(); } public long getCandidate_id() { return candidate_id; } public void setCandidate_id(long candidate_id) { this.candidate_id = candidate_id; }; @Override public String toString(){ return "Name : " + first_name + " " + last_name + "\n" + super.toString(); } }
true
8da1a34393c6e2fb4700e876624c1be43978df1f
Java
temirgaliyev/sdu_programming_abstractions
/task6fx/SimpleControl.java
UTF-8
637
2.765625
3
[]
no_license
import javafx.scene.control.TextArea; public class SimpleControl { private Command copy, cut, paste, undo; SimpleControl(TextArea textArea){ this.copy = new CopyCommand(textArea); this.cut = new CutCommand(textArea); this.paste = new PasteCommand(textArea); this.undo = new UndoCommand(textArea); } public void copyWasPressed(){ copy.execute(); } public void cutWasPressed(){ cut.execute(); } public void pasteWasPressed(){ paste.execute(); } public void undoWasPressed(){ undo.execute(); } }
true
7071247b33b9ecab692a11093d2134eb0ac128bc
Java
derenv/sourceread
/app/src/main/java/derenvural/sourceread_prototype/data/login/LoggedInUser.java
UTF-8
26,647
2
2
[]
no_license
package derenvural.sourceread_prototype.data.login; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentSnapshot; import org.json.JSONObject; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.UnknownHostException; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import derenvural.sourceread_prototype.R; import derenvural.sourceread_prototype.SourceReadActivity; import derenvural.sourceread_prototype.data.asyncTasks.deleteArticleAsyncTask; import derenvural.sourceread_prototype.data.asyncTasks.populateAppsAsyncTask; import derenvural.sourceread_prototype.data.asyncTasks.populateUserAsyncTask; import derenvural.sourceread_prototype.data.asyncTasks.writeAppsAsyncTask; import derenvural.sourceread_prototype.data.cards.apps.App; import derenvural.sourceread_prototype.data.cards.articles.Article; import derenvural.sourceread_prototype.data.asyncTasks.importArticlesAsyncTask; import derenvural.sourceread_prototype.data.asyncTasks.userAccessAsyncTask; import derenvural.sourceread_prototype.data.dialog.choiceDialog; import derenvural.sourceread_prototype.data.dialog.helpDialog; import derenvural.sourceread_prototype.data.storage.storageSaver; public class LoggedInUser implements Serializable { // Basic data private MutableLiveData<String> userId = new MutableLiveData<String>(); private MutableLiveData<String> displayName = new MutableLiveData<String>(); private MutableLiveData<String> email = new MutableLiveData<String>(); // App data private MutableLiveData<ArrayList<App>> apps = new MutableLiveData<ArrayList<App>>(); // Article data private MutableLiveData<ArrayList<Article>> articles = new MutableLiveData<ArrayList<Article>>(); // Statistical data private MutableLiveData<String> veracity = new MutableLiveData<String>(); // Serialisation private static final long serialVersionUID = 1L; // Standard constructor public LoggedInUser(@NonNull FirebaseUser user) { // Populate object from database setUserId(user.getUid()); setDisplayName(user.getDisplayName()); setEmail(user.getEmail()); } public void loadInstanceState(@NonNull Bundle outState) { // Basic data setUserId((String) outState.getSerializable("id")); setDisplayName((String) outState.getSerializable("displayName")); setEmail((String) outState.getSerializable("email")); // App data setApps((ArrayList) outState.getSerializable("apps")); // Article data setArticles((ArrayList) outState.getSerializable("articles")); // Statistical data setVeracity((String) outState.getSerializable("veracity")); } public void saveInstanceState(@NonNull Bundle bundle) { // Basic data bundle.putSerializable("id", getUserId().getValue()); bundle.putSerializable("displayName", getDisplayName().getValue()); bundle.putSerializable("email", getEmail().getValue()); // App data bundle.putSerializable("apps", getApps().getValue()); // Article data bundle.putSerializable("articles", getArticles().getValue()); // Statistical data bundle.putSerializable("veracity", getVeracity().getValue()); } public void writeObject(@NonNull ObjectOutputStream stream) throws IOException { // Basic data stream.writeObject(getUserId().getValue()); stream.writeObject(getDisplayName().getValue()); stream.writeObject(getEmail().getValue()); // App data stream.writeObject(getApps().getValue()); // Article data stream.writeObject(getArticles().getValue()); // Statistical data stream.writeObject(getVeracity().getValue()); } public void readObject(@NonNull ObjectInputStream stream) throws IOException, ClassNotFoundException { // Basic data setUserId((String) stream.readObject()); setDisplayName((String) stream.readObject()); setEmail((String) stream.readObject()); // App data setApps((ArrayList) stream.readObject()); // Article data setArticles((ArrayList) stream.readObject()); // Statistical data setVeracity((String) stream.readObject()); } public void request_token(final SourceReadActivity currentActivity, App app, Response.Listener<JSONObject> responseListener, Response.ErrorListener failureListener){ // Get request token request URL for current app HashMap<String, String> app_requests = app.getRequests(); String url = app_requests.get("request"); // Cut out redirect URL from url String[] fullUrl = url.split("\\?"); url = fullUrl[0]; String redirect_uri = fullUrl[1]; // Fetch app key String app_key = app.getKey(); // Add JSON parameters HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("consumer_key",app_key); parameters.put("redirect_uri",redirect_uri); // Make https POST request currentActivity.getHttpHandler().make_volley_request_post(url, parameters, responseListener, failureListener ); } //Population Methods public void populate(final SourceReadActivity currentActivity) { // Create async task final populateUserAsyncTask task = new populateUserAsyncTask(currentActivity); // execute async task task.execute(this); // Check for task finish task.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { if(task.getData().getValue() != null) { // Get user object result LoggedInUser user1 = task.getData().getValue(); currentActivity.setUser(user1); // Check for access tokens user1.verify_apps(currentActivity); // Only reached if network error currentActivity.activate_interface(); } } } }); } public void verify_apps(@NonNull final SourceReadActivity currentActivity){ if(getApps() != null && getApps().getValue() != null && getApps().getValue().size() > 0) { for (App app : getApps().getValue()) { if((app.getAccessToken() == null || app.getAccessToken().equals("")) && (app.getRequestToken() != null)){ // Open app in browser for authentication Creates callback // Get login URL HashMap<String, String> requests = app.getRequests(); String app_login_url = requests.get("auth"); if(app_login_url != null && !app_login_url.equals("")) { // Insert request token String url = app_login_url.replaceAll("REPLACEME", app.getRequestToken()); // Store this object using local persistence if (storageSaver.write(currentActivity, getUserId().getValue(), this)) { // Redirect to browser for app login currentActivity.getHttpHandler().browser_open(currentActivity, url); } else { Log.e("HTTP", "login url request failure"); } } } } }else{ currentActivity.activate_interface(); } } public void access_tokens(@NonNull final SourceReadActivity currentActivity, @NonNull final String app_name){ // Create async task final userAccessAsyncTask task = new userAccessAsyncTask(currentActivity.getHttpHandler(), app_name); // execute async task task.execute(this); // Check for task finish task.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { if(task.getData().getValue() == null){ // Create listeners DialogInterface.OnClickListener negative = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Remove request token final ArrayList<App> new_apps = new ArrayList<App>(); for(App app : getApps().getValue()){ if (app.getTitle().equals(app_name)) { // Remove token app.setRequestToken(null); new_apps.add(app); }else{ // ignore other apps new_apps.add(app); } } setApps(new_apps); // Next app verify_apps(currentActivity); // Reactivate the UI currentActivity.activate_interface(); // cancel dialog.dismiss(); } }; DialogInterface.OnClickListener positive = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // retry verify_apps(currentActivity); } }; // Build dialog helpDialog retryDialog = new helpDialog(currentActivity, negative, positive, R.string.dialog_authenticate_app_title, R.string.user_ok, R.string.user_cancel, R.string.dialog_authenticate_app); // Display dialog box to choose sort method (default is A to Z) retryDialog.show(); }else { // Set new apps setApps(task.getData().getValue()); // move onto next app verify_apps(currentActivity); // Reactivate the UI currentActivity.activate_interface(); } } } }); } public void disconnectApp(@NonNull final SourceReadActivity currentActivity, @NonNull final App app, @NonNull final Integer destination){ // create list of all remaining apps in user object ArrayList<App> currentApps = getApps().getValue(); ArrayList<App> newApps = new ArrayList<App>(); for(App this_app : currentApps){ // If matching app if(this_app.getTitle().equals(app.getTitle())){ // If any articles exist if(getArticles().getValue() != null && getArticles().getValue().size() != 0) { // Count articles from app int amount = 0; for (Article countArticle : getArticles().getValue()) { if (countArticle.getApp().equals(app.getTitle())) { amount++; } } // If some articles from this app are still present if (amount != 0) { // Invalidate app but remain on list (so user can delete) this_app.setRequestToken(null); this_app.setAccessToken(null); newApps.add(this_app); } } }else{ newApps.add(this_app); } } // Remove app from user object setApps(newApps); // Create async task writeAppsAsyncTask task = new writeAppsAsyncTask(currentActivity.getDatabase()); // execute async task task.execute(newApps); // Check for task finish task.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { // Notify user Toast.makeText(currentActivity, app.getTitle()+" disconnected!", Toast.LENGTH_LONG).show(); // Reactivate the UI currentActivity.activate_interface(); // Redirect to list of apps page currentActivity.fragment_redirect(destination, new Bundle()); } } }); } public void connectApp(@NonNull final SourceReadActivity currentActivity, @NonNull final App app){ // create list of all remaining apps in user object ArrayList<App> currentApps = getApps().getValue(); if(currentApps == null){ currentApps = new ArrayList<App>(); } currentApps.add(app); // Remove app from user object setApps(currentApps); // Create async task final writeAppsAsyncTask writeAppsTask = new writeAppsAsyncTask(currentActivity.getDatabase()); final LoggedInUser user = this; // execute async task writeAppsTask.execute(currentApps); // Check for task finish writeAppsTask.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { //Create HashMap<String, Object> of apps HashMap<String, Long> found_apps = writeAppsTask.getData().getValue(); // Get app data then ask for request token final populateAppsAsyncTask appTask = new populateAppsAsyncTask(currentActivity); // execute async task appTask.execute(found_apps); // Check for task finish appTask.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { // Get apps data setApps(appTask.getData().getValue()); for(App appToOpen: getApps().getValue()){ if(appToOpen.getTitle().equals(app.getTitle())){ // Open app in browser for authentication Creates callback // Get login URL HashMap<String, String> requests = appToOpen.getRequests(); String app_login_url = requests.get("login"); // Insert request token String url = app_login_url.replaceAll("REPLACEME", appToOpen.getRequestToken()); // Store this object using local persistence if (storageSaver.write(currentActivity, getUserId().getValue(), user)) { // Redirect to browser for app login currentActivity.getHttpHandler().browser_open(currentActivity, url); } else { Log.e("HTTP", "login url request failure"); } } } } } }); } } }); } public void importArticles(@NonNull final SourceReadActivity currentActivity, @NonNull final App app){ if(app.getAccessToken() != null && !app.getAccessToken().equals("")) { // Create async task final importArticlesAsyncTask task = new importArticlesAsyncTask(currentActivity); // execute async task task.execute(app); // Check for task finish task.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { // Retrieve data setArticles(task.getData().getValue()); // Create map object containing timestamp with correct format final long request_stamp = Instant.now().getEpochSecond(); HashMap<String, Object> new_stamp = new HashMap<String, Object>(); new_stamp.put(app.getTitle(), request_stamp); // Store timestamp in database & user object currentActivity.getDatabase().update_user_field("apps", new_stamp, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> stamp_task) { if (stamp_task.isSuccessful()) { // Store timestamp in user object ArrayList<App> old_apps = getApps().getValue(); ArrayList<App> new_apps = new ArrayList<App>(); for(App this_app : old_apps) { if (this_app.getTitle().equals(app.getTitle())) { // store timestamp this_app.setTimestamp(request_stamp); new_apps.add(this_app); }else{ new_apps.add(this_app); } } setApps(new_apps); // Notify user Toast.makeText(currentActivity, "All your articles from "+app.getTitle()+" imported!", Toast.LENGTH_SHORT).show(); // Reactivate the UI currentActivity.activate_interface(); }else{ // Log error Log.e("DB", "write failed: ", stamp_task.getException()); } } }); } } }); // Notify user Toast.makeText(currentActivity, "Importing all articles from " + app.getTitle() + "..", Toast.LENGTH_SHORT).show(); }else{ // Reactivate the UI currentActivity.activate_interface(); // Notify user Toast.makeText(currentActivity, "Cannot import articles from " + app.getTitle() + ", needs authenticated!", Toast.LENGTH_SHORT).show(); } } public void deleteAllArticles(@NonNull final SourceReadActivity currentActivity, @NonNull final String app_name){ // Build list of articles to remove if(getArticles() != null && getArticles().getValue() != null && getArticles().getValue().size() > 0) { ArrayList<Article> articles = new ArrayList<Article>(); for(Article article : getArticles().getValue()){ if(article.getApp().equals(app_name)) { articles.add(article); } } if(articles.size() > 0) { // Create async task final deleteArticleAsyncTask task = new deleteArticleAsyncTask(this, currentActivity.getDatabase()); // execute async task task.execute(articles); // Check for task finish task.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { Log.d("TASK", "article deletion task done!"); // Retrieve data setArticles(task.getData().getValue()); // If missing request & access tokens remove from apps list for(App this_app : getApps().getValue()) { if (this_app.getAccessToken() == null && this_app.getRequestToken() == null) { disconnectApp(currentActivity, this_app, R.id.nav_apps); } } // Replace timestamp with invalid ArrayList<App> old_apps = getApps().getValue(); ArrayList<App> new_apps = new ArrayList<App>(); for (App this_app : old_apps) { if (this_app.getTitle().equals(app_name)) { // Store timestamp in user object this_app.setTimestamp(0L); new_apps.add(this_app); // Store timestamp in database Map<String, Object> new_stamp = new HashMap<>(); new_stamp.put(app_name, 0L); currentActivity.getDatabase().update_user_field("apps", new_stamp, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> stampTask) { if (stampTask.isSuccessful()) { Log.d("DB", "update done"); // Reactivate the UI Toast.makeText(currentActivity, "All articles imported from " + app_name + " deleted!", Toast.LENGTH_SHORT).show(); currentActivity.activate_interface(); } else { // Log error Log.e("DB", "update failed: ", stampTask.getException()); } } }); } else { new_apps.add(this_app); } } setApps(new_apps); } } }); }else{ Toast.makeText(currentActivity, "no articles from "+app_name+" to delete!", Toast.LENGTH_SHORT).show(); Log.d("TASK", "no articles from "+app_name+" to delete!"); currentActivity.activate_interface(); } }else{ Toast.makeText(currentActivity, "no articles from "+app_name+" to delete!", Toast.LENGTH_SHORT).show(); Log.d("TASK", "no articles from "+app_name+" to delete!"); currentActivity.activate_interface(); } } public void deleteArticle(@NonNull final SourceReadActivity currentActivity, @NonNull final ArrayList<Article> articles){ // Create async task final deleteArticleAsyncTask task = new deleteArticleAsyncTask(this, currentActivity.getDatabase()); // execute async task task.execute(articles); final LoggedInUser user = this; // Check for task finish task.getDone().observe(currentActivity, new Observer<Boolean>() { @Override public void onChanged(Boolean done) { if (done) { Log.d("TASK", "article deletion task done!"); // Retrieve data user.setArticles(task.getData().getValue()); // Reactivate the UI currentActivity.activate_interface(); } } }); } // SET private void setUserId(String userId) { this.userId.setValue(userId); } private void setDisplayName(String displayName) { this.displayName.setValue(displayName); } private void setEmail(String email) { this.email.setValue(email); } public void setApps(ArrayList<App> apps) { this.apps.setValue(apps); } public void setArticles(ArrayList<Article> articles) { this.articles.setValue(articles); } public void setVeracity(String veracity) { this.veracity.setValue(veracity); } // GET public LiveData<String> getUserId() { return userId; } public LiveData<String> getDisplayName() { return displayName; } public LiveData<String> getEmail() { return email; } public LiveData<ArrayList<App>> getApps() { return apps; } public LiveData<ArrayList<Article>> getArticles() { return articles; } public LiveData<String> getVeracity() { return veracity; } }
true
fae8545a9582aa5b310ad9f0c2de44700f23e776
Java
nangongruixue123/creditCard
/src/zws/fengqin/test/test.java
UTF-8
706
2
2
[]
no_license
package zws.fengqin.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import zws.fengqin.model.CreditCard; import zws.fengqin.service.impl.CreditCardServiceImpl; public class test { public static void main(String[] args) { ApplicationContext context =new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml"); CreditCardServiceImpl creditCardService = context.getBean(CreditCardServiceImpl.class); List<CreditCard> stus = creditCardService.queryAll(); //System.out.println(stus.size()); for (CreditCard stu : stus) { System.out.println(stu.getFakahang()); } } }
true
fdf499656596622ae3e5d21c4becbf948e8323a0
Java
hcoles/QuickTheories
/src/main/java/org/quicktheories/quicktheories/api/Function4.java
UTF-8
146
1.859375
2
[ "Apache-2.0" ]
permissive
package org.quicktheories.quicktheories.api; @FunctionalInterface public interface Function4<A, B, C, D, T> { T apply(A a, B b, C c, D d); }
true
a10033fc2509056b46af13f15207ca10fd28eacd
Java
hamidovmurad/Qr_CodeAttendanceCheck-Mob-app-
/app/src/main/java/az/codeacademy/codeacademy/ProfileActivity.java
UTF-8
13,109
1.65625
2
[]
no_license
package az.codeacademy.codeacademy; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.util.HashMap; import az.codeacademy.codeacademy.api.retrofitUrl.RetrofitProfileDataUrl; import az.codeacademy.codeacademy.api.retrofitUrl.RetrofitQRcode; import az.codeacademy.codeacademy.api.retrofitUrl.token.generator.TokenCreate; import az.codeacademy.codeacademy.login.system.UserProfile; import az.codeacademy.codeacademy.qr.code.sendUrl.QRcodeResponse; import az.codeacademy.codeacademy.shared.preference.SharedPreferenceA; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ProfileActivity extends AppCompatActivity { String userid; private ProgressDialog progressDialog; public static final String BASE_URL = "http://codeacademyattendancesystemapi.azurewebsites.net/api/student/"; SharedPreferenceA sp; private String qrcodetext; String named ,surnamed,phoned,fathernamed,groupd, group_Scheduled, lessonTimed,lessonBeginTimed,lessonEndTimed,attendanceRatiod; ImageView logoutbtn,scanbtn,attd; TextView namesurname,phone,group, group_Schedule, lessonTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); sp=new SharedPreferenceA(ProfileActivity.this); HashMap<String,String> map=sp.DetailStore(); userid=map.get(sp.KEY_ID); Log.e("Prof",""+userid); sp.checkLogin(); if (userid==null){ Toast.makeText(getApplicationContext(),"userid "+userid,Toast.LENGTH_SHORT).show(); }else{ postRequestMethodProfile(); } //TextView----------------------------------------- namesurname=findViewById(R.id.namesurname); logoutbtn=findViewById(R.id.logoutbtn); group_Schedule=findViewById(R.id.group_Schedule); group=findViewById(R.id.group); phone=findViewById(R.id.phone); lessonTime=findViewById(R.id.lessonTime); attd=findViewById(R.id.attd);//-------------------------------------------------------------------- attd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressDialog =new ProgressDialog(ProfileActivity.this); progressDialog.setMessage(getString(R.string.loading)); progressDialog.show(); Intent i=new Intent(ProfileActivity.this,AttendanceActivity.class); startActivity(i); finish(); } }); //log out button----------------------------------------------------- logoutbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this); builder.setMessage( R.string.exsit) .setCancelable(false) .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // FIRE ZE MISSILES! sp.logOut(); sp.checkLogin(); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog alert=builder.create(); alert.show(); } }); //------------------------------------------------------------------ //scan qr code camera------------------------------------ final Activity activity; activity = this; scanbtn=findViewById(R.id.scanbtn); scanbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { IntentIntegrator integrator=new IntentIntegrator(activity); integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES); integrator.setOrientationLocked(false); integrator.setPrompt(getString(R.string.scan_qr_code)); integrator.setCameraId(0); integrator.setBeepEnabled(true); integrator.setBarcodeImageEnabled(false); integrator.initiateScan(); } }); //----------------------------------------------------------------------------------------- } //Profile data text send code---------------------------------------------------- private void postRequestMethodProfile(){ progressDialog =new ProgressDialog(ProfileActivity.this); progressDialog.setMessage(getString(R.string.loading)); progressDialog.show(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitProfileDataUrl retrofitProfileDataUrl = retrofit.create(RetrofitProfileDataUrl.class); String deviceid=WelcomeActivity.deviceid.toString(); Intent i=getIntent(); //token class object-------------------------------------- TokenCreate tokenCreate=new TokenCreate(); String tokencode=tokenCreate.getSpesificKey()+userid ; String token=TokenCreate.get_SHA_512_SecurePassword(tokencode); //-------------------------------------------------------- Call<UserProfile> call = retrofitProfileDataUrl.profildata(userid,deviceid,token); Log.w("request",call.request().toString()); call.enqueue(new Callback<UserProfile>() { @Override public void onResponse(Call<UserProfile> call, Response<UserProfile> response) { progressDialog.dismiss(); UserProfile userProfile = response.body(); if (userProfile.getSuccess() && userProfile.getSetNewPassword() == false) { named=userProfile.getSuccessMessage().getName(); surnamed=userProfile.getSuccessMessage().getSurname(); phoned=userProfile.getSuccessMessage().getPhone(); fathernamed=userProfile.getSuccessMessage().getFatherName(); groupd=userProfile.getSuccessMessage().getGrup(); group_Scheduled=userProfile.getSuccessMessage().getGroupSchedule(); lessonTimed=userProfile.getSuccessMessage().getLessonTime(); lessonBeginTimed=userProfile.getSuccessMessage().getLessonBeginTime(); lessonEndTimed=userProfile.getSuccessMessage().getLessonEndTime(); attendanceRatiod=userProfile.getSuccessMessage().getAttendanceRatio(); //textview settext------------------------------------------------------ String allname=""; if (named!=null){ allname+=named; }if(surnamed!=null){ allname+=" "+surnamed; } if(fathernamed!=null){ allname+=" "+fathernamed; } namesurname.setText(allname); if (phoned!=null){ phone.setText(getString(R.string.phone)+phoned);} if (groupd!=null){ group.setText(getString(R.string.group_000)+groupd);} if (group_Scheduled!=null){group_Schedule.setText(""+group_Scheduled+"");} if (lessonTimed!=null|| lessonBeginTimed!=null|| lessonEndTimed!=null){ lessonTime.setText(getString(R.string.lessontime)+lessonTimed+" - "+lessonBeginTimed+" "+lessonEndTimed); } } else { Toast.makeText(getApplicationContext(), userProfile.getErrorMessage(), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<UserProfile> call, Throwable t) { progressDialog.dismiss(); } }); } //---------------------------------------------------------------- //qr code text send code---------------------------------------------------- private void postRequestMethod(){ progressDialog =new ProgressDialog(ProfileActivity.this); progressDialog.setMessage(getString(R.string.loading)); progressDialog.show(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitQRcode retrofitQRcode = retrofit.create(RetrofitQRcode.class); String deviceid=WelcomeActivity.deviceid.toString(); //token class object-------------------------------------- TokenCreate tokenCreate=new TokenCreate(); String tokencode=tokenCreate.getSpesificKey()+userid; String token=TokenCreate.get_SHA_512_SecurePassword(tokencode); //-------------------------------------------------------- Call<QRcodeResponse> call = retrofitQRcode.qrcodesend(userid,deviceid,qrcodetext,token); Log.w("request",call.request().toString()); call.enqueue(new Callback<QRcodeResponse>() { @Override public void onResponse(Call<QRcodeResponse> call, Response<QRcodeResponse> response) { progressDialog.dismiss(); QRcodeResponse qRcodeResponse = response.body(); AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this); String upmsg="Empty"; if (qRcodeResponse.getSuccess()&&qRcodeResponse.getSetNewPassword() == false) { upmsg=qRcodeResponse.getSuccessMessage(); Toast.makeText(getApplicationContext(), qRcodeResponse.getSuccessMessage(), Toast.LENGTH_SHORT).show(); builder.setView(R.layout.chekediconlayout); } else { upmsg= qRcodeResponse.getErrorMessage(); Toast.makeText(getApplicationContext(), qRcodeResponse.getErrorMessage(), Toast.LENGTH_SHORT).show(); builder.setView(R.layout.unchekediconlayout); } builder.setMessage(upmsg) .setCancelable(false) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) {} }); AlertDialog alert=builder.create(); alert.show(); } @Override public void onFailure(Call<QRcodeResponse> call, Throwable t) { progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Fail Run", Toast.LENGTH_SHORT).show(); } }); } //---------------------------------------------------------------- //camrea result---------------------------------------------------------------------- @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result=IntentIntegrator.parseActivityResult(requestCode,resultCode,data); if (result!=null){ String nulltest=result.getContents(); if (result.getContents()==null ){ Toast.makeText(this, R.string.stop_scan,Toast.LENGTH_SHORT).show(); }else if (nulltest==null ||nulltest==""||nulltest==" "){ Toast.makeText(this,"empty QR code",Toast.LENGTH_SHORT).show(); }else{ qrcodetext=nulltest; Toast.makeText(this,getString(R.string.good_scan),Toast.LENGTH_SHORT).show(); postRequestMethod(); } }else{ super.onActivityResult(requestCode, resultCode, data); } } //------------------------------------------------------------------------------------------------------- }
true
1f2f65b283d9dd56d7a920fdfd5ec5b85cbf4244
Java
ColdMelody/Jav
/src/thinkinjava/collection/CountingIntegerList.java
UTF-8
581
3.046875
3
[]
no_license
package thinkinjava.collection; import java.util.AbstractList; /** * 定制具有任意尺寸的容器 * Created by Bill on 2016/7/20. * Email androidBaoCP@163.com */ public class CountingIntegerList extends AbstractList<Integer>{ private int size; public CountingIntegerList(int size){ this.size=size<0?0:size; } @Override public Integer get(int index) { return index; } @Override public int size() { return size; } public static void main(String[] args){ System.out.println(new CountingIntegerList(30)); } }
true
c0560e61b6e9b24916109c3b1797e8621bf0c1d6
Java
nakedsnake888/prova-crud
/bcc-anagrafiche/src/main/java/eu/winwinit/bcc/controllers/ArticoliController.java
UTF-8
3,826
2.328125
2
[]
no_license
package eu.winwinit.bcc.controllers; import java.util.List; import javax.persistence.EntityNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import eu.winwinit.bcc.constants.AuthorityRolesConstants; import eu.winwinit.bcc.entities.Articolo; import eu.winwinit.bcc.service.ArticoloService; import io.swagger.annotations.Api; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.*; import io.swagger.v3.oas.annotations.media.*; @Api(description="API per la gestione degli articoli", tags = "Articoli") @RestController @RequestMapping("/articoli") public class ArticoliController { @Autowired ArticoloService articoloService; @Operation(summary = "Cerca Articoli per nome", description = "Questo metodo permette di cercare gli Articoli per nome.", responses = { @ApiResponse( description = "OK", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Articolo.class))) }) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<Articolo>> cercaArticoloPerNome ( @RequestHeader(value=AuthorityRolesConstants.HEADER_STRING) String jwtToken, @RequestParam(value="name") String name ) { List<Articolo> articoli = articoloService.findByName(name); return new ResponseEntity<>(articoli, HttpStatus.OK); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseEntity<Articolo> cercaArticoloPerId ( @RequestHeader(value=AuthorityRolesConstants.HEADER_STRING) String jwtToken, @PathVariable Integer id ) { Articolo articolo = articoloService.findById(id); if(articolo == null) throw new EntityNotFoundException(); return new ResponseEntity<>(articolo, HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<String> creaArticolo ( @RequestHeader(value=AuthorityRolesConstants.HEADER_STRING) String jwtToken, @RequestBody Articolo articolo ) { System.out.println(articolo.getDescrizione()); articoloService.save(articolo); return new ResponseEntity<>(HttpStatus.OK.getReasonPhrase(), HttpStatus.OK); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public ResponseEntity<String> modificaArticolo ( @RequestHeader(value=AuthorityRolesConstants.HEADER_STRING) String jwtToken, @RequestBody Articolo articolo, @PathVariable Integer id ) { Articolo oldArticolo = articoloService.findById(id); oldArticolo.replaceArticolo(articolo); articoloService.save(oldArticolo); return new ResponseEntity<>(HttpStatus.OK.getReasonPhrase(), HttpStatus.OK); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public ResponseEntity<String> deleteArticolo ( @RequestHeader(value=AuthorityRolesConstants.HEADER_STRING) String jwtToken, @PathVariable Integer id ) { Articolo oldArticolo = articoloService.findById(id); articoloService.delete(oldArticolo); return new ResponseEntity<>(HttpStatus.OK.getReasonPhrase(), HttpStatus.OK); } }
true
def7bb6f79a67758cb425674af36620ca2aa4dfa
Java
Geomatys/geotoolkit
/geotk-client-wfs/src/main/java/org/geotoolkit/data/wfs/AbstractUpdate.java
UTF-8
2,327
1.882813
2
[]
no_license
/* * Geotoolkit - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2009, Geomatys * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotoolkit.data.wfs; import java.util.HashMap; import java.util.Map; import org.opengis.feature.PropertyType; import org.opengis.util.GenericName; import org.opengis.filter.Filter; import org.opengis.referencing.crs.CoordinateReferenceSystem; /** * * @author Johann Sorel (Geomatys) * @module */ public class AbstractUpdate implements Update{ protected final Map<PropertyType,Object> updates = new HashMap<>(); protected GenericName typeName = null; protected String handle = null; protected Filter filter = null; protected CoordinateReferenceSystem crs = null; protected String inputFormat = null; @Override public Map<PropertyType,Object> updates() { return updates; } @Override public String getHandle() { return handle; } @Override public void setHandle(final String handle) { this.handle = handle; } @Override public Filter getFilter() { return filter; } @Override public void setFilter(final Filter filter) { this.filter = filter; } @Override public CoordinateReferenceSystem getCoordinateReferenceSystem() { return crs; } @Override public void setCoordinateReferenceSystem(final CoordinateReferenceSystem crs) { this.crs = crs; } @Override public String getInputFormat() { return inputFormat; } @Override public void setInputFormat(final String format) { this.inputFormat = format; } @Override public GenericName getTypeName() { return typeName; } @Override public void setTypeName(final GenericName type) { this.typeName = type; } }
true
d03609558b5482799c6c37ed0a5b99090bd0ef00
Java
chengniu/biomedicus
/biomedicus-core/src/main/java/edu/umn/biomedicus/modification/ContextSearch.java
UTF-8
4,350
1.96875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2016 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.modification; import edu.umn.biomedicus.common.labels.Label; import edu.umn.biomedicus.common.labels.LabelIndex; import edu.umn.biomedicus.common.types.syntax.PartOfSpeech; import edu.umn.biomedicus.common.types.text.*; import java.util.HashMap; import java.util.List; import java.util.Map; final class ContextSearch { private final LabelIndex<Sentence> sentences; private final LabelIndex<TermToken> tokens; private final LabelIndex<PartOfSpeech> partOfSpeechLabelIndex; private final LabelIndex<?> modifiableTerms; private final ContextCues contextCues; ContextSearch(ContextCues contextCues, LabelIndex<Sentence> sentences, LabelIndex<?> modifiableTerms, LabelIndex<TermToken> tokens, LabelIndex<PartOfSpeech> partOfSpeechLabelIndex) { this.contextCues = contextCues; this.sentences = sentences; this.modifiableTerms = modifiableTerms; this.tokens = tokens; this.partOfSpeechLabelIndex = partOfSpeechLabelIndex; } Map<Span, List<Label<TermToken>>> findMatches() { Map<Span, List<Label<TermToken>>> matchingSpans = new HashMap<>(); for (Label<Sentence> sentence : sentences) { LabelIndex<TermToken> sentenceTokens = tokens.insideSpan(sentence); for (Label<?> modifiableTerm : modifiableTerms.insideSpan(sentence)) { List<Label<TermToken>> matches = matches(sentenceTokens, modifiableTerm); if (matches != null) { matchingSpans.put(modifiableTerm.toSpan(), matches); } } } return matchingSpans; } private List<Label<TermToken>> matches(LabelIndex<TermToken> sentenceTokens, Label<?> modifiableTerm) { LabelIndex<TermToken> leftContextTokens = sentenceTokens.leftwardsFrom(modifiableTerm); List<Label<TermToken>> labels = contextCues.searchLeft(leftContextTokens.all(), partOfSpeechLabelIndex); if (labels != null) { return labels; } LabelIndex<TermToken> rightContextTokens = sentenceTokens.rightwardsFrom(modifiableTerm); labels = contextCues.searchRight(rightContextTokens.all(), partOfSpeechLabelIndex); if (labels != null) { return labels; } return null; } static final class ContextSearchBuilder { private ContextCues contextCues; private LabelIndex<Sentence> sentences; private LabelIndex<?> modifiableTerms; private LabelIndex<TermToken> tokens; private LabelIndex<PartOfSpeech> partOfSpeechLabelIndex; ContextSearchBuilder setContextCues(ContextCues contextCues) { this.contextCues = contextCues; return this; } ContextSearchBuilder setSentences(LabelIndex<Sentence> sentences) { this.sentences = sentences; return this; } ContextSearchBuilder setModifiableTerms(LabelIndex<?> modifiableTerms) { this.modifiableTerms = modifiableTerms; return this; } ContextSearchBuilder setTokens(LabelIndex<TermToken> tokens) { this.tokens = tokens; return this; } ContextSearchBuilder setPartOfSpeechLabelIndex(LabelIndex<PartOfSpeech> partOfSpeechLabelIndex) { this.partOfSpeechLabelIndex = partOfSpeechLabelIndex; return this; } ContextSearch createContextSearch() { return new ContextSearch(contextCues, sentences, modifiableTerms, tokens, partOfSpeechLabelIndex); } } }
true
c240bee46f6024ecca36ee3f96c86d0493d9220f
Java
sparkpool/TicTacToeGame
/src/main/java/com/tictactoe/dao/IGamePlayDAO.java
UTF-8
407
2.515625
3
[]
no_license
package com.tictactoe.dao; import com.tictactoe.model.Board; import com.tictactoe.model.Cell; import com.tictactoe.model.player.Player; public interface IGamePlayDAO { void makeTurn(String gameID, Player player, Cell cell); String startGame(Player player1, Player player2); Player lastTurn(String gameID); Board getBoard(String gameID); Player getComputerPlayer(String gameID); }
true
e85246b4752c0bb0b0862d023428e361a9eafa38
Java
shivadeepthi/cmpe273-assignment1
/src/main/java/edu/sjsu/cmpe/library/repository/BookRepositoryInterface.java
UTF-8
1,306
2.453125
2
[]
no_license
package edu.sjsu.cmpe.library.repository; import java.util.ArrayList; import com.yammer.dropwizard.jersey.params.LongParam; import edu.sjsu.cmpe.library.domain.Book.Authors; import edu.sjsu.cmpe.library.domain.Book; //import edu.sjsu.cmpe.library.domain.Book.Reviews; //import java.util.concurrent.*; //import java.util.*; /** * Book repository interface. * * What is repository pattern? * * @see http://martinfowler.com/eaaCatalog/repository.html */ public interface BookRepositoryInterface { /** * Save a new book in the repository * * @param newBook * a book instance to be create in the repository * @return a newly created book instance with auto-generated ISBN */ Book saveBook(Book newBook); // Authors saveAuthor(Authors newAuthors); /** * Retrieve an existing book by ISBN * * @param isbn * a valid ISBN * @return a book instance */ Book getBookByISBN(long isbn); Book deleteBookByIsbn(long isbn); Book updateBookByIsbn(long isbn); Book.Reviews createReviews(Book.Reviews review); Book.Reviews viewReviewsById(long Id); Book viewAllReviews(long Id); Book viewBookAuthorsById(long Id); Book viewAllAuthors(long isbn); // TODO: add other operations here! }
true
a652d8dee1681494774873334fe86ca5f676e284
Java
QuickLift/QuickLiftDriver
/app/src/main/java/com/example/adarsh/quickliftdriver/activities/FeedbackActivity.java
UTF-8
11,028
2.125
2
[]
no_license
package com.example.adarsh.quickliftdriver.activities; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RatingBar; import android.widget.TextView; import com.example.adarsh.quickliftdriver.R; import com.example.adarsh.quickliftdriver.Util.SequenceStack; import com.example.adarsh.quickliftdriver.model.SequenceModel; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.Stack; public class FeedbackActivity extends AppCompatActivity { private static Button feed; SharedPreferences log_id,ride_info; TextView fare; private RatingBar rate_bar; private DatabaseReference feed_rate; boolean submit = false; String id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feedback); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); log_id=getApplicationContext().getSharedPreferences("Login",MODE_PRIVATE); ride_info = getApplicationContext().getSharedPreferences("ride_info",MODE_PRIVATE); id = ride_info.getString("customer_id",null); rate_bar = (RatingBar)findViewById(R.id.feed_rate); feed_rate = FirebaseDatabase.getInstance().getReference("DriverFeedback/"+id); fare = (TextView)findViewById(R.id.fare); fare.setText(ride_info.getString("price",null)); feed = (Button)findViewById(R.id.feed_btn); feed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { feed_rate.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()){ Map<String,Object> feedback= (Map<String,Object>)dataSnapshot.getValue(); int no = Integer.parseInt(feedback.get("no").toString()); Float rate = Float.parseFloat(feedback.get("rate").toString()); rate = rate * no; Float curr_rate = (Float) ((rate+rate_bar.getRating())/(no+1)); HashMap<String,String> current_feed = new HashMap<>(); current_feed.put("no",Integer.toString(no+1)); current_feed.put("rate",curr_rate.toString()); feed_rate.setValue(current_feed); submit = true; }else { HashMap<String,String> current_feed = new HashMap<>(); current_feed.put("no",Integer.toString(1)); current_feed.put("rate",Float.toString(rate_bar.getRating())); feed_rate.setValue(current_feed); } } @Override public void onCancelled(DatabaseError databaseError) { Log.i("OK","failed to create reference"); } }); GregorianCalendar gregorianCalendar=new GregorianCalendar(); String date = String.valueOf(gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH)); String month = String.valueOf(gregorianCalendar.get(GregorianCalendar.MONTH)+1); String year = String.valueOf(gregorianCalendar.get(GregorianCalendar.YEAR)); final String formateDate = year+"-"+month+"-"+date; final DatabaseReference driver_acc = FirebaseDatabase.getInstance().getReference("Driver_Account_Info/"+log_id.getString("id",null)+"/"+formateDate); driver_acc.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot data : dataSnapshot.getChildren()){ Map<String,Object> map = (Map<String,Object>)data.getValue(); int confirm = Integer.parseInt(map.get("book").toString()); Float earn = Float.parseFloat(map.get("earn").toString()); confirm = confirm+1; earn = earn + Float.parseFloat(ride_info.getString("price",null)); String key = data.getKey(); try { driver_acc.child(key).child("book").setValue(Integer.toString(confirm)); driver_acc.child(key).child("earn").setValue(Float.toString(earn)); }catch (Exception e){ e.printStackTrace(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); DatabaseReference resp=FirebaseDatabase.getInstance().getReference("Response/"+log_id.getString("id",null)); resp.removeValue(); DatabaseReference cus=FirebaseDatabase.getInstance().getReference("CustomerRequests/"+log_id.getString("id",null)+"/"+id); cus.removeValue(); SharedPreferences.Editor editor=log_id.edit(); editor.putString("ride",""); editor.commit(); Stack<SequenceModel> stack = new SequenceStack().getStack(); if (!stack.isEmpty()){ stack.pop(); startActivity(new Intent(FeedbackActivity.this,MapActivity.class)); finish(); }else { DatabaseReference tripstatus= FirebaseDatabase.getInstance().getReference("Status/"+log_id.getString("id",null)); tripstatus.removeValue(); finish(); } //startActivity(new Intent(FeedbackActivity.this,Welcome.class)); } }); } @Override public void onBackPressed() { } @Override protected void onStop() { if (!submit){ feed_rate.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()){ Map<String,Object> feedback= (Map<String,Object>)dataSnapshot.getValue(); int no = Integer.parseInt(feedback.get("no").toString()); Float rate = Float.parseFloat(feedback.get("rate").toString()); rate = rate * no; Float curr_rate = (Float) ((rate+5)/(no+1)); HashMap<String,String> current_feed = new HashMap<>(); current_feed.put("no",Integer.toString(no+1)); current_feed.put("rate",curr_rate.toString()); feed_rate.setValue(current_feed); }else { HashMap<String,String> current_feed = new HashMap<>(); current_feed.put("no",Integer.toString(1)); current_feed.put("rate",Float.toString(5)); feed_rate.setValue(current_feed); } } @Override public void onCancelled(DatabaseError databaseError) { Log.i("OK","failed to create reference"); } }); GregorianCalendar gregorianCalendar=new GregorianCalendar(); String date = String.valueOf(gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH)); String month = String.valueOf(gregorianCalendar.get(GregorianCalendar.MONTH)+1); String year = String.valueOf(gregorianCalendar.get(GregorianCalendar.YEAR)); final String formateDate = year+"-"+month+"-"+date; final DatabaseReference driver_acc = FirebaseDatabase.getInstance().getReference("Driver_Account_Info/"+log_id.getString("id",null)+"/"+formateDate); driver_acc.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot data : dataSnapshot.getChildren()){ Map<String,Object> map = (Map<String,Object>)data.getValue(); int confirm = Integer.parseInt(map.get("book").toString()); Float earn = Float.parseFloat(map.get("earn").toString()); confirm = confirm+1; earn = earn + Float.parseFloat(ride_info.getString("price",null)); String key = data.getKey(); try { driver_acc.child(key).child("book").setValue(Integer.toString(confirm)); driver_acc.child(key).child("earn").setValue(Float.toString(earn)); }catch (Exception e){ e.printStackTrace(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); DatabaseReference resp=FirebaseDatabase.getInstance().getReference("Response/"+log_id.getString("id",null)); resp.removeValue(); DatabaseReference cus=FirebaseDatabase.getInstance().getReference("CustomerRequests/"+log_id.getString("id",null)+"/"+id); cus.removeValue(); SharedPreferences.Editor editor=log_id.edit(); editor.putString("ride",""); editor.commit(); Stack<SequenceModel> stack = new SequenceStack().getStack(); if (!stack.isEmpty()){ stack.pop(); startActivity(new Intent(FeedbackActivity.this,MapActivity.class)); finish(); }else { DatabaseReference tripstatus= FirebaseDatabase.getInstance().getReference("Status/"+log_id.getString("id",null)); tripstatus.removeValue(); finish(); } } super.onStop(); } }
true
0eec916df3f9b89f784da05031c579d8c651fee8
Java
KimGames/projetoSD
/Servidor/src/main/java/com/projetosd/grpc/server/ExecutionThread.java
UTF-8
5,187
2.53125
3
[]
no_license
package com.projetosd.grpc.server; import com.projetosd.grpc.resources.ActionsEnum; import com.projetosd.grpc.resources.Input; import org.apache.ratis.client.RaftClient; import org.apache.ratis.protocol.Message; import org.apache.ratis.protocol.RaftClientReply; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.HashMap; import java.util.concurrent.BlockingQueue; public class ExecutionThread implements Runnable { /*Fila de Execução*/ private BlockingQueue<Input> executionQueue; /*Banco de dados e chave*/ private HashMap<BigInteger, byte[]> dataBase; private BigInteger queryKey; /*Raft*/ private RaftClient raftClient; private RaftClientReply getValue; /*Comando de entrada e resposta*/ private Input input; private String response; public ExecutionThread(BlockingQueue<Input> _executionQueue, HashMap<BigInteger, byte[]> _dataBase, RaftClient _raftClient) { this.executionQueue = _executionQueue; this.dataBase = _dataBase; this.raftClient = _raftClient; } public void run() { try { while (true) { input = executionQueue.take(); ActionsEnum actionOperation = ActionsEnum.values()[input.getOperation()]; switch (actionOperation) { /*Função set*/ case SET: /*Recupero a chave informada*/ queryKey = input.getId(); /*Verifico se a chave já existe*/ if (dataBase.containsKey(queryKey)) { /*Comparativo com id passado*/ if (input.getEventSource() != null) { input.getEventSource().reply("(ERROR) Chave enviada ja possui valores"); } } else { /*Adiciono o valor em meu RATIS*/ getValue = raftClient.send(Message.valueOf("set:" + queryKey + ":" + input.getContent())); response = getValue.getMessage().getContent().toString(Charset.defaultCharset()); System.out.println("Resposta:" + response); if (input.getEventSource() != null) { input.getEventSource().reply("(SUCCESS) " + queryKey + ":" + input.getContent()); } } break; /*Função get*/ case GET: if (input.getContent().compareTo("*") == 0) { /*Comparativo com todos*/ String response = ""; for (HashMap.Entry<BigInteger, byte[]> pair : dataBase.entrySet()) { response += pair.getKey().toString() + ":" + new String(pair.getValue()) + " - "; } if (input.getEventSource() != null) { input.getEventSource().reply("(SUCCESS) " + response); } } else if (dataBase.containsKey(input.getId())) { /*Comparativo com id passado*/ if (input.getEventSource() != null) { getValue = raftClient.sendReadOnly(Message.valueOf("get:" + input.getId())); response = getValue.getMessage().getContent().toString(Charset.defaultCharset()); System.out.println("Resposta:" + response); String response = input.getId() + ":" + new String(dataBase.get(input.getId())); input.getEventSource().reply("(SUCCESS) " + response); } } else { /*Não foi passado chave e/ou nao existe*/ if (input.getEventSource() != null) { input.getEventSource().reply("(ERROR) Nao informado chave e/ou chave invalida"); } } break; /*Função testandset*/ case TESTANDSET: if (dataBase.containsKey(input.getId())) { /*Comparativo com id passado*/ /*Atualizo no ratis*/ getValue = raftClient.send(Message.valueOf("testandset:" + input.getId() + ":" + input.getContent())); response = getValue.getMessage().getContent().toString(Charset.defaultCharset()); System.out.println("Resposta:" + response); if (input.getEventSource() != null) { input.getEventSource().reply("(SUCCESS) " + input.getId() + ":" + input.getContent()); } } else { /*Não foi passado chave e/ou nao existe*/ if (input.getEventSource() != null) { input.getEventSource().reply("(ERROR) Nao informado chave e/ou chave invalida"); } } break; /*Função del*/ case DEL: if (dataBase.containsKey(input.getId())) { /*Comparativo com id passado*/ /*Atualizo no ratis*/ getValue = raftClient.send(Message.valueOf("del:" + input.getId())); response = getValue.getMessage().getContent().toString(Charset.defaultCharset()); System.out.println("Resposta:" + response); if (input.getEventSource() != null) { input.getEventSource().reply("(SUCCESS) " + input.getId() + " removido."); } } else { /*Não foi passado chave e/ou nao existe*/ if (input.getEventSource() != null) { input.getEventSource().reply("(ERROR) Nao informado chave e/ou chave invalida"); } } break; default: if (input.getEventSource() != null) { input.getEventSource().reply("(ERROR) Comando nao conhecido"); } break; } } } catch (InterruptedException e) { System.out.println("Ocorreu uma falha na execução das requisições.\nO servidor será finalizado."); } catch (IOException ioException) { System.out.println("ioException: " + ioException.getMessage()); } } }
true
6cc9e1212b7a336cedd1183ff071f10875ac7bec
Java
darktaoist/IChingElement
/app/src/main/java/kr/co/taoists/cmnn/dto/BaseDTO.java
UTF-8
166
1.695313
2
[]
no_license
package kr.co.taoists.cmnn.dto; import kr.co.taoists.cmnn.exception.BusinessException; public abstract class BaseDTO { public BaseDTO() { super(); } }
true
1dd0fb46449a7cfca9836e0ce945ed702764e229
Java
9and3r/octoprint-java-display
/Code/src/com/and3r/octoprint/javadisplay/ui/components/icons/HomeIcon.java
UTF-8
601
2.53125
3
[]
no_license
package com.and3r.octoprint.javadisplay.ui.components.icons; public class HomeIcon extends ClickableIcon { @Override protected void init(Object... params) { } @Override protected int getMargin() { return 20; } @Override protected int[][] getInitialXPoints() { return new int[][]{{0, 50, 100, 80, 80, 20, 20}}; } @Override protected int[][] getInitialYPoints() { return new int[][]{{30, 0, 30, 30, 80, 80, 30}}; } @Override protected int getStrokeWidth(int i) { return super.getStrokeWidth(i) * 2; } }
true
40d17357bbbbf1d3a7a56b343f608ad08b439ca6
Java
DLB832/CPSC2800_Intro_to_Operating_Systems
/Barrier.java
UTF-8
594
2.875
3
[]
no_license
/** * Barrier.java * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Tenth Edition * Copyright John Wiley & Sons - 2018. */ public interface Barrier { /** * Each thread calls this method when it reaches the barrier. * All threads are released to continue processing when the * last thread calls this method. */ public void waitForOthers(); /** * Release all threads from waiting for the barrier. * Any future calls to waitForOthers() will not wait * until the Barrier is set again with a call to the constructor. */ public void freeAll(); }
true
fd07ef9ef63f565eb7016cbb78c0f548056b55e9
Java
ZZUGeneral/shipping
/front/src/main/java/com/cit/its/shipping/front/entity/WeatherGeneral.java
UTF-8
1,325
1.992188
2
[]
no_license
package com.cit.its.shipping.front.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @TableName("msg_weather_general") @ApiModel("气象数据") public class WeatherGeneral { @ApiModelProperty("数据项ID") @TableId(type = IdType.AUTO) @TableField("id") private Long id; @ApiModelProperty("时间") @TableField("time") private Long time; @ApiModelProperty("温度") @TableField("temperature") private Float temperature; @ApiModelProperty("湿度") @TableField("humidity") private Float humidity; @ApiModelProperty("气压") @TableField("air_pressure") private Float airPressure; @ApiModelProperty("风速") @TableField("wind_speed") private Float windSpeed; @ApiModelProperty("风向") @TableField("wind_direction") private Float windDirection; @ApiModelProperty("mqtt 主题") @TableField("topic") private String topic; }
true
5b2276f22873987666c9c42ed4b0c21f3a436049
Java
filipbittara/creatures-hunting
/creatures-hunting-service/src/main/java/cz/muni/fi/pa165/service/facade/UserFacadeImpl.java
UTF-8
3,030
2.28125
2
[]
no_license
package cz.muni.fi.pa165.service.facade; import cz.muni.fi.pa165.dto.ChangeImageDTO; import cz.muni.fi.pa165.dto.UserAuthenticateDTO; import cz.muni.fi.pa165.dto.UserDTO; import cz.muni.fi.pa165.facade.UserFacade; import cz.muni.fi.pa165.persistence.entity.User; import cz.muni.fi.pa165.service.BeanMappingService; import cz.muni.fi.pa165.service.UserService; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author Filip Bittara */ @Service @Transactional @Configurable public class UserFacadeImpl implements UserFacade{ @Autowired private UserService userService; @Autowired private BeanMappingService beanMappingService; public void setUserService(UserService creatureService) { this.userService = creatureService; } public void setBeanMappingService(BeanMappingService beanMappingService) { this.beanMappingService = beanMappingService; } @Override public UserDTO findUserById(Long userId) { User user = userService.findUserById(userId); return (user == null) ? null : beanMappingService.mapTo(user, UserDTO.class); } @Override public UserDTO findUserByEmail(String email) { User user = userService.findUserByEmail(email); return (user == null) ? null : beanMappingService.mapTo(user, UserDTO.class); } @Override public UserDTO findUserByUsername(String username) { User user = userService.findUserByUsername(username); return (user == null) ? null : beanMappingService.mapTo(user, UserDTO.class); } @Override public void registerUser(UserDTO user, String unencryptedPassword) { User userEntity = beanMappingService.mapTo(user, User.class); userService.registerUser(userEntity, unencryptedPassword); user.setId(userEntity.getId()); } @Override public Collection<UserDTO> getAllUsers() { return beanMappingService.mapTo(userService.getAllUsers(), UserDTO.class); } @Override public boolean authenticate(UserAuthenticateDTO auth) { return userService.authenticate( userService.findUserById(auth.getUserId()), auth.getPassword()); } @Override public boolean isAdmin(UserDTO user) { return userService.isAdmin(beanMappingService.mapTo(user, User.class)); } @Override public void changePassword(UserAuthenticateDTO auth, String newUnencryptedPassword) { userService.changePassword(userService.findUserById(auth.getUserId()), auth.getPassword(), newUnencryptedPassword); } @Override public void changeImage(ChangeImageDTO imageChange) { User u = userService.findUserById(imageChange.getId()); u.setImage(imageChange.getImage()); u.setImageMimeType(imageChange.getImageMimeType()); } }
true
aade66189a55ab13859ccee1035d6800422cfe7b
Java
karlnicholas/encyclopediaofsf
/src/main/java/com/github/karlnicholas/encyclopediaofsf/EncyclopediaOfSfStreamHandler.java
UTF-8
2,157
1.890625
2
[]
no_license
/* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.github.karlnicholas.encyclopediaofsf; import com.amazon.ask.Skill; import com.amazon.ask.SkillStreamHandler; import com.amazon.ask.Skills; import com.github.karlnicholas.encyclopediaofsf.handlers.CancelandStopIntentHandler; import com.github.karlnicholas.encyclopediaofsf.handlers.FallbackIntentHandler; import com.github.karlnicholas.encyclopediaofsf.handlers.HelpIntentHandler; import com.github.karlnicholas.encyclopediaofsf.handlers.LaunchRequestHandler; import com.github.karlnicholas.encyclopediaofsf.handlers.EncyclopediaOfSfSearchIntentHandler; import com.github.karlnicholas.encyclopediaofsf.handlers.SessionEndedRequestHandler; import com.github.karlnicholas.encyclopediaofsf.handlers.EncyclopediaOfSfQuoteIntentHandler; public class EncyclopediaOfSfStreamHandler extends SkillStreamHandler { private static Skill getSkill() { return Skills.standard() .addRequestHandlers( new EncyclopediaOfSfQuoteIntentHandler(), new EncyclopediaOfSfSearchIntentHandler(), new LaunchRequestHandler(), new CancelandStopIntentHandler(), new SessionEndedRequestHandler(), new HelpIntentHandler(), new FallbackIntentHandler()) // Add your skill id below .withSkillId("amzn1.ask.skill.000cb015-f612-4f2a-a83f-7d24090d136c") .build(); } public EncyclopediaOfSfStreamHandler() { super(getSkill()); } }
true
86c17a3501352f5e61196c9f2de515deb6153a97
Java
isaac9422/tallerDocker
/back/taller/src/test/java/co/com/cidenet/hulkStore/services/ProductServiceTest.java
UTF-8
6,951
2.375
2
[]
no_license
package co.com.cidenet.hulkStore.services; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.UUID; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import co.com.cidenet.hulkStore.domains.Product; import co.com.cidenet.hulkStore.dto.ProductDTO; import co.com.cidenet.hulkStore.exceptions.ControlledException; import co.com.cidenet.hulkStore.exceptions.ProductoInvalidoException; import co.com.cidenet.hulkStore.exceptions.ProductoNoEncontradoException; import co.com.cidenet.hulkStore.repositories.ProductRepository; @RunWith(MockitoJUnitRunner.class) public class ProductServiceTest { @Mock ProductRepository productRepository; @Mock TransactionService transactionService; @InjectMocks ProductService productService; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void createProductTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(1000.0); Product product = new Product(productDTO); Product productSaved = new Product(); productSaved.setId(productDTO.getId()); productSaved.setName("Product 2"); productSaved.setQuantity(200l); productSaved.setValue(2000.0); Mockito.when(productRepository.save(product)).thenReturn(productSaved); Mockito.doNothing().when(transactionService).createTransaction(ArgumentMatchers.any(ProductDTO.class), ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyLong()); ProductDTO productDTOResult = productService.createProduct(productDTO); Assert.assertNotNull(productDTOResult); } @Test public void deleteProductTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(1000.0); Product product = new Product(productDTO); Mockito.doNothing().when(productRepository).deleteById(product.getId()); Mockito.when(productRepository.findById(product.getId())).thenReturn(Optional.of(product)); productService.deleteProduct(product.getId()); Mockito.verify(productRepository, Mockito.times(1)).deleteById(product.getId()); } @Test public void updateProductTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(1000.0); Product product = new Product(productDTO); ProductDTO productDTOExpected = new ProductDTO(); productDTOExpected.setId(productDTO.getId()); productDTOExpected.setName("Product 2"); productDTOExpected.setQuantity(200l); productDTOExpected.setValue(2000.0); Product productSaved = new Product(productDTOExpected); Mockito.when(productRepository.save(product)).thenReturn(productSaved); Mockito.when(productRepository.findById(product.getId())).thenReturn(Optional.of(product)); Mockito.doNothing().when(transactionService).createTransaction(ArgumentMatchers.any(ProductDTO.class), ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyLong()); ProductDTO productDTOResult = productService.updateProduct(productDTOExpected, product.getId()); Assert.assertEquals(productDTOExpected, productDTOResult); } @Test public void retrieveProductTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(1000.0); Product product = new Product(productDTO); Mockito.when(productRepository.findById(product.getId())).thenReturn(Optional.of(product)); ProductDTO productDTOExpected = productService.getProductDTOById(product.getId()); Assert.assertEquals(productDTOExpected, productDTO); } @Test public void retrieveProductsTest() { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(1000.0); Product product = new Product(productDTO); ProductDTO productDTOExpected = new ProductDTO(); productDTOExpected.setId(UUID.randomUUID()); productDTOExpected.setName("Product 2"); productDTOExpected.setQuantity(200l); productDTOExpected.setValue(2000.0); Product productSaved = new Product(productDTOExpected); Product[] productList = { product, productSaved }; List<ProductDTO> productDTOList = new ArrayList<ProductDTO>(); productDTOList.add(productDTO); productDTOList.add(productDTOExpected); Mockito.when(productRepository.findAll()).thenReturn(Arrays.asList(productList)); List<ProductDTO> productDTOListResult = productService.findAll(); Assert.assertEquals(productDTOList, productDTOListResult); } @Test(expected = ProductoNoEncontradoException.class) public void retrieveProductNotRegisteredTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(1000.0); Product product = new Product(productDTO); productService.getProductDTOById(product.getId()); } @Test(expected = ProductoInvalidoException.class) public void createProductQuantityInvalidTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(-100l); productDTO.setValue(1000.0); productService.createProduct(productDTO); } @Test(expected = ProductoInvalidoException.class) public void createProductValueInvalidTest() throws ControlledException { ProductDTO productDTO = new ProductDTO(); productDTO.setId(UUID.randomUUID()); productDTO.setName("Product"); productDTO.setQuantity(100l); productDTO.setValue(-1000.0); productService.createProduct(productDTO); } }
true
9a6deb7b8ff3f52f18c0877965c390c6ec8b1c45
Java
fastforwardray/AddressBookJersey
/src/edu/intuit/addressbook/interfaces/Entity.java
UTF-8
128
1.5
2
[]
no_license
/** * */ package edu.intuit.addressbook.interfaces; /** * @author Harsha.Ramakrishnapp * */ public interface Entity { }
true
a16f0e86d590708f83fdcce0c5aff3b84e9df1bc
Java
thoslin/ELF
/client/plugins/elf.client.finance.management/src/main/java/elf/client/finance/management/cashpool/CashPoolConfig.java
GB18030
1,353
2.1875
2
[ "BSD-3-Clause" ]
permissive
package elf.client.finance.management.cashpool; import java.io.Serializable; import java.math.BigDecimal; public class CashPoolConfig implements Serializable { private static final long serialVersionUID = 5388891483911114983L; /** ʽ **/ private String cashPoolName; /** **/ private String bankName; /** пʺ **/ private String bankAccountNo; /** ʻ **/ private BigDecimal balance; public CashPoolConfig() { } public CashPoolConfig(String cashPoolName, String bankName, String bankAccountNo, BigDecimal balance) { this.cashPoolName = cashPoolName; this.bankName = bankName; this.bankAccountNo = bankAccountNo; this.balance = balance; } public String getCashPoolName() { return cashPoolName; } public void setCashPoolName(String cashPoolName) { this.cashPoolName = cashPoolName; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
true
93a929390bf06f835380de151206924705aed7df
Java
cstevenson93/Recycler_View_Demo
/app/src/main/java/com/example/recyclerviewdemo/browserWebView.java
UTF-8
3,537
1.992188
2
[]
no_license
package com.example.recyclerviewdemo; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import java.util.ArrayList; public class browserWebView extends AppCompatActivity { String url; Uri uri; String appPackage; WebView myWebView; private void launchPage(View view){ Bundle extras = getIntent().getExtras(); url = extras.getString("url"); appPackage = extras.getString("package"); Intent goToMarket = new Intent(Intent.ACTION_VIEW,uri.parse("market://details?id="+appPackage)); //Toast.makeText(this, url, Toast.LENGTH_SHORT).show(); //Toast.makeText(this, appPackage, Toast.LENGTH_SHORT).show(); if(url.equals("https://camden.bywatersolutions.com/")){ myWebView.loadUrl(url); } else { Intent launchIntent = getPackageManager().getLaunchIntentForPackage(appPackage); if (launchIntent != null) { startActivity(launchIntent); finish(); } else { startActivity(goToMarket); finish(); //setContentView(myWebView); //myWebView.loadUrl(url); //Toast.makeText(MainActivity.this, "There is no package available in android", Toast.LENGTH_LONG).show(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final String javascriptUrlUser = "javascript: (function() {document.getElementById('userid').value= '50000005754949';}) ();"; final String javascriptUrlPass = "javascript: (function() {document.getElementById('password').value= '4949';}) ();"; final String javascriptUrlLogin ="javascript: (function() {document.getElementsByTagName('input')[9].click();}) ();"; //final String javascriptURL = "javascript:document.getElementById(\"userid\").value='5';"; myWebView = new WebView(this); //myWebView.getSettings().setJavaScriptEnabled(true); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); webSettings.setSupportZoom(true); webSettings.setDefaultTextEncodingName("utf-8"); setContentView(myWebView); launchPage(myWebView); myWebView.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView view, String url) { if(url.equals("https://camden.bywatersolutions.com/")) { //Toast.makeText(browserWebView.this, "Current Url: " + url, Toast.LENGTH_LONG).show(); //myWebView.getSettings().setJavaScriptEnabled(true); view.loadUrl(javascriptUrlUser); view.loadUrl(javascriptUrlPass); view.loadUrl(javascriptUrlLogin); } } }); } }
true
8ae7bd41a98383d4cad5f5be0b03e5b19428e2f6
Java
NightWarriorbg/Epay-Consumes-Project
/src/main/java/me/nightwarrior/epayconsumes/model/MerchantList.java
UTF-8
475
1.929688
2
[]
no_license
package me.nightwarrior.epayconsumes.model; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import java.util.ArrayList; import java.util.List; @Data @RequiredArgsConstructor @NoArgsConstructor(access = AccessLevel.PRIVATE, force=true) public class MerchantList { private final String categoryType; private final Integer categoryId; private List<Merchant> merchants = new ArrayList<>(); }
true
8ca25905e966de0d751973b3f15160dd2e34ce68
Java
SuperBr/suber-root
/suber-base/src/main/java/com/dataStructure/Sort_Main.java
UTF-8
4,022
3.5625
4
[]
no_license
package com.dataStructure; import jdk.nashorn.internal.ir.ReturnNode; import org.junit.Test; import java.time.chrono.MinguoChronology; import java.util.Arrays; public class Sort_Main { /** * 8大排序 3大插入 * * @param args */ public static void main(String[] args) { } @Test public void merger2St_Test() { int a[] = {1, 5, 8, 9}; int b[] = {2, 3, 6, 34}; System.out.println(Arrays.toString(merger2St(a, b))); } @Test public void merger_sort_Test() { int a[] = {7, 1, 5, 8, 9, 6, 15}; System.out.println(Arrays.toString(merger_sort(a, 0, a.length - 1))); } /** * 归并排序 * <p> * 稳定 * * @param old * @return 优点:始终都是O(nlogn)的时间复杂度 */ public static int[] merger_sort(int[] old, int left, int r) { if (left == r) { return old; } int mid = (left + r) / 2; merger_sort(old, left, mid); merger_sort(old, mid + 1, r); merger2St(old, left, mid, r); return old; } public static void merger2St(int[] arr, int left, int mid, int right) { int n[] = new int[right - left + 1]; int i = left, j = mid + 1, k = 0; while (i <= mid && j <= right) { n[k++] = arr[i] > arr[j] ? arr[j++] : arr[i++]; } while (i <= mid) { n[k++] = arr[i++]; } while (j <= right) { n[k++] = arr[j++]; } int index = 0; while (left <= right) { arr[left++] = n[index++]; } } public static int[] merger2St(int[] arrA, int[] arrB) { int a = arrA.length; int b = arrB.length; int n[] = new int[a + b]; int i = 0, j = 0, k = 0; while (i < a && j < b) { n[k++] = arrA[i] > arrB[j] ? arrB[j++] : arrA[i++]; } while (i < a) { n[k++] = arrA[i++]; } while (j < b) { n[k++] = arrB[j++]; } return n; } /** * 冒泡排序 * N^2 */ public void Bubble_Sort() { } /** * 选择排序 * <p> * 不稳定 * <p> * <p> * 最稳定的排序算法之一,因为无论什么数据进去都是O(n2)的时间复杂度,所以用到它的时候,数据规模越小越好 */ public void Selection_Sort() { } @Test public void Insertion_Sort_Test() { int a[] = {4, 48, 12, 7, 1, 5, 8, 9, 2}; System.out.println(Arrays.toString(Insertion_Sort(a))); } /** * 插入排序 * <p> * 稳定 */ public int[] Insertion_Sort(int[] arr) { int len = arr.length; for (int i = 1; i < len; i++) { int tmp = arr[i]; for (int j = i - 1; j >= -1; j--) { if (j >= 0 && tmp < arr[j]) { arr[j + 1] = arr[j]; } else { arr[j + 1] = tmp; break; } } } return arr; } @Test public void Shell_Sort_Test() { int a[] = {4, 48, 12, 7, 1, 5, 8, 9, 2}; System.out.println(Arrays.toString(Shell_Sort(a))); } /** * 希尔排序 * <p> * 不稳定 * <p> * 希尔排序就是对直接插入排序的一个优化 */ public int[] Shell_Sort(int arr[]) { int increment = arr.length / 2; while (increment >0) { for (int a = 0; a < arr.length; a++) { for (int b = a; b < arr.length - increment; b = b + increment) { if (arr[b] > arr[b + increment]) { int tmp = arr[b+increment]; arr[b + increment] = arr[b]; arr[b] = tmp; } } } increment = increment / 2; } return arr; } }
true
bf4e6717ec7f88d0d245b138d30f6ed661dc3184
Java
ai-overflow/ai_backend
/backend/src/main/java/de/hskl/ki/db/repository/interfaces/CustomPageRepository.java
UTF-8
158
1.820313
2
[ "MIT" ]
permissive
package de.hskl.ki.db.repository.interfaces; import de.hskl.ki.db.document.Page; public interface CustomPageRepository { Page getPageById(String id); }
true
59ab158aaca7e7e8790862cee6680b99b77b0a61
Java
denklewer/GWTGames
/src/games/shared/BaseModelListener.java
UTF-8
128
1.757813
2
[]
no_license
package games.shared; public interface BaseModelListener extends GameModelListener { void startMove(); void endMove(); }
true
4e1585ec05f8edcb5628b83c00a4274ecd4ba82d
Java
08Gauri/PJP2
/Income.Calculator/src/main/java/conversion/ConversionRates.java
UTF-8
485
2.859375
3
[]
no_license
package conversion; import java.util.HashMap; public class ConversionRates { static HashMap<String , Float> conversionRate = new HashMap<String, Float>(); static { conversionRate.put("USD" , (float) 1.0); conversionRate.put("INR" , (float) 66.0); conversionRate.put("GBP" , (float) 0.67); conversionRate.put("SGD" , (float) 1.5); conversionRate.put("HKD" , (float) 8.0); } public float getCurrentFactor(String currency) { return conversionRate.get(currency); } }
true
69071823f9b501277d88713eebf14596be34385c
Java
zhongxingyu/Seer
/Diff-Raw-Data/30/30_a1b317ce6e6ce80a2d918a237213b0cf1c744256/Multiplier/30_a1b317ce6e6ce80a2d918a237213b0cf1c744256_Multiplier_t.java
UTF-8
1,400
2.515625
3
[]
no_license
package net.dandielo.citizens.traders_v3.utils.items.attributes; import org.bukkit.inventory.ItemStack; import net.dandielo.citizens.traders_v3.core.exceptions.InvalidItemException; import net.dandielo.citizens.traders_v3.core.exceptions.attributes.AttributeInvalidValueException; import net.dandielo.citizens.traders_v3.core.exceptions.attributes.AttributeValueNotFoundException; import net.dandielo.citizens.traders_v3.utils.items.Attribute; import net.dandielo.citizens.traders_v3.utils.items.ItemAttr; @Attribute(name = "Multiplier", key = "m", standalone = true, priority = 0) public class Multiplier extends ItemAttr { private double multiplier; public Multiplier(String key) { super(key); } public double getMultiplier() { return multiplier; } @Override public void onLoad(String data) throws AttributeInvalidValueException { try { multiplier = Double.parseDouble(data); } catch( Exception e ) { throw new AttributeInvalidValueException(getInfo(), data); } } @Override public String onSave() { return String.format("%.2f", multiplier); } @Override public void onAssign(ItemStack item) throws InvalidItemException { //unused } @Override public void onFactorize(ItemStack item) throws AttributeValueNotFoundException { throw new AttributeValueNotFoundException(); } }
true
d557a77fb5f6070a7d50fbd0018c83e0a4e522a2
Java
navspeak/mallbuddy
/MallBuddy/src/main/java/com/nav/csv/util/CSVUtil.java
UTF-8
1,268
2.96875
3
[]
no_license
package com.nav.csv.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public class CSVUtil { private static Logger logger = Logger.getLogger(CSVUtil.class); /** * Checks if a string is valid file path * @param path * @return absolute file path if the input is valid * else return null */ public static String checkPath(String path){ if (path == null) return null; try { File file = new File(path); if (file.exists() == true) { return file.getAbsolutePath(); } } catch (Exception e) { logger.warn(path + "doesn't exist. Moving on..."); // return null } return null; } /** * * @param fileName * @return * @throws IOException */ public static List<String[]> readFromCSV(String fileName) throws IOException{ Path filePath = Paths.get(fileName); List<String[]> elements = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(filePath)) { String line = ""; while ((line = reader.readLine()) != null){ elements.add(line.split(",")); } } return elements; } }
true
6919c7b8d08a92ce35f3d3a74acdaf0f27e125ff
Java
liangbingtian/miaosha
/spring-boot-starter-metadata/src/main/java/com/yonyou/einvoice/common/metadata/enums/DirectionEnum.java
UTF-8
216
2
2
[]
no_license
package com.yonyou.einvoice.common.metadata.enums; import lombok.Getter; @Getter public enum DirectionEnum { ASC("asc"), DESC("desc"); String code; DirectionEnum(String code) { this.code = code; } }
true
4484290c353e2c462837654f7103134ec8275634
Java
xiongkai888/kang
/kang/app/src/main/java/com/lanmei/kang/ui/merchant/ReserveInfoActivity.java
UTF-8
9,569
1.867188
2
[]
no_license
package com.lanmei.kang.ui.merchant; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import com.data.volley.Response; import com.data.volley.error.VolleyError; import com.lanmei.kang.R; import com.lanmei.kang.alipay.AlipayHelper; import com.lanmei.kang.api.KangQiMeiApi; import com.lanmei.kang.bean.MerchantDetailsBean; import com.lanmei.kang.bean.OrderIDBean; import com.lanmei.kang.bean.WeiXinBean; import com.lanmei.kang.bean.ZhiFuBaoBean; import com.lanmei.kang.event.PaySucceedEvent; import com.lanmei.kang.helper.WXPayHelper; import com.lanmei.kang.ui.mine.activity.MyItemsOrderActivity; import com.lanmei.kang.util.CommonUtils; import com.lanmei.kang.util.EditTextWatcher; import com.xson.common.api.AbstractApi; import com.xson.common.app.BaseActivity; import com.xson.common.bean.DataBean; import com.xson.common.helper.BeanRequest; import com.xson.common.helper.HttpClient; import com.xson.common.utils.DoubleUtil; import com.xson.common.utils.IntentUtil; import com.xson.common.utils.StringUtils; import com.xson.common.utils.UIHelper; import com.xson.common.widget.CenterTitleToolbar; import org.greenrobot.eventbus.Subscribe; import butterknife.InjectView; import butterknife.OnClick; /** * 预定信息 */ public class ReserveInfoActivity extends BaseActivity { int type = 6;//支付类型 7:微信支付 1:支付宝 6:余额支付 @InjectView(R.id.toolbar) CenterTitleToolbar mToolbar; @InjectView(R.id.order_num_et) EditText orderNumEt;//订购数量 @InjectView(R.id.cb_zhifubao) CheckBox mZhifubaoCB;//支付宝 @InjectView(R.id.cb_weixin) CheckBox mWeixinCB;//微信 @InjectView(R.id.cb_balance) CheckBox mBalanceCB;//余额 MerchantDetailsBean.GoodsBean bean;//商家的服务项目 int orderNum = 1;//订购数量,默认1 double price; @InjectView(R.id.name_tv) TextView nameTv; @InjectView(R.id.items_tv) TextView itemsTv; @InjectView(R.id.reserve_date_tv) TextView reserveDateTv; @InjectView(R.id.total_price_tv) TextView totalPriceTv; @Override public int getContentViewId() { return R.layout.activity_reserve_info; } @Override public void initIntent(Intent intent) { super.initIntent(intent); Bundle bundle = intent.getBundleExtra("bundle"); bean = (MerchantDetailsBean.GoodsBean) bundle.getSerializable("bean"); } @Override protected void initAllMembersView(Bundle savedInstanceState) { setSupportActionBar(mToolbar); ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayShowTitleEnabled(true); actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setTitle(R.string.reserve_info); actionbar.setHomeAsUpIndicator(R.mipmap.back_g); String priceStr = bean.getSell_price(); if (!StringUtils.isEmpty(priceStr)) { price = Double.valueOf(priceStr); } nameTv.setText(bean.getPlace_name()); itemsTv.setText(bean.getName()); totalPriceTv.setText(price + ""); reserveDateTv.setText(CommonUtils.getData()); orderNumEt.addTextChangedListener(new EditTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (StringUtils.isEmpty(s + "")) { orderNum = 0; } else { orderNum = EditTextWatcher.StringToInt(s); } } }); } //选择支付方式 private void selectCheckBox(CheckBox cb1, CheckBox cb2, CheckBox cb3, int type) { this.type = type; cb1.setChecked(true); if (cb2.isChecked() || cb3.isChecked()) { cb2.setChecked(false); cb3.setChecked(false); } } public boolean isSelect() { return type == 6 || type == 7 || type == 1; } private void ajaxBalancePay() { HttpClient httpClient = HttpClient.newInstance(this); KangQiMeiApi api = new KangQiMeiApi("reservation/save"); api.add("uid",api.getUserId(this)); api.add("mid",bean.getMid()); api.add("items_id",bean.getId()); api.add("guest",orderNum); long time = System.currentTimeMillis(); api.add("stime",time); api.add("etime",time); api.add("pay_type",type); api.add("token",api.getToken(this)); httpClient.loadingRequest(api, new BeanRequest.SuccessListener<DataBean<OrderIDBean>>() { @Override public void onResponse(DataBean<OrderIDBean> response) { if (isFinishing()) { return; } OrderIDBean bean = response.data; if (bean != null) { loadPayMent(bean.getOrder_id() + ""); } } }); } private void loadPayMent(String order_id) { KangQiMeiApi api = new KangQiMeiApi("payment/pay"); api.add("order_id",order_id); api.add("uid",api.getUserId(this)); api.add("token",api.getToken(this)); api.setMethod(AbstractApi.Method.GET); HttpClient httpClient = HttpClient.newInstance(this); if (type == 1) {//支付宝支付 httpClient.loadingRequest(api, new BeanRequest.SuccessListener<DataBean<String>>() { @Override public void onResponse(DataBean<String> response) { if (isFinishing()) { return; } String bean = response.data; AlipayHelper alipayHelper = new AlipayHelper(ReserveInfoActivity.this); alipayHelper.setPayParam(bean); alipayHelper.payNow(); } }); } else if (type == 7) {//微信支付 httpClient.loadingRequest(api, new BeanRequest.SuccessListener<DataBean<WeiXinBean>>() { @Override public void onResponse(DataBean<WeiXinBean> response) { if (isFinishing()) { return; } WeiXinBean bean = response.data; WXPayHelper payHelper = new WXPayHelper(ReserveInfoActivity.this); payHelper.setPayParam(bean); payHelper.orderNow(); } }); } else if (type == 6) {//余额 httpClient.loadingRequest(api, new BeanRequest.SuccessListener<DataBean<ZhiFuBaoBean>>() { @Override public void onResponse(DataBean<ZhiFuBaoBean> response) { if (isFinishing()) { return; } IntentUtil.startActivity(ReserveInfoActivity.this, MyItemsOrderActivity.class); finish(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { UIHelper.ToastMessage(ReserveInfoActivity.this, getString(R.string.balance_insufficient)); } }); } } @OnClick({R.id.order_subtract_iv, R.id.order_add_iv, R.id.ll_zhifubao_pay, R.id.ll_weixin_pay, R.id.ll_balance_pay, R.id.cb_zhifubao, R.id.cb_weixin, R.id.cb_balance, R.id.particulars_tv, R.id.bt_pay}) public void onViewClicked(View view) { if (!CommonUtils.isLogin(this)){ return; } switch (view.getId()) { case R.id.order_subtract_iv://订购减 if (orderNum <= 1) { return; } orderNum--; orderNumEt.setText(orderNum + ""); totalPriceTv.setText(DoubleUtil.formatFloatNumber(orderNum * price)); break; case R.id.order_add_iv://订购加 if (orderNum == 9999) { return; } orderNum++; orderNumEt.setText(orderNum + ""); totalPriceTv.setText(DoubleUtil.formatFloatNumber(orderNum * price)); break; case R.id.ll_weixin_pay: case R.id.cb_weixin://微信 selectCheckBox(mWeixinCB, mZhifubaoCB, mBalanceCB, 7); break; case R.id.ll_zhifubao_pay: case R.id.cb_zhifubao://支付宝 selectCheckBox(mZhifubaoCB, mWeixinCB, mBalanceCB, 1); break; case R.id.ll_balance_pay: case R.id.cb_balance://余额支付 selectCheckBox(mBalanceCB, mWeixinCB, mZhifubaoCB, 6); break; case R.id.particulars_tv://明细 UIHelper.ToastMessage(this, R.string.developing); break; case R.id.bt_pay://确认并支付 if (isSelect()) { ajaxBalancePay(); } else { UIHelper.ToastMessage(this, R.string.developing); } break; } } //支付成功调用 @Subscribe public void paySucceedEvent(PaySucceedEvent event) { IntentUtil.startActivity(ReserveInfoActivity.this, MyItemsOrderActivity.class); finish(); } }
true
82689da2eb0f4b3d426dc69aee98c4e4de4a576e
Java
jmallikharjun/BethAPIService
/src/main/java/com/beth/infy/controller/AbstractController.java
UTF-8
2,400
2.15625
2
[]
no_license
package com.beth.infy.controller; import com.beth.infy.util.CommonConstants; import com.google.gson.Gson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class AbstractController { public static final Gson gson = new Gson(); public static final Logger logger = LoggerFactory.getLogger(CommonConstants.LOGGER_FILE_NAME); String FILE_UPLOAD_LOCATION = CommonConstants.FILE_CONVERT_DESTINATION_FOLDER_LOCATION; public boolean templateSkeletonAlreadyGenerated(String templateName) { File tmpDir = new File(templateName); return(tmpDir.exists()); } public String loadFileContents(String fileName) { try { return new String(Files.readAllBytes(Paths.get(fileName))); } catch (IOException e) { e.printStackTrace(); return null; } } public boolean verifyTemplateMappingExists(String templateName) { //TODO - need logic to check if tempalate mapping already done. return true; } protected String convertFileContentToJson(String fileContents, String fileType) { //TODO - need to convert to json string dynamically. return "" + "{\n" + " \"key3\": {\n" + " \"key103\": \"STG\",\n" + " \"key113\": \"RR40\",\n" + " \"key108\": \"2913105368733B06\",\n" + " \"key111\": \"001\",\n" + " \"key121\": \"0234cd54-dcf7-4361-b87f-6c0ddbaab3a2\"\n" + " },\n" + " \"key4\": {\n" + " \"key20\": \"AT78096594500102\",\n" + " \"key21\": \"FT39BT003401\",\n" + " \"key32A\": \"190527GBP250000\",\n" + " \"key52A\": \"BANKUS33XXX\",\n" + " \"key56A\": \"//SC730018 PARBGB2LLON\",\n" + " \"key57A\": \"INSECHZZXXX\",\n" + " \"key58A\": \"/GB16RBOS16043110339295 BANKCHZZXXX\"\n" + " },\n" + " \"key1\": \"F01BOFAGB22DXXX4003469973\",\n" + " \"key2\": \"I202RBOSGB55XXXXN\"\n" + "}"; } protected String getMappingFileName(String fileType) { if (fileType.equalsIgnoreCase(CommonConstants.TEMPLATE_TYPE)) { return CommonConstants.PS009_TEMPLATE_MAPPING_LOCATION; } return null; } }
true
bda46226d09b057eff54730c136d6907462b36b5
Java
zhanshilixinhao/GiftCircle
/app/src/main/java/com/chouchongkeji/service/iwant/merchant/impl/MerchantServiceImpl.java
UTF-8
4,204
2.171875
2
[]
no_license
package com.chouchongkeji.service.iwant.merchant.impl; import com.alibaba.fastjson.JSON; import com.chouchongkeji.dial.dao.iwant.merchant.MerchantMapper; import com.chouchongkeji.goexplore.common.Response; import com.chouchongkeji.goexplore.common.ResponseFactory; import com.chouchongkeji.dial.pojo.iwant.merchant.Merchant; import com.chouchongkeji.service.iwant.merchant.MerchantService; import com.chouchongkeji.service.iwant.merchant.vo.MerchantVo; import com.chouchongkeji.util.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author yy * @date 2018/6/20 **/ @Service public class MerchantServiceImpl implements MerchantService{ @Autowired private MerchantMapper merchantMapper; /** * 商家认证申请 * * @param: [userId 用户id,merchantVo 商家信息] * @return: com.chouchongkeji.goexplore.common.Response * @author: yy * @Date: 2018/6/20 */ @Override public Response applyMerchant(Integer userId, MerchantVo merchantVo) { Merchant merchant = merchantMapper.selectByUserId(userId); if (merchant != null) { if (merchant.getStatus() == Constants.MERCHANT_STATUS.PASS){ return ResponseFactory.err("商家认证已提交,并且已通过!"); }else if (merchant.getStatus() == Constants.MERCHANT_STATUS.NO_PASS){ // 被驳回,重新提交 merchant.setUserId(userId); merchant.setUpdated(new Date()); merchant.setStatus((byte)2); merchant.setRegistrationNo(merchantVo.getRegistrationNo()); merchant.setPhone(merchantVo.getPhone()); if (merchantVo.getOtherPics() != null && merchantVo.getOtherPics().size() > 0) { merchant.setOtherPics(JSON.toJSONString(merchantVo.getOtherPics())); } merchant.setName(merchantVo.getName()); merchant.setLicensePic(merchantVo.getLicensePic()); merchant.setLegalPerson(merchantVo.getLegalPerson()); merchant.setCreated(new Date()); merchant.setAddress(merchantVo.getAddress()); int i = merchantMapper.updateByPrimaryKeySelective(merchant); if (i < 1) { return ResponseFactory.err("申请失败"); } return ResponseFactory.sucMsg("重新申请成功"); }else { return ResponseFactory.err("商家认证审核中!"); } } merchant = new Merchant(); merchant.setUserId(userId); merchant.setUpdated(new Date()); merchant.setStatus((byte)2); merchant.setRegistrationNo(merchantVo.getRegistrationNo()); merchant.setPhone(merchantVo.getPhone()); if (merchantVo.getOtherPics() != null && merchantVo.getOtherPics().size() > 0) { merchant.setOtherPics(JSON.toJSONString(merchantVo.getOtherPics())); } merchant.setName(merchantVo.getName()); merchant.setLicensePic(merchantVo.getLicensePic()); merchant.setLegalPerson(merchantVo.getLegalPerson()); merchant.setCreated(new Date()); merchant.setAddress(merchantVo.getAddress()); int count = merchantMapper.insert(merchant); if (count == 1) { return ResponseFactory.sucMsg("申请成功"); } return ResponseFactory.err("申请失败"); } /** * 获得该用户的商家认证状态 * * @param: [userId 用户id] * @return: com.chouchongkeji.goexplore.common.Response * @author: yy * @Date: 2018/6/20 */ @Override public Response getMerchantStatus(Integer userId) { Map map = new HashMap(); Merchant merchant = merchantMapper.selectByUserId(userId); if (merchant != null) { map.put("status", merchant.getStatus()); return ResponseFactory.sucData(map); } map.put("status", 0); return ResponseFactory.sucData(map); } }
true
2999dbae36a7bc2b29ff7118b6639ac5de6bc158
Java
happy6eve/cap-other
/cap-metadata/src/main/java/com/comtop/cap/bm/metadata/page/template/model/QueryAreaComponentVO.java
UTF-8
3,215
1.976563
2
[]
no_license
/****************************************************************************** * Copyright (C) 2015 ShenZhen ComTop Information Technology Co.,Ltd * All Rights Reserved. * 本软件为深圳康拓普开发研制。未经本公司正式书面同意,其他任何个人、团体不得使用、 * 复制、修改或发布本软件. *****************************************************************************/ package com.comtop.cap.bm.metadata.page.template.model; import java.util.ArrayList; import java.util.List; import com.comtop.cap.bm.metadata.base.model.BaseMetadata; import comtop.org.directwebremoting.annotations.DataTransferObject; /** * 界面配置元数据模版表单产生的数据值 * * @author 诸焕辉 * @version jdk1.6 * @version 2016-1-7 诸焕辉 */ @DataTransferObject public class QueryAreaComponentVO extends BaseMetadata { /** 标识 */ private static final long serialVersionUID = 1L; /** * 控件Id */ private String id; /** * 选择的实体ID */ private String entityId; /** * 实体别名 */ private String entityAlias; /** * 固定查询区域数据集 */ private List<FormAreaComponentVO> fixedQueryAreaList = new ArrayList<FormAreaComponentVO>(); /** * 更多查询区域数据集 */ private List<FormAreaComponentVO> moreQueryAreaList = new ArrayList<FormAreaComponentVO>(); /** * @return 获取 id属性值 */ public String getId() { return id; } /** * @param id 设置 id 属性值为参数值 id */ public void setId(String id) { this.id = id; } /** * @return 获取 entityId属性值 */ public String getEntityId() { return entityId; } /** * @param entityId 设置 entityId 属性值为参数值 entityId */ public void setEntityId(String entityId) { this.entityId = entityId; } /** * @return 获取 fixedQueryAreaList属性值 */ public List<FormAreaComponentVO> getFixedQueryAreaList() { return fixedQueryAreaList; } /** * @param fixedQueryAreaList 设置 fixedQueryAreaList 属性值为参数值 fixedQueryAreaList */ public void setFixedQueryAreaList(List<FormAreaComponentVO> fixedQueryAreaList) { this.fixedQueryAreaList = fixedQueryAreaList; } /** * @return 获取 moreQueryAreaList属性值 */ public List<FormAreaComponentVO> getMoreQueryAreaList() { return moreQueryAreaList; } /** * @param moreQueryAreaList 设置 moreQueryAreaList 属性值为参数值 moreQueryAreaList */ public void setMoreQueryAreaList(List<FormAreaComponentVO> moreQueryAreaList) { this.moreQueryAreaList = moreQueryAreaList; } /** * @return 获取 entityAlias属性值 */ public String getEntityAlias() { return entityAlias; } /** * @param entityAlias 设置 entityAlias 属性值为参数值 entityAlias */ public void setEntityAlias(String entityAlias) { this.entityAlias = entityAlias; } }
true
14a52019748dcdec479665633b34f2496033e7ab
Java
Nomiracle/springboot
/LoggingSpringBoot/src/main/java/App/Application.java
UTF-8
524
2.3125
2
[]
no_license
package App; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class,args); logger.info("Simple log statement with input {},{} and {}",1,2,3); } }
true
b9f129442e4cd988a31208fcea6d8c9d84be0b95
Java
Samartinho/AcessoClube
/AcessoClube/Classes/Pessoa.java
ISO-8859-1
1,241
3.375
3
[]
no_license
import java.time.LocalDate; public class Pessoa { private String Nome; private long cpf; private LocalDate dataDeNascimento; public Pessoa(String nome, long CPF, LocalDate Data) throws Exceo { this.setCpf(CPF); this.setDataDeNascimento(Data); this.setNome(nome); } public String getNome() { return Nome; } public void setNome(String nome) throws Exceo{ if(nome != null) { this.Nome = nome; } else { throw new Exceo("Nome Invalido"); } } public long getCpf() { return cpf; } public void setCpf(long cpf) throws Exceo { if(cpf > 100000000) { this.cpf = cpf; } else { throw new Exceo("CPF invalido"); } } public LocalDate getDataDeNascimento() { return dataDeNascimento; } public void setDataDeNascimento(LocalDate dataDeNascimento) throws Exceo { if(dataDeNascimento.isAfter(LocalDate.of(1900, 1, 1))) { this.dataDeNascimento = dataDeNascimento; } else { throw new Exceo("Data de Nascimento invalida"); } } @Override public String toString() { return "Pessoa { nome:" + Nome + ", CPF: " + cpf + ", Data de Nascimento: " + dataDeNascimento.toString() + "}"; } }
true
d1c13ae87b26dbccc9c202dcd74a510c6e33e230
Java
liorg/runnerdevice
/src/il/co/runnerdevice/Tutorial/LoginActivity.java
UTF-8
5,906
2.296875
2
[]
no_license
package il.co.runnerdevice.Tutorial; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import il.co.runnerdevice.R; //http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ public class LoginActivity extends Activity { // Email, password edittext EditText txtUsername, txtPassword; // login button Button btnLogin; // Alert Dialog Manager AlertDialogManager alert = new AlertDialogManager(); // Session Manager Class SessionManager session; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Session Manager session = new SessionManager(getApplicationContext()); // Email, Password input text txtUsername = (EditText) findViewById(R.id.txtUsername); txtPassword = (EditText) findViewById(R.id.txtPassword); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG) .show(); // Login button btnLogin = (Button) findViewById(R.id.btnLogin); // Login button click event btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { String username = txtUsername.getText().toString(); String password = txtPassword.getText().toString(); if (username.trim().length() > 0 && password.trim().length() > 0) { new LoginRunner(username.trim(), password.trim(), session) .execute(); } else { // user didn't entered username or password // Show alert asking him to enter the details alert.showAlertDialog(LoginActivity.this, "Login failed..", "Please enter username and password", false); } } }); } public class LoginRunner extends AsyncTask<Void, Void, String> { String _user, _pws; SessionManager _session; JSONObject _access_token; ProgressDialog _dialog; @Override protected void onPreExecute() { super.onPreExecute(); _dialog = ProgressDialog.show(LoginActivity.this, "נא המתן", "נא המתן שיתבצע התהליך", true, false); } public LoginRunner(String user, String pws, SessionManager session) { super(); _user = user; _pws = pws; _session = session; } @Override protected String doInBackground(Void... params) { String text = null; String token = ""; List<NameValuePair> nameValuePairs = CustomHttpClient.GetLoginData( _user, _pws); HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httppost = new HttpPost("http://kipodeal.co.il:4545/token"); httppost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8"); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // Execute HTTP Post Request try { HttpResponse response = httpClient.execute(httppost); Log.d("Response:", response.toString()); text = CustomHttpClient.GetASCIIContentFromEntity(response .getEntity()); _access_token = new JSONObject(text); } catch (JSONException eej) { eej.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return token; } protected void onPostExecute(String results) { _dialog.dismiss(); String err; String errDesc = ""; if (_access_token == null) { alert.showAlertDialog(LoginActivity.this, "Login failed..", "Error Ocuur", false); return; } try { if (_access_token.has("error")) { err = _access_token.getString("error"); errDesc = _access_token.has("error_description") ? _access_token .getString("error_description") : "error occur!!!"; alert.showAlertDialog(LoginActivity.this, "Login failed..", errDesc, false); } else { String token = _access_token.getString("access_token"); String refresh_token = _access_token .getString("refresh_token"); String userName = _access_token.getString("userName"); String currentTime = _access_token .getString("m:currentTime"); String userId = _access_token.getString("m:userId"); String exTime = _access_token.getString("m:expiredOn"); String roles = _access_token.getString("roles"); // createLoginSession(String name, String refresh,String // currentdate,String expireddate,String token,String roles) _session.createLoginSession(userName, refresh_token, currentTime, exTime, token, roles, userId); Toast.makeText(getApplicationContext(), "המשתמש אומת", Toast.LENGTH_LONG).show(); // alert.showAlertDialog(LoginActivity.this, "Ok", "Ok", // false); // Staring MainActivity Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); finish(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
1f0079a69379db58e2882abd54fa9c617a1519dc
Java
biemo8/bbs-cloud
/app-biz/biemo-bbs/biemo-bbs-api/src/main/java/com/biemo/cloud/bbs/api/vo/BUserVo.java
UTF-8
4,580
1.867188
2
[ "Apache-2.0" ]
permissive
package com.biemo.cloud.bbs.api.vo; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import java.io.Serializable; /** * 对象 b_user * * @author makesoft * @date 2021-08-11 */ public class BUserVo implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String username; private String email; private Integer emailVerified; private String nickname; private String avatar; private String backgroundImage; private String password; private String homePage; private String description; private Long score; private Long status; private Long topicCount; private Long commentCount; private String roles; private Long type; private Long forbiddenEndTime; private Long createTime; private Long updateTime; private String captchaId; private String captchaCode; private String rePassword; public String getCaptchaId() { return captchaId; } public void setCaptchaId(String captchaId) { this.captchaId = captchaId; } public String getCaptchaCode() { return captchaCode; } public void setCaptchaCode(String captchaCode) { this.captchaCode = captchaCode; } public String getRePassword() { return rePassword; } public void setRePassword(String rePassword) { this.rePassword = rePassword; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setEmailVerified(Integer emailVerified) { this.emailVerified = emailVerified; } public Integer getEmailVerified() { return emailVerified; } public void setNickname(String nickname) { this.nickname = nickname; } public String getNickname() { return nickname; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getAvatar() { return avatar; } public void setBackgroundImage(String backgroundImage) { this.backgroundImage = backgroundImage; } public String getBackgroundImage() { return backgroundImage; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public void setHomePage(String homePage) { this.homePage = homePage; } public String getHomePage() { return homePage; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setScore(Long score) { this.score = score; } public Long getScore() { return score; } public void setStatus(Long status) { this.status = status; } public Long getStatus() { return status; } public void setTopicCount(Long topicCount) { this.topicCount = topicCount; } public Long getTopicCount() { return topicCount; } public void setCommentCount(Long commentCount) { this.commentCount = commentCount; } public Long getCommentCount() { return commentCount; } public void setRoles(String roles) { this.roles = roles; } public String getRoles() { return roles; } public void setType(Long type) { this.type = type; } public Long getType() { return type; } public void setForbiddenEndTime(Long forbiddenEndTime) { this.forbiddenEndTime = forbiddenEndTime; } public Long getForbiddenEndTime() { return forbiddenEndTime; } }
true
83d3f634dd29890dd8da8eefa66ef1d4b38800f9
Java
messi1913/jdfaster
/jdfsample/src/main/java/com/jdfaster/jdfsample/utils/SvcAdapter.java
UTF-8
2,494
2.203125
2
[]
no_license
package com.jdfaster.jdfsample.utils; import java.nio.charset.Charset; import org.apache.http.client.fluent.Content; import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Response; import org.apache.http.entity.ContentType; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.codehaus.jackson.map.ObjectMapper; import com.jdfaster.jdfsample.utils.SvcUtils.Svc; import com.jdfaster.service.DefaultServiceAdapter; import com.jdfaster.service.ServiceAdapter; import com.jdfaster.test.TestConfigs; public class SvcAdapter extends DefaultServiceAdapter implements ServiceAdapter { private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); } @Override public Object invoke(ProceedingJoinPoint point) throws Throwable { // Test test = TestUtils.getCurrentTest(); // if (test == null) // throw new IllegalArgumentException("Cannot find Current Test!"); Signature signature = point.getSignature(); Object[] args = point.getArgs(); Svc svc = SvcUtils.getSvc(signature, args); if (svc == null) throw new IllegalArgumentException("Cannot find Service!"); String uri; { StringBuffer buf = new StringBuffer(); { TestConfigs configs = TestConfigs.getInstance(""); buf = buf.append(configs.getTargetUrl()); String id = svc.getUrl(); if (buf.toString().endsWith("/")) { if (id.startsWith("/")) id = id.substring(1); } else { if (!id.startsWith("/")) buf.append("/"); } buf.append(id); } uri = buf.toString(); } { Object input = args[0]; String inStr; { inStr = mapper.writeValueAsString(input); } Request req; { switch (svc.getMethod()) { case GET: req = Request.Get(uri); break; case POST: req = Request.Post(uri); break; case PUT: req = Request.Put(uri); break; case DELETE: req = Request.Delete(uri); break; default: throw new IllegalArgumentException("Unsupported HTTP Method for Test"); } } req.bodyString(inStr, ContentType.APPLICATION_JSON); Response resp = req.execute(); String outStr; { Content content = resp.returnContent(); outStr = content.asString(Charset.forName("UTF-8")); } Object output = new ObjectMapper().readValue(outStr, svc.getOutputType()); return output; } } }
true
7b7b3582d26796c40c7a8f5afc4bfc268c716b9f
Java
AryanSankholkar/WeightLoss-Coach
/src/Example.java
UTF-8
2,999
2.96875
3
[]
no_license
import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Font; import java.awt.Color; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JPasswordField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Example { private JFrame frame; /** * Launch the application. */ public static void NewScreen() { EventQueue.invokeLater(new Runnable() { public void run() { try { Example window = new Example(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Example() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.getContentPane().setBackground(Color.WHITE); frame.setBackground(Color.BLACK); frame.getContentPane().setForeground(Color.WHITE); frame.setBounds(100, 100, 553, 428); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel(""); ImageIcon img = new ImageIcon(this.getClass().getResource("/image.jpg")); lblNewLabel.setIcon(img); lblNewLabel.setBounds(10, 0, 517, 109); frame.getContentPane().add(lblNewLabel); JButton btnNewButton_1 = new JButton("WORKOUT "); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bt1 nw = new Bt1(); nw.NewScreen(); } }); btnNewButton_1.setBounds(20, 355, 100, 23); frame.getContentPane().add(btnNewButton_1); JButton btnNewButton_2 = new JButton("DIET "); btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bt2 nw = new Bt2(); nw.NewScreen(); } }); btnNewButton_2.setBounds(224, 355, 100, 23); frame.getContentPane().add(btnNewButton_2); JButton btnNewButton_3 = new JButton("MY PROFILE "); btnNewButton_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bt3 nw = new Bt3(); nw.NewScreen(); } }); btnNewButton_3.setBounds(427, 355, 100, 23); frame.getContentPane().add(btnNewButton_3); JLabel lblNewLabel_1 = new JLabel(""); ImageIcon image = new ImageIcon(this.getClass().getResource("/Dumbelll.png")); lblNewLabel_1.setIcon(image); lblNewLabel_1.setBounds(10, 120, 184, 224); frame.getContentPane().add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("New label"); lblNewLabel_2.setIcon(new ImageIcon("C:\\Users\\Aryan Sankholkar\\Downloads\\weights.png")); lblNewLabel_2.setBounds(135, 173, 260, 150); frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("New label"); lblNewLabel_3.setIcon(new ImageIcon("C:\\Users\\Aryan Sankholkar\\Downloads\\Diet.png")); lblNewLabel_3.setBounds(416, 173, 100, 150); frame.getContentPane().add(lblNewLabel_3); } }
true
e37a52b4008027d19874337a3834f5a1a8b7ea85
Java
elsahmed/Greenfoot-final-project
/Instructions.java
UTF-8
2,143
3.234375
3
[]
no_license
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Instructions on how to play the game, includes what key actions and game rules * * @author Elsa Ahmed * @version December 2020 */ public class Instructions extends World { /** * Constructor for Instructions class. */ public Instructions() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 600, 1); StartGame sg = new StartGame(); addObject(sg, 0, 0); Label htp = new Label("How To Play", 50); addObject(htp, 500, 40); Label s1 = new Label("1. Press 'UP' arrow key to move the rocket forward", 35); addObject(s1, 345, 160); Label s2 = new Label("2. Press 'LEFT' or 'RIGHT' arrow key to turn the rocket the direction", 35); addObject(s2, 455, 200); Label s3 = new Label("3. Press 'X' AND 'UP' arrow key to accelerate the rocket forward", 35); addObject(s3, 430, 240); Label s4 = new Label("4. Press 'SPACE' key to shoot a bullet", 35); addObject(s4, 265, 280); Label s5 = new Label("5. If rocket is hit by a Meteoroid 5 times, game over", 35); addObject(s5, 350, 320); Label s6 = new Label("6. If no bullets left AND a Meteoroid hits the end of the screen, game over", 35); addObject(s6, 495, 360); Label s7 = new Label("7. Move the rocket to the golden ball to get more ammo", 35); addObject(s7, 375, 400); Label s8 = new Label("8. Press [ESC] to exit game at anytime", 35); addObject(s8, 265, 440); /* Label s9 = new Label("9. Press 'UP' arrow key to move the rocket forward", 35); addObject(s9, 350, 480); Label s10 = new Label("10. Press 'UP' arrow key to move the rocket forward", 35); addObject(s10, 342, 520); */ Label start = new Label("Press [space] to start the game", 35); start.setFillColor(Color.YELLOW); addObject(start, 500, 550); } }
true
345951876f8930e16e0a68609a95641085a2ff25
Java
JackChan1999/boohee_v5.6
/src/main/java/com/ToxicBakery/viewpager/transforms/ZoomOutTranformer.java
UTF-8
651
2.46875
2
[ "Apache-2.0" ]
permissive
package com.ToxicBakery.viewpager.transforms; import android.view.View; public class ZoomOutTranformer extends ABaseTransformer { protected void onTransform(View view, float position) { float scale = 1.0f + Math.abs(position); view.setScaleX(scale); view.setScaleY(scale); view.setPivotX(((float) view.getWidth()) * 0.5f); view.setPivotY(((float) view.getHeight()) * 0.5f); float f = (position < -1.0f || position > 1.0f) ? 0.0f : 1.0f - (scale - 1.0f); view.setAlpha(f); if (position == -1.0f) { view.setTranslationX((float) (view.getWidth() * -1)); } } }
true
47f234235f42fc8ea1d7d8951c323331879418b8
Java
igara432/mf-predictor
/mf-predictor/mf_predictor/trunk/mf_predictor/src/main/java/jp/ndca/recommend/common/data/DatasetAnalyzer.java
UTF-8
3,810
2.9375
3
[]
no_license
package jp.ndca.recommend.common.data; import java.util.Iterator; import it.unimi.dsi.fastutil.ints.Int2DoubleMap; import jp.ndca.recommend.common.structure.vector.Vector; public class DatasetAnalyzer { /** * average all feature values * @param dataset * @return */ public static double aveValue( RatingDataset dataset ){ double ave = 0; int featureNum = 0; for( RatingData data : dataset ){ Vector vector = data.getVector(); Iterator<Int2DoubleMap.Entry> ite = vector.iterator(); int size = vector.size(); featureNum += size; for( int i = 0 ; i < size ; i++ ){ Int2DoubleMap.Entry entry = ite.next(); ave += entry.getDoubleValue(); } } return ave / (double)featureNum; } public static <K extends Vector> double aveValue( K[] dataset ){ double ave = 0; int featureNum = 0; for( Vector vector : dataset ){ Iterator<Int2DoubleMap.Entry> ite = vector.iterator(); int size = vector.size(); featureNum += size; for( int i = 0 ; i < size ; i++ ){ Int2DoubleMap.Entry entry = ite.next(); ave += entry.getDoubleValue(); } } return ave / (double)featureNum; } public static double varValue( RatingDataset dataset ){ double ave = aveValue(dataset); return varValue( dataset, ave ); } public static double varValue( RatingDataset dataset, double ave ){ double var = 0; int featureNum = 0; for( RatingData data : dataset ){ Vector vector = data.getVector(); Iterator<Int2DoubleMap.Entry> ite = vector.iterator(); int size = vector.size(); featureNum += size; for( int i = 0 ; i < size ; i++ ){ Int2DoubleMap.Entry entry = ite.next(); double diff = ave - entry.getDoubleValue(); var += diff * diff; } } return var / (double)featureNum; } /** * get MaxID in the dataset * @param dataset * @return */ public static int getMaxFeatureID( RatingDataset dataset ) { int datasetMaxID = Integer.MIN_VALUE; for( RatingData data : dataset ){ Vector vector = data.getVector(); int maxID = vector.getMaxID(); if( datasetMaxID < maxID ) datasetMaxID = maxID; } return datasetMaxID; } public static <K extends Vector> int getMaxFeatureID( Iterable<K> dataset ){ int maxIndex = 0; for( Vector vector : dataset){ if( vector == null ) continue; int index = vector.getMaxID(); if( maxIndex < index ) maxIndex = index; } return maxIndex; } public static <K extends Vector> int getMaxFeatureID( K[] dataset ){ int maxIndex = 0; for( Vector vector : dataset){ if( vector == null ) continue; int index = vector.getMaxID(); if( maxIndex < index ) maxIndex = index; } return maxIndex; } /** * get MaxValue * @param dataset * @return */ public static double getMaxValue( RatingDataset dataset ) { double datasetMaxValue = Double.NEGATIVE_INFINITY; for( RatingData basicData : dataset ){ Vector vector = basicData.getVector(); double maxValue = vector.getMaxValue(); if( datasetMaxValue < maxValue ) datasetMaxValue = maxValue; } return datasetMaxValue; } public static <K extends Vector> double getMaxValue( Iterable<K> dataset ){ double maxValue = 0; for( Vector vector : dataset){ if( vector == null ) continue; double value = vector.getMaxValue(); if( maxValue < value ) maxValue = value; } return maxValue; } public static <K extends Vector> double getMaxValue( K[] dataset ){ double maxValue = 0; for( Vector vector : dataset){ if( vector == null ) continue; double value = vector.getMaxValue(); if( maxValue < value ) maxValue = value; } return maxValue; } }
true
7a6255630600cfee7d7b9fb73161d42f45fb5293
Java
michelsantos10/caelum_tdd
/testes-de-unidade/src/main/java/br/com/caelum/leilao/dominio/FiltroDeLances.java
UTF-8
597
3.140625
3
[]
no_license
package br.com.caelum.leilao.dominio; import java.util.ArrayList; import java.util.List; public class FiltroDeLances { public List<Lance> filtra(List<Lance> lances) { List<Lance> resultado = new ArrayList<Lance>(); for (Lance lance : lances) { if (lance.getValorProposto() > 1000.00 && lance.getValorProposto() < 3000.00) { resultado.add(lance); } else if (lance.getValorProposto() > 500.00 && lance.getValorProposto() < 700.00) { resultado.add(lance); } else if (lance.getValorProposto() > 5000.00) { resultado.add(lance); } } return resultado; } }
true
c40d19c477afcc15e1b4cbee8603a2bc5528e3b2
Java
vagneraragao/v1ms
/src/main/java/pt/credibom/checklist/interfaces/command/StatusCommand.java
UTF-8
884
2.203125
2
[]
no_license
package pt.credibom.checklist.interfaces.command; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import pt.credibom.checklist.domain.StatusEnum; import pt.credibom.checklist.domain.common.ValueObject; /** * Estado da documentação pendente */ @Data @Builder @AllArgsConstructor @NoArgsConstructor /*TPEND004 - status*/ public class StatusCommand implements ValueObject<Integer> { private static final long serialVersionUID = 4650243620510551231L; private StatusEnum id; @Size(max = 20) @NotNull private String description; private boolean active; @Override public Integer getCode() { return Integer.getInteger(id.getCode()); } @Override public String getDescription() { return description; } }
true
3bbe8fb3e12caa81960c7941fe3652ffb599ed69
Java
AliceYanYan/directory-kerby
/kerby-kerb/kerb-admin-server/src/test/java/org/apache/kerby/kerberos/kerb/admin/admin/AdminServerTest.java
UTF-8
1,781
1.882813
2
[ "Apache-2.0" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.admin.admin; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServer; import org.apache.kerby.util.NetworkUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class AdminServerTest { public static void main(String[] args) throws KrbException { String serverHost = "localhost"; AdminServer adminServer; adminServer = new AdminServer(); adminServer.setAdminHost(serverHost); adminServer.setAllowUdp(false); adminServer.setAllowTcp(true); adminServer.setAdminTcpPort(65417); adminServer.init(); adminServer.start(); System.out.println("Server started!"); } }
true
aa704edce5a79369dbc8efcde626a4f8570e9df2
Java
JackyWu15/Server
/app/src/main/java/com/hechuangwu/server/service/AIDLServer.java
UTF-8
3,315
2.5625
3
[]
no_license
package com.hechuangwu.server.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import com.hechuangwu.server.aidl.Book; import com.hechuangwu.server.aidl.IBookAidlInterface; import com.hechuangwu.server.aidl.IBookListenerlInterface; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by cwh on 2019/3/18. * 功能: */ public class AIDLServer extends Service { // private List<Book> mBookList = new ArrayList<>( ); //处理线程同步问题 private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<>( ); //客户端传到服务端会生成新的接口对象,RemoteCallbackList可以通过Binder处理 private RemoteCallbackList<IBookListenerlInterface> mBookListenerList = new RemoteCallbackList<>( ); private AtomicBoolean mAtomicBoolean = new AtomicBoolean(false); @Override public void onCreate() { super.onCreate(); Book book1 = new Book(1,"埃斯库罗斯","1000.00$" ); Book book2 = new Book(1,"索福克勒斯","2000.00$" ); mBookList.add( book1 ); mBookList.add( book2 ); new Thread( new AddBookRunnable() ).start(); } @Override public IBinder onBind(Intent intent) { return mBinder; } private IBookAidlInterface.Stub mBinder = new IBookAidlInterface.Stub() { @Override public void addBook(Book book) throws RemoteException { mBookList.add( book ); } @Override public List<Book> getBookList() throws RemoteException { //模仿耗时 SystemClock.sleep( 10000 ); return mBookList; } @Override public void registerBookListener(IBookListenerlInterface iBookListenerlInterface) throws RemoteException { mBookListenerList.register( iBookListenerlInterface ); } @Override public void unRegisterBookListener(IBookListenerlInterface iBookListenerlInterface) throws RemoteException { mBookListenerList.unregister( iBookListenerlInterface ); Log.i( "data", "unRegisterBookListener: "+mBookListenerList.beginBroadcast() ); mBookListenerList.finishBroadcast(); } }; private class AddBookRunnable implements Runnable{ @Override public void run() { while (!mAtomicBoolean.get()){ SystemClock.sleep( 5000 ); Book book = new Book( 1, "托马斯莫尔", "10000$" ); try { addNewBook( book ); } catch (RemoteException e) { e.printStackTrace(); } } } } private void addNewBook(Book book) throws RemoteException { int size = mBookListenerList.beginBroadcast(); for (int i = 0; i < size; i++) { IBookListenerlInterface iBookListenerlInterface = mBookListenerList.getBroadcastItem( i ); iBookListenerlInterface.addNewBookListener( book ); } mBookListenerList.finishBroadcast(); } }
true
c1d51bdf816f64232d9e5e7271e145af8a789448
Java
yxj870449537/springboot
/11_springboot_swagger/src/main/java/com/sxt/vo/ResultInfo.java
UTF-8
471
2.109375
2
[]
no_license
package com.sxt.vo; import lombok.Data; @Data public class ResultInfo<T> { private int code; private String message; private T body; public ResultInfo(int code, String message, T body) { this.code = code; this.message = message; this.body = body; } public ResultInfo(int code, String message) { this(code, message, null); } public ResultInfo(String message) { this(200, message, null); } }
true
23c2c2f2f8a1e0464fb7b8e4463898ee880c76cb
Java
canvaser/tongche2
/app/src/main/java/com/siwei/tongche/module/main/activity/MainActivity.java
UTF-8
12,566
1.578125
2
[]
no_license
package com.siwei.tongche.module.main.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.siwei.tongche.R; import com.siwei.tongche.baidumap.LocationManager; import com.siwei.tongche.common.AppConstants; import com.siwei.tongche.common.BaseActivity; import com.siwei.tongche.common.BaseUIOpe; import com.siwei.tongche.dialog.MiddleSelectPop; import com.siwei.tongche.dialog.NormalSelectPop; import com.siwei.tongche.dialog.SelectMenuBean; import com.siwei.tongche.events.EventTag; import com.siwei.tongche.module.accident.AccidentReportListActivity; import com.siwei.tongche.module.bind_unit.BindUserUnitActivity; import com.siwei.tongche.module.buildtask.BuildTaskActivity; import com.siwei.tongche.module.carmanager.activity.AddCarActivity; import com.siwei.tongche.module.gasstation.activity.AddGasListActivity; import com.siwei.tongche.module.login.bean.UserInfo; import com.siwei.tongche.module.main.fragment.ExpressListFragment; import com.siwei.tongche.module.main.fragment.MapInfoFragment; import com.siwei.tongche.module.main.fragment.RentMapFragment; import com.siwei.tongche.module.main.fragment.TaskFragment; import com.siwei.tongche.module.main.ope.MainDAOpe; import com.siwei.tongche.module.main.ope.MainUIOpe; import com.siwei.tongche.module.main.ope.ScanResultOpe; import com.siwei.tongche.module.scan.activity.UserInfoActivity; import com.siwei.tongche.module.scan.fragment.TicketFrag; import com.siwei.tongche.module.usercenter.activity.UserCenterActivity; import com.siwei.tongche.utils.CacheUtils; import com.siwei.tongche.utils.DensityUtil; import com.siwei.tongche.utils.MyFormatUtils; import com.siwei.tongche.utils.MyLogUtils; import com.siwei.tongche.utils.MyRegexpUtils; import com.siwei.tongche.zxing.ZXingQRCodeUtils; import com.sunday.busevent.SDBaseEvent; import java.util.ArrayList; import butterknife.Bind; import butterknife.OnClick; import de.greenrobot.event.EventBus; /** * 首页 */ public class MainActivity extends BaseActivity { private UserInfo mUserInfo; ScanResultOpe scanResultOpe; MainDAOpe mMainDAOpe; MainUIOpe mMainUIOpe; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserInfo = CacheUtils.getLocalUserInfo(); scanResultOpe= new ScanResultOpe(); mMainDAOpe=new MainDAOpe(mUserInfo); mMainUIOpe=new MainUIOpe(this,rootView); CacheUtils.setLocalUserInfo(mUserInfo); getLocation(); mMainUIOpe.initView(this,mUserInfo); toggleFragment(0); } @Override protected void onStart() { super.onStart(); mMainUIOpe.getmLayout_unbind().setVisibility(View.VISIBLE); mMainUIOpe.checkUnit(mUserInfo); } @Override public int getContentView() { return R.layout.activity_main; } private void toggleFragment(int index) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); for (Fragment fragment : mMainUIOpe.getmAllFragments()) { fragmentTransaction.hide(fragment); } fragmentTransaction.show(mMainUIOpe.getmAllFragments().get(index)); fragmentTransaction.commit(); //设置首页标题 if(mMainDAOpe.getmTypeData()!=null&&mMainDAOpe.getmTypeData().size()>0){ mMainUIOpe.getmTvMain_title().setText(mMainDAOpe.getmTypeData().get(index)); } } @OnClick({R.id.main_title, R.id.main_title_more, R.id.main_title_user_center, R.id.bindUnit_scan, R.id.bindUnit_userCenter}) public void onClick(View view) { switch (view.getId()) { case R.id.main_title: showMiddleDialog(view); break; case R.id.main_title_more: showMenu(view); break; case R.id.main_title_user_center: startActivity(new Intent(this, UserCenterActivity.class)); break; case R.id.bindUnit_scan://扫描绑定单位 ZXingQRCodeUtils.startScan(MainActivity.this); break; case R.id.bindUnit_userCenter://个人中心绑定单位 if (MyRegexpUtils.isEmpty(mUserInfo.getUUnitId())) {//没有绑定单位 startActivity(new Intent(this, BindUserUnitActivity.class).putExtra(BindUserUnitActivity.KEY_UNIT,BindUserUnitActivity.MY_UNIT)); } else if (MyRegexpUtils.isEmpty(mUserInfo.getUVehicleId())) {//没有绑定车辆 startActivity(new Intent(this, AddCarActivity.class)); } else if (MyRegexpUtils.isEmpty(mUserInfo.getUBindSendUnitId())) {//没有绑定发货单位 startActivity(new Intent(this, BindUserUnitActivity.class).putExtra(BindUserUnitActivity.KEY_UNIT,BindUserUnitActivity.SEND_UNIT)); } break; } } private void showMenu(View view) { NormalSelectPop normalSelectPop = new NormalSelectPop(this, mMainDAOpe.getmMenuData(), new NormalSelectPop.OnItemClickListener() { @Override public void itemClick(String title, int position) { if (title.equals("新建任务")) {//新建任务 startActivity(new Intent(MainActivity.this, BuildTaskActivity.class)); return; } switch (position) { case 0://扫一扫 ZXingQRCodeUtils.startScan(MainActivity.this); break; case 1://故障报告 startActivity(new Intent(MainActivity.this, AccidentReportListActivity.class)); break; case 2://加点油吧 startActivity(new Intent(MainActivity.this, AddGasListActivity.class)); break; } } }, mMainDAOpe.getmMenuData().size()); normalSelectPop.showBlowView(view, DensityUtil.dip2px(2)); } /** * 选择类别 */ private void showMiddleDialog(View view) { if (mMainDAOpe.getmTypeData().size() == 0) { return; } MiddleSelectPop typePop = new MiddleSelectPop(this, mMainDAOpe.getmTypeData(), new MiddleSelectPop.OnItemClickListener() { @Override public void itemClick(String title, int position) { toggleFragment(position); } }, 100, mMainDAOpe.getmTypeData().size()); typePop.showBlowView(view, DensityUtil.dip2px(10)); } /** * 开启百度地图定位 */ private void getLocation() { LocationManager.newInstance().getLocation(LocationManager.LocationMultiple, new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { //Receive Location StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(location.getTime()); sb.append("\nerror code : "); sb.append(location.getLocType()); sb.append("\nlatitude : "); sb.append(location.getLatitude()); sb.append("\nlontitude : "); sb.append(location.getLongitude()); sb.append("\nradius : "); sb.append(location.getRadius()); if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果 sb.append("\nspeed : "); sb.append(location.getSpeed());// 单位:公里每小时 sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); sb.append("\nheight : "); sb.append(location.getAltitude());// 单位:米 sb.append("\ndirection : "); sb.append(location.getDirection());// 单位度 sb.append("\naddr : "); sb.append(location.getAddrStr()); sb.append("\ndescribe : "); sb.append("gps定位成功"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果 sb.append("\naddr : "); sb.append(location.getAddrStr()); //运营商信息 sb.append("\noperationers : "); sb.append(location.getOperators()); sb.append("\ndescribe : "); sb.append("网络定位成功"); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 sb.append("\ndescribe : "); sb.append("离线定位成功,离线定位结果也是有效的"); } else if (location.getLocType() == BDLocation.TypeServerError) { sb.append("\ndescribe : "); sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { sb.append("\ndescribe : "); sb.append("网络不同导致定位失败,请检查网络是否通畅"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { sb.append("\ndescribe : "); sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); } sb.append("\nlocationdescribe : "); sb.append(location.getLocationDescribe());// 位置语义化信息 MyLogUtils.e("BaiduLocationApiDem", MyFormatUtils.getDetailTimeByLongTime(System.currentTimeMillis() / 1000l + "")); MyLogUtils.e("BaiduLocationApiDem", sb.toString()); MyLogUtils.e("BaiduLocationApiDem", " location.getSpeed()==" + location.getSpeed()); CacheUtils.setLatitudes(location.getLatitude() + ""); CacheUtils.setLongitude(location.getLongitude() + ""); CacheUtils.setAddress(location.getAddrStr()); EventBus.getDefault().post(new SDBaseEvent(null, EventTag.EVENT_REFRESH_LOCATION)); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case ZXingQRCodeUtils.START_SCAN: //当普通用户扫描管理员二维码,页面出现管理员信息与【绑定单位】按钮,用户点击【绑定单位】,管理员即收到用户消息,点击【接受】即可。 //当管理员扫描普通用户二维码,页面出现普通用户信息与【添加用户】按钮,用户点击【添加用户】,普通用户即收到添加消息,点击【接受】即可。 //创建者扫描普通用户二维码,页面跳转后可指定该用户是否为管理员。 //当管理员扫描驾驶员二维码,页面出现驾驶员信息与【添加】按钮,用户点击【添加】,驾驶员即收到添加消息,点击【接受】即可。 if(data!=null && data.getStringExtra("result")!=null){ Fragment fragment = scanResultOpe.analyze(this,data.getStringExtra("result")); if(fragment!=null){ //跳转到小票列表 if(fragment.getClass().getSimpleName().equals(TicketFrag.class.getSimpleName())){ }else{ Intent intent = new Intent(this,UserInfoActivity.class); intent.putExtra("fragment",fragment.getClass().getSimpleName()); startActivity(intent); } } } break; } } }
true
af45b91173c9b5d8f41488aab65e867211d6efd1
Java
Manish-Alekar/Cognizant_Training
/Day 14/Encapsulation.java
UTF-8
320
3.34375
3
[]
no_license
class Example{ private int age; private int salary; public int getAge() { return age; } public void setAge(int age) { this.age=age; } } public class Encapsulation { public static void main(String[] args) { Example exp = new Example(); exp.setAge(10); int age=exp.getAge(); System.out.print(age); } }
true
db26816a73fa4dff0a29b82e6ebe04717db75675
Java
LenDu/ITSchool
/src/enums/EnumDemo.java
UTF-8
1,897
3.9375
4
[]
no_license
package enums; /** * Created by Lena on 12/23/2017. */ public class EnumDemo { public static void main(String[] args) { Apple2 ap; ap = Apple2.RedDel; System.out.println("Value of ap:" + ap); System.out.println(); ap = Apple2.GoldenDel; if (ap == Apple2.GoldenDel) { System.out.println("ap contains GoldenDel.\n"); } switch (ap) { case Jonathan: System.out.println("Jonathan is red."); break; case GoldenDel: System.out.println("Golden Delocious is yellow"); break; } Apple2 allapples[] = Apple2.values(); for (Apple2 a : allapples) { System.out.println(a); } System.out.println(); //valueOf преобразовывает строку в обьект ap = Apple2.valueOf("Winesap"); System.out.println("app contains: " + ap); Apple2 ap1, ap2, ap3; //ordinal возвращает номер значения в enum System.out.println("Here are all apple constants" + " and their ordinal values: "); for (Apple2 a : Apple2.values()) { System.out.println(a + " " + a.ordinal()); } ap1 = Apple2.RedDel; ap2 = Apple2.GoldenDel; ap3 = Apple2.RedDel; System.out.println(); if (ap1.compareTo(ap2) < 0) System.out.println(ap1 + " comes before " + ap2); if (ap1.compareTo(ap2) > 0) System.out.println(ap2 + " comes before " + ap1); if (ap1.compareTo(ap3) == 0) System.out.println(ap1 + " equals " + ap2); System.out.println(); if (ap1.equals(ap3)) System.out.println(ap1 + " equals " + ap3); if (ap1 == ap3) System.out.println(ap1 + " == " + ap3); } }
true
19435900c29dd838ef0fbfe5584b193cceed3724
Java
dong-df/ovirt-engine
/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/ManagedBlockStorageLocationInfo.java
UTF-8
3,149
2.234375
2
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.core.common.businessentities; import java.util.Map; import java.util.Objects; import java.util.StringJoiner; import org.ovirt.engine.core.common.businessentities.storage.VolumeFormat; import org.ovirt.engine.core.compat.Guid; public class ManagedBlockStorageLocationInfo extends LocationInfo { private String url; private Map<String, Object> lease; private Integer generation; private boolean zeroed; private VolumeFormat format; private Guid storageDomainId; public ManagedBlockStorageLocationInfo(String url, Map<String, Object> lease, Integer generation, VolumeFormat format, boolean zeroed, Guid storageDomainId) { this.url = url; this.lease = lease; this.generation = generation; this.format = format; this.zeroed = zeroed; this.storageDomainId = storageDomainId; } public ManagedBlockStorageLocationInfo() { } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, Object> getLease() { return lease; } public void setLease(Map<String, Object> lease) { this.lease = lease; } public Integer getGeneration() { return generation; } public void setGeneration(Integer generation) { this.generation = generation; } public VolumeFormat getFormat() { return format; } public void setFormat(VolumeFormat format) { this.format = format; } public boolean isZeroed() { return zeroed; } public void setZeroed(boolean zeroed) { this.zeroed = zeroed; } public Guid getStorageDomainId() { return storageDomainId; } public void setStorageDomainId(Guid storageDomainId) { this.storageDomainId = storageDomainId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ManagedBlockStorageLocationInfo)) { return false; } ManagedBlockStorageLocationInfo that = (ManagedBlockStorageLocationInfo) o; return zeroed == that.zeroed && Objects.equals(url, that.url) && Objects.equals(lease, that.lease) && Objects.equals(generation, that.generation) && format == that.format && Objects.equals(storageDomainId, that.storageDomainId); } @Override public int hashCode() { return Objects.hash(url, lease, generation, zeroed, format, storageDomainId); } @Override public String toString() { return new StringJoiner(", ", ManagedBlockStorageLocationInfo.class.getSimpleName() + "[", "]") .add("url='" + url + "'") .add("lease=" + lease) .add("generation=" + generation) .add("zeroed=" + zeroed) .add("format=" + format) .add("storageDomainId=" + storageDomainId) .toString(); } }
true
fb4019d894276793f7bf343575c8c3d0c9ea96cc
Java
jpragey/Sirius
/org.sirius.frontend/src/main/java/org/sirius/frontend/apiimpl/IntegerConstantExpressionImpl.java
UTF-8
294
2.171875
2
[ "Apache-2.0" ]
permissive
package org.sirius.frontend.apiimpl; import org.sirius.frontend.api.IntegerConstantExpression; import org.sirius.frontend.api.Type; public record IntegerConstantExpressionImpl(int value) implements IntegerConstantExpression { @Override public Type type() { return Type.integerType; } }
true
892381fd8715353f2882b65f74e274901d7f71ba
Java
PuntusovAleksandr/androidClientW8Monitor
/app/src/main/java/com/w8/w8monitor/android/d_base/RealmObj.java
UTF-8
56,193
1.734375
2
[]
no_license
package com.w8.w8monitor.android.d_base; import android.content.Context; import android.support.annotation.NonNull; import android.widget.Toast; import com.w8.w8monitor.android.App; import com.w8.w8monitor.android.activity.interfaces.views.AlarmView; import com.w8.w8monitor.android.activity.interfaces.views.ChangePasswordView; import com.w8.w8monitor.android.activity.interfaces.views.LoginView; import com.w8.w8monitor.android.activity.interfaces.views.MainView; import com.w8.w8monitor.android.activity.interfaces.views.RegisterView; import com.w8.w8monitor.android.api.event.UpdateUiEvent; import com.w8.w8monitor.android.api.model.ProfileApi; import com.w8.w8monitor.android.api.model.UserApi; import com.w8.w8monitor.android.api.model.UserApiData; import com.w8.w8monitor.android.d_base.model.AlarmModel; import com.w8.w8monitor.android.d_base.model.ParamsBody; import com.w8.w8monitor.android.d_base.model.Profile; import com.w8.w8monitor.android.d_base.model.StringRealm; import com.w8.w8monitor.android.d_base.model.UserLibr; import com.w8.w8monitor.android.fragments.main.CircleGraphView; import com.w8.w8monitor.android.fragments.main.LinerGraphView; import com.w8.w8monitor.android.utils.STATICS_PARAMS; import com.w8.w8monitor.android.utils.SettingsApp; import java.util.Date; import java.util.List; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmList; import io.realm.RealmResults; import io.realm.Sort; import static com.w8.w8monitor.android.utils.LoggerApp.saveAllLogs; import static com.w8.w8monitor.android.utils.STATICS_PARAMS.TEST_USER; /** * Created by AleksandrP on 14.09.2016. */ public class RealmObj { public static final String LOG_REALM = "LOG_REALM"; private static RealmObj sRealmObj; private Context context; private Realm realm; private int allNameTypeCalendarsByUser; public synchronized static RealmObj getInstance() { if (sRealmObj == null) { sRealmObj = new RealmObj(); } return sRealmObj; } /** * for creating (or change) data base, need reopen Realm * This method need calling after save data in Shared preference */ public static void stopRealm() { if (sRealmObj != null) { sRealmObj.closeRealm(App.getContext()); } } private void closeRealm(Context context) { if (realm != null) { realm.close(); realm = null; setRealmData(context); } } private RealmObj() { this.context = App.getContext(); if (realm == null) { setRealmData(context); } } private void setRealmData(Context context) { String nameDB = RealmObj.class.getName(); realm = Realm.getInstance( new RealmConfiguration.Builder(context) .name(nameDB) .deleteRealmIfMigrationNeeded() .schemaVersion(STATICS_PARAMS.VERSION_DB) .build() ); } // =============================================================== // START GET // =============================================================== public UserLibr getUserByMail(String email) { UserLibr userLibr = null; try { userLibr = realm.where(UserLibr.class) .equalTo("email", email) .findFirst(); } catch (Exception mE) { mE.printStackTrace(); return null; } return userLibr; } public void getUserByMailAndPass(final String mLogin, final String mPass, final LoginView mListenerLoginView, UpdateUiEvent mEvent) { UserLibr userByMail = getUserByMail(mLogin); boolean userServer = SettingsApp.getInstance().isUserServer(); boolean fullProfile = userByMail == null ? userServer : userByMail.isFullProfile(); final UserApi userApi = (UserApi) mEvent.getData(); final UserApiData userApiData = userApi.getUser(); final List<ProfileApi> profileApis = userApiData.getProfileApis(); final UserLibr userLibr = new UserLibr(); userLibr.setEmail(userApiData.getEmail()); userLibr.setPassword(mPass); userLibr.setToken(userApi.getToken()); userLibr.setId_server(userApiData.getId()); userLibr.setCreated_at(userApiData.getCreated_at()); userLibr.setUpdated_at(userApiData.getUpdated_at()); userLibr.setIs_imperial(userApiData.is_imperial()); userLibr.setKeep_login(userApiData.isKeep_login()); userLibr.setTheme(userApiData.getTheme()); userLibr.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); userLibr.setLanguage(userApiData.getLanguage()); userLibr.setFullProfile(fullProfile); RealmList<Profile> profiles = userLibr.getProfiles(); if (profiles != null) { profiles.clear(); } else { userLibr.setProfiles(new RealmList<Profile>()); } for (int i = 0; i < profileApis.size(); i++) { ProfileApi profileApi = profileApis.get(i); Profile profile = new Profile(); profile.setId(profileApi.getId()); profile.setUser_id(profileApi.getUser_id()); profile.setActivity_type(profileApi.getActivity_type()); profile.setHeight(profileApi.getHeight()); profile.setGender(profileApi.getGender()); profile.setAge(profileApi.getBirthday()); profile.setCreated_at(profileApi.getCreated_at()); profile.setUpdated_at(profileApi.getUpdated_at()); profile.setNumber(profileApi.getNumber()); profile.setIs_current(profileApi.is_current()); profile.setTarget_weight(profileApi.getTarget_weight()); profile.setMeasurements_count(profileApi.getMeasurements_count()); userLibr.getProfiles().add(profile); } realm.executeTransactionAsync( new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { SettingsApp.getInstance().setUserName(mLogin); SettingsApp.getInstance().setUserPassword(mPass); mListenerLoginView.userExist(true, userLibr); setAlarmByUserByLogin(mLogin, userApiData.getAlarms()); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { mListenerLoginView.userExist(false, null); } }); } public void checkEmail(String mEmail, LoginView mListenerLoginView) { long count = realm.where(UserLibr.class) .equalTo("email", mEmail) .count(); mListenerLoginView.changePassUserExist((count > 0), mEmail); } public void getStateUser(StateListener mProfileViewt) { String userName = SettingsApp.getInstance().getUserName(); int profileBLE = SettingsApp.getInstance().getProfileBLE(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); int state = -1; if (userLibr != null) { RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { state = profiles.get(i).getGender(); if (state == 0) { state = -1; } } } } mProfileViewt.isSave(state); } public void getBodyUser(BodyListener mListener) { String userName = SettingsApp.getInstance().getUserName(); int profileBLE = SettingsApp.getInstance().getProfileBLE(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); int body = -1; if (userLibr != null) { RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { body = profiles.get(i).getActivity_type(); if (body == 0) { body = -1; } } } } mListener.isBody(body); } public void getProfileBle(ProfileBLeListener mListener) { String userName = SettingsApp.getInstance().getUserName(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); int prfileBle = -1; if (userLibr != null) { prfileBle = userLibr.getProfileBLE(); } mListener.isProfileBLE(prfileBle); } public void getDayBith(BirthDayListener mListener) { String userName = SettingsApp.getInstance().getUserName(); int profileBLE = SettingsApp.getInstance().getProfileBLE(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); String date = ""; if (userLibr != null) { RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { date = profiles.get(i).getAge() + ""; if (date.equals("0")) { date = "30"; } } } } mListener.isBirthDay(date); } public void getHeight(HeightListener mListener) { String userName = SettingsApp.getInstance().getUserName(); int profileBLE = SettingsApp.getInstance().getProfileBLE(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); String height = ""; if (userLibr != null) { RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { height = profiles.get(i).getHeight() + ""; if (height.equals("0")) { height = "0"; } } } } mListener.isHeight(height); } public RealmResults<AlarmModel> getAlarmFromDb(String mUserName) { return realm.where(AlarmModel.class) .equalTo("email", SettingsApp.getInstance().getUserName()) .findAll(); } public void getAlarmFromDb(AlarmView mAlarmView) { RealmResults<AlarmModel> alarmItems = realm.where(AlarmModel.class) .equalTo("email", SettingsApp.getInstance().getUserName()) .findAll(); mAlarmView.updateAlarms(); mAlarmView.setAlarmItem(alarmItems); } public void getAlarmFromDb(StringBuilder mMsgStr, AlarmListener mListener) { mListener.getAllAlarm(realm.where(AlarmModel.class) .findAll(), mMsgStr); } public UserLibr getUserForConnectBLE() { String userName = SettingsApp.getInstance().getUserName(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); return userLibr; } public void getDataForCircle(final int mI, final CircleGraphView mCircleGraphView) { float weight_max = 0, weight_min = Float.MAX_VALUE, body_max = 0, body_min = Float.MAX_VALUE, fat_max = 0, fat_min = Float.MAX_VALUE, muscle_max = 0, muscle_min = Float.MAX_VALUE, water_max = 0, water_min = Float.MAX_VALUE, visceralFat_max = 0, visceralFat_min = Float.MAX_VALUE, emr_max = 0, emr_min = Float.MAX_VALUE, bmi_max = 0, bmi_min = Float.MAX_VALUE; RealmResults<ParamsBody> allSorted = realm.where(ParamsBody.class) .equalTo("userName_id", SettingsApp.getInstance().getUserName()) .equalTo("profileBLE", SettingsApp.getInstance().getProfileBLE()) .findAllSorted("date_time", Sort.DESCENDING); ParamsBody last = new ParamsBody(); ParamsBody preLast = new ParamsBody(); if (allSorted != null && allSorted.size() > 0) { last = allSorted.get(0); if (allSorted.size() < 2) { preLast.setWeight(0f); preLast.setBody(0f); preLast.setFat(0f); preLast.setMuscle(0f); preLast.setWater(0f); preLast.setVisceralFat(0f); preLast.setEmr(0f); preLast.setBodyAge(0f); preLast.setDate_time(last.getDate_time()); preLast.setBmi(0f); preLast.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); } else { preLast = allSorted.get(1); } for (int i = 0; i < allSorted.size(); i++) { ParamsBody body = allSorted.get(i); if (body.getWeight() > weight_max) { weight_max = body.getWeight(); } if (body.getWeight() < weight_min) { weight_min = body.getWeight(); } if (body.getBody() > body_max) { body_max = body.getBody(); } if (body.getBody() < body_min) { body_min = body.getBody(); } if (body.getFat() > fat_max) { fat_max = body.getFat(); } if (body.getFat() < fat_min) { fat_min = body.getFat(); } if (body.getMuscle() > muscle_max) { muscle_max = body.getMuscle(); } if (body.getMuscle() < muscle_min) { muscle_min = body.getMuscle(); } if (body.getWater() > water_max) { water_max = body.getWater(); } if (body.getWater() < water_min) { water_min = body.getWater(); } if (body.getVisceralFat() > visceralFat_max) { visceralFat_max = body.getVisceralFat(); } if (body.getVisceralFat() < visceralFat_min) { visceralFat_min = body.getVisceralFat(); } if (body.getEmr() > emr_max) { emr_max = body.getEmr(); } if (body.getEmr() < emr_min) { emr_min = body.getEmr(); } if (body.getBmi() > bmi_max) { bmi_max = body.getBmi(); } if (body.getBmi() < bmi_min) { bmi_min = body.getBmi(); } } } else { last = null; preLast = null; } float[] massParams = new float[]{ weight_max, weight_min, body_max, body_min, fat_max, fat_min, muscle_max, muscle_min, water_max, water_min, visceralFat_max, visceralFat_min, emr_max, emr_min, bmi_max, bmi_min}; mCircleGraphView.showDataCircle(mI, last, preLast, massParams); } public void getDataForLineChart(long timeNow, long timeStart, int mPickerBottomValue, LinerGraphView mLinerGraphView) { int id = 0; UserLibr userByMail = getUserByMail(SettingsApp.getInstance().getUserName()); RealmList<Profile> profiles = userByMail.getProfiles(); for (int i = 0; i < profiles.size(); i++) { Profile profile = profiles.get(i); if (profile.is_current() && profile.getNumber() == SettingsApp.getInstance().getProfileBLE()) { id = profile.getId(); } } mLinerGraphView.getDataForLineChart( realm.where(ParamsBody.class) .equalTo("userName_id", SettingsApp.getInstance().getUserName()) .equalTo("profile_id", id) .between("date_time", timeStart, timeNow) .findAllSorted("date_time", Sort.ASCENDING), mPickerBottomValue); } public void getUserForSettings(GetUserForSettings mGetUserForSettings) { String userName = SettingsApp.getInstance().getUserName(); mGetUserForSettings.getUserForSettings( realm.where(UserLibr.class) .equalTo("email", userName) .findFirst()); } public ParamsBody getLastBodyParam(String mUserName, long mTime) { return realm.where(ParamsBody.class) .equalTo("userName_id", mUserName) .equalTo("date_time", mTime) .findFirst(); } public RealmResults<ParamsBody> getAllNoSyncParamBodies(int mIdProfileNow) { return realm.where(ParamsBody.class) .equalTo("profile_id", mIdProfileNow) .equalTo("synced", false) .findAll(); } public RealmResults<ParamsBody> getAllParamBodies(int mIdProfileNow) { return realm.where(ParamsBody.class) .equalTo("profile_id", mIdProfileNow) .findAll(); } public void getLastBodyParamsByServer(MainView mMainView) { mMainView.getAllMeasurementsFromServer( realm.where(ParamsBody.class) .equalTo("userName_id", SettingsApp.getInstance().getUserName()) .findAllSorted("date_time", Sort.ASCENDING)); } public ParamsBody getLastParamsBody() { int id = 0; UserLibr userByMail = getUserByMail(SettingsApp.getInstance().getUserName()); RealmList<Profile> profiles = userByMail.getProfiles(); for (int i = 0; i < profiles.size(); i++) { Profile profile = profiles.get(i); if (profile.is_current() && profile.getNumber() == SettingsApp.getInstance().getProfileBLE()) { id = profile.getId(); } } RealmResults<ParamsBody> allSorted = realm.where(ParamsBody.class) .equalTo("userName_id", SettingsApp.getInstance().getUserName()) .equalTo("profile_id", id) .findAllSorted("date_time", Sort.DESCENDING); return allSorted.get(0); } public RealmResults<ParamsBody> getDataUserForGoogleFit(int mIdProfile) { RealmResults<ParamsBody> allSorted = realm.where(ParamsBody.class) .equalTo("userName_id", SettingsApp.getInstance().getUserName()) .equalTo("profile_id", mIdProfile) .findAllSorted("date_time", Sort.DESCENDING); return allSorted; } // =============================================================== // END GET // =============================================================== // START PUT // =============================================================== // from register activity public void putUser(String mLogin, String mPass, final RegisterView mListener, UpdateUiEvent mEvent) { UserLibr userByMail = getUserByMail(mLogin); final UserApi userApi = (UserApi) mEvent.getData(); final UserApiData userApiData = userApi.getUser(); final List<ProfileApi> profileApis = userApiData.getProfileApis(); final UserLibr userLibr = new UserLibr(); userLibr.setEmail(userApiData.getEmail()); userLibr.setPassword(mPass); userLibr.setToken(userApi.getToken()); userLibr.setId_server(userApiData.getId()); userLibr.setCreated_at(userApiData.getCreated_at()); userLibr.setUpdated_at(userApiData.getUpdated_at()); userLibr.setIs_imperial(userApiData.is_imperial()); userLibr.setKeep_login(userApiData.isKeep_login()); userLibr.setTheme(userApiData.getTheme()); userLibr.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); userLibr.setLanguage(userApiData.getLanguage()); userLibr.setFullProfile(userByMail == null ? false : userByMail.isFullProfile()); RealmList<Profile> profiles = userLibr.getProfiles(); if (profiles != null) { profiles.clear(); } else { userLibr.setProfiles(new RealmList<Profile>()); } for (int i = 0; i < profileApis.size(); i++) { ProfileApi profileApi = profileApis.get(i); Profile profile = new Profile(); profile.setId(profileApi.getId()); profile.setUser_id(profileApi.getUser_id()); profile.setActivity_type(profileApi.getActivity_type()); profile.setHeight(profileApi.getHeight()); profile.setGender(profileApi.getGender()); profile.setAge(profileApi.getBirthday()); profile.setCreated_at(profileApi.getCreated_at()); profile.setUpdated_at(profileApi.getUpdated_at()); profile.setNumber(profileApi.getNumber()); profile.setIs_current(profileApi.is_current()); profile.setTarget_weight(profileApi.getTarget_weight()); profile.setMeasurements_count(profileApi.getMeasurements_count()); userLibr.getProfiles().add(profile); } realm.executeTransactionAsync( new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { mListener.isUserSaveLogin(true, userLibr); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { mListener.isUserSaveLogin(true, null); } }); } /** * get defoult user for saving in db * * @param email * @param password * @return */ @NonNull private UserLibr getDefoultUser(final String email, String password) { UserLibr userLibr = getUserByMail(TEST_USER); if (userLibr != null) { realm.beginTransaction(); userLibr.setKeep_login(SettingsApp.getInstance().getAutoLogin()); userLibr.setTheme(SettingsApp.getInstance().isThemeDark() ? 1 : 0); realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); return userLibr; } else { String data = new Date().getTime() + ""; userLibr = new UserLibr(); userLibr.setEmail(email); userLibr.setPassword(password); userLibr.setToken(""); // default userLibr.setId_server(0); // default userLibr.setCreated_at(data); // default userLibr.setUpdated_at(data); // default userLibr.setIs_imperial(!SettingsApp.getInstance().getMetric()); // default userLibr.setKeep_login(SettingsApp.getInstance().getAutoLogin()); // default userLibr.setTheme(SettingsApp.getInstance().isThemeDark() ? 1 : 0); // default userLibr.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); // default userLibr.setLanguage(SettingsApp.getInstance().getLanguages()); userLibr.setFullProfile(false); RealmList<Profile> profiles = new RealmList<>(); for (int i = 0; i < 2; i++) { Profile profile = new Profile(); profile.setId(i); profile.setUser_id(userLibr.getId_server()); profile.setActivity_type(0); profile.setHeight(0); profile.setGender(0); profile.setAge(30); profile.setCreated_at(data); profile.setUpdated_at(data); profile.setNumber(i + 1); profiles.add(profile); } userLibr.setProfiles(profiles); } return userLibr; } private RealmResults<ParamsBody> getParamsBodyByEmail(String mEmail) { return realm.where(ParamsBody.class) .equalTo("userName_id", mEmail) .findAll(); } // from login (test) activity public void putUser(final String email, final String password, final LoginView mListener) { final UserLibr userLibr = getDefoultUser(email, password); realm.executeTransactionAsync( new Realm.Transaction() { @Override public void execute(Realm realm) { realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { SettingsApp.getInstance().setUserName(email); SettingsApp.getInstance().setUserPassword(password); mListener.userExist(true, userLibr); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { mListener.userExist(true, userLibr); } }); } public void setAlarmInDb(boolean isAmPicker, String mTime, AlarmView mAlarmView) { AlarmModel model = new AlarmModel(); model.setAm(isAmPicker); model.setTime(mTime); model.setEmail(SettingsApp.getInstance().getUserName()); realm.beginTransaction(); realm.copyToRealmOrUpdate(model); realm.commitTransaction(); // set alarm in system device mAlarmView.setAlarmInSystem(isAmPicker, mTime); // get data from db getAlarmFromDb(mAlarmView); } public void addParamsBody(final float mWeightBody, final float mBody, final float mFat, final float mMuscul, final float mWaterBody, final float mFatVis, final float mEmr, final float mAgeBody, final float bmi, final long time, final CircleGraphView mCircleGraphView, final boolean sync) { final String userName = SettingsApp.getInstance().getUserName(); int id_profile = 0; UserLibr userByMail = getUserByMail(SettingsApp.getInstance().getUserName()); RealmList<Profile> profiles = userByMail.getProfiles(); for (int i = 0; i < profiles.size(); i++) { Profile profile = profiles.get(i); if (profile.is_current() && profile.getNumber() == SettingsApp.getInstance().getProfileBLE()) { id_profile = profile.getId(); } } final int finalId_profile = id_profile; realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { ParamsBody paramsBody = new ParamsBody(); paramsBody.setUserName_id(userName); paramsBody.setDate_time(time); paramsBody.setWeight(mWeightBody); paramsBody.setBody(mBody); paramsBody.setFat(mFat); paramsBody.setMuscle(mMuscul); paramsBody.setWater(mWaterBody); paramsBody.setVisceralFat(mFatVis); paramsBody.setEmr(mEmr); paramsBody.setBodyAge(mAgeBody); paramsBody.setBmi(bmi); paramsBody.setProfile_id(finalId_profile); paramsBody.setSynced(sync); paramsBody.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); bgRealm.copyToRealmOrUpdate(paramsBody); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { float[] mMassParams = new float[9]; mMassParams[0] = mWeightBody; mMassParams[1] = mBody; mMassParams[2] = mFat; mMassParams[3] = mMuscul; mMassParams[4] = mWaterBody; mMassParams[5] = mFatVis; mMassParams[6] = mEmr; mMassParams[7] = mAgeBody; mMassParams[8] = bmi; mCircleGraphView.showParams(mMassParams, time, sync); saveAllLogs("addParamsBody onSuccess"); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { mCircleGraphView.showMessageError(); saveAllLogs("ERROR in db addUserFromFacebook =" + error.getMessage()); } }); } public void addParamsBody(final String email, final float mWeightBody, final float mBody, final float mFat, final float mMuscul, final float mWaterBody, final float mFatVis, final float mEmr, final float mAgeBody, final long time) { realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { ParamsBody paramsBody = new ParamsBody(); paramsBody.setUserName_id(email); paramsBody.setDate_time(time); paramsBody.setWeight(mWeightBody); paramsBody.setBody(mBody); paramsBody.setFat(mFat); paramsBody.setMuscle(mMuscul); paramsBody.setWater(mWaterBody); paramsBody.setVisceralFat(mFatVis); paramsBody.setEmr(mEmr); paramsBody.setBodyAge(mAgeBody); paramsBody.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); bgRealm.copyToRealm(paramsBody); } }); } private void setAlarmByUserByLogin(String mLogin, List<String> mAlarms) { if (mAlarms == null || (mAlarms != null && mAlarms.size() == 1 && mAlarms.get(0).equalsIgnoreCase("*"))) { return; } RealmResults<AlarmModel> alarmFromDb = getAlarmFromDb(mLogin); if (alarmFromDb.size() > 0) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<AlarmModel> alarmModels = realm.where(AlarmModel.class) .equalTo("email", SettingsApp.getInstance().getUserName()) .findAll(); alarmModels.deleteAllFromRealm(); } }); } try { for (int i = 0; i < mAlarms.size(); i++) { String alarmText = mAlarms.get(i); String[] split = alarmText.split("/"); boolean isAmPicker = split[2].equalsIgnoreCase("am"); StringBuilder builder = new StringBuilder(); builder = builder.append(split[0]); builder = builder.append(":"); builder = builder.append(split[1]); AlarmModel model = new AlarmModel(); model.setAm(isAmPicker); model.setTime(builder.toString()); model.setEmail(mLogin); realm.beginTransaction(); realm.copyToRealmOrUpdate(model); realm.commitTransaction(); } } catch (Exception mE) { mE.printStackTrace(); Toast.makeText(context, "Error read alarms from server", Toast.LENGTH_SHORT).show(); } } private void saveParamsBody() { final String name = SettingsApp.getInstance().getUserName(); final UserLibr user = getUserByMail(name); boolean loginFRomLogout = SettingsApp.getInstance().getLoginFRomLogout(); if (loginFRomLogout) { SettingsApp.getInstance().setLoginFRomLogout(false); UserLibr userTest = getUserByMail(TEST_USER); RealmList<Profile> profiles = userTest.getProfiles(); for (int i = 0; i < profiles.size(); i++) { Profile profile = profiles.get(i); final RealmResults<ParamsBody> allParamBodies = getAllParamBodies(profile.getId()); for (int j = 0; j < allParamBodies.size(); j++) { final int finalJ = j; final int finalI = i; realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { final ParamsBody paramsBody = allParamBodies.get(finalJ); paramsBody.setUserName_id(user.getEmail()); paramsBody.setProfile_id(user.getProfiles().get(finalI).getId()); paramsBody.setSynced(false); realm.copyToRealmOrUpdate(paramsBody); } }); } } realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<UserLibr> result = realm.where(UserLibr.class) .equalTo("email", TEST_USER) .findAll(); result.deleteAllFromRealm(); } }); SettingsApp.getInstance().setFirstStart(false); SettingsApp.getInstance().setSettingsStatus(false); SettingsApp.getInstance().setMetric(false); // SettingsApp.getInstance().setShowLoginTutorial(true); // SettingsApp.getInstance().setShowMainTutorial(true); } } // =============================================================== // END PUT // =============================================================== // update // =============================================================== public void checkAndChangePassword(String mMailUser, String mPasswordTextOld, String mPasswordText, ChangePasswordView mPasswordView, UpdateUiEvent mEvent) { UserLibr userLibr_ = transformUpdateEventUserApi(mEvent); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", mMailUser) // .equalTo("password", mPasswordTextOld) .findFirst(); if (userLibr != null) { realm.beginTransaction(); userLibr.setPassword(mPasswordText); realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); mPasswordView.showMessageOkChangePass(); } else { mPasswordView.showMessageNotFoundUser(); } } public void setStateUser(String mUserName, int mState, StateListener mListener) { int profileBLE = SettingsApp.getInstance().getProfileBLE(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", mUserName) .findFirst(); if (userLibr != null) { realm.beginTransaction(); RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { profiles.get(i).setGender(mState); } } realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); mListener.isSave(mState); } else { mListener.isSave(-1); } } public void setBodyUser(int mBodyType, BodyListener mBodyListener) { int profileBLE = SettingsApp.getInstance().getProfileBLE(); String userName = SettingsApp.getInstance().getUserName(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); if (userLibr != null) { realm.beginTransaction(); RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { profiles.get(i).setActivity_type(mBodyType); } } realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); mBodyListener.isBody(mBodyType); } else { mBodyListener.isBody(-1); } } public void setProfileBLE(int mProfile, ProfileBLeListener mListener) { SettingsApp.getInstance().setProfileBLE(mProfile); String userName = SettingsApp.getInstance().getUserName(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); if (userLibr != null) { realm.beginTransaction(); userLibr.setProfileBLE(mProfile); userLibr.setFullProfile(true); realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); mListener.isProfileBLE(mProfile); } else { mListener.isProfileBLE(-1); } } public void setDayBith(String mDate, BirthDayListener mListener) { int profileBLE = SettingsApp.getInstance().getProfileBLE(); String userName = SettingsApp.getInstance().getUserName(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); if (userLibr != null) { realm.beginTransaction(); RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { profiles.get(i).setAge(Integer.parseInt(mDate)); } } realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); } mListener.isBirthDay(mDate); } public void saveHeight(String mHeight, HeightListener mListener) { int profileBLE = SettingsApp.getInstance().getProfileBLE(); String userName = SettingsApp.getInstance().getUserName(); UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); if (userLibr != null) { realm.beginTransaction(); RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { profiles.get(i).setHeight((int) Float.parseFloat(mHeight)); } } realm.copyToRealmOrUpdate(userLibr); realm.commitTransaction(); } mListener.isHeight(mHeight); } public void saveWeight(final String mDate, ProfileFirstStartGoogleFit mListener) { final String userName = SettingsApp.getInstance().getUserName(); final long time = new Date().getTime() / 1000; int id_profile = 0; UserLibr userByMail = getUserByMail(SettingsApp.getInstance().getUserName()); RealmList<Profile> profiles = userByMail.getProfiles(); for (int i = 0; i < profiles.size(); i++) { Profile profile = profiles.get(i); if (profile.is_current() && profile.getNumber() == SettingsApp.getInstance().getProfileBLE()) { id_profile = profile.getId(); } } final int finalId_profile = id_profile; realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { ParamsBody paramsBody = new ParamsBody(); paramsBody.setUserName_id(userName); paramsBody.setDate_time(time); paramsBody.setWeight(Float.parseFloat(mDate.isEmpty() ? "0" : mDate)); paramsBody.setBody(0); paramsBody.setFat(0); paramsBody.setMuscle(0); paramsBody.setWater(0); paramsBody.setVisceralFat(0); paramsBody.setEmr(0); paramsBody.setBodyAge(0); paramsBody.setBmi(0); paramsBody.setProfile_id(finalId_profile); paramsBody.setSynced(false); paramsBody.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); bgRealm.copyToRealmOrUpdate(paramsBody); } }); mListener.isTargetWeight(mDate); } public void setFullSettings(final ProfileBLeListener mBLeListener) { final String userName = SettingsApp.getInstance().getUserName(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); userLibr.setFullProfile(true); realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { mBLeListener.isOkFullSettings(true); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db setFullSettings =" + error.getMessage()); mBLeListener.isOkFullSettings(false); } }); } public void setFullFirsStartSettings(final ProfileFirstStartGoogleFit mBLeListener) { final String userName = SettingsApp.getInstance().getUserName(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); userLibr.setFullProfile(true); realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { mBLeListener.isOkFullSettings(true); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db setFullSettings =" + error.getMessage()); mBLeListener.isOkFullSettings(false); } }); } public void setFullFirsStartSettings(final ProfileFirstStartBLeListener mBLeListener) { final String userName = SettingsApp.getInstance().getUserName(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); userLibr.setFullProfile(true); realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { mBLeListener.isOkFullSettings(true); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db setFullSettings =" + error.getMessage()); mBLeListener.isOkFullSettings(false); } }); } public void setStateUserFromSettings(final int mRes, final GetUserForSettings mGetUserForSettings) { final String userName = SettingsApp.getInstance().getUserName(); final int profileBLE = SettingsApp.getInstance().getProfileBLE(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { profiles.get(i).setGender(mRes); } } realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { getUserForSettings(mGetUserForSettings); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db setStateUserFromSettings =" + error.getMessage()); } }); } public void setTypeProfile(final int mRes, final GetUserForSettings mGetUserForSettings) { final String userName = SettingsApp.getInstance().getUserName(); final int profileBLE = SettingsApp.getInstance().getProfileBLE(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userName) .findFirst(); RealmList<Profile> profiles = userLibr.getProfiles(); for (int i = 0; i < profiles.size(); i++) { if (profiles.get(i).getNumber() == profileBLE) { profiles.get(i).setActivity_type(mRes); } } realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { getUserForSettings(mGetUserForSettings); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db setTypeProfile =" + error.getMessage()); } }); } public void updateUserDb(final MainView mGraphView, UserApi mEvent) { final UserApiData userApiData = mEvent.getUser(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { UserLibr userLibr = realm.where(UserLibr.class) .equalTo("email", userApiData.getEmail()) .findFirst(); userLibr.setUpdated_at(userApiData.getUpdated_at()); RealmList<StringRealm> userLibrAlarms = userLibr.getAlarms(); if (userLibrAlarms != null) { userLibrAlarms.clear(); } else { userLibrAlarms = new RealmList<StringRealm>(); } List<String> alarms = userApiData.getAlarms(); if (alarms != null) { for (String str : alarms) { StringRealm stringRealm = new StringRealm(); stringRealm.text = str; userLibrAlarms.add(stringRealm); } userLibr.setAlarms(userLibrAlarms); } realm.copyToRealmOrUpdate(userLibr); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { saveParamsBody(); mGraphView.makeRequestUpdateMeasurement(); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db setTypeProfile =" + error.getMessage()); } }); } // =============================================================== // END update // =============================================================== // DELETE // =============================================================== public void deleteAlarmFromDn(final String mTimeText, final AlarmView mAlarmView) { realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<AlarmModel> result = realm.where(AlarmModel.class) .equalTo("time", mTimeText) .equalTo("email", SettingsApp.getInstance().getUserName()) .findAll(); result.deleteAllFromRealm(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { getAlarmFromDb(mAlarmView); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { saveAllLogs("ERROR in db deleteAlarmFromDn =" + error.getMessage()); } }); } public void deleteAllDataTestUser(final DeleteDataUserListener mListener) { realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { String userName = SettingsApp.getInstance().getUserName(); RealmResults<ParamsBody> results = realm.where(ParamsBody.class) .equalTo("userName_id", userName) .findAll(); results.deleteAllFromRealm(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { deleteAllDataTestUserNext(mListener); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { mListener.isDeleteOk(false); saveAllLogs("ERROR in db deleteAllDataTestUser" + error.getMessage()); } }); } private void deleteAllDataTestUserNext(final DeleteDataUserListener mListener) { realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { String userName = SettingsApp.getInstance().getUserName(); RealmResults<UserLibr> result = realm.where(UserLibr.class) .equalTo("email", userName) .findAll(); result.deleteAllFromRealm(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { mListener.isDeleteOk(true); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { mListener.isDeleteOk(false); saveAllLogs("ERROR in db deleteAllDataTestUser" + error.getMessage()); } }); } // =============================================================== // END DELETE // =============================================================== // LISTENER // =============================================================== public interface StateListener { void isSave(int state); } public interface BodyListener { void isBody(int body); } public interface BirthDayListener { void isBirthDay(String date); } public interface HeightListener { void isHeight(String height); } public interface ProfileFirstStartBLeListener { void isOkFullSettings(boolean mIsOkFullSettings); } public interface ProfileFirstStartGoogleFit { void isOkFullSettings(boolean mIsOkFullSettings); void isTargetWeight(String height); } public interface ProfileBLeListener { void isProfileBLE(int prfileBle); void isOkFullSettings(boolean mIsOkFullSettings); } public interface AlarmListener { void getAllAlarm(RealmResults<AlarmModel> mAll, StringBuilder mMsgStr); } public interface GetUserForSettings { void getUserForSettings(UserLibr mUserLibr); } public interface DeleteDataUserListener { void isDeleteOk(boolean isDelete); } //============================================================== private UserLibr transformUpdateEventUserApi(UpdateUiEvent mEvent) { UserLibr userLibr = new UserLibr(); RealmList<Profile> profiles = new RealmList<>(); UserApi userApi = (UserApi) mEvent.getData(); UserApiData userApiData = userApi.getUser(); List<ProfileApi> profileApis = userApiData.getProfileApis(); for (int i = 0; i < profileApis.size(); i++) { ProfileApi profileApi = profileApis.get(i); Profile profile = new Profile(); profile.setId(profileApi.getId()); profile.setUser_id(profileApi.getUser_id()); profile.setActivity_type(profileApi.getActivity_type()); profile.setHeight(profileApi.getHeight()); profile.setGender(profileApi.getGender()); profile.setAge(profileApi.getBirthday()); profile.setCreated_at(profileApi.getCreated_at()); profile.setUpdated_at(profileApi.getUpdated_at()); profile.setNumber(profileApi.getNumber()); profile.setTarget_weight(profileApi.getTarget_weight()); profile.setMeasurements_count(profileApi.getMeasurements_count()); profiles.add(profile); } userLibr.setEmail(userApiData.getEmail()); userLibr.setPassword(SettingsApp.getInstance().getUserPassword()); userLibr.setToken(userApi.getToken()); userLibr.setId_server(userApiData.getId()); userLibr.setCreated_at(userApiData.getCreated_at()); userLibr.setUpdated_at(userApiData.getUpdated_at()); userLibr.setIs_imperial(!SettingsApp.getInstance().getMetric()); userLibr.setKeep_login(SettingsApp.getInstance().getAutoLogin()); userLibr.setTheme(userApiData.getTheme()); userLibr.setLanguage(userApiData.getLanguage()); userLibr.setProfileBLE(SettingsApp.getInstance().getProfileBLE()); userLibr.setProfiles(profiles); return userLibr; } //============================================================== }
true
ccb8bde6c727c71e4ee32e367c324c77e23edd9a
Java
joersaac/Los-kks_parcial01_POO
/Ejercicio Parcial 01/src/com/JESA/s00159619/PlazaFija.java
UTF-8
721
2.609375
3
[]
no_license
package com.JESA.s00159619; public class PlazaFija extends Empleado { private int extencion; public PlazaFija(String nombre, String puesto, double salario, int extencion) { super(nombre, puesto, salario); this.extencion = extencion; } public void setExtencion(int extencion) { this.extencion = extencion; } public int getExtencion() { return extencion; } @Override public String toString() { return "PlazaFija{" + "extencion=" + extencion + ", Nombre='" + Nombre + '\'' + ", puesto='" + puesto + '\'' + ", salario=" + salario + '}' + "\n " + Documentos.toString(); } }
true
3338059f6c26dab0323c4cc69d90807e162d8af2
Java
cuanfraser/cs3200-final-project
/src/main/java/com/example/springtemplate/daos/GameDao.java
UTF-8
2,657
2.46875
2
[]
no_license
package com.example.springtemplate.daos; import com.example.springtemplate.models.Game; import com.example.springtemplate.models.Team; import com.example.springtemplate.repositories.GameRepository; import com.example.springtemplate.repositories.TeamRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @CrossOrigin(origins = "*") public class GameDao { @Autowired GameRepository repository; @Autowired TeamRepository teamRepository; @PostMapping("/api/games") public Game createGame(@RequestBody Game game) { return repository.save(game); } // SPECIFIC CREATE API FOR ADDING GAME WITH 2 TEAMS @PostMapping("/api/games/home/{hid}/away/{aid}") public Game createHomeGameForTeam( @PathVariable("hid") Integer hid, @PathVariable("aid") Integer aid, @RequestBody Game game) { Team home = teamRepository.findById(hid).get(); Team away = teamRepository.findById(aid).get(); game.setHome(home); game.setAway(away); return repository.save(game); } @GetMapping("/api/teams/{tid}/games") public List<Game> findGamesForTeam( @PathVariable("tid") Integer tid) { Team team = teamRepository.findById(tid).get(); return team.getGames(); } @GetMapping("/api/games") public List<Game> findAllGames() { return (List<Game>) repository.findAll(); } @GetMapping("/api/games/{id}") public Game findGameById( @PathVariable("id") Integer id) { return repository.findById(id).get(); } @PutMapping("/api/games/{id}") public Game updateGame( @PathVariable("id") Integer id, @RequestBody() Game newGame) { Game game = this.findGameById(id); game.setLocation(newGame.getLocation()); game.setStartTime(newGame.getStartTime()); // TODO: UPDATE TEAMS return repository.save(game); } @DeleteMapping("/api/games/{id}") public void deleteGame( @PathVariable("id") Integer id) { repository.deleteById(id); } }
true
baf878732a39aca7298798989ca5ed9897743895
Java
liepeiming/xposed_chatbot
/alimama/src/main/java/mtopsdk/mtop/upload/DefaultFileUploadListener.java
UTF-8
2,130
2.296875
2
[]
no_license
package mtopsdk.mtop.upload; import mtopsdk.common.util.TBSdkLog; import mtopsdk.mtop.upload.domain.UploadFileInfo; public class DefaultFileUploadListener implements FileUploadBaseListener { private static final String TAG = "mtopsdk.DefaultFileUploadListener"; private FileUploadListener oldListener; public DefaultFileUploadListener() { } public DefaultFileUploadListener(FileUploadListener fileUploadListener) { this.oldListener = fileUploadListener; } public void onStart() { if (this.oldListener != null) { this.oldListener.onStart(); } if (TBSdkLog.isLogEnable(TBSdkLog.LogEnable.DebugEnable)) { TBSdkLog.d(TAG, "[onStart]onStart called." + ", ThreadName:" + Thread.currentThread().getName()); } } public void onProgress(int i) { if (this.oldListener != null) { this.oldListener.onProgress(i); } if (TBSdkLog.isLogEnable(TBSdkLog.LogEnable.DebugEnable)) { TBSdkLog.d(TAG, "[onProgress]onProgress (percentage=" + i + "), ThreadName:" + Thread.currentThread().getName()); } } public void onFinish(UploadFileInfo uploadFileInfo, String str) { if (this.oldListener != null) { this.oldListener.onFinish(str); } else { onFinish(str); } } public void onError(String str, String str2, String str3) { if (this.oldListener != null) { this.oldListener.onError(str2, str3); } else { onError(str2, str3); } } @Deprecated public void onError(String str, String str2) { if (TBSdkLog.isLogEnable(TBSdkLog.LogEnable.DebugEnable)) { TBSdkLog.d(TAG, "[onError]onError errCode=" + str + ", errMsg=" + str2 + " , ThreadName:" + Thread.currentThread().getName()); } } @Deprecated public void onFinish(String str) { if (TBSdkLog.isLogEnable(TBSdkLog.LogEnable.DebugEnable)) { TBSdkLog.d(TAG, "[onFinish]onFinish url=" + str + ", ThreadName:" + Thread.currentThread().getName()); } } }
true
f2d3c03f328f7be53c9d40c39a826f1f53f82866
Java
whatafree/JCoffee
/benchmark/bigclonebenchdata_partial/14282702.java
UTF-8
1,688
2.296875
2
[]
no_license
class c14282702 { @Override public void runTask(HashMap jobStack) throws Exception { String lstrFilter = (String) getResources().get("filter"); String lstrTarget = (String) getResources().get("target"); String lstrSource = (String) getResources().get("source"); String[] lstrFilesFound = null; lstrFilesFound = searchForFiles(lstrSource, lstrFilter); if (lstrFilesFound != null) { for (int i = 0; i < lstrFilesFound.length; i++) { getLog().debug("Found match [" + lstrSource + File.separator + lstrFilesFound[i] + "]"); File lfileSource = new File(lstrSource + File.separator + lstrFilesFound[i]); File lfileTarget = new File(lstrTarget + File.separator + lstrFilesFound[i]); FileChannel lfisInput = null; FileChannel lfosOutput = null; try { lfisInput = new FileInputStream(lfileSource).getChannel(); lfosOutput = new FileOutputStream(lfileTarget).getChannel(); int maxCount = (32 * 1024 * 1024) - (32 * 1024); long size = lfisInput.size(); long position = 0; while (position < size) { position += lfisInput.transferTo(position, maxCount, lfosOutput); } } finally { if (lfisInput != null) { lfisInput.close(); } if (lfosOutput != null) { lfosOutput.close(); } } } } } }
true