blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2 values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 5.41M | extension stringclasses 11 values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
444877850ecb162eb96626212699a1b024151501 | 08ac62c91fd90fc04a0dc5af59dfa8c7e093ce84 | /airville/Robot.java | a66f2528ee06ea6ba513002e50135e35a7ce3500 | [] | no_license | drewtoak/EECS-293-Airville-Game | 09880ba309a96714f7e030af800a2e48f262512c | 2f2a2a250190c29d43ba2317ee9b278101c59cc8 | refs/heads/master | 2021-07-07T16:18:30.610591 | 2017-10-04T22:20:37 | 2017-10-04T22:20:37 | 105,812,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,392 | java | package airville;
import java.math.BigDecimal;
/**
* The Robot class extends the Staff class;
* sets up an automated line to process a line of passengers.
*
* @author Andrew Hwang
* @version 1.0 Dec. 03, 2015
*/
public class Robot extends Staff {
/**
* Determines if a Supervisor is helping this Robot
*/
private boolean supervisorPresent;
/**
* The Constructor takes in the same value as the Constructor in the Staff class.
* And functions similarly to the Staff's constructor.
*
* @param checkedInLine a line passed to this Robot.
*/
public Robot(CheckedInLine checkedInLine) {
super(checkedInLine);
this.supervisorPresent = false;
}
/**
* Overrides the processNextPassenger function in the Staff class:
* if the next passenger is a slow type of passenger,
* then that passenger is redirected to a line that will be processed by a Staff.
*
* @return total time it takes to process the next passenger.
*/
@Override
public BigDecimal processNextPassenger() {
Passenger nextPassenger = this.checkedInLine.getNextPassenger();
BigDecimal passengerProcessTime = nextPassenger.getPassengerProcessTime();
//if the passenger is a slow type, then redirect them to a different line.
if (nextPassenger.isSlowPassenger()) {
Game.QUEUE_OF_REDIRECTED_PASSENGERS.add(nextPassenger);
return null;
}
//same as Staff's processNextPassenger function.
else {
if (this.supervisorPresent) {
passengerProcessTime = passengerProcessTime.multiply(BigDecimal.valueOf(Game.SUPERVISOR_TIME_MULTIPLIER));
this.supervisorPresent = false;
Game.NUMBER_OF_BUSY_SUPERVISORS--;
}
if (nextPassenger.isPartOfGroup()) {
if (nextPassenger.processedGroupForDiamond(passengerProcessTime)) {
Game.DIAMONDS++;
}
Game.POINTS += Game.REWARDED_POINTS*nextPassenger.getNumberOfGroupMembers();
}
else {
Game.POINTS += Game.REWARDED_POINTS;
}
}
return passengerProcessTime;
}
/**
* Sets a non-busy Supervisor to help this Robot.
*
* @throws EmployeeException all supervisors are busy.
*/
@Override
public void setSupervisor() throws EmployeeException{
if (Game.NUMBER_OF_BUSY_SUPERVISORS < Game.NUMBER_OF_SUPERVISORS) {
this.supervisorPresent = true;
Game.NUMBER_OF_BUSY_SUPERVISORS++;
}
else {
throw new EmployeeException(EmployeeException.EmployeeErrorCode.ALL_SUPERVISORS_ARE_BUSY);
}
}
/**
* Removes a busy Supervisor from helping this Robot.
*
* @throws EmployeeException EmployeeException there are no supervisors here.
*/
@Override
public void removeSupervisor() throws EmployeeException{
if (this.isSupervisorPresent()) {
this.supervisorPresent = false;
Game.NUMBER_OF_BUSY_SUPERVISORS--;
}
else {
throw new EmployeeException(EmployeeException.EmployeeErrorCode.NO_SUPERVISORS_PRESENT);
}
}
/**
* Verifies if a Supervisor is currently helping this Robot.
*
* @return a boolean whether the supervisor is present with this Robot.
*/
@Override
public boolean isSupervisorPresent() {
return this.supervisorPresent;
}
/**
* Shifts this Robot to a different line to process,
* if the previous line was completely processed.
*
* @param newLine the desired line to process.
* @throws EmployeeException there are still passengers in the automated line.
*/
@Override
public void setCheckedInLine(CheckedInLine newLine) throws EmployeeException{
if (this.isTheLineEmpty()) {
this.checkedInLine = newLine;
}
else {
throw new EmployeeException(EmployeeException.EmployeeErrorCode.PASSENGERS_STIL_PRESENT);
}
}
/**
* Verifies if the line being processed is empty.
*
* @return a boolean if there is no line for the Robot to process.
*/
public boolean isTheLineEmpty() {
return this.checkedInLine.thisLineIsEmpty();
}
}
| [
"ath50@case.edu"
] | ath50@case.edu |
e799233d39cb9c51d306556179908e5317e39d50 | 816fbba1325bd747fe13b8b3165833f081b17c79 | /RatingsWeProvide/src/main/java/com/self/RatingsWeProvide/configuration/Config.java | e3f571badfd60a463278b4eb92daf9c58c1b547d | [] | no_license | Abhijitklkrni/RatingsWeProvide | da39171b29d4d62dd76377555a91ca6d4263a888 | 771db5944a9486e95b5dfd26bcad0a4f048f838b | refs/heads/master | 2022-12-03T11:25:20.964238 | 2020-08-22T20:34:41 | 2020-08-22T20:34:41 | 289,553,759 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,656 | java | package com.self.RatingsWeProvide.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("com.self.RatingsWeProvide.Service com.self.RatingsWeProvide.DAO com.self.RatingsWeProvide.Entity ")
public class Config {
// It will automatically read database properties from application.properties and create DataSource object
@Autowired
private DataSource dataSource;
@Autowired
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean getSessionFactory() { // creating session factory
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan(new String[]{"com.self.RatingsWeProvide.Entity"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
private Properties hibernateProperties()
{
// configure hibernate properties
Properties properties = new Properties();
properties.put("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "false");
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
@Bean public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("oracle.jdbc.OracleDriver");
dataSourceBuilder.url("jdbc:oracle:thin:@localhost:1521:orcl");
dataSourceBuilder.username("scott");
dataSourceBuilder.password("tiger");
return dataSourceBuilder.build(); }
@Autowired
@Bean(name = "transactionManager") // creating transaction manager factory
public HibernateTransactionManager getTransactionManager( SessionFactory sessionFactory)
{
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
| [
"abhij@DESKTOP-4099KDI"
] | abhij@DESKTOP-4099KDI |
770a232718db439d46a8a11f26bdebfa092d4fa6 | 8b1ed09effcefe62895abe21e9e44964e29491c8 | /src/main/java/br/com/meta/repository/ProdutoRepository.java | 227e11318cea5fd17325441e568c3b67f46ec6d1 | [
"MIT"
] | permissive | fabianodecastromonteiro/meta-fabiano | afcdc6b1b9458a95a0c0f554a2179dcfa470797f | 5e85286b0d7671327d6017f7d6e1f564871948ac | refs/heads/master | 2020-03-26T22:42:08.144534 | 2018-08-23T21:00:02 | 2018-08-23T21:00:02 | 145,480,760 | 0 | 0 | MIT | 2018-08-23T21:00:03 | 2018-08-20T23:29:40 | Java | UTF-8 | Java | false | false | 273 | java | package br.com.meta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.meta.model.Produto;
@Repository
public interface ProdutoRepository extends JpaRepository<Produto, Integer> {
}
| [
"fabianodecastromonteiro@outlook.com"
] | fabianodecastromonteiro@outlook.com |
4f725828ddedaced69e55e4c43b147310a67b245 | 9cdf4a803b5851915b53edaeead2546f788bddc6 | /mapdb-integration/jbpm-human-task-mapdb/src/main/java/org/jbpm/services/task/impl/model/EmailNotificationHeaderImpl.java | 52f7f8e653b0bd2734dcaed665915e07f97d341c | [] | no_license | kiegroup/droolsjbpm-contributed-experiments | 8051a70cfa39f18bc3baa12ca819a44cc7146700 | 6f032d28323beedae711a91f70960bf06ee351e5 | refs/heads/master | 2023-06-01T06:11:42.641550 | 2020-07-15T15:09:02 | 2020-07-15T15:09:02 | 1,184,582 | 1 | 13 | null | 2021-06-24T08:45:52 | 2010-12-20T15:42:26 | Java | UTF-8 | Java | false | false | 5,127 | java | /**
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.jbpm.services.task.impl.model;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class EmailNotificationHeaderImpl implements org.kie.internal.task.api.model.EmailNotificationHeader {
private long id;
private String language;
private String replyTo;
private String from;
private String subject;
private String body;
public void writeExternal(ObjectOutput out) throws IOException {
out.writeLong( id );
if ( language != null ) {
out.writeBoolean( true );
out.writeUTF( language );
} else {
out.writeBoolean( false );
}
if ( subject != null ) {
out.writeBoolean( true );
out.writeUTF( subject );
} else {
out.writeBoolean( false );
}
if ( replyTo != null ) {
out.writeBoolean( true );
out.writeUTF( replyTo );
} else {
out.writeBoolean( false );
}
if ( from != null ) {
out.writeBoolean( true );
out.writeUTF( from );
} else {
out.writeBoolean( false );
}
if ( body != null ) {
out.writeBoolean( true );
out.writeUTF( body );
} else {
out.writeBoolean( false );
}
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
id = in.readLong();
if ( in.readBoolean() ) {
language = in.readUTF();
}
if ( in.readBoolean() ) {
subject = in.readUTF();
}
if ( in.readBoolean() ) {
replyTo = in.readUTF();
}
if ( in.readBoolean() ) {
from = in.readUTF();
}
if ( in.readBoolean() ) {
body = in.readUTF();
}
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getReplyTo() {
return replyTo;
}
public void setReplyTo(String replyTo) {
this.replyTo = replyTo;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((subject == null) ? 0 : subject.hashCode());
result = prime * result + ((body == null) ? 0 : body.hashCode());
result = prime * result + ((from == null) ? 0 : from.hashCode());
result = prime * result + ((language == null) ? 0 : language.hashCode());
result = prime * result + ((replyTo == null) ? 0 : replyTo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( !(obj instanceof EmailNotificationHeaderImpl) ) return false;
EmailNotificationHeaderImpl other = (EmailNotificationHeaderImpl) obj;
if ( subject == null ) {
if ( other.subject != null ) return false;
} else if ( !subject.equals( other.subject ) ) return false;
if ( body == null ) {
if ( other.body != null ) return false;
} else if ( !body.equals( other.body ) ) return false;
if ( from == null ) {
if ( other.from != null ) return false;
} else if ( !from.equals( other.from ) ) return false;
if ( language == null ) {
if ( other.language != null ) return false;
} else if ( !language.equals( other.language ) ) return false;
if ( replyTo == null ) {
if ( other.replyTo != null ) return false;
} else if ( !replyTo.equals( other.replyTo ) ) return false;
return true;
}
} | [
"swiderski.maciej@gmail.com"
] | swiderski.maciej@gmail.com |
c06953bcad2d3bcb617cdd7408e29d05b55fb972 | 7e708b4b52b80277f0c99352ff256ed8c6ade1f6 | /thread/src/main/java/com/threadpool/ThreadPoolTest.java | 856d873c1fd32fe4c67522ec8870130dccecd2fe | [] | no_license | yangwenshuo/demo | 21c02c6387db081be80b31196b1ab856ee40db3f | 6a36476e45f0f728f24a092ff3fc695c73ca2e62 | refs/heads/master | 2023-03-05T05:24:48.992209 | 2019-05-25T16:51:43 | 2019-05-25T16:51:43 | 155,945,953 | 1 | 0 | null | 2022-09-01T22:58:43 | 2018-11-03T03:22:51 | JavaScript | WINDOWS-1252 | Java | false | false | 482 | java | package com.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 5; i++) {
threadPool.submit(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("¶À¹Â°ÜÌìÀ´Ò²");
}
});
}
}
}
| [
"root"
] | root |
5d87cc0b1d63e2c3caddd14091b7d05e2bbb088f | 982b7e679c6d54fde45f947c6d4ccdd10c098cf6 | /app/src/main/java/lan/tmsystem/bookhostel/data/Hostel.java | 0a9787c08768a522f8e53ade538b421af25ac696 | [] | no_license | jarvaang-enterprises/bookhostel | f383fdf528e2e3e3a86ed9e3a14d77ea86307bb0 | 6b86202f387a2f90c2b75afc3b4dfe2c6c5e872e | refs/heads/main | 2023-03-13T23:32:51.773819 | 2021-02-27T07:20:33 | 2021-02-27T07:20:33 | 336,495,486 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,494 | java | package lan.tmsystem.bookhostel.data;
import com.google.firebase.firestore.GeoPoint;
import java.util.ArrayList;
import java.util.List;
public class Hostel {
private String mName;
private GeoPoint mLocation;
private String userId;
private String price;
private List<HostelRoom> rooms;
private String numSingles;
private String numDoubles;
public Hostel(){};
public Hostel(String name, String price, String numSingles, String numDoubles, GeoPoint location, String userId){
this.setName(name);
this.setLocation(location);
this.setUserId(userId);
List<HostelRoom> r = new ArrayList<HostelRoom>();
this.setRooms(r);
this.setPrice(price);
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public GeoPoint getLocation() {
return mLocation;
}
public void setLocation(GeoPoint location) {
mLocation = location;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<HostelRoom> getRooms() {
return rooms;
}
public void setRooms(List<HostelRoom> rooms) {
this.rooms = rooms;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
class HostelRoom {
public HostelRoom(){}
}
| [
"aanga26@gmail.com"
] | aanga26@gmail.com |
b7ab043a66e8e87668746fafe53c4f6b1059a888 | 62b8441631f0d262bf59e7e2451a88603915aadf | /.svn/pristine/0a/0a2830efa0db6a7450f228cd9f5f6e1797bd3445.svn-base | db4f456088660473d1e8d8e197b9522737083da1 | [] | no_license | WJtoy/mainHousehold- | 496fc5af19657d938324d384f2d0b72d70e60c0e | 4cff9537a5f78058a84d4b33f5f58595380597d8 | refs/heads/master | 2023-06-17T22:55:08.988873 | 2021-07-15T07:18:25 | 2021-07-15T07:18:25 | 385,202,403 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,012 | package com.wolfking.jeesite.modules.fi.web;
import com.wolfking.jeesite.common.persistence.AjaxJsonEntity;
import com.wolfking.jeesite.common.persistence.Page;
import com.wolfking.jeesite.common.utils.DateUtils;
import com.wolfking.jeesite.common.web.BaseController;
import com.wolfking.jeesite.modules.fi.entity.CustomerCharge;
import com.wolfking.jeesite.modules.fi.entity.CustomerChargeCondition;
import com.wolfking.jeesite.modules.fi.service.CustomerChargeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
/**
* 客户结帐Controller
*
* @author Jeff Zhao
* @version 2014-10-15
*/
@Controller
@RequestMapping(value = "${adminPath}/fi/customerinvoice")
public class CustomerInvoiceController extends BaseController
{
@Autowired
private CustomerChargeService customerChargeService;
// @Autowired
// private CustomerInvoiceService customerInvoiceService;
// @Autowired
// private CustomerCurrencyService customerCurrencyService;
@RequiresPermissions("fi:customerinvoice:edit")
@RequestMapping(value = { "form", "" }, method = RequestMethod.GET)
public String formGet(@RequestParam Map<String, Object> paramMap,
HttpServletRequest request, HttpServletResponse response,
Model model) {
paramMap.put("beginDate", DateUtils.getDate("yyyy-MM-01"));
paramMap.put("endDate", DateUtils.getDate());
model.addAttribute("page", null);
model.addAllAttributes(paramMap);
return "modules/fi/customerInvoiceForm";
}
@RequiresPermissions("fi:customerinvoice:edit")
@RequestMapping(value = { "form", "" }, method = RequestMethod.POST)
public String formPost(@RequestParam Map<String, Object> paramMap,
HttpServletRequest request, HttpServletResponse response,
Model model) {
CustomerChargeCondition customerChargeCondition = new CustomerChargeCondition();
// 客户
if (paramMap.containsKey("customerId") && paramMap.get("customerId").toString().length() > 0){
customerChargeCondition.setCustomerId(Long.parseLong(paramMap.get("customerId").toString()));
}
int month = -1;
// 日期,今天 到往前一月
Date beginDate = DateUtils.parseDate(paramMap.get("beginDate"));
if (beginDate == null){
beginDate = DateUtils.addMonth(new Date(), month);
paramMap.put("beginDate",
DateUtils.formatDate(beginDate, "yyyy-MM-dd"));
}
beginDate = DateUtils.getDateStart(beginDate);
Date endDate = DateUtils.parseDate(paramMap.get("endDate"));
if (endDate == null){
endDate = new Date();
paramMap.put("endDate", DateUtils.formatDate(endDate, "yyyy-MM-dd"));
}
endDate = DateUtils.getDateEnd(endDate);
// 对帐日期:
if (beginDate != null && endDate != null){
customerChargeCondition.setCreateBeginDate(beginDate);
customerChargeCondition.setCreateEndDate(endDate);
}
// 订单编号:
if (paramMap.containsKey("orderNo") && paramMap.get("orderNo").toString().trim().length() > 0){
customerChargeCondition.setOrderNo(paramMap.get("orderNo").toString());
}//下单日期
if (paramMap.containsKey("createBeginDate") && paramMap.get("createBeginDate").toString().trim().length() > 0){
customerChargeCondition.setOrderCreateBeginDate(DateUtils.parseDate(paramMap.get("createBeginDate")));
}
if (paramMap.containsKey("createEndDate") && paramMap.get("createEndDate").toString().trim().length() > 0){
customerChargeCondition.setOrderCreateEndDate(DateUtils.parseDate(paramMap.get("createEndDate")));
}
//完成日期
if (paramMap.containsKey("closeBeginDate") && paramMap.get("closeBeginDate").toString().trim().length() > 0){
customerChargeCondition.setOrderCloseBeginDate(DateUtils.parseDate(paramMap.get("closeBeginDate")));
}
if (paramMap.containsKey("closeEndDate") && paramMap.get("closeEndDate").toString().trim().length() > 0){
customerChargeCondition.setOrderCloseEndDate(DateUtils.parseDate(paramMap.get("closeEndDate")));
}
Page<CustomerCharge> page = customerChargeService.find(new Page<>(request, response), customerChargeCondition);
model.addAttribute("page", page);
model.addAllAttributes(paramMap);
return "modules/fi/customerInvoiceForm";
}
/**
* 结帐确认 form
*
* @param request
* @param model
* @return
*/
@RequiresPermissions("fi:customerinvoice:edit")
@RequestMapping(value = "save", method = RequestMethod.GET)
public String saveConfirm(String customerId, String totalCharge,
HttpServletRequest request, Model model) {
model.addAttribute("customerId", customerId);
model.addAttribute("totalCharge", totalCharge);
model.addAttribute("currentDate",
DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
model.addAttribute("customerCharge", new CustomerCharge());
return "modules/fi/customerInvoiceConfirmForm";
}
@ResponseBody
@RequiresPermissions("fi:customerinvoice:edit")
@RequestMapping(value = { "save" })
public AjaxJsonEntity save(@RequestParam String ids,
@RequestParam Date invoiceDate, @RequestParam String remarks,
HttpServletResponse response) {
response.setContentType("application/json; charset=UTF-8");
AjaxJsonEntity jsonEntity = new AjaxJsonEntity(true);
try
{
// 保存
// customerInvoiceService.add(ids.split(","), invoiceDate, remarks);
} catch (Exception e)
{
jsonEntity.setSuccess(false);
jsonEntity.setMessage(e.getMessage().toString());
}
return jsonEntity;
}
// /**
// * 结帐确认 form
// *
// * @param request
// * @param model
// * @return
// */
// @RequiresPermissions("fi:customerinvoice:invoiceall")
// @RequestMapping(value = "invoiceall", method = RequestMethod.GET)
// public String invoiceAllConfirm(String customerId, String customerChargeNo,
// String beginDate, String endDate, String orderNo,
// String createBeginDate, String createEndDate,
// String closeBeginDate, String closeEndDate,
// HttpServletRequest request, Model model)
// {
// model.addAttribute("customerId", customerId);
// model.addAttribute("customerChargeNo", customerChargeNo);
// model.addAttribute("beginDate", beginDate);
// model.addAttribute("endDate", endDate);
// model.addAttribute("orderNo", orderNo);
// model.addAttribute("createBeginDate", createBeginDate);
// model.addAttribute("createEndDate", createEndDate);
// model.addAttribute("closeBeginDate", closeBeginDate);
// model.addAttribute("closeEndDate", closeEndDate);
// model.addAttribute("currentDate",
// DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
// model.addAttribute("order", new Order());
// return "modules/sd/customerInvoiceConfirmAllForm";
// }
//
// @ResponseBody
// @RequiresPermissions("fi:customerinvoice:invoiceall")
// @RequestMapping(value =
// { "invoiceall" })
// public AjaxJsonEntity invoiceAll(String customerId,
// String customerChargeNo, String beginDate, String endDate,
// String orderNo, String createBeginDate, String createEndDate,
// String closeBeginDate, String closeEndDate,
// @RequestParam Date invoiceDate, @RequestParam String remarks,
// HttpServletResponse response)
// {
// response.setContentType("application/json; charset=UTF-8");
// AjaxJsonEntity jsonEntity = new AjaxJsonEntity(true);
// try
// {
//
// Map<String, Object> paraMap = new HashMap<String, Object>();
// paraMap.put("customerId", customerId);
// paraMap.put("customerChargeNo", customerChargeNo);
// paraMap.put("beginDate", beginDate);
// paraMap.put("endDate", endDate);
// paraMap.put("orderNo", orderNo);
// paraMap.put("createBeginDate", createBeginDate);
// paraMap.put("createEndDate", createEndDate);
// paraMap.put("closeBeginDate", closeBeginDate);
// paraMap.put("closeEndDate", closeEndDate);
// paraMap.put("status", CustomerChargeMaster.CC_STATUS_CONFIRMED);
// List<CustomerChargeMaster> needInvoiceList = customerChargeService
// .find(paraMap);
//
// // 保存
// customerInvoiceService.invoiceAll(needInvoiceList, invoiceDate,
// remarks);
// } catch (Exception e)
// {
// jsonEntity.setSuccess(false);
// jsonEntity.setMessage(e.getMessage().toString());
// }
// return jsonEntity;
// }
}
| [
"1227679550@qq.com"
] | 1227679550@qq.com | |
67a450c3786d00f28eea370e5485f00b7d3bf71d | 5502127275fe61cd03cca21305192cdc0ab533b2 | /src/br/fameg/testers/Tester.java | 16e624480411bfbdd59798c74949c5526ea7d740 | [] | no_license | allankanzler/POO2 | 506e9c0ae4add3de5235c4bdac583d7b6b664263 | 7de7514188f11dadc90a357e6bbbc1e2668f6408 | refs/heads/master | 2021-01-10T14:28:35.071632 | 2015-11-27T02:40:53 | 2015-11-27T02:40:53 | 46,956,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,441 | java | /*
* 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 br.fameg.testers;
import br.fameg.domain.Palavra;
import br.fameg.domain.TransformadorDePalavraEmVetor;
import br.fameg.domain.VerificadorDeLetras;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Allan
*/
public class Tester {
public static void main(String[] args) {
ArrayList<Palavra> array = new ArrayList<>();
array.add(new Palavra("lalala","bacon"));
array.add(new Palavra("lalala","cerveja"));
array.add(new Palavra("lalala","tungstenio"));
array.add(new Palavra("lalala","pinga"));
System.out.println("vetor: "+array);
ArrayList<char[]> vetor = TransformadorDePalavraEmVetor.transformar(array);
System.out.println("----");
for(char[] c:vetor){
System.out.println("vetor: "+Arrays.toString(c));
}
System.out.println("----");
System.out.println("NOVO TESTE!!!");
vetor = VerificadorDeLetras.palavraMaior(vetor);
System.out.println("-");
for(char[] c:vetor){
System.out.println("vetor: "+Arrays.toString(c));
}
}
}
| [
"paraibakan@gmail.com"
] | paraibakan@gmail.com |
46cbfcd387399b55878d5f65efb02128fad655af | e39b62dc4d8b791e01560734be40a5985fdd061a | /app/src/main/java/source/kevtimov/starwarsapp/fragments/OptionsFragment.java | addf96811eb7f0b65b5c6b43c597e64b71220b8a | [] | no_license | kaevtimov/StarWarsAPP | 5c13fb388753e9ea2329db97371e41dfaef94f23 | 5fdac104a5eb50eb5d05fe10c729118205ca6e09 | refs/heads/master | 2020-03-26T00:22:35.973860 | 2018-08-20T07:12:36 | 2018-08-20T07:12:36 | 144,317,750 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 964 | java | package source.kevtimov.starwarsapp.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import source.kevtimov.starwarsapp.R;
/**
* A simple {@link Fragment} subclass.
*/
public class OptionsFragment extends Fragment {
private ImageView mImageView;
public OptionsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_options, container, false);
mImageView = root.findViewById(R.id.iv_sith_jedi);
return root;
}
public static OptionsFragment createInstance(){
return new OptionsFragment();
}
}
| [
"kaevtimov@gmail.com"
] | kaevtimov@gmail.com |
a48802a9209845fa29c48a770fcf836bf753e049 | 97f65fdc2171d3ae88372f5971b92c5bd187bf47 | /app/src/main/java/NEGOCIO/singletonDatos.java | 6bdfc7c36a81709fccb23f8019b77818eb3770a1 | [] | no_license | juanmanuelco/plantas_app | ee0884b1198a63f1306dd596f0b2751dab491417 | f5aa7b878be65d66d7fb3ebc73a3506155f7d3f6 | refs/heads/master | 2020-03-24T02:33:59.095668 | 2018-07-26T03:08:15 | 2018-07-26T03:08:15 | 142,381,568 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 965 | java | package NEGOCIO;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class singletonDatos
{
private static singletonDatos instanciaSingleton;
private RequestQueue requestDatos;
private static Context mCtx;
private singletonDatos (Context context){
mCtx=context;
requestDatos=getRequestDatos();
}
public static synchronized singletonDatos getInstancia(Context context){
if(instanciaSingleton==null){
instanciaSingleton=new singletonDatos(context);
}
return instanciaSingleton;
}
public RequestQueue getRequestDatos(){
if(requestDatos==null){
requestDatos= Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestDatos;
}
public <T>void addToRequest(Request<T> request){
requestDatos.add(request);
}
}
| [
"juanmanuelco@yahoo.es"
] | juanmanuelco@yahoo.es |
60c50e6717fea5d2cef4ef4c02217a56c9a715c8 | 9bf6dee1407f112cebf42443e0f492e89d0d3fbc | /commons/src/org/openaion/commons/database/dao/DAOAlreadyRegisteredException.java | a16e48d22266d873cb06360432c751d26b0ab4fa | [] | no_license | vavavr00m/aion-source | 6caef6738fee6d4898fcb66079ea63da46f5c9c0 | 8ce4c356d860cf54e5f3fe4a799197725acffc3b | refs/heads/master | 2021-01-10T02:08:43.965463 | 2011-08-22T10:47:12 | 2011-08-22T10:47:12 | 50,949,918 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 821 | java | package org.openaion.commons.database.dao;
/**
* This exception is thrown if DAO is already registered in {@link org.openaion.commons.database.dao.DAOManager}
*
* @author SoulKeeper
*/
public class DAOAlreadyRegisteredException extends DAOException
{
/**
* SerialID
*/
private static final long serialVersionUID = -4966845154050833016L;
public DAOAlreadyRegisteredException()
{
}
/**
* @param message
*
*/
public DAOAlreadyRegisteredException(String message)
{
super(message);
}
/**
* @param message
* @param cause
*
*/
public DAOAlreadyRegisteredException(String message, Throwable cause)
{
super(message, cause);
}
/**
* @param cause
*
*/
public DAOAlreadyRegisteredException(Throwable cause)
{
super(cause);
}
}
| [
"tomulescu@gmail.com"
] | tomulescu@gmail.com |
ace69cd3b9b34be7575a0624a704d6f9919b2232 | 24d8cf871b092b2d60fc85d5320e1bc761a7cbe2 | /JFreeChart/rev91-2272/right-trunk-2272/source/org/jfree/chart/ChartTransferable.java | 1d36be96d23975865adda8188c6b90cb0580b59d | [] | no_license | joliebig/featurehouse_fstmerge_examples | af1b963537839d13e834f829cf51f8ad5e6ffe76 | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | refs/heads/master | 2016-09-05T10:24:50.974902 | 2013-03-28T16:28:47 | 2013-03-28T16:28:47 | 9,080,611 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 3,852 | java |
package org.jfree.chart;
import java.awt.Graphics2D;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class ChartTransferable implements Transferable {
final DataFlavor imageFlavor = new DataFlavor(
"image/x-java-image; class=java.awt.Image", "Image");
private JFreeChart chart;
private int width;
private int height;
private int minDrawWidth;
private int minDrawHeight;
private int maxDrawWidth;
private int maxDrawHeight;
public ChartTransferable(JFreeChart chart, int width, int height) {
this(chart, width, height, true);
}
public ChartTransferable(JFreeChart chart, int width, int height,
boolean cloneData) {
this(chart, width, height, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE,
true);
}
public ChartTransferable(JFreeChart chart, int width, int height,
int minDrawW, int minDrawH, int maxDrawW, int maxDrawH,
boolean cloneData) {
try {
this.chart = (JFreeChart) chart.clone();
}
catch (CloneNotSupportedException e) {
this.chart = chart;
}
this.width = width;
this.height = height;
this.minDrawWidth = minDrawW;
this.minDrawHeight = minDrawH;
this.maxDrawWidth = maxDrawW;
this.maxDrawHeight = maxDrawH;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {this.imageFlavor};
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return this.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (this.imageFlavor.equals(flavor)) {
return createBufferedImage(this.chart, this.width, this.height,
this.minDrawWidth, this.minDrawHeight, this.maxDrawWidth,
this.maxDrawHeight);
}
else {
throw new UnsupportedFlavorException(flavor);
}
}
private BufferedImage createBufferedImage(JFreeChart chart, int w, int h,
int minDrawW, int minDrawH, int maxDrawW, int maxDrawH) {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
boolean scale = false;
double drawWidth = w;
double drawHeight = h;
double scaleX = 1.0;
double scaleY = 1.0;
if (drawWidth < minDrawW) {
scaleX = drawWidth / minDrawW;
drawWidth = minDrawW;
scale = true;
}
else if (drawWidth > maxDrawW) {
scaleX = drawWidth / maxDrawW;
drawWidth = maxDrawW;
scale = true;
}
if (drawHeight < minDrawH) {
scaleY = drawHeight / minDrawH;
drawHeight = minDrawH;
scale = true;
}
else if (drawHeight > maxDrawH) {
scaleY = drawHeight / maxDrawH;
drawHeight = maxDrawH;
scale = true;
}
Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth,
drawHeight);
if (scale) {
AffineTransform st = AffineTransform.getScaleInstance(scaleX,
scaleY);
g2.transform(st);
}
chart.draw(g2, chartArea, null, null);
g2.dispose();
return image;
}
}
| [
"joliebig@fim.uni-passau.de"
] | joliebig@fim.uni-passau.de |
bf197ade4e3b28b80426dfb188b8b91a7d801c09 | 4043748e14165adad7fd59004fae9879b5fdbd0e | /src/main/java/pages/DashBoardPage.java | 8305d023d8cd98e2053d9d1edf5a65c3aaf65ab6 | [] | no_license | artie-sh/haufe_qa_task | 1214886780418e34cebbf3dc087eb7627e268238 | 8ad4a98d28bfc4f752c4fb89cfb42a8eb2522196 | refs/heads/master | 2020-03-18T17:43:35.261079 | 2018-05-28T11:48:27 | 2018-05-28T11:48:27 | 135,046,835 | 0 | 1 | null | 2018-05-28T11:48:28 | 2018-05-27T13:03:19 | Java | UTF-8 | Java | false | false | 1,212 | java | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.Arrays;
public class DashBoardPage extends BasePage {
private By dashboardHeader = By.xpath("//a[text()='Dashboard']");
private By jobsDiv = By.xpath("//div/h1[contains(text(), 'Jobs')]");
private String jobXpathTemplate = "//h3[@title='%s']";
private By jobApplications = By.xpath("//job-applications");
private String applicationByCandidateName = "//article//h4[text()='%s']";
public DashBoardPage(WebDriver driver) {
super(driver);
waitUntilElementsVisible(Arrays.asList(dashboardHeader, jobsDiv));
}
public void clickOnJob(String jobName) {
driver.findElement(By.xpath(String.format(jobXpathTemplate, jobName))).click();
waitUntilElementsVisible(Arrays.asList(jobApplications));
}
public ApplicationDetailsPage getOnApplicationDetailsPage(String candidateName) {
By application = By.xpath(String.format(applicationByCandidateName, candidateName));
waitUntilElementsVisible(Arrays.asList(application));
driver.findElement(application).click();
return new ApplicationDetailsPage(driver);
}
}
| [
"artem.shendrikov.contractor@weather.com"
] | artem.shendrikov.contractor@weather.com |
f4f8e6c6edf698028dd12d1c23104f00a940617d | 6f207d7c6f0a4294078198684c29a81159fd6c21 | /app/src/test/java/com/example/cobahello/ExampleUnitTest.java | 6a113ab57a4362f0819b431d1e7f228dea9fb96a | [] | no_license | destasp/InsertUpdate | 558e23be1c1b02debcc33b8d2f525d16a60e4128 | 078e6a7c36adf42273076e5af00281ae4e6441fe | refs/heads/master | 2020-09-21T16:38:24.963782 | 2019-11-29T12:37:53 | 2019-11-29T12:37:53 | 224,851,559 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 382 | java | package com.example.cobahello;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"desta.siwi@si.ukdw.ac.id"
] | desta.siwi@si.ukdw.ac.id |
77a5458be5ee4a00a355d8e9aa79c134ad33223d | 7072ba01700d47b792f9604d23b819ce5bc5e364 | /abtests/src/test/java/ru/alfabank/platform/experiment/involvements/positive/InvolvementsTest.java | 06ec906b00e54c16fdc78d9ca12af0cc1d371513 | [] | no_license | kjetester/alfa-plt | c42869bce36d6cc720e7e309e03c1ec71e76ff3e | 27a456d0d781ee9e2829034eaacb16ba2237affa | refs/heads/master | 2022-12-11T16:31:08.692686 | 2020-09-04T11:13:36 | 2020-09-04T11:13:36 | 288,755,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,027 | java | package ru.alfabank.platform.experiment.involvements.positive;
import static org.assertj.core.api.Assertions.assertThat;
import static ru.alfabank.platform.businessobjects.enums.Device.desktop;
import static ru.alfabank.platform.businessobjects.enums.Device.mobile;
import static ru.alfabank.platform.businessobjects.enums.ExperimentOptionName.DEFAULT;
import static ru.alfabank.platform.businessobjects.enums.ExperimentOptionName.FOR_AB_TEST;
import static ru.alfabank.platform.helpers.GeoGroupHelper.RU;
import static ru.alfabank.platform.steps.BaseSteps.CREATED_PAGES;
import static ru.alfabank.platform.users.ContentManager.getContentManager;
import com.epam.reportportal.annotations.ParameterKey;
import java.util.List;
import org.assertj.core.api.SoftAssertions;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.alfabank.platform.businessobjects.abtests.Experiment;
import ru.alfabank.platform.businessobjects.enums.Device;
import ru.alfabank.platform.experiment.involvements.InvolvementsBaseTest;
public class InvolvementsTest extends InvolvementsBaseTest {
private int pageId;
private Experiment runningDesktopExperiment;
private Experiment runningMobileExperiment;
/**
* Before method.
*/
@BeforeMethod(description = "Выполнение предусловий:\n"
+ "\t1. Создание страницы"
+ "\t2. Создание корневого виджета по-умолчанию для десктоп версии"
+ "\t3. Создание корневого виджета для АБ-теста для десктоп версии"
+ "\t4. Создание корневого виджета по-умолчанию для мобильной версии"
+ "\t5. Создание корневого виджета для АБ-теста для мобильной версии"
+ "\t6. Создание эксперимента для десктоп версии"
+ "\t7. Создание эксперимента для мобильной версии"
+ "\t8. Создание варианта по-умолчанию для десктоп версии"
+ "\t9. Создание 2х вариантов АБ-теста для десктоп версии"
+ "\t10. Создание варианта по-умолчанию для мобильной версии"
+ "\t11. Создание 2х вариантов АБ-теста для мобильной версии"
+ "\t12. Запуск эксперимента десктоп версии"
+ "\t13. Запуск эксперимента мобильной версии",
firstTimeOnly = true)
public void beforeMethod() {
final var date_from = getValidWidgetDateFrom();
final var date_to = getValidExperimentEndDatePlusWeek();
pageId = PAGES_STEPS.createPage(
date_from,
date_to,
true,
null,
getContentManager());
final var default_desktop_widget = DRAFT_STEPS.createWidget(
CREATED_PAGES.get(pageId),
null,
desktop,
true,
DEFAULT,
true,
List.of(RU),
date_from,
date_to,
getContentManager());
final var abTest_desktop_widget = DRAFT_STEPS.createWidget(
CREATED_PAGES.get(pageId),
null,
desktop,
false,
FOR_AB_TEST,
false,
List.of(RU),
date_from,
date_to,
getContentManager());
final var defaultMobileWidget = DRAFT_STEPS.createWidget(
CREATED_PAGES.get(pageId),
null,
mobile,
true,
DEFAULT,
true,
List.of(RU),
date_from,
date_to,
getContentManager());
final var abTest_mobile_widget = DRAFT_STEPS.createWidget(
CREATED_PAGES.get(pageId),
null,
mobile,
false,
FOR_AB_TEST,
false,
List.of(RU),
date_from,
date_to,
getContentManager());
final var desktop_experiment = EXPERIMENT_STEPS.createExperiment(
desktop,
pageId,
null,
getValidExperimentEndDate(),
.5D,
getContentManager());
final var mobile_experiment = EXPERIMENT_STEPS.createExperiment(
mobile,
pageId,
null,
getValidExperimentEndDate(),
.5D,
getContentManager());
defaultDesktopOption = OPTION_STEPS.createOption(
true,
List.of(default_desktop_widget.getUid()),
desktop_experiment.getUuid(),
.33D,
getContentManager());
abTestDesktopOption1 = OPTION_STEPS.createOption(
false,
null,
desktop_experiment.getUuid(),
.33D,
getContentManager());
abTestDesktopOption2 = OPTION_STEPS.createOption(
false,
List.of(abTest_desktop_widget.getUid()),
desktop_experiment.getUuid(),
.34D,
getContentManager());
defaultMobileOption = OPTION_STEPS.createOption(
true,
List.of(defaultMobileWidget.getUid()),
mobile_experiment.getUuid(),
.33D,
getContentManager());
abTestMobileOption1 = OPTION_STEPS.createOption(
false,
null,
mobile_experiment.getUuid(),
.33D,
getContentManager());
abTestMobileOption2 = OPTION_STEPS.createOption(
false,
List.of(abTest_mobile_widget.getUid()),
mobile_experiment.getUuid(),
.34D,
getContentManager());
runningDesktopExperiment =
EXPERIMENT_STEPS.runExperimentAssumingSuccess(desktop_experiment, getContentManager());
runningMobileExperiment =
EXPERIMENT_STEPS.runExperimentAssumingSuccess(mobile_experiment, getContentManager());
}
@Test(description = "Тест получения признака участия в эксперименте\n"
+ "\t1. Статус эксперимента 'RUNNING'",
dataProvider = "dataProvider")
public void involvementsRunningExperimentPositiveTest(
@ParameterKey("Устройство пользователя") final Device clientDevice,
@ParameterKey("Гео-метка пользователя") final List<String> geos) {
final var response = EXPERIMENT_STEPS.getInvolvements(
pageId,
clientDevice,
geos,
getContentManager());
final var softly = new SoftAssertions();
boolean isInvolved;
if (clientDevice.equals(desktop)) {
assertThat(isInvolved = response.jsonPath().getBoolean("involved"))
.as("Проверка наличия признака вовлеченности")
.isNotNull();
if (isInvolved) {
String optionName;
softly.assertThat(optionName = response.jsonPath().getString("optionName"))
.as("Проверка наименования варианта АБ-теста")
.isIn(
defaultDesktopOption.getName(),
abTestDesktopOption1.getName(),
abTestDesktopOption2.getName());
if (optionName.equals(abTestDesktopOption1.getName())) {
abTestDesktopOption1counter++;
} else if (optionName.equals(abTestDesktopOption2.getName())) {
abTestDesktopOption2counter++;
} else {
defaultDesktopOptionCounter++;
}
} else {
softly.assertThat(response.jsonPath().getString("optionName"))
.as("Проверка наименования дефолтного варианта")
.isEqualTo(defaultDesktopOption.getName());
}
softly.assertThat(response.jsonPath().getString("uuid"))
.as("Проверка UUID эксперимента")
.isEqualTo(runningDesktopExperiment.getUuid());
softly.assertThat(response.jsonPath().getString("cookieValue"))
.as("Проверка cookieValue эксперимента")
.isEqualTo(runningDesktopExperiment.getCookieValue());
softly.assertThat(response.jsonPath().getString("endDate"))
.as("Проверка даты завершения эксперимента")
.isEqualTo(runningDesktopExperiment.getEndDate());
} else {
assertThat(isInvolved = response.jsonPath().getBoolean("involved"))
.as("Приверка наличия признака вовлеченности")
.isNotNull();
if (isInvolved) {
String optionName;
softly.assertThat(optionName = response.jsonPath().getString("optionName"))
.as("Проверка наименования варианта АБ-теста")
.isIn(
defaultMobileOption.getName(),
abTestMobileOption1.getName(),
abTestMobileOption2.getName());
if (optionName.equals(abTestMobileOption1.getName())) {
abTestMobileOption1counter++;
} else if (optionName.equals(abTestMobileOption2.getName())) {
abTestMobileOption2counter++;
} else {
defaultMobileOptionCounter++;
}
} else {
softly.assertThat(response.jsonPath().getString("optionName"))
.as("Проверка наименования дефолтного варианта")
.isEqualTo(defaultMobileOption.getName());
}
softly.assertThat(response.jsonPath().getString("uuid"))
.as("Проверка UUID эксперимента")
.isEqualTo(runningMobileExperiment.getUuid());
softly.assertThat(response.jsonPath().getString("cookieValue"))
.as("Проверка cookieValue эксперимента")
.isEqualTo(runningMobileExperiment.getCookieValue());
softly.assertThat(response.jsonPath().getString("endDate"))
.as("Проверка даты завершения эксперимента")
.isEqualTo(runningMobileExperiment.getEndDate());
}
softly.assertAll();
}
}
| [
"ykolodzey@alfabank.ru"
] | ykolodzey@alfabank.ru |
71c73a0be2ae8634da5366873d08b835da9dc131 | d4d84e61a42147ce59eed18ab72aba636d598bbb | /core/src/main/java/com/orientechnologies/orient/core/exception/OTransactionBlockedException.java | 3286af6d6cae23423cdafdf6f1861dcb1c87a98f | [
"Apache-2.0"
] | permissive | nengxu/OrientDB | 0bc39c04b957b103658ab61c8d18938e936f4a13 | 60eb4bf2a645142fb4a0905db9d466609bd379d0 | refs/heads/master | 2021-01-04T02:36:03.244060 | 2012-12-09T19:55:30 | 2012-12-09T19:55:30 | 6,015,539 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,057 | java | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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 com.orientechnologies.orient.core.exception;
public class OTransactionBlockedException extends OTransactionException {
private static final long serialVersionUID = 2347493191705052402L;
public OTransactionBlockedException(String message, Throwable cause) {
super(message, cause);
}
public OTransactionBlockedException(String message) {
super(message);
}
}
| [
"l.garulli@3625ad7b-9c83-922f-a72b-73d79161f2ea"
] | l.garulli@3625ad7b-9c83-922f-a72b-73d79161f2ea |
bf82ad24647b2c5ed5dd5b0461b89982ccc949fe | 85a48a7cf2e9837ca044cf543a3bd9ce54a04149 | /siga-auth/src/main/java/ee.openeid.siga.auth/HibernateStringEncryptorConfiguration.java | 35d109263841f3de7618a6ba26eff8f9d2d17a18 | [] | no_license | mohbadar/SiGa | 6518f25f4cd5be029e7e6e1e29f437d1dec981ab | b72ec463261d35682f89578d46acee6606994a3a | refs/heads/master | 2022-02-15T11:20:16.208297 | 2019-06-18T13:52:32 | 2019-06-18T13:52:32 | 198,023,859 | 2 | 0 | null | 2019-07-21T07:00:31 | 2019-07-21T07:00:31 | null | UTF-8 | Java | false | false | 1,227 | java | package ee.openeid.siga.auth;
import ee.openeid.siga.auth.properties.SecurityConfigurationProperties;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.hibernate5.encryptor.HibernatePBEStringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HibernateStringEncryptorConfiguration {
public final static String HIBERNATE_STRING_ENCRYPTOR = "HIBERNATE_STRING_ENCRYPTOR";
@Autowired
private SecurityConfigurationProperties securityConfigurationProperties;
@Bean
public HibernatePBEStringEncryptor hibernatePBEStringEncryptor() {
HibernatePBEStringEncryptor hibernateEncryptor = new HibernatePBEStringEncryptor();
hibernateEncryptor.setRegisteredName(HIBERNATE_STRING_ENCRYPTOR);
hibernateEncryptor.setProvider(new BouncyCastleProvider());
hibernateEncryptor.setPassword(securityConfigurationProperties.getJasypt().getEncryptionKey());
hibernateEncryptor.setAlgorithm(securityConfigurationProperties.getJasypt().getEncryptionAlgo());
return hibernateEncryptor;
}
}
| [
"mart.aarma@gmail.com"
] | mart.aarma@gmail.com |
57bb951b815814e1c8a6e9d8577b5c99dd908a91 | 6d5a6c6e084c6ec8ebe25acfe483abd81e08e762 | /src/main/java/com/wenxiahy/hy/common/annotation/validation/constraint/IntegerRangeConstraintValidator.java | cba2472c6a8b0bcef647d189bd56e10691d59490 | [] | no_license | wenxiahy/hy-common | 09b89853a579816bf9d79b9a06cbcc6537977014 | f947daeb7c69e0f930de2fa63482b01f00a75b56 | refs/heads/master | 2023-02-05T05:42:48.595323 | 2020-12-29T02:51:17 | 2020-12-29T02:51:17 | 321,912,418 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 976 | java | package com.wenxiahy.hy.common.annotation.validation.constraint;
import com.wenxiahy.hy.common.annotation.validation.IntegerRange;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @Author zhouw
* @Description
* @Date 2020-12-15
*/
public class IntegerRangeConstraintValidator implements ConstraintValidator<IntegerRange, Integer> {
private int[] ranges;
@Override
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
if (value == null) {
return false;
}
if (ranges == null || ranges.length == 0) {
return true;
}
for (int i : ranges) {
if (value.intValue() == i) {
return true;
}
}
return false;
}
@Override
public void initialize(IntegerRange constraintAnnotation) {
ranges = constraintAnnotation.value();
}
}
| [
"zhouwei@techfuser.net"
] | zhouwei@techfuser.net |
9655263774f2fbebdd95335aec6d02b130f99be0 | 8b3d66e2494fe13a7f96ad070d132daa83b2340c | /coffee-data/src/main/java/com/jovi/magic/coffee/service/CoffeeTypeService.java | 70eb744e59dd905e470835e222bb321abd985573 | [] | no_license | Fadedaway/project-coffee | 9179024a7bbf88f032ef5cd4ddea29909137ecdb | 2e04616c68e9750037c917099fee0033dbd45c1c | refs/heads/master | 2020-04-26T23:06:16.752368 | 2019-03-08T15:15:00 | 2019-03-08T15:15:00 | 173,892,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 137 | java | package com.jovi.magic.coffee.service;
/**
* @author fanjiawei
* @date Created on 2019/3/8
*/
public interface CoffeeTypeService {
}
| [
"joyce221088@163.com"
] | joyce221088@163.com |
e5c6a56aa73052704c17ed1587a4d373385659ac | daf5b7e9e2a903c429e9c913697fb08bdbb8d350 | /renren-api/src/main/java/io/renren/service/impl/DgjjReportTechnologyServiceImpl.java | 08b32f81a91a949dff1a6c0e1a37eb9e81d25dbc | [] | no_license | zhangbowen3026803/dgjj-project | 00b979a9c183b51dfb38e6aed11d0d6cad4b7744 | 60aa03da938116736ebd6e987dbbafaf8f53d428 | refs/heads/master | 2020-03-28T23:13:55.104183 | 2018-09-18T13:09:28 | 2018-09-18T13:09:28 | 149,282,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,111 | java | /**
* Copyright 2018 人人开源 http://www.renren.io
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.renren.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.dao.DgjjReportTechnologyDao;
import io.renren.entity.DgjjReportTechEntity;
import io.renren.service.DgjjReportTechnologyService;
@Service("dgjjReportTechnologyService")
public class DgjjReportTechnologyServiceImpl extends ServiceImpl<DgjjReportTechnologyDao, DgjjReportTechEntity> implements DgjjReportTechnologyService {
}
| [
"15142354016@163.om"
] | 15142354016@163.om |
24d969aff18063984faea6a03a6faf224426dcb8 | c75dff60b6537319d670db2a35733374e2c57db3 | /NOT DEFTERİ/NoteBook/app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/activity/R.java | 87d64d1a0be82bf4971fd92b9b016c88110982c6 | [] | no_license | maakinci/Android-App | 46acfd63ef2bb3160c0703b7e85ad5fad4e3699a | eed920ba2ead830da78a94d2d0b6866217920c25 | refs/heads/master | 2023-01-28T00:18:09.166876 | 2019-12-19T03:40:37 | 2019-12-19T03:40:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,477 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package androidx.activity;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f030028;
public static final int font = 0x7f0300eb;
public static final int fontProviderAuthority = 0x7f0300ed;
public static final int fontProviderCerts = 0x7f0300ee;
public static final int fontProviderFetchStrategy = 0x7f0300ef;
public static final int fontProviderFetchTimeout = 0x7f0300f0;
public static final int fontProviderPackage = 0x7f0300f1;
public static final int fontProviderQuery = 0x7f0300f2;
public static final int fontStyle = 0x7f0300f3;
public static final int fontVariationSettings = 0x7f0300f4;
public static final int fontWeight = 0x7f0300f5;
public static final int ttcIndex = 0x7f03022d;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f050076;
public static final int notification_icon_bg_color = 0x7f050077;
public static final int ripple_material_light = 0x7f050082;
public static final int secondary_text_default_material_light = 0x7f050084;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f060053;
public static final int compat_button_inset_vertical_material = 0x7f060054;
public static final int compat_button_padding_horizontal_material = 0x7f060055;
public static final int compat_button_padding_vertical_material = 0x7f060056;
public static final int compat_control_corner_material = 0x7f060057;
public static final int compat_notification_large_icon_max_height = 0x7f060058;
public static final int compat_notification_large_icon_max_width = 0x7f060059;
public static final int notification_action_icon_size = 0x7f0600c8;
public static final int notification_action_text_size = 0x7f0600c9;
public static final int notification_big_circle_margin = 0x7f0600ca;
public static final int notification_content_margin_start = 0x7f0600cb;
public static final int notification_large_icon_height = 0x7f0600cc;
public static final int notification_large_icon_width = 0x7f0600cd;
public static final int notification_main_column_padding_top = 0x7f0600ce;
public static final int notification_media_narrow_margin = 0x7f0600cf;
public static final int notification_right_icon_size = 0x7f0600d0;
public static final int notification_right_side_padding_top = 0x7f0600d1;
public static final int notification_small_icon_background_padding = 0x7f0600d2;
public static final int notification_small_icon_size_as_large = 0x7f0600d3;
public static final int notification_subtext_size = 0x7f0600d4;
public static final int notification_top_pad = 0x7f0600d5;
public static final int notification_top_pad_large_text = 0x7f0600d6;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f070093;
public static final int notification_bg = 0x7f070094;
public static final int notification_bg_low = 0x7f070095;
public static final int notification_bg_low_normal = 0x7f070096;
public static final int notification_bg_low_pressed = 0x7f070097;
public static final int notification_bg_normal = 0x7f070098;
public static final int notification_bg_normal_pressed = 0x7f070099;
public static final int notification_icon_background = 0x7f07009a;
public static final int notification_template_icon_bg = 0x7f07009b;
public static final int notification_template_icon_low_bg = 0x7f07009c;
public static final int notification_tile_bg = 0x7f07009d;
public static final int notify_panel_notification_icon_bg = 0x7f07009e;
}
public static final class id {
private id() {}
public static final int accessibility_action_clickable_span = 0x7f080006;
public static final int accessibility_custom_action_0 = 0x7f080007;
public static final int accessibility_custom_action_1 = 0x7f080008;
public static final int accessibility_custom_action_10 = 0x7f080009;
public static final int accessibility_custom_action_11 = 0x7f08000a;
public static final int accessibility_custom_action_12 = 0x7f08000b;
public static final int accessibility_custom_action_13 = 0x7f08000c;
public static final int accessibility_custom_action_14 = 0x7f08000d;
public static final int accessibility_custom_action_15 = 0x7f08000e;
public static final int accessibility_custom_action_16 = 0x7f08000f;
public static final int accessibility_custom_action_17 = 0x7f080010;
public static final int accessibility_custom_action_18 = 0x7f080011;
public static final int accessibility_custom_action_19 = 0x7f080012;
public static final int accessibility_custom_action_2 = 0x7f080013;
public static final int accessibility_custom_action_20 = 0x7f080014;
public static final int accessibility_custom_action_21 = 0x7f080015;
public static final int accessibility_custom_action_22 = 0x7f080016;
public static final int accessibility_custom_action_23 = 0x7f080017;
public static final int accessibility_custom_action_24 = 0x7f080018;
public static final int accessibility_custom_action_25 = 0x7f080019;
public static final int accessibility_custom_action_26 = 0x7f08001a;
public static final int accessibility_custom_action_27 = 0x7f08001b;
public static final int accessibility_custom_action_28 = 0x7f08001c;
public static final int accessibility_custom_action_29 = 0x7f08001d;
public static final int accessibility_custom_action_3 = 0x7f08001e;
public static final int accessibility_custom_action_30 = 0x7f08001f;
public static final int accessibility_custom_action_31 = 0x7f080020;
public static final int accessibility_custom_action_4 = 0x7f080021;
public static final int accessibility_custom_action_5 = 0x7f080022;
public static final int accessibility_custom_action_6 = 0x7f080023;
public static final int accessibility_custom_action_7 = 0x7f080024;
public static final int accessibility_custom_action_8 = 0x7f080025;
public static final int accessibility_custom_action_9 = 0x7f080026;
public static final int action_container = 0x7f08002f;
public static final int action_divider = 0x7f080031;
public static final int action_image = 0x7f080032;
public static final int action_text = 0x7f080038;
public static final int actions = 0x7f080039;
public static final int async = 0x7f080042;
public static final int blocking = 0x7f080046;
public static final int chronometer = 0x7f080050;
public static final int dialog_button = 0x7f080063;
public static final int forever = 0x7f08007a;
public static final int icon = 0x7f080085;
public static final int icon_group = 0x7f080086;
public static final int info = 0x7f08008b;
public static final int italic = 0x7f08008d;
public static final int line1 = 0x7f080097;
public static final int line3 = 0x7f080098;
public static final int normal = 0x7f0800b2;
public static final int notification_background = 0x7f0800b7;
public static final int notification_main_column = 0x7f0800b8;
public static final int notification_main_column_container = 0x7f0800b9;
public static final int right_icon = 0x7f0800c8;
public static final int right_side = 0x7f0800c9;
public static final int tag_accessibility_actions = 0x7f0800f8;
public static final int tag_accessibility_clickable_spans = 0x7f0800f9;
public static final int tag_accessibility_heading = 0x7f0800fa;
public static final int tag_accessibility_pane_title = 0x7f0800fb;
public static final int tag_screen_reader_focusable = 0x7f0800fc;
public static final int tag_transition_group = 0x7f0800fd;
public static final int tag_unhandled_key_event_manager = 0x7f0800fe;
public static final int tag_unhandled_key_listeners = 0x7f0800ff;
public static final int text = 0x7f080100;
public static final int text2 = 0x7f080101;
public static final int time = 0x7f080111;
public static final int title = 0x7f080112;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f09000f;
}
public static final class layout {
private layout() {}
public static final int custom_dialog = 0x7f0b0023;
public static final int notification_action = 0x7f0b003c;
public static final int notification_action_tombstone = 0x7f0b003d;
public static final int notification_template_custom_big = 0x7f0b0044;
public static final int notification_template_icon_group = 0x7f0b0045;
public static final int notification_template_part_chronometer = 0x7f0b0049;
public static final int notification_template_part_time = 0x7f0b004a;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0f0052;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f100119;
public static final int TextAppearance_Compat_Notification_Info = 0x7f10011a;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f10011c;
public static final int TextAppearance_Compat_Notification_Time = 0x7f10011f;
public static final int TextAppearance_Compat_Notification_Title = 0x7f100121;
public static final int Widget_Compat_NotificationActionContainer = 0x7f1001cb;
public static final int Widget_Compat_NotificationActionText = 0x7f1001cc;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030028 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] FontFamily = { 0x7f0300ed, 0x7f0300ee, 0x7f0300ef, 0x7f0300f0, 0x7f0300f1, 0x7f0300f2 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300eb, 0x7f0300f3, 0x7f0300f4, 0x7f0300f5, 0x7f03022d };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
| [
"arda.akinci12@outlook.com"
] | arda.akinci12@outlook.com |
b15cf449baa9143f962d2e9939757812f476f9f7 | 98415fdfd2e96b9b2dd6be376c1bd0e8584e7cb6 | /app/src/main/java/com/universalstudios/orlandoresort/controller/userinterface/wayfinding/PathFragmentPagerAdapter.java | 4397410f5a03bcc26c2aca4830216dd6a2807b12 | [] | no_license | SumanthAndroid/UO | 202371c7ebdcb5c635bae88606b4a4e0d004862c | f201c043eae70eecac9972f2e439be6a03a61df6 | refs/heads/master | 2021-01-19T13:41:20.592334 | 2017-02-28T08:04:42 | 2017-02-28T08:04:42 | 82,409,297 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,708 | java | package com.universalstudios.orlandoresort.controller.userinterface.wayfinding;
import java.lang.ref.WeakReference;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.util.SparseArray;
import android.view.ViewGroup;
import com.universalstudios.orlandoresort.BuildConfig;
import com.universalstudios.orlandoresort.model.network.domain.wayfinding.Path;
import com.universalstudios.orlandoresort.view.viewpager.JazzyViewPager;
public class PathFragmentPagerAdapter extends FragmentStatePagerAdapter {
private static final String TAG = PathFragmentPagerAdapter.class.getSimpleName();
private final SparseArray<WeakReference<Fragment>> mPagerFragments;
private JazzyViewPager mJazzyViewPager;
private final List<Path> mPaths;
public PathFragmentPagerAdapter(JazzyViewPager jazzyViewPager, FragmentManager fm, List<Path> paths) {
super(fm);
mJazzyViewPager = jazzyViewPager;
mPagerFragments = new SparseArray<WeakReference<Fragment>>();
mPaths = paths;
}
@Override
public Fragment getItem(int position) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "getItem: position = " + position);
}
Path path = mPaths.get(position);
return PathFragment.newInstance(path.toJson(), position + 1, getCount());
}
@Override
public int getCount() {
return mPaths.size();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "instantiateItem: position = " + position);
}
// Add reference to pager fragment to refer to later
Fragment fragment = (Fragment) super.instantiateItem(container, position);
mPagerFragments.put(position, new WeakReference <Fragment> (fragment));
// Add reference for the view pager transitions
mJazzyViewPager.setObjectForPosition(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "destroyItem: position = " + position);
}
// Remove reference of pager fragment
mPagerFragments.remove(position);
// Remove the reference for the view pager transitions
mJazzyViewPager.removeObjectForPosition(position);
super.destroyItem(container, position, object);
}
public Fragment getPagerFragment(int position) {
WeakReference <Fragment> fragmentReference = mPagerFragments.get(position);
if (fragmentReference != null) {
return fragmentReference.get();
}
return null;
}
// Release references to objects that are contained in contexts
public void destroy() {
mJazzyViewPager = null;
}
}
| [
"kartheek222@gmail.com"
] | kartheek222@gmail.com |
990367d31daa9952417b381d190639116fdaecab | f3d2242f1f826f1b673a6bc01c55ad71815f114b | /src/DerekBanasBasics/src/GetTheMail.java | 754a2b61213d1aaeb150b5dab28a314faff3ea3f | [] | no_license | KuuHakuBlank/DerekBanasTutorials | 1ce99226bdff92aee8016f80b9c369437ff835cd | 4ba3b1c974b008cf8bab510536e0df2dacdc0bc2 | refs/heads/master | 2021-09-01T02:07:08.014781 | 2017-12-24T10:07:56 | 2017-12-24T10:07:56 | 115,253,223 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 837 | java | // You can use the Runnable interface instead of
// wasting your 1 class extension.
public class GetTheMail implements Runnable {
// Stores the number of seconds before the code
// will be executed
private int startTime;
// Constructor that sets the wait time for each
// new Thread
public GetTheMail(int startTime){
this.startTime = startTime;
}
// All of the code that the thread executes must be
// in the run method, or be in a method called for
// from inside of the run method
public void run(){
try
{
// Don't execute until 10 seconds has passed if
// startTime equals 10
Thread.sleep(startTime * 1000);
}
catch(InterruptedException e)
{}
System.out.println("Checking for Mail");
}
} | [
"jedispartin@gmail.com"
] | jedispartin@gmail.com |
4054dc5896c7563ab4bf9618e66b6e6abfdfa9fe | bb63dce30d42a67826a50335ed5ca662b7ff958c | /galleon-plugins/src/main/java/org/wildfly/galleon/plugin/ThinModuleTemplateProcessor.java | ae93cd5a44dc68815fba3ab6ae96268dc870d3da | [
"Apache-2.0"
] | permissive | rhusar/galleon-plugins | 863f113684b403aca69d8a931a1e198032883473 | b08d99afae17205be828f7b38de0406eed0525e3 | refs/heads/main | 2022-07-24T04:45:28.730171 | 2022-06-24T10:23:31 | 2022-06-24T10:23:31 | 135,279,613 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,496 | java | /*
* Copyright 2016-2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.galleon.plugin;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import org.jboss.galleon.ProvisioningException;
import org.jboss.galleon.universe.maven.MavenArtifact;
import org.jboss.galleon.universe.maven.MavenUniverseException;
/**
* A Template processor that process templates when provisioning thin server. In
* this case module.xml artifacts are updated with a version.
* The installer is in charge to compute the correct version to be referenced. Artifact version could be modified
* in case of Jakarta transformation.
*
* @author jdenise
*/
class ThinModuleTemplateProcessor extends AbstractModuleTemplateProcessor {
ThinModuleTemplateProcessor(WfInstallPlugin plugin,
AbstractArtifactInstaller installer, Path targetPath, ModuleTemplate template, Map<String, String> versionProps, boolean channelArtifactResolution) {
super(plugin, installer, targetPath, template, versionProps, channelArtifactResolution);
}
@Override
protected void processArtifact(ModuleArtifact moduleArtifact) throws IOException, MavenUniverseException, ProvisioningException {
MavenArtifact artifact = moduleArtifact.getMavenArtifact();
String installedVersion = getInstaller().installArtifactThin(artifact);
// ignore jandex variable, just resolve coordinates to a string
final StringBuilder buf = new StringBuilder();
buf.append(artifact.getGroupId());
buf.append(':');
buf.append(artifact.getArtifactId());
buf.append(':');
buf.append(installedVersion);
if (!artifact.getClassifier().isEmpty()) {
buf.append(':');
buf.append(artifact.getClassifier());
}
moduleArtifact.updateThinArtifact(buf.toString());
}
}
| [
"jdenise@redhat.com"
] | jdenise@redhat.com |
7762a49839bfad0d0375c7e238b4dc432d6ebf7b | d2b88ae5011d6d27094268db84d78413dad73610 | /Goldman_6/src/ru/javabegin/training/goldman/objects/maps/FSGameMap.java | c0df6829b6da4a049b276161c2ab1974527cbd3f | [] | no_license | Antonppavlov/GoldManAll | 25d91fc45584d8618ff7a3aebcd31df60e224c73 | 77c2cff0ec146607206ea41a4d6f4eaa1f4b1472 | refs/heads/master | 2021-01-09T20:47:47.973301 | 2016-08-11T23:52:42 | 2016-08-11T23:52:42 | 64,775,890 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,138 | java | package ru.javabegin.training.goldman.objects.maps;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import ru.javabegin.training.goldman.abstracts.AbstractGameMap;
import ru.javabegin.training.goldman.abstracts.AbstractGameObject;
import ru.javabegin.training.goldman.enums.GameObjectType;
import ru.javabegin.training.goldman.interfaces.collections.GameCollection;
import ru.javabegin.training.goldman.objects.Coordinate;
import ru.javabegin.training.goldman.objects.creators.GameObjectCreator;
public class FSGameMap extends AbstractGameMap {
public FSGameMap(){
super();
}
public FSGameMap(GameCollection gameCollection) {
super(gameCollection);
}
@Override
public boolean loadMap(Object source) {
File file = new File(source.toString());
if (!file.exists()) {
throw new IllegalArgumentException("filename must not be empty!");
}
try {
setExitExist(false);
setGoldManExist(false);
setHeight(getLineCount(file));
BufferedReader br = new BufferedReader(new FileReader(file));
String strLine = br.readLine().trim(); // считываем первую строку для определения имени, длины, ширины карты. убираем пробела по краям
// разбиваем первую строку на токены, разделенные запятой.
setName(strLine.split(",")[0]);
setTimeLimit(Integer.valueOf(strLine.split(",")[1]).intValue());
setWidth(Integer.valueOf(strLine.split(",")[2]).intValue());
int y = 0; // номер строки в массиве
int x = 0; // номер столбца в массиве
while ((strLine = br.readLine()) != null) {
x = 0; // чтобы каждый раз с первого столбца начинал
for (String str : strLine.split(",")) {
// вытаскивать все значения в строке между запятыми, чтобы заполнить карту элементами
createGameObject(str, new Coordinate(x, y));
x++;
}
y++;
}
if (!isValidMap()) {
throw new Exception("The map is not valid!");
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
private void createGameObject(String str, Coordinate coordinate) {
GameObjectType type = GameObjectType.valueOf(str.toUpperCase());
AbstractGameObject newObj = GameObjectCreator.getInstance().createObject(type, coordinate);
getGameCollection().addGameObject(newObj);
if (newObj.getType() == GameObjectType.EXIT) {
setExitExist(true);
} else if (newObj.getType() == GameObjectType.GOLDMAN) {
setGoldManExist(true);
}
}
@Override
public boolean saveMap(Object source) {
throw new UnsupportedOperationException("Not supported yet.");
}
private int getLineCount(File file) {
BufferedReader reader = null;
int lineCount = 0;
try {
reader = new BufferedReader(new FileReader(file));
while (reader.readLine() != null) {
lineCount++;
}
lineCount = lineCount - 1;// lineNumber-1 потому что первая строка из файла не входит в карту
} catch (IOException ex) {
Logger.getLogger(FSGameMap.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(FSGameMap.class.getName()).log(Level.SEVERE, null, ex);
}
}
return lineCount;
}
}
| [
"ap_pavlov@bingo-boom.ru"
] | ap_pavlov@bingo-boom.ru |
1b03d25c9c5685e0280155ceeeec4ce645f98b3d | acf06fa2bd4eaf0cd98a1bd074361886d27ea425 | /vlc-android/src/vlcUI/SqliteDAO.java | 86d229d2667e6b1472b85f5b3a57741db90d53a4 | [] | no_license | blackdotroot/h264player_basedonVLC | 889e320a3016751267b1651d2898107b57c2d0f8 | bccc1d351f8bf46f90e462f2e46ffa6d21e2594a | refs/heads/master | 2020-02-26T17:08:54.579536 | 2016-10-22T18:10:44 | 2016-10-22T18:10:44 | 71,654,902 | 2 | 0 | null | null | null | null | GB18030 | Java | false | false | 3,832 | java | package vlcUI;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class SqliteDAO {
private SqliteHandler SqliteHandler;
public SqliteDAO(Context context) {
this.SqliteHandler = new SqliteHandler(context, "db4dev.db", null, 1);
}
public void save(DEV dev) {// 插入记录
SQLiteDatabase db = SqliteHandler.getWritableDatabase();// 取得数据库操作
db.execSQL("CREATE TABLE IF NOT EXISTS t_dev (id integer primary key autoincrement, name varchar(60), ip varchar(60),status varchar(60))");
db.execSQL("insert into t_dev (name,ip,status) values(?,?,?)", new Object[] { dev.getName(), dev.getIP(),dev.getStatus() });
db.close();// 记得关闭数据库操作
}
public void delete(String ip) {// 删除纪录
SQLiteDatabase db = SqliteHandler.getWritableDatabase();
db.execSQL("delete from t_dev where ip=?", new Object[] { ip.toString() });
db.close();
}
public void update(DEV DEV) {// 修改纪录
SQLiteDatabase db = SqliteHandler.getWritableDatabase();
db.execSQL("update t_dev set name=?,status=?,ip=? where" + " id=?", new Object[] { DEV.getName(), DEV.getStatus(), DEV.getIP(), DEV.getId()});
db.close();
}
public DEV find(String ip) {// 根据ID查找纪录
DEV dev = null;
SQLiteDatabase db = SqliteHandler.getReadableDatabase();
db.execSQL("CREATE TABLE IF NOT EXISTS t_dev (id integer primary key autoincrement, name varchar(60), ip varchar(60),status varchar(60))");
// 用游标Cursor接收从数据库检索到的数据
Cursor cursor = db.rawQuery("select * from t_dev where ip=?", new String[] { ip.toString() });
if (cursor.moveToFirst()) {// 依次取出数据
dev = new DEV();
dev.setId(cursor.getInt(cursor.getColumnIndex("id")));
dev.setIP(cursor.getString(cursor.getColumnIndex("ip")));
dev.setName(cursor.getString(cursor.getColumnIndex("name")));
dev.setStatus(cursor.getString(cursor.getColumnIndex("status")));
}
db.close();
return dev;
}
public List<DEV> findAll() {// 查询所有记录
List<DEV> lists = new ArrayList<DEV>();
DEV dev = null;
SQLiteDatabase db = SqliteHandler.getReadableDatabase();
db.execSQL("CREATE TABLE IF NOT EXISTS t_dev (id integer primary key autoincrement, name varchar(60), ip varchar(60),status varchar(60))");
// Cursor cursor=db.rawQuery("select * from t_dev limit ?,?", new
// String[]{offset.toString(),maxLength.toString()});
// //这里支持类型MYSQL的limit分页操作
Cursor cursor = db.rawQuery("select * from t_dev ", null);
while (cursor.moveToNext()) {
dev = new DEV();
dev.setIP(cursor.getString(cursor.getColumnIndex("ip")));
dev.setName(cursor.getString(cursor.getColumnIndex("name")));
dev.setStatus(cursor.getString(cursor.getColumnIndex("status")));
lists.add(dev);
}
db.close();
return lists;
}
public long getCount() {//统计所有记录数
SQLiteDatabase db = SqliteHandler.getReadableDatabase();
Cursor cursor = db.rawQuery("select count(*) from t_dev ", null);
cursor.moveToFirst();
db.close();
return cursor.getLong(0);
}
public void delete_all() {//删除表
SQLiteDatabase db = SqliteHandler.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS t_dev");
db.close();
}
}
| [
"AllenSunRoot@163.com"
] | AllenSunRoot@163.com |
da57ea166be574080ced6e3127eb6b72d9b4b100 | b30692933a8e560bd7ad299f2d1433c8effd2e5c | /org.drury.mo631/src-gen/org/drury/mo631/project/impl/EditTextImpl.java | fdfdd371e4393b85075a12bc9b2e11d41988077a | [] | no_license | carlosdanieldrury/mo631Project | cc59e06997a779a8dbeafd2a4ffac1d6efe50fcd | dd6c874e45dd2a45f793625fdf931fc86e23cd1d | refs/heads/master | 2020-09-22T05:34:30.174981 | 2019-12-01T00:56:14 | 2019-12-01T00:56:14 | 225,068,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 698 | java | /**
*/
package org.drury.mo631.project.impl;
import org.drury.mo631.project.EditText;
import org.drury.mo631.project.projectPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Edit Text</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class EditTextImpl extends ViewImpl implements EditText {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EditTextImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return projectPackage.Literals.EDIT_TEXT;
}
} //EditTextImpl
| [
"carlosdaniel.drury@ifood.com.br"
] | carlosdaniel.drury@ifood.com.br |
e3a70ee1e710a3ba543603101cd730358c2f4b03 | ec197039589b600408a9aaf560bedec45674d47d | /Task2_2.java | 5a76c4185ef9ccc6fe5cf54862e561393faad215 | [] | no_license | ZakharovKyrylo/home2 | 94df6748fbe4db3050522e8b70f86653dbd80660 | dba342d62346b4450565727ab7db4275a861e984 | refs/heads/master | 2020-04-06T06:59:15.221108 | 2015-08-06T09:08:25 | 2015-08-06T09:08:25 | 39,070,334 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 797 | java | package org.sourceit.zakharov.home02;
public class Task2_2 {
public static void main(String[] args) {
ToDec toDec=new ToDec();
String num2_1="111000111";
String num2_2="100011011";
System.out.println(ToDec.toDec(num2_1));
System.out.println(ToDec.toDec(num2_2));
}
}
class ToDec{
public static int toDec(String s){
int[] strToInt= new int[s.length()];
int dec=0;
int i=0;
while (s.length()>0){
if (s.endsWith("0")) strToInt[i] = 0 ;
else strToInt[i] = 1;
s = s.substring(0, s.length() - 1);
if((i==0)&(strToInt[i] == 0)) dec = 0;
else dec= (int) (dec+Math.pow((strToInt[i]*2),i));
i++;
}
return dec;
}
} | [
"zakharovkyrylo@gmail.com"
] | zakharovkyrylo@gmail.com |
cd0bc5d4ce031d9f4819dc9872dbe66a15cbbba6 | a866b7d5b917a65a2d01f5b6f9f958d73ece8a70 | /src/Day04_Variables/Variable_Practice.java | 34f38a25e59ea77b80de7d1fcbc38f7783f21bf2 | [] | no_license | OksanaGood/Summer2020_B20 | d716d1a3113c901ec2c1318b8e78f4471854f380 | 1497c2a3e271606e0be7a53456c3b38402ba7d55 | refs/heads/master | 2022-12-13T12:14:42.140967 | 2020-08-25T20:05:56 | 2020-08-25T20:05:56 | 284,592,681 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 530 | java | package Day04_Variables;
public class Variable_Practice {
public static void main(String[] args) {
byte num1 = 100;
short num2 = 10000;
double num3 = 3.5;
float num4 = 2.5f;
long num5 = 999999999999L;
int num6 = 850000;// why int, its smaller then previous.
System.out.println(num1 + 1);
System.out.println(num2);
System.out.println(num3);
System.out.println(num4);
System.out.println(num5);
System.out.println(num6);
}
}
| [
"oksana.shnurkina.76@mail.ru"
] | oksana.shnurkina.76@mail.ru |
df328cd12327573bad4356838402dc1b17706e81 | 0bf6f83f246537ffe661ea7ae0663dd191ebe3ea | /src/main/java/array/MergeTwoSortedLists21.java | 999b9c5b64425a1be852611917e57ad3f9af2bf8 | [] | no_license | fengliejv/leetCode | 3c9da7d7772c8b9c7bd9e6285ac846f93451c225 | 630ac6486774a04e77f1cb77daca72f18a8d862b | refs/heads/master | 2021-06-08T21:37:18.225854 | 2021-05-30T01:19:32 | 2021-05-30T01:19:32 | 101,889,734 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 916 | java | package array;
import math.ListNode;
/**
* Created by fengliejv on 2017/10/17.
*/
public class MergeTwoSortedLists21 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null||l2==null){
return l2==null?l1:l2;
}
while (l2!=null&&l2.val<l1.val){
ListNode node1 = l1;
ListNode node2 = l2.next;
l1 =l2;
l2.next=node1;
l2 = node2;
}
ListNode header = l1;
while (l2!=null){
if(l1.next==null){
l1.next=l2;
break;
}
if(l1.next.val<l2.val){
l1= l1.next;
}else {
ListNode node2 = l2.next;
ListNode node = l1.next;
l1.next=l2;
l2.next= node;
l2=node2;
}
}
return header;
}
}
| [
"1091892391@qq.com"
] | 1091892391@qq.com |
90138897c24e8703e37b421350b95e625cd62c98 | 4b6d534b678c008718c9d67c0a1feca0a685c076 | /src/c_minimax/TicTacToeSearchResult.java | b67206e80d7885006536373f300dc28be3b45684 | [] | no_license | calvint/SarahNoahCalvinCheckers | e53e1689a4020a8b7ed2dffe96ae97064fc56ded | 0c6db85605de96c752b243da1011afff165b3e2a | refs/heads/master | 2020-05-30T21:33:43.036457 | 2015-05-01T15:32:44 | 2015-05-01T15:32:44 | 34,762,789 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,418 | java | package c_minimax;
//author: Gary Kalmanovich; rights reserved
class TicTacToeSearchResult implements InterfaceSearchResult {
InterfaceIterator bestMoveSoFar = null;
float bestScoreSoFar = Float.NEGATIVE_INFINITY;
@Override
public InterfaceIterator getBestMoveSoFar() {
return bestMoveSoFar;
}
@Override
public float getBestScoreSoFar() {
return bestScoreSoFar;
}
@Override
public void setBestMoveSoFar(InterfaceIterator newMove, float newScore) {
bestMoveSoFar = new TicTacToeIterator(newMove);
bestScoreSoFar = newScore;
}
@Override
public float getOpponentBestScoreOnPreviousMoveSoFar() {
// Not used in this strategy
return 0;
}
@Override
public void setOpponentBestScoreOnPreviousMoveSoFar(float scoreToBeat) {
// Not used in this strategy
}
@Override
public int getClassStateCompacted() {
// Not used in this strategy
return 0;
}
@Override
public void setClassStateFromCompacted(int compacted) {
// Not used in this strategy
}
@Override
public void setIsResultFinal(boolean isFinal) {
// Not used in this strategy
}
@Override
public boolean isResultFinal() {
// Not used in this strategy
return false;
}
}
| [
"noah.johnson13@ncf.edu"
] | noah.johnson13@ncf.edu |
4daae2895300d238bb0b0d7b5880a5fafe70e4ad | 73308ecf567af9e5f4ef8d5ff10f5e9a71e81709 | /en62300912/src/main/java/com/example/en62300912/En62300912Application.java | 1053fa6df3e45eb5ae6368bf95b1eaff9a87c408 | [] | no_license | yukihane/stackoverflow-qa | bfaf371e3c61919492e2084ed4c65f33323d7231 | ba5e6a0d51f5ecfa80bb149456adea49de1bf6fb | refs/heads/main | 2023-08-03T06:54:32.086724 | 2023-07-26T20:02:07 | 2023-07-26T20:02:07 | 194,699,870 | 3 | 3 | null | 2023-03-02T23:37:45 | 2019-07-01T15:34:08 | Java | UTF-8 | Java | false | false | 323 | java | package com.example.en62300912;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class En62300912Application {
public static void main(String[] args) {
SpringApplication.run(En62300912Application.class, args);
}
}
| [
"yukihane.feather@gmail.com"
] | yukihane.feather@gmail.com |
99763ce3c3d12741586b8963311b52dda0ec2174 | 0ab41db01e72977143b8021fe9720c4afbd6f035 | /dach2008/dachMW/src/ibis/masterworker/Worker.java | b69240d828fcd5feb3cd00325a7d839fdc6826d8 | [] | no_license | JungleComputing/lab | 554c307642518459ac46d2ae49e3b2215d2ee44a | 78c20f8d417f847d9bad72087761c41ed7938677 | refs/heads/master | 2021-08-19T16:11:41.369491 | 2009-03-16T14:02:42 | 2009-03-16T14:02:42 | 112,115,846 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,375 | java | package ibis.masterworker;
import ibis.dfs.DFSClient;
import ibis.ipl.IbisIdentifier;
import ibis.simpleComm.SimpleCommunication;
import ibis.simpleComm.Upcall;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
public class Worker implements Upcall {
private static final int DEFAULT_TIMEOUT = 60000;
private static final int DEFAULT_END_TIMEOUT = 10000;
private static final int MAX_JOB_WAIT = 30000;
private static final int INITIAL_JOB_WAIT = 1000;
private static final Logger logger = Logger.getLogger("masterworker.worker");
private final String node;
private final String location;
private final boolean preferSmall;
private final long initialTimeout;
private long timeout;
private final JobProcessor processor;
private final SimpleCommunication comm;
private final IbisIdentifier master;
private final LinkedList<Job> jobs = new LinkedList<Job>();
private final DFSClient dfsClient;
private boolean done = false;
private class WorkerThread extends Thread {
private final int workerNo;
public WorkerThread(final int workerNo) {
this.workerNo = workerNo;
}
public void run() {
while (!getDone()) {
Job job = getJob();
while (job != null) {
logger.info("WorkerThread" + workerNo + ": Processing job");
activeWorkers.incrementAndGet();
Result r = processor.process(job);
activeWorkers.decrementAndGet();
if (!comm.send(master, r)) {
logger.warn("Could not return result to master!");
}
job = getJob();
}
}
}
}
private final WorkerThread [] workers;
private AtomicInteger requiredJobs = new AtomicInteger(0);
private AtomicInteger activeWorkers = new AtomicInteger(0);
private final int totalWorkers;
private long stealID = 0;
private ReplyHandler replies = new ReplyHandler();
public Worker(JobProcessor processor, String serverAddress, String hubAddresses,
String pool, String node, String location, String masterID, boolean preferSmall,
long timeout, int concurrentJobs) throws Exception {
logger.info("Starting worker on " + node + " at location " + location);
this.node = node;
this.location = location;
this.processor = processor;
this.preferSmall = preferSmall;
this.totalWorkers = concurrentJobs;
if (timeout > INITIAL_JOB_WAIT) {
this.initialTimeout = Math.min(timeout, MAX_JOB_WAIT);
} else {
this.initialTimeout = INITIAL_JOB_WAIT;
}
this.timeout = this.initialTimeout + (int) (Math.random() * INITIAL_JOB_WAIT);
try {
comm = SimpleCommunication.create("DACH", this, serverAddress, hubAddresses, pool);
} catch (Exception e) {
logger.warn("Failed to initialize communication layer!", e);
throw new Exception("Failed to initialize communication layer!", e);
}
master = comm.getElectionResult(masterID, DEFAULT_TIMEOUT);
if (master == null) {
throw new Exception("Failed to retrieve master ID (" + masterID + ")!");
}
dfsClient = new DFSClient(node, location);
logger.warn("Starting " + concurrentJobs + " workers!");
workers = new WorkerThread[concurrentJobs];
for (int i=0;i<concurrentJobs;i++) {
workers[i] = new WorkerThread(i);
workers[i].start();
}
}
public DFSClient getDFSClient() {
return dfsClient;
}
/*
private synchronized void handleStealReply(IbisIdentifier src, StealReply r) {
if (r.job != null) {
jobs.addLast(r.job);
timeout = initialTimeout;
logger.info("Got steal reply (work, " + jobs.size() + "): " + r.job);
} else if (r.done) {
done = true;
timeout = initialTimeout;
logger.info("Got steal reply (done, " + jobs.size() + ")");
} else {
// When we get an 'no jobs' reply, we increment the
// steal timeout and queue a new request.
// requiredJobs.incrementAndGet();
increaseTimeout();
logger.info("Got steal reply (no work, " + jobs.size() + ")");
}
gotReply = true;
notifyAll();
}*/
private void handleAbort(IbisIdentifier src, Abort a) {
logger.info("Got abort request: " + a.JobID);
// First try to abort the job in the local queue
synchronized (this) {
if (a.JobID == -1) {
jobs.clear();
} else {
ListIterator<Job> itt = jobs.listIterator();
while (itt.hasNext()) {
Job j = itt.next();
if (j.ID == a.JobID) {
itt.remove();
return;
}
}
}
// If the jobs hasn't been found, we pass the abort on to the processor
processor.abort(a.JobID);
}
}
public boolean upcall(IbisIdentifier src, Object o) {
if (o instanceof StealReply) {
StealReply reply = (StealReply) o;
replies.storeReply(reply.stealID, reply);
return true;
} else if (o instanceof Abort) {
handleAbort(src, (Abort) o);
return true;
}
return false;
}
public void died(IbisIdentifier src) {
// We only care about the master
if (src.equals(master)) {
logger.warn("WARNING: Master died! -- Exiting");
done();
} else if (src.equals(comm.getIdentifier())) {
logger.warn("WARNING: We have been declared dead -- Exiting");
done();
}
}
public void end(long timeout) {
comm.end(timeout);
}
public void end() {
end(DEFAULT_END_TIMEOUT);
}
private synchronized Job getJob() {
requiredJobs.incrementAndGet();
notifyAll();
while (jobs.size() == 0 && !getDone()) {
try {
wait();
} catch (Exception e) {
// ignore
}
}
requiredJobs.decrementAndGet();
if (getDone()) {
return null;
}
if (jobs.size() > 0) {
return jobs.removeFirst();
}
return null;
}
private synchronized void done() {
done = true;
replies.done();
}
private synchronized boolean getDone() {
return done;
}
private void sleepForTimeout() {
logger.info("Sleeping for " + timeout + " ms.");
try {
Thread.sleep(timeout);
} catch (Exception e) {
// ignored
}
}
private synchronized void increaseTimeout() {
timeout *= 2 + (int)(Math.random() * INITIAL_JOB_WAIT);
if (timeout > MAX_JOB_WAIT + INITIAL_JOB_WAIT) {
timeout = MAX_JOB_WAIT + (int)(Math.random() * INITIAL_JOB_WAIT);
}
logger.info("Job timeout is " + timeout);
}
/*
private void doRequest() {
StealRequest s = new StealRequest(getStealID(), location, node, preferSmall);
int tmp = requiredJobs.get();
while (tmp > 0 && !getDone()) {
sleepForTimeout();
logger.info("Sending steal request");
clearReply();
if (!comm.send(master, s)) {
logger.warn("Failed to send to master!");
increaseTimeout();
} else {
waitForReply();
tmp = requiredJobs.decrementAndGet();
}
}
}
*/
private synchronized int queuedJobs() {
return jobs.size();
}
private synchronized long getStealID() {
return stealID++;
}
private synchronized void handleStealReply(long stealID) {
StealReply r = replies.waitForReply(stealID);
if (r == null) {
// we are done ?
logger.info("Got empty reply! " + stealID);
notifyAll();
return;
}
if (r.job != null) {
logger.info("Got steal reply " + stealID + " (work, " + jobs.size() + "): " + r.job);
jobs.addLast(r.job);
timeout = initialTimeout;
} else if (r.done) {
logger.info("Got steal reply " + stealID + " (done, " + jobs.size() + ")");
done = true;
timeout = initialTimeout;
} else {
// When we get an 'no jobs' reply, we increment the
// steal timeout and queue a new request.
logger.info("Got steal reply " + stealID + " (no work, " + jobs.size() + ")");
increaseTimeout();
}
notifyAll();
}
public void start() {
logger.info("Worker register at master...");
Register reg = new Register(node, 0);
while (!comm.send(master, reg)) {
logger.info("Worker failed to send register message!");
try {
Thread.sleep(2000);
} catch (Exception e) {
// ignore
}
}
logger.info("Worker registered at master...");
long nextStatusMessage = System.currentTimeMillis() + 30000;
long stealID = 0;
while (!getDone()) {
sleepForTimeout();
if (System.currentTimeMillis() > nextStatusMessage) {
Status s = new Status(location, node, activeWorkers.get(), totalWorkers);
logger.info("Sending status: " + activeWorkers + " / " + totalWorkers);
if (!comm.send(master, s)) {
logger.warn("Failed to send status message to master!");
}
nextStatusMessage = System.currentTimeMillis() + 30000;
}
if (!getDone() && queuedJobs() == 0 && requiredJobs.get() > 0) {
stealID = getStealID();
StealRequest s = new StealRequest(stealID, location, node, preferSmall);
replies.registerSingleRequest(stealID);
logger.info("Sending steal request (" + requiredJobs.get() + " / " + jobs.size() + ")");
if (!comm.send(master, s)) {
logger.warn("Failed to send steal request to master!");
replies.clearRequest(stealID);
increaseTimeout();
} else {
handleStealReply(stealID);
}
} else {
logger.info("NOT sending steal request (" + getDone() + " / "
+ requiredJobs.get() + " / " + jobs.size() + ")");
}
}
}
}
| [
"j.maassen@esciencecenter.nl"
] | j.maassen@esciencecenter.nl |
8502889905baf7f96f44b1f19eefb834936ea8d8 | e124c06aa37b93502a84f8931e1e792539883b9d | /Chess-master/src/chess/grid/Location.java | ec5b6fc6bc88df248c98feb40dc95e435fe50550 | [] | no_license | m-shayanshafi/FactRepositoryProjects | 12d7b65505c1e0a8e0ec3577cf937a1e3d17c417 | 1d45d667b454064107d78213e8cd3ec795827b41 | refs/heads/master | 2020-06-13T12:04:53.891793 | 2016-12-02T11:30:49 | 2016-12-02T11:30:49 | 75,389,381 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,635 | java | /*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2002-2006 College Entrance Examination Board
* (http://www.collegeboard.com).
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Alyce Brady
* @author Chris Nevison
* @author APCS Development Committee
* @author Cay Horstmann
*/
package chess.grid;
/**
* A <code>Location</code> object represents the row and column of a location
* in a two-dimensional grid. <br />
* The API of this class is testable on the AP CS A and AB exams.
*/
public class Location implements Comparable
{
private int row; // row location in grid
private int col; // column location in grid
/**
* The turn angle for turning 90 degrees to the left.
*/
public static final int LEFT = -90;
/**
* The turn angle for turning 90 degrees to the right.
*/
public static final int RIGHT = 90;
/**
* The turn angle for turning 45 degrees to the left.
*/
public static final int HALF_LEFT = -45;
/**
* The turn angle for turning 45 degrees to the right.
*/
public static final int HALF_RIGHT = 45;
/**
* The turn angle for turning a full circle.
*/
public static final int FULL_CIRCLE = 360;
/**
* The turn angle for turning a half circle.
*/
public static final int HALF_CIRCLE = 180;
/**
* The turn angle for making no turn.
*/
public static final int AHEAD = 0;
/**
* The compass direction for north.
*/
public static final int NORTH = 0;
/**
* The compass direction for northeast.
*/
public static final int NORTHEAST = 45;
/**
* The compass direction for east.
*/
public static final int EAST = 90;
/**
* The compass direction for southeast.
*/
public static final int SOUTHEAST = 135;
/**
* The compass direction for south.
*/
public static final int SOUTH = 180;
/**
* The compass direction for southwest.
*/
public static final int SOUTHWEST = 225;
/**
* The compass direction for west.
*/
public static final int WEST = 270;
/**
* The compass direction for northwest.
*/
public static final int NORTHWEST = 315;
/**
* Constructs a location with given row and column coordinates.
* @param r the row
* @param c the column
*/
public Location(int r, int c)
{
row = r;
col = c;
}
/**
* Gets the row coordinate.
* @return the row of this location
*/
public int getRow()
{
return row;
}
/**
* Gets the column coordinate.
* @return the column of this location
*/
public int getCol()
{
return col;
}
/**
* Gets the adjacent location in any one of the eight compass directions.
* @param direction the direction in which to find a neighbor location
* @return the adjacent location in the direction that is closest to
* <tt>direction</tt>
*/
public Location getAdjacentLocation(int direction)
{
// reduce mod 360 and round to closest multiple of 45
int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE;
if (adjustedDirection < 0)
adjustedDirection += FULL_CIRCLE;
adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT;
int dc = 0;
int dr = 0;
if (adjustedDirection == EAST)
dc = 1;
else if (adjustedDirection == SOUTHEAST)
{
dc = 1;
dr = 1;
}
else if (adjustedDirection == SOUTH)
dr = 1;
else if (adjustedDirection == SOUTHWEST)
{
dc = -1;
dr = 1;
}
else if (adjustedDirection == WEST)
dc = -1;
else if (adjustedDirection == NORTHWEST)
{
dc = -1;
dr = -1;
}
else if (adjustedDirection == NORTH)
dr = -1;
else if (adjustedDirection == NORTHEAST)
{
dc = 1;
dr = -1;
}
return new Location(getRow() + dr, getCol() + dc);
}
/**
* Returns the direction from this location toward another location. The
* direction is rounded to the nearest compass direction.
* @param target a location that is different from this location
* @return the closest compass direction from this location toward
* <code>target</code>
*/
public int getDirectionToward(Location target)
{
int dx = target.getCol() - getCol();
int dy = target.getRow() - getRow();
// y axis points opposite to mathematical orientation
int angle = (int) Math.toDegrees(Math.atan2(-dy, dx));
// mathematical angle is counterclockwise from x-axis,
// compass angle is clockwise from y-axis
int compassAngle = RIGHT - angle;
// prepare for truncating division by 45 degrees
compassAngle += HALF_RIGHT / 2;
// wrap negative angles
if (compassAngle < 0)
compassAngle += FULL_CIRCLE;
// round to nearest multiple of 45
return (compassAngle / HALF_RIGHT) * HALF_RIGHT;
}
/**
* Indicates whether some other <code>Location</code> object is "equal to"
* this one.
* @param other the other location to test
* @return <code>true</code> if <code>other</code> is a
* <code>Location</code> with the same row and column as this location;
* <code>false</code> otherwise
*/
public boolean equals(Object other)
{
if (!(other instanceof Location))
return false;
Location otherLoc = (Location) other;
return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol();
}
/**
* Generates a hash code.
* @return a hash code for this location
*/
public int hashCode()
{
return getRow() * 3737 + getCol();
}
/**
* Compares this location to <code>other</code> for ordering. Returns a
* negative integer, zero, or a positive integer as this location is less
* than, equal to, or greater than <code>other</code>. Locations are
* ordered in row-major order. <br />
* (Precondition: <code>other</code> is a <code>Location</code> object.)
* @param other the other location to test
* @return a negative integer if this location is less than
* <code>other</code>, zero if the two locations are equal, or a positive
* integer if this location is greater than <code>other</code>
*/
public int compareTo(Object other)
{
Location otherLoc = (Location) other;
if (getRow() < otherLoc.getRow())
return -1;
if (getRow() > otherLoc.getRow())
return 1;
if (getCol() < otherLoc.getCol())
return -1;
if (getCol() > otherLoc.getCol())
return 1;
return 0;
}
/**
* Creates a string that describes this location.
* @return a string with the row and column of this location, in the format
* (row, col)
*/
public String toString()
{
return "(" + getRow() + ", " + getCol() + ")";
}
}
| [
"mshayanshafi@gmail.com"
] | mshayanshafi@gmail.com |
41702505c9f29d617071eef4a599eda343a65251 | a6faa1a4f59a4f5bd25c38fa4ad2652311f4ab73 | /Login/src/Paquete/Administrador.java | 75de23657c4817c1462604195d28dcc7b39ad1bc | [] | no_license | sanlaba08/Hostel | 8b7a2260ef862f9bf5f1a7911cfd3263357d6189 | fc9a55a25df7e7c12db68891e8a5738d0e8f93ec | refs/heads/master | 2022-11-10T15:20:46.797749 | 2020-06-20T23:12:58 | 2020-06-20T23:12:58 | 273,798,691 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 483 | java | package Paquete;
public class Administrador extends Persona {
private Usuario cuenta;
public Administrador(String nombre, String apellido, String edad, String direccion, String dni, Usuario cuenta,
Administrador administrador) {
super(nombre, apellido, edad, direccion, dni);
this.cuenta = cuenta;
}
@Override
public String toString() {
return "| Nombre: " +nombre+ " | Apellido: " +apellido+ " | Edad: "+edad+" | DNI: "+dni+" | Direccion: "+direccion;
}
} | [
"51683556+sanlaba08@users.noreply.github.com"
] | 51683556+sanlaba08@users.noreply.github.com |
c6418a9011679fd9e0e7500c569fd391794e978a | 11bdb955d06ef8705f675941604b819f4eca71a9 | /app/src/main/java/tufer/com/menutest/UIActivity/network/networkfove/EthernetSettings.java | 5b21251825121200437666e7fdf38842b4ed3f16 | [] | no_license | Tuferzzz/TuferTVMenu6.0 | 61c6bdcc983ddd2d9aa83ce264e53581788b3d32 | 51449ca35ab7b74dbc382fadcd0bfc4580c8f2bd | refs/heads/master | 2021-09-01T09:40:04.610558 | 2017-12-26T08:40:53 | 2017-12-26T08:40:53 | 103,482,747 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,147 | java | package tufer.com.menutest.UIActivity.network.networkfove;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.EthernetManager;
import android.net.IpConfiguration;
import android.net.IpConfiguration.IpAssignment;
import android.net.LinkAddress;
import android.net.NetworkUtils;
import android.net.StaticIpConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Iterator;
import tufer.com.menutest.UIActivity.network.networkfove.ProxySettings.ProxyInfo;
import tufer.com.menutest.R;
import tufer.com.menutest.Util.Tools;
public class EthernetSettings extends NetworkSettings implements INetworkSettingsListener, ConnectivityListener.Listener, WifiManager.ActionListener {
private static final String TAG = "MSettings.EthernetSettings";
private NetworkSettingsActivity mNetworkSettingsActivity;
private EthernetSettingsHolder mEthernetHolder;
private CheckBox mEthernetToggle;
private CheckBox mAutoIpToggle;
private CheckBox mIPv6Toggle;
private CheckBox mDevToggle;
private boolean DeviceFlag = false;
private ConnectivityManager mConnectivityManager;
private NetworkConfiguration mConfiguration;
private ConnectivityListener mConnectivityListener;
private IpConfiguration mIpConfiguration;
private final NetworkConfiguration mInitialConfiguration;
// foucs item on the right
private Ethernetnet methnet;
private int mSettingItem = Constants.SETTING_ITEM_0;
public interface Listener {
void onSaveWifiConfigurationCompleted(int result);
}
private EthernetManager mEthernetManager;
private LinearLayout mEthernetset;
public EthernetManager getmEthernetManager() {
return mEthernetManager;
}
public EthernetSettings(NetworkSettingsActivity networkSettingsActivity, NetworkConfiguration initialConfiguration) {
super(networkSettingsActivity);
mInitialConfiguration = initialConfiguration;
mEthernetHolder = new EthernetSettingsHolder(networkSettingsActivity, DeviceFlag);
mEthernetToggle = mEthernetHolder.getEthernetToggleCheckBox();
mAutoIpToggle = mEthernetHolder.getAutoIpCheckBox();
mIPv6Toggle = mEthernetHolder.getIPv6CheckBox();
mNetworkSettingsActivity = networkSettingsActivity;
mEthernetset = mEthernetHolder.getRlethetsting();
mConnectivityListener = new ConnectivityListener(networkSettingsActivity, this);
methnet = new Ethernetnet();
mIpConfiguration = (initialConfiguration != null) ?
mInitialConfiguration.getIpConfiguration() :
new IpConfiguration();
mConfiguration = NetworkConfigurationFactory.createNetworkConfiguration(
mNetworkSettingsActivity, NetworkConfigurationFactory.TYPE_ETHERNET);
Log.d("yesuo", "mConfiguration1" + mConfiguration);
Log.d("yesuo", "mConfiguration1" + mConfiguration);
((EthernetConfig) mConfiguration).load();
ischen();
setOnli();
}
private void setOnli() {
mEthernetToggle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mConnectivityListener.setState(Constants.ETHERNET_STATE_DISABLED);
}
});
mEthernetHolder.getSaveButton().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
IpConfiguration ipConfiguration = mConnectivityListener.getIpConfiguration();
//if(!mConnectivityListener.getEthernetIpAddress().isEmpty()){
if (mAutoIpToggle.isChecked()) {
if (ipConfiguration.getIpAssignment() == IpAssignment.DHCP) {
refreshEthernetStatus();
//
} else {
mIpConfiguration.setIpAssignment(IpAssignment.DHCP);
mIpConfiguration.setProxySettings(ipConfiguration.getProxySettings());
mIpConfiguration.setStaticIpConfiguration(null);
save();
}
} else {
if (mEthernetHolder.isednull()) {
processIpSettings();
save();
} else {
return;
}
}
//}
}
});
mEthernetHolder.getCancelButton().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//if(!mConnectivityListener.getEthernetIpAddress().isEmpty()){
IpConfiguration ipConfiguration = mConnectivityListener.getIpConfiguration();
if (ipConfiguration.getIpAssignment() == IpAssignment.STATIC) {
mAutoIpToggle.setChecked(false);
} else {
mAutoIpToggle.setChecked(true);
}
refreshEthernetStatus();
//}
}
});
}
public void getnull() {
}
private int processIpSettings() {
IpConfiguration ipConfiguration = mConnectivityListener.getIpConfiguration();
mIpConfiguration.setIpAssignment(IpAssignment.STATIC);
mIpConfiguration.setProxySettings(ipConfiguration.getProxySettings());
StaticIpConfiguration staticConfig = new StaticIpConfiguration();
// mIpConfiguration.setStaticIpConfiguration(staticConfig);
// String ipAddr = mIpAddressPage.getDataSummary();
String ipAddr = mEthernetHolder.getEthernetV4Address();
if (ipAddr == null) {
ipAddr = "192.168.1.110";
}
Log.d("yesuo", "AdcabcdewifioptionFlowipAddr" + ipAddr);
if (TextUtils.isEmpty(ipAddr))
return R.string.wifi_ip_settings_invalid_ip_address;
Inet4Address inetAddr = null;
Log.d("yesuo", "AdcabcdewifioptionFlowinetAdd" + inetAddr);
try {
inetAddr = (Inet4Address) NetworkUtils.numericToInetAddress(ipAddr);
Log.d("yesuo", "AdcabcdewifioptionFlowinetAdd1" + inetAddr);
} catch (IllegalArgumentException | ClassCastException e) {
return R.string.wifi_ip_settings_invalid_ip_address;
}
int networkPrefixLength = -1;
String netmasks = mEthernetHolder.getEthernetV4Netmask();
Log.d("yesuo", "netmasks:" + netmasks);
if (netmasks == null) {
netmasks = "255.255.255.0";
}
// methnet.setWosnet(netmasks);
SharedPreferences.Editor localEditor =mNetworkSettingsActivity.getSharedPreferences("MyNetmask", 0).edit();
localEditor.putString("MyNetmask", netmasks);
localEditor.apply();
int wasks = Tools.twoget(netmasks);
Log.d("yesuo", "wasks:" + wasks);
try {
// networkPrefixLength = Integer.parseInt(mNetworkPrefixLengthPage.getDataSummary());
networkPrefixLength = wasks;
if (networkPrefixLength < 0 || networkPrefixLength > 32) {
return R.string.wifi_ip_settings_invalid_network_prefix_length;
}
staticConfig.ipAddress = new LinkAddress(inetAddr, networkPrefixLength);
Log.d("yesuo", "staticConfig.ipAddress:" + staticConfig.ipAddress);
} catch (NumberFormatException e) {
return R.string.wifi_ip_settings_invalid_ip_address;
}
//String gateway = mGatewayPage.getDataSummary();
String gateway = mEthernetHolder.getEthernetV4Gateway();
if (gateway == null) {
gateway = "192.168.1.1";
}
Log.d("yesuo", "AdcabcdewifioptionFlowgateway" + gateway);
if (!TextUtils.isEmpty(gateway)) {
try {
staticConfig.gateway = (Inet4Address) NetworkUtils.numericToInetAddress(gateway);
} catch (IllegalArgumentException | ClassCastException e) {
return R.string.wifi_ip_settings_invalid_gateway;
}
}
// String dns1 = mDns1Page.getDataSummary();
String dns1 = mEthernetHolder.getEthernetV4Dns1();
if (dns1 == null) {
dns1 = "192.168.1.1";
}
Log.d("yesuo", "AdcabcdewifioptionFlowDNS1DNS1" + dns1);
if (!TextUtils.isEmpty(dns1)) {
try {
staticConfig.dnsServers.add(
(Inet4Address) NetworkUtils.numericToInetAddress(dns1));
} catch (IllegalArgumentException | ClassCastException e) {
return R.string.wifi_ip_settings_invalid_dns;
}
}
//String dns2 = mDns2Page.getDataSummary();
String dns2 = mEthernetHolder.getEthernetV4Dns2();
Log.d("yesuo", "AdcabcdewifioptionFlowDNS2DNS2" + dns2);
if (!TextUtils.isEmpty(dns2)) {
try {
staticConfig.dnsServers.add(
(Inet4Address) NetworkUtils.numericToInetAddress(dns1));
} catch (IllegalArgumentException | ClassCastException e) {
return R.string.wifi_ip_settings_invalid_dns;
}
}
mIpConfiguration.setStaticIpConfiguration(staticConfig);
return 0;
}
private void ischen() {
IpConfiguration ipConfiguration = mConnectivityListener.getIpConfiguration();
if (ipConfiguration.getIpAssignment() == IpAssignment.STATIC) {
mAutoIpToggle.setChecked(false);
} else {
mAutoIpToggle.setChecked(true);
}
if (mAutoIpToggle.isChecked()) {
mEthernetHolder.setV4EditTextWritable(false);
} else {
mEthernetHolder.setV4EditTextWritable(true);
}
if (mEthernetset.getVisibility() == View.VISIBLE) {
refreshEthernetStatus();
} else {
}
}
/**
* ethernet setting layout visible.
*
* @param visible if visible.
*/
public void setVisible(boolean visible) {
Log.d(TAG, "visible, " + visible);
mEthernetHolder.setEthernetVisible(visible);
if (visible) {
// showEthernetInfo();
refreshEthernetStatus();
}
}
@Override
public void onExit() {
}
@Override
public boolean onKeyEvent(int keyCode, KeyEvent keyEvent) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (mSettingItem > Constants.SETTING_ITEM_0
&& mSettingItem <= Constants.SETTING_ITEM_8) {
mSettingItem--;
mEthernetHolder.requestFocus(mSettingItem);
} else if (mSettingItem == Constants.SETTING_ITEM_9) {
mSettingItem -= 2;
mEthernetHolder.requestFocus(mSettingItem);
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (mSettingItem == Constants.SETTING_ITEM_0) {
if (mEthernetHolder.isEthernetOpened()) {
mSettingItem++;
mEthernetHolder.requestFocus(mSettingItem);
} else {
return true;
}
} else if (mSettingItem > Constants.SETTING_ITEM_0
&& mSettingItem <= Constants.SETTING_ITEM_7) {
mSettingItem++;
mEthernetHolder.requestFocus(mSettingItem);
}
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (mSettingItem >= Constants.SETTING_ITEM_3
&& mSettingItem <= Constants.SETTING_ITEM_7) {
return false;
} else if (mSettingItem == Constants.SETTING_ITEM_9) {
mSettingItem--;
mEthernetHolder.requestFocus(mSettingItem);
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (mSettingItem >= Constants.SETTING_ITEM_0
&& mSettingItem <= Constants.SETTING_ITEM_2) {
return true;
} else if (mSettingItem >= Constants.SETTING_ITEM_3
&& mSettingItem <= Constants.SETTING_ITEM_7) {
if (isLastFocused()) {
return true;
}
} else if (mSettingItem == Constants.SETTING_ITEM_8) {
mSettingItem++;
mEthernetHolder.requestFocus(mSettingItem);
return true;
} else if (mSettingItem == Constants.SETTING_ITEM_9) {
return true;
}
break;
default:
break;
}
return false;
}
@Override
public void onFocusChange(boolean hasFocus) {
if (hasFocus) {
mEthernetHolder.requestFocus(Constants.SETTING_ITEM_0);
} else {
mEthernetHolder.clearFocus(mSettingItem);
mSettingItem = Constants.SETTING_ITEM_0;
}
}
public boolean isV4FirstFocused() {
if (mEthernetHolder.isV4FirstFocused() || mEthernetHolder.isV6Focus()) {
return true;
} else {
return false;
}
}
public boolean isConfigEditTextFocused() {
if (mSettingItem >= Constants.SETTING_ITEM_3 && mSettingItem <= Constants.SETTING_ITEM_7) {
return true;
} else {
return false;
}
}
private boolean isLastFocused() {
if (mEthernetHolder.isV4LastFocused() || mEthernetHolder.isV6Focus()) {
return true;
} else {
return false;
}
}
private void refreshEthernetStatus() {
Log.d(TAG, "refreshEthernetStatus");
// show connect type.
// show network information.
String ip = mConnectivityListener.getEthernetIpAddress();
String netmask = null;
String defaultWay = null;
String firstdns = null;
String secDns = null;
//if (!mConnectivityListener.getEthernetIpAddress().isEmpty()) {
IpConfiguration ipConfiguration = mConnectivityListener.getIpConfiguration();
if (ipConfiguration != null) {
if (ipConfiguration.getIpAssignment() == IpAssignment.STATIC) {
StaticIpConfiguration cifi = ipConfiguration.getStaticIpConfiguration();
if (cifi != null) {
LinkAddress net = cifi.ipAddress;
Log.d("yesuo", net + "net");
if (net != null) {
if (ip == null) {
InetAddress address = net.getAddress();
if (address instanceof Inet4Address) {
ip = address.getHostAddress();
}
}
int nemask = net.describeContents();
int neamask = net.getNetworkPrefixLength();
int nesmask = net.getScope();
Log.d("yesuo", nemask + "net0");
Log.d("yesuo", neamask + "net1");
Log.d("yesuo", nesmask + "net2");
String s = cifi.domains;
Log.d("yesuo", s + "net2");
}
InetAddress way = cifi.gateway;
if (way != null) {
defaultWay = way.getHostAddress();
}
// String nets = methnet.getWosnet();
String nets = mNetworkSettingsActivity.getSharedPreferences("MyNetmask", 0).getString("MyNetmask", "255.255.255.0");
if (nets != null&&!nets.equals("")) {
netmask = nets;
} else {
if (ip != null && defaultWay != null) {
netmask = Tools.buildUpNetmask(ip, defaultWay);
Log.d("yesuo", ip + ":ip "+defaultWay+":defaultWay");
}
}
Iterator<InetAddress> dns = cifi.dnsServers.iterator();
if (dns.hasNext()) {
firstdns = dns.next().getHostAddress();
if (firstdns!=null&&firstdns.equals("")&&!Tools.matchIP(firstdns)) {
firstdns = null;
}
}
if (dns.hasNext()) {
secDns = dns.next().getHostAddress();
if (secDns!=null&&secDns.equals("")&&!Tools.matchIP(secDns)) {
secDns = null;
}
}
Log.d("yesuo", ipConfiguration.getStaticIpConfiguration() + "netmask" + cifi.dnsServers + "dnsserver");
mEthernetHolder.refreshNetworkInfo(ip, netmask, defaultWay, firstdns, secDns);
InputIPAddress.isForwardRightWithTextChange = true;
}
} else {
// misethernetChboxs.setChecked(false);
ip = mConnectivityListener.getEthernetIpAddress();
// SystemProperties.set("dhcp.eth0.mask","255.255.255.0");
// SystemProperties.set("dhcp.eth0.gateway","192.168.1.1");
// SystemProperties.set("dhcp.eth0.dns1","192.168.1.1");
// SystemProperties.set("dhcp.eth0.dns2","192.168.1.1");
netmask = SystemProperties.get("dhcp.eth0.mask");
defaultWay = SystemProperties.get("dhcp.eth0.gateway");
firstdns = SystemProperties.get("dhcp.eth0.dns1");
secDns = SystemProperties.get("dhcp.eth0.dns2");
if (secDns!=null&&secDns.equals("")&&!Tools.matchIP(secDns)) {
secDns = null;
}
mEthernetHolder.refreshNetworkInfo(ip, netmask, defaultWay, firstdns, secDns);
InputIPAddress.isForwardRightWithTextChange = true;
}
} else {
// }
}
// }
//}
}
@Override
public void onConnectivityChange(Intent intent) {
}
@Override
public void onProxyChanged(boolean enabled, ProxyInfo proxyInfo) {
}
@Override
public void onWifiHWChanged(boolean isOn) {
}
private void save() {
updateConfiguration(mConfiguration);
mConfiguration.save(this);
}
// public void updateConfiguration(WifiConfiguration configuration) {
// Log.d("yesuo","updateConfiguration"+configuration+mIpConfiguration);
// configuration.setIpConfiguration(mIpConfiguration);
// }
public void updateConfiguration(NetworkConfiguration configuration) {
Log.d("yesuo", "updateConfiguration(" + configuration + mIpConfiguration);
configuration.setIpConfiguration(mIpConfiguration);
}
@Override
public void onFailure(int arg0) {
Toast.makeText(mNetworkSettingsActivity, arg0, Toast.LENGTH_SHORT).show();
mIpConfiguration.setIpAssignment(IpAssignment.DHCP);
mIpConfiguration.setStaticIpConfiguration(null);
save();
refreshEthernetStatus();
}
@Override
public void onSuccess() {
Toast.makeText(mNetworkSettingsActivity, "save success", Toast.LENGTH_SHORT).show();
refreshEthernetStatus();
}
}
| [
"1126179195@qq.com"
] | 1126179195@qq.com |
f8c5a4fc3f6d516b3dbed26bccaa8410969866dd | 498dd2daff74247c83a698135e4fe728de93585a | /clients/google-api-services-artifactregistry/v1beta2/1.31.0/com/google/api/services/artifactregistry/v1beta2/model/Tag.java | 068af2ae410884cffb86c04d55d667a90eb57992 | [
"Apache-2.0"
] | permissive | googleapis/google-api-java-client-services | 0e2d474988d9b692c2404d444c248ea57b1f453d | eb359dd2ad555431c5bc7deaeafca11af08eee43 | refs/heads/main | 2023-08-23T00:17:30.601626 | 2023-08-20T02:16:12 | 2023-08-20T02:16:12 | 147,399,159 | 545 | 390 | Apache-2.0 | 2023-09-14T02:14:14 | 2018-09-04T19:11:33 | null | UTF-8 | Java | false | false | 3,969 | java | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.artifactregistry.v1beta2.model;
/**
* Tags point to a version and represent an alternative name that can be used to access the version.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Artifact Registry API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Tag extends com.google.api.client.json.GenericJson {
/**
* The name of the tag, for example: "projects/p1/locations/us-
* central1/repositories/repo1/packages/pkg1/tags/tag1". If the package part contains slashes, the
* slashes are escaped. The tag part can only have characters in [a-zA-Z0-9\-._~:@], anything else
* must be URL encoded.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The name of the version the tag refers to, for example: "projects/p1/locations/us-
* central1/repositories/repo1/packages/pkg1/versions/sha256:5243811" If the package or version ID
* parts contain slashes, the slashes are escaped.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String version;
/**
* The name of the tag, for example: "projects/p1/locations/us-
* central1/repositories/repo1/packages/pkg1/tags/tag1". If the package part contains slashes, the
* slashes are escaped. The tag part can only have characters in [a-zA-Z0-9\-._~:@], anything else
* must be URL encoded.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The name of the tag, for example: "projects/p1/locations/us-
* central1/repositories/repo1/packages/pkg1/tags/tag1". If the package part contains slashes, the
* slashes are escaped. The tag part can only have characters in [a-zA-Z0-9\-._~:@], anything else
* must be URL encoded.
* @param name name or {@code null} for none
*/
public Tag setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The name of the version the tag refers to, for example: "projects/p1/locations/us-
* central1/repositories/repo1/packages/pkg1/versions/sha256:5243811" If the package or version ID
* parts contain slashes, the slashes are escaped.
* @return value or {@code null} for none
*/
public java.lang.String getVersion() {
return version;
}
/**
* The name of the version the tag refers to, for example: "projects/p1/locations/us-
* central1/repositories/repo1/packages/pkg1/versions/sha256:5243811" If the package or version ID
* parts contain slashes, the slashes are escaped.
* @param version version or {@code null} for none
*/
public Tag setVersion(java.lang.String version) {
this.version = version;
return this;
}
@Override
public Tag set(String fieldName, Object value) {
return (Tag) super.set(fieldName, value);
}
@Override
public Tag clone() {
return (Tag) super.clone();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
2945b5f38311f0cb256d30d5cdd394703dda25d3 | 3972d195a307179be20e94213bc8edd859a333e1 | /src/main/java/com/hw/springannotation/test/Test_TX.java | 8b01fde85642ea79fb05121a459b9de95ed813d2 | [] | no_license | zoeforever/Spring-Annotation | 5f11ba0eff475bc45c5c224f6599bccdf900328f | e8d662d06d22f16b9cf607cf221b7f9a72ac09a8 | refs/heads/master | 2020-09-29T14:53:48.259582 | 2018-12-17T11:37:18 | 2018-12-17T11:37:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 657 | java | package com.hw.springannotation.test;
import com.hw.springannotation.tx.TxConfig;
import com.hw.springannotation.tx.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Description
* @Author Administrator
* @Date 2018/12/16
*/
public class Test_TX {
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TxConfig.class);
UserService userService = applicationContext.getBean(UserService.class);
userService.insertUser();
applicationContext.close();
}
}
| [
"jiao.hongwei@qq.com"
] | jiao.hongwei@qq.com |
9ae3684ac2ca1141b8ea773cafcc51483a87a549 | b60caf384767e6c8ff237c32cfe21ab55ace1797 | /src/client/Client.java | 7e4b6940f5af00f8c179a6f6b5f7fdb313262ebc | [] | no_license | plaistocene/Ceng_344_Term_Project | d81b928fb61076d1069ae028d9211b54ad7a68a4 | 88bec08659e27bf1a877da7a0a49b56429262f23 | refs/heads/master | 2022-10-22T06:16:22.039800 | 2020-05-04T21:00:19 | 2020-05-04T21:00:19 | 261,040,461 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,048 | java | package client;
import server.ClientInfo;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
private DatagramSocket socket;
private InetAddress address;
private int port;
private String name;
private boolean running;
public Client(String name, String addr, int port) {
try {
this.name = name;
this.address = InetAddress.getByName(addr);
this.port = port;
socket = new DatagramSocket();
running = true;
listen();
send("\\con:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public void send(String message) {
try {
if (!message.startsWith("\\")) {
message = "[" + name + "] : " + message;
}
message += "\\e";
byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
socket.send(packet);
System.out.println("Sent Message To -> " + address.getHostAddress() + ":" + port);
} catch (Exception e) {
e.printStackTrace();
}
}
private void listen() {
Thread listenThread = new Thread("ChatProgram Listener") {
public void run() {
try {
while (running) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
socket.receive(packet);
String message = new String(data);
message = message.substring(0, message.indexOf("\\e"));
//FIXME: Manage Message
if (!isCommand(message, packet)) {
ClientWindow.printToConsole(message);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
listenThread.start();
}
/*
* SERVER COMMAND LIST
* \con:[name] -> Connects Client to Server
* \dis:[id] -> Disconnect Client from Server
*/
private static boolean isCommand(String message, DatagramPacket packet) {
if (message.startsWith("\\con:")) {
//Run Connection Code
return true;
}
return false;
}
// @Override
// protected void finalize() {
// running = false;
// send("\\dis:" + name);
// }
}
| [
"bugra.sln@gmail.com"
] | bugra.sln@gmail.com |
d0b227b13b9a700e291a6993c94da22306402153 | 05ebfa70220c77d2ac272a10eefe0fc17d3f3b82 | /src/main/java/za/ac/cput/project/domain/Invoice.java | dddcc681854c9fb16ce0096bf78dc25e1e71789a | [] | no_license | umkhuru/TP_FinalAssignment | 964ef97019857a868b54a72131d6ff277473b2fa | ade8e1338f3ff56ae803a38ea04dd84b2bccecf9 | refs/heads/master | 2021-01-10T02:01:58.640478 | 2016-01-17T20:39:14 | 2016-01-17T20:39:14 | 44,516,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | package za.ac.cput.project.domain;
/**
* Created by student on 2015/10/24.
*/
public class Invoice {
}
| [
"etiramakhutla@hotmail.com"
] | etiramakhutla@hotmail.com |
0d9abc933e6e26fa568db3d1d6565a1a6e202893 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/orientechnologies--orientdb/ddcdca686a983429c5d7760e15c34cf10b796bbc/after/SQLSelectByLinkedPropertyIndexReuseTest.java | 3b49ca3e795d1ee5e266f9dec8a109cdc102809e | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,086 | java | package com.orientechnologies.orient.test.database.auto;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/**
* <p>
* Testing functionality of {@link com.orientechnologies.orient.core.sql.OIndexProxy}.
* </p>
* <p>
* Each test method tests different traverse index combination with different operations.
* </p>
* <p>
* Method name are used to describe test case, first part is chain of types of indexes that are used in test, second part define
* operation which are tested, and the last part describe whether or not {@code limit} operator are used in query.
* </p>
*
* <p>
* Prefix "lpirt" in class names means "LinkedPropertyIndexReuseTest".
* </p>
*/
@Test(groups = { "index" })
public class SQLSelectByLinkedPropertyIndexReuseTest extends AbstractIndexReuseTest {
@Parameters(value = "url")
public SQLSelectByLinkedPropertyIndexReuseTest(final String iURL) {
super(iURL);
}
@BeforeClass
public void beforeClass() throws Exception {
if (database.isClosed()) {
database.open("admin", "admin");
}
createSchemaForTest();
fillDataSet();
}
@AfterClass
public void afterClass() throws Exception {
if (database.isClosed()) {
database.open("admin", "admin");
}
database.command(new OCommandSQL("drop class lpirtStudent")).execute();
database.command(new OCommandSQL("drop class lpirtGroup")).execute();
database.command(new OCommandSQL("drop class lpirtCurator")).execute();
database.getMetadata().getSchema().reload();
database.getLevel2Cache().clear();
database.close();
}
@Test
public void testNotUniqueUniqueNotUniqueEqualsUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.name = 'Someone'"));
assertEquals(result.size(), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "John Smith"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testNotUniqueUniqueUniqueEqualsUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.salary = 2000"));
assertEquals(result.size(), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "John Smith"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testNotUniqueUniqueNotUniqueEqualsLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.name = 'Someone else' limit 1"));
assertEquals(result.size(), 1);
assertTrue(Arrays.asList("Jane Smith", "James Bell", "Roger Connor").contains((String) result.get(0).field("name")));
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testNotUniqueUniqueUniqueMinorUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.salary < 1000"));
assertEquals(result.size(), 3);
assertEquals(containsDocumentWithFieldValue(result, "name", "Jane Smith"), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "James Bell"), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "Roger Connor"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testNotUniqueUniqueUniqueMinorLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.salary < 1000 limit 2"));
assertEquals(result.size(), 2);
final List<String> expectedNames = Arrays.asList("Jane Smith", "James Bell", "Roger Connor");
for (ODocument aResult : result) {
assertTrue(expectedNames.contains((String) aResult.field("name")));
}
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testUniqueNotUniqueMinorEqualsUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>("select from lpirtStudent where diploma.GPA <= 4"));
assertEquals(result.size(), 2);
assertEquals(containsDocumentWithFieldValue(result, "name", "John Smith"), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "James Bell"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testUniqueNotUniqueMinorEqualsLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database
.query(new OSQLSynchQuery<ODocument>("select from lpirtStudent where diploma.GPA <= 4 limit 1"));
assertEquals(result.size(), 1);
assertTrue(Arrays.asList("John Smith", "James Bell").contains((String) result.get(0).field("name")));
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testNotUniqueUniqueUniqueMajorUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.salary > 1000"));
assertEquals(result.size(), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "John Smith"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testNotUniqueUniqueUniqueMajorLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where group.curator.salary > 550 limit 1"));
assertEquals(result.size(), 1);
final List<String> expectedNames = Arrays.asList("John Smith", "James Bell", "Roger Connor");
for (ODocument aResult : result) {
assertTrue(expectedNames.contains((String) aResult.field("name")));
}
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 3);
}
@Test
public void testUniqueUniqueBetweenUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtGroup where curator.salary between 500 and 1000"));
assertEquals(result.size(), 2);
assertEquals(containsDocumentWithFieldValue(result, "name", "PZ-08-2"), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "PZ-08-3"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testUniqueUniqueBetweenLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtGroup where curator.salary between 500 and 1000 limit 1"));
assertEquals(result.size(), 1);
final List<String> expectedNames = Arrays.asList("PZ-08-2", "PZ-08-3");
for (ODocument aResult : result) {
assertTrue(expectedNames.contains((String) aResult.field("name")));
}
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testUniqueUniqueInUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtGroup where curator.salary in [500, 600]"));
assertEquals(result.size(), 2);
assertEquals(containsDocumentWithFieldValue(result, "name", "PZ-08-2"), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "PZ-08-3"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testUniqueUniqueInLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtGroup where curator.salary in [500, 600] limit 1"));
assertEquals(result.size(), 1);
final List<String> expectedNames = Arrays.asList("PZ-08-2", "PZ-08-3");
for (ODocument aResult : result) {
assertTrue(expectedNames.contains((String) aResult.field("name")));
}
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testUniqueFulltextContainsTextUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where diploma.thesis CONTAINSTEXT 'student'"));
assertEquals(result.size(), 2);
assertEquals(containsDocumentWithFieldValue(result, "name", "John Smith"), 1);
assertEquals(containsDocumentWithFieldValue(result, "name", "James Bell"), 1);
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
@Test
public void testUniqueFulltextContainsTextLimitUsing() throws Exception {
long oldIndexUsage = profiler.getCounter("db.demo.query.indexUsed");
if (oldIndexUsage == -1) {
oldIndexUsage = 0;
}
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>(
"select from lpirtStudent where diploma.thesis CONTAINSTEXT 'student' limit 1"));
assertEquals(result.size(), 1);
final List<String> expectedNames = Arrays.asList("John Smith", "James Bell");
for (ODocument aResult : result) {
assertTrue(expectedNames.contains((String) aResult.field("name")));
}
assertEquals(profiler.getCounter("db.demo.query.indexUsed") - oldIndexUsage, 2);
}
private void fillDataSet() {
ODocument curator1 = database.newInstance("lpirtCurator");
curator1.field("name", "Someone");
curator1.field("salary", 2000);
final ODocument group1 = database.newInstance("lpirtGroup");
group1.field("name", "PZ-08-1");
group1.field("curator", curator1);
group1.save();
final ODocument diploma1 = database.newInstance("lpirtDiploma");
diploma1.field("GPA", 3.);
diploma1.field("thesis", "Researching and visiting universities before making a final decision is very "
+ "beneficial because you student be able to experience the campus, meet the professors, and truly "
+ "understand the traditions of the university.");
final ODocument student1 = database.newInstance("lpirtStudent");
student1.field("name", "John Smith");
student1.field("group", group1);
student1.field("diploma", diploma1);
student1.save();
ODocument curator2 = database.newInstance("lpirtCurator");
curator2.field("name", "Someone else");
curator2.field("salary", 500);
final ODocument group2 = database.newInstance("lpirtGroup");
group2.field("name", "PZ-08-2");
group2.field("curator", curator2);
group2.save();
final ODocument diploma2 = database.newInstance("lpirtDiploma");
diploma2.field("GPA", 5.);
diploma2.field("thesis", "While both Northerners and Southerners believed they fought against tyranny and "
+ "oppression, Northerners focused on the oppression of slaves while Southerners defended their own "
+ "right to self-government.");
final ODocument student2 = database.newInstance("lpirtStudent");
student2.field("name", "Jane Smith");
student2.field("group", group2);
student2.field("diploma", diploma2);
student2.save();
ODocument curator3 = database.newInstance("lpirtCurator");
curator3.field("name", "Someone else");
curator3.field("salary", 600);
final ODocument group3 = database.newInstance("lpirtGroup");
group3.field("name", "PZ-08-3");
group3.field("curator", curator3);
group3.save();
final ODocument diploma3 = database.newInstance("lpirtDiploma");
diploma3.field("GPA", 4.);
diploma3.field("thesis", "College student shouldn't have to take a required core curriculum, and many core "
+ "courses are graded too stiffly.");
final ODocument student3 = database.newInstance("lpirtStudent");
student3.field("name", "James Bell");
student3.field("group", group3);
student3.field("diploma", diploma3);
student3.save();
final ODocument student4 = database.newInstance("lpirtStudent");
student4.field("name", "Roger Connor");
student4.field("group", group3);
student4.save();
}
private void createSchemaForTest() {
final OSchema schema = database.getMetadata().getSchema();
if (!schema.existsClass("lpirtStudent")) {
final OClass curatorClass = schema.createClass("lpirtCurator");
curatorClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
curatorClass.createProperty("salary", OType.INTEGER).createIndex(OClass.INDEX_TYPE.UNIQUE);
curatorClass.createIndex("curotorCompositeIndex", OClass.INDEX_TYPE.UNIQUE, "salary", "name");
final OClass groupClass = schema.createClass("lpirtGroup");
groupClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
groupClass.createProperty("curator", OType.LINK, curatorClass).createIndex(OClass.INDEX_TYPE.UNIQUE);
final OClass diplomaClass = schema.createClass("lpirtDiploma");
diplomaClass.createProperty("GPA", OType.DOUBLE).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
diplomaClass.createProperty("thesis", OType.STRING).createIndex(OClass.INDEX_TYPE.FULLTEXT);
diplomaClass.createIndex("diplomaThesisUnique", OClass.INDEX_TYPE.UNIQUE, "thesis");
final OClass studentClass = schema.createClass("lpirtStudent");
studentClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
studentClass.createProperty("group", OType.LINK, groupClass).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
studentClass.createProperty("diploma", OType.LINK, diplomaClass);
studentClass.createIndex("studentDiplomaAndNameIndex", OClass.INDEX_TYPE.UNIQUE, "diploma", "name");
schema.save();
}
}
private int containsDocumentWithFieldValue(final List<ODocument> docList, final String fieldName, final Object fieldValue) {
int count = 0;
for (final ODocument docItem : docList) {
if (fieldValue.equals(docItem.field(fieldName))) {
count++;
}
}
return count;
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
229aa18c64cbd5d3b80844d0a806ea5c8a33f447 | 877d3e453e9f5577a9607d4d161f6fb7f629266f | /mstx-gateway/src/main/java/com/mstx/framework/gateway/handler/ServiceFilterHandler.java | bd873a19fbbea17228022bf3cbe97e6524bcbc77 | [] | no_license | Jebel8296/snooker | e4ec9128b642fee24d961c63061c23d63f173cc9 | 8377e6ff18b397760fe0a65cf31c186c5942d078 | refs/heads/master | 2020-03-28T13:35:31.687950 | 2018-09-12T02:33:54 | 2018-09-12T02:33:54 | 148,408,656 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 459 | java | package com.mstx.framework.gateway.handler;
import com.mstx.framework.gateway.handler.impl.ServiceFilterHandlerImpl;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.ext.web.RoutingContext;
@VertxGen
public interface ServiceFilterHandler extends Handler<RoutingContext> {
static ServiceFilterHandler create(Vertx vertx) {
return new ServiceFilterHandlerImpl(vertx);
}
}
| [
"kezheng1234@126.com"
] | kezheng1234@126.com |
17938b80fe176882891378f084e03d67861d3133 | da67a550bd2e1cc8e7c3300a743e03cf3b87e7d0 | /app/src/main/java/com/example/acer/exampapers/SemesterTwoComputer.java | 4f3a0256390b23a92bf30bacb10c1ee5e7aab42a | [] | no_license | suhitkoyani/ExamPapers | df9d8c233ac94d8545cc9928495d79cbf130b8bb | 8682835cbd4f214c59327f67d65f81da440008a3 | refs/heads/master | 2023-03-04T15:29:54.340251 | 2021-02-17T10:22:36 | 2021-02-17T10:22:36 | 109,720,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,839 | java | package com.example.acer.exampapers;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by acer on 7/9/2017.
*/
public class SemesterTwoComputer extends AppCompatActivity {
private List<Branch> SemesterList = new ArrayList<>();
private RecyclerView recyclerView;
private BranchAdapter branchAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
branchAdapter = new BranchAdapter(SemesterList);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(SemesterTwoComputer.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(branchAdapter);
addSubjectData();
}
public void addSubjectData(){
Branch branch_obj = new Branch("VCLA");
SemesterList.add(branch_obj);
branch_obj = new Branch("Basic Civil Engineering");
SemesterList.add(branch_obj);
branch_obj = new Branch("Computer Programming");
SemesterList.add(branch_obj);
branch_obj = new Branch("Basic Electrical Technology");
SemesterList.add(branch_obj);
branch_obj = new Branch("Engineering Graphics");
SemesterList.add(branch_obj);
branch_obj = new Branch("VEHRLP");
SemesterList.add(branch_obj);
}
}
| [
"suhitkoyani@gmail.com"
] | suhitkoyani@gmail.com |
5d0db6c3d654bad0b96814e07be1850067752f5f | 5b27dae1efe7dcfce9348139aae54cbefb6c736b | /src/main/java/me/porcelli/nio/jgit/impl/op/commands/GetRef.java | 22fafb98d426707411bafa62810e48f454c7bd66 | [
"Apache-2.0"
] | permissive | porcelli/jgit-nio2 | ed63ce527622ef120aa3feba1ee512a0523a5f8c | ba68f5c32a388cf63fbed571f14bc7a85396c0cc | refs/heads/master | 2021-06-25T18:05:58.913277 | 2020-01-20T15:43:11 | 2020-01-20T15:43:11 | 222,013,709 | 0 | 1 | Apache-2.0 | 2021-04-26T19:41:42 | 2019-11-15T22:31:01 | Java | UTF-8 | Java | false | false | 2,137 | java | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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 me.porcelli.nio.jgit.impl.op.commands;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectIdRef;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import static org.eclipse.jgit.lib.Constants.OBJ_TREE;
public class GetRef {
private final Repository repo;
private final String name;
public GetRef(final Repository repo,
final String name) {
this.repo = repo;
this.name = name;
}
public Ref execute() {
try {
final Ref value = repo.getRefDatabase().findRef(name);
if (value != null) {
return value;
}
final ObjectId treeRef = repo.resolve(name + "^{tree}");
if (treeRef != null) {
try (final ObjectReader objectReader = repo.getObjectDatabase().newReader()) {
final ObjectLoader loader = objectReader.open(treeRef);
if (loader.getType() == OBJ_TREE) {
return new ObjectIdRef.PeeledTag(Ref.Storage.NEW,
name,
ObjectId.fromString(name),
treeRef);
}
}
}
} catch (final Exception ignored) {
}
return null;
}
}
| [
"alexandre.porcelli@gmail.com"
] | alexandre.porcelli@gmail.com |
127c715f9578f67ae3e748c0362e824d14a0b7d0 | 18dd2def6db6b02d653a1e2d5fb5ff76964b2dd5 | /Trabalho de Implementação - Cinema/IngressoInteiro.java | 656cb671dc56a704f9851d31f053a50be9da3585 | [] | no_license | EduardaAChagas/LP2 | 2b22c764fc193d53aefc61346f51b82888704a8d | d6d2560bcbffe59a4101b215745ac51502229303 | refs/heads/master | 2021-09-28T16:54:37.182853 | 2021-09-27T19:23:34 | 2021-09-27T19:23:34 | 244,975,351 | 0 | 2 | null | 2020-10-22T01:34:15 | 2020-03-04T18:32:33 | Java | UTF-8 | Java | false | false | 219 | java | package Cinema;
public class IngressoInteiro extends Ingresso(){
private double valor;
private int cadeira;
public class IngressoInteiro(double valor,int cadeira){
super(valor/2,cadeira);
}
}
| [
"eduardamachagas@gmail.com"
] | eduardamachagas@gmail.com |
cdf0142bd93b730549b5fafa56d0ece149e849ac | 57784fb314e024f0a59e7c962733a37ffe81d681 | /gemfire-examples/src/main/java/quickstart/DeltaPropagationServer.java | d4ac81eabdd18ce87bc861cffb09614f0b1aa529 | [
"Apache-2.0",
"LGPL-2.1-only",
"JSON",
"Plexus",
"LicenseRef-scancode-other-permissive",
"MIT",
"Apache-1.1",
"GPL-2.0-only",
"BSD-2-Clause"
] | permissive | TIBCOSoftware/snappy-store | a5ea4df265acf60697a5dad3c74cc1e12e41381b | d6ef57196127f1e87cc902e1aa20055025590b2d | refs/heads/snappy/master | 2023-09-03T13:29:24.241765 | 2022-06-27T21:24:32 | 2022-06-27T21:24:32 | 48,800,286 | 3 | 4 | Apache-2.0 | 2023-04-16T22:34:56 | 2015-12-30T12:44:56 | Java | UTF-8 | Java | false | false | 2,392 | java | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. 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. 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. See accompanying
* LICENSE file.
*/
package quickstart;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
/**
* DeltaPropagationServer.java has the server to which the
* DeltaPropagationClient connects. See the DeltaPropagationClient or the
* quickstart guide for run instructions. To stop the server, type "Exit" in
* server console.
* <p>
*
* @author GemStone Systems, Inc.
*/
public class DeltaPropagationServer {
private static void writeToStdout(String msg) {
System.out.println(msg);
}
public static void main(String[] args) throws Exception {
writeToStdout("This example demonstrates delta propagation. This program is a server,");
writeToStdout("listening on a port for client requests. The client program connects and");
writeToStdout("requests data. The client in this example is also configured to produce/consume");
writeToStdout("information on data destroys and updates.");
writeToStdout("To stop the program, press Ctrl c in console.");
writeToStdout("Connecting to the distributed system and creating the cache...");
// Create the cache which causes the cache-xml-file to be parsed
Cache cache = new CacheFactory()
.set("name", "DeltaPropagationServer")
.set("cache-xml-file", "xml/DeltaServer.xml")
.set("mcast-port", "38485")
.create();
writeToStdout("Connected to the distributed system.");
writeToStdout("Created the cache.");
writeToStdout("Please press Enter to stop the server.");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
bufferedReader.readLine();
cache.close();
}
}
| [
"swale@snappydata.io"
] | swale@snappydata.io |
c11164d79cd5cde2259e023312241246644b6f4c | b3f0cb9a7b7c3f691862c9021e3053c5691f677a | /src/entities/BusinessAccount.java | 162628c08326826d048b0e814203cca714f2173c | [] | no_license | paulokiki/Upcasting_Dawncasting | 0da1b46b94e1c64d7a015ca0799e761d716a8275 | ef98ca1435b88d939c79fdda20c796bcf1a3ee5f | refs/heads/master | 2020-06-16T00:53:24.041711 | 2019-07-05T16:57:23 | 2019-07-05T16:57:23 | 195,436,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package entities;
public class BusinessAccount extends Account {
private double loanLimit;
public BusinessAccount() {
super();
}
public BusinessAccount(double loanLimit, Integer number, String holder, Double balance) {
super(number, holder, balance);
this.loanLimit = loanLimit;
}
public double getLoanLimit() {
return loanLimit;
}
public void setLoanLimit(double loanLimit) {
this.loanLimit = loanLimit;
}
public void loan(double amount) {
if (amount <= loanLimit) {
balance += amount - 10.0;
}
}
@Override
public void withdraw(double amount){
super.withdraw(amount);
balance -= 2.0;
}
} | [
"vieiralinspaulo@gmail.com"
] | vieiralinspaulo@gmail.com |
87e05fc0f83acffb4a91d33e6ca6f0b869f0f4a4 | 5c32e054005c593f78ef8e60aaff9b8da49b43fb | /Proyecto_Empresa/Tercer Entrega/PagWebEmpresa/src/java/Controlador/DAO/ProductosDAO.java | 96ae38479226c3367ec379461dd96930a64a1f76 | [] | no_license | santiagoRojas/FIS | 7101fa7504fb85413ccea52a228be00d25de8fcc | 5e94f261488d142e0762d86b6ca1f02ba9a81dae | refs/heads/master | 2021-07-07T04:26:13.931902 | 2019-03-06T21:58:38 | 2019-03-06T21:58:38 | 145,930,490 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,271 | java | /*
* 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 Controlador.DAO;
import Controlador.Conexion.Conexion;
import Mundo.Producto;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author TOSHIBA
*/
public class ProductosDAO {
private Connection con;
private Statement st;
private ResultSet rs;
private ArrayList<Producto> productos;
public ProductosDAO() {
con = null;
st = null;
rs=null;
}
public ArrayList<Producto> consultarProductos(){
productos = null;
String consulta = "SELECT * FROM public.\"Producto\" ";
try {
con = Conexion.getConexion();
st = con.createStatement();
rs = st.executeQuery(consulta);
productos = new ArrayList<>();
while(rs.next()){
Producto producto = new Producto();
producto = new Producto();
producto.setNit(rs.getInt("nitProducto"));
producto.setNombre(rs.getString("nombre"));
producto.setTipoo(rs.getString("tipo"));
producto.setDescripcion(rs.getString("descripcion"));
producto.setValor(rs.getInt("valor"));
producto.setFoto(rs.getString("foto"));
producto.setIdProducto(rs.getInt("idProducto"));
productos.add(producto);
}
st.close();
Conexion.cerrarConexion();
} catch (Exception e) {
System.err.println("No se pudo realizar la consulta");
return null;
}
return productos;
}
//falta insertar la foto correctamente
public boolean agregarProducto(Producto producto) throws ClassNotFoundException{
String insertar = "INSERT INTO public.\"Producto\"(\n" +
" descripcion, nombre, tipo, valor, foto)\n" +
" VALUES ('"+producto.getDescripcion()+"', '"+producto.getNombre()+"', '"+producto.getTipoo()+"', "+producto.getValor()+", "+producto.getFoto()+") ";
try {
con = Conexion.getConexion();
st = con.createStatement();
st.executeUpdate(insertar);
st.close();
Conexion.cerrarConexion();
return true;
} catch (SQLException e) {
System.out.println("no se pudo realizar el agregado");
}
return false;
}
public boolean eliminarProducto(int nit) throws ClassNotFoundException{
String eliminar = "DELETE FROM public.\"Producto\"\n" +
" WHERE \"nitProducto\" ="+nit;
try {
con = Conexion.getConexion();
st = con.createStatement();
st.executeUpdate(eliminar);
st.close();
Conexion.cerrarConexion();
return true;
} catch (SQLException e) {
System.out.println("no se pudo realizar la eliminacion");
}
return false;
}
} | [
"noreply@github.com"
] | noreply@github.com |
fe22c60f503be23ab558fa3be86939efd4c37874 | 51779adf522c5599119be0057764123f8f5268d8 | /jimfs/src/test/java/com/google/common/jimfs/RegularFileTest.java | 837d7a126a9b501bb1774937662c00a58cbdcfe4 | [
"Apache-2.0"
] | permissive | tixo/jimfs | 88441e16d48bb11a9adc3e8b2361c002aee06df5 | 2a215404d2f222c0c361426908e8bd4c466c4646 | refs/heads/master | 2021-01-15T12:55:05.437321 | 2015-04-22T22:19:32 | 2015-04-23T03:11:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 33,009 | java | /*
* Copyright 2013 Google Inc.
*
* 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 com.google.common.jimfs;
import static com.google.common.jimfs.TestUtils.buffer;
import static com.google.common.jimfs.TestUtils.buffers;
import static com.google.common.jimfs.TestUtils.bytes;
import static com.google.common.primitives.Bytes.concat;
import static org.junit.Assert.assertArrayEquals;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* Tests for {@link RegularFile} and by extension for {@link HeapDisk}. These tests test files
* created by a heap disk in a number of different states.
*
* @author Colin Decker
*/
public class RegularFileTest {
/**
* Returns a test suite for testing file methods with a variety of {@code HeapDisk}
* configurations.
*/
public static TestSuite suite() {
TestSuite suite = new TestSuite();
for (ReuseStrategy reuseStrategy : EnumSet.allOf(ReuseStrategy.class)) {
TestSuite suiteForReuseStrategy = new TestSuite(reuseStrategy.toString());
Set<List<Integer>> sizeOptions = Sets.cartesianProduct(
ImmutableList.of(BLOCK_SIZES, CACHE_SIZES));
for (List<Integer> options : sizeOptions) {
int blockSize = options.get(0);
int cacheSize = options.get(1);
if (cacheSize > 0 && cacheSize < blockSize) {
// skip cases where the cache size is not -1 (all) or 0 (none) but it is < blockSize,
// because this is equivalent to a cache size of 0
continue;
}
TestConfiguration state = new TestConfiguration(blockSize, cacheSize, reuseStrategy);
TestSuite suiteForTest = new TestSuite(state.toString());
for (Method method : TEST_METHODS) {
RegularFileTestRunner tester = new RegularFileTestRunner(method.getName(), state);
suiteForTest.addTest(tester);
}
suiteForReuseStrategy.addTest(suiteForTest);
}
suite.addTest(suiteForReuseStrategy);
}
return suite;
}
public static final ImmutableSet<Integer> BLOCK_SIZES = ImmutableSet.of(2, 8, 128, 8192);
public static final ImmutableSet<Integer> CACHE_SIZES = ImmutableSet.of(0, 4, 16, 128, -1);
private static final ImmutableList<Method> TEST_METHODS = FluentIterable
.from(Arrays.asList(RegularFileTestRunner.class.getDeclaredMethods()))
.filter(new Predicate<Method>() {
@Override
public boolean apply(Method method) {
return method.getName().startsWith("test")
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0;
}
})
.toList();
/**
* Different strategies for handling reuse of disks and/or files between tests, intended to
* ensure that {@link HeapDisk} operates properly in a variety of usage states including newly
* created, having created files that have not been deleted yet, having created files that have
* been deleted, and having created files some of which have been deleted and some of which have
* not.
*/
public enum ReuseStrategy {
/**
* Creates a new disk for each test.
*/
NEW_DISK,
/**
* Retains files after each test, forcing new blocks to be allocated.
*/
KEEP_FILES,
/**
* Deletes files after each test, allowing caching to be used if enabled.
*/
DELETE_FILES,
/**
* Randomly keeps or deletes a file after each test.
*/
KEEP_OR_DELETE_FILES
}
/**
* Configuration for a set of test cases.
*/
public static final class TestConfiguration {
private final int blockSize;
private final int cacheSize;
private final ReuseStrategy reuseStrategy;
private HeapDisk disk;
public TestConfiguration(int blockSize, int cacheSize, ReuseStrategy reuseStrategy) {
this.blockSize = blockSize;
this.cacheSize = cacheSize;
this.reuseStrategy = reuseStrategy;
if (reuseStrategy != ReuseStrategy.NEW_DISK) {
this.disk = createDisk();
}
}
private HeapDisk createDisk() {
int maxCachedBlockCount = cacheSize == -1 ? Integer.MAX_VALUE : (cacheSize / blockSize);
return new HeapDisk(blockSize, Integer.MAX_VALUE, maxCachedBlockCount);
}
public RegularFile createRegularFile() {
if (reuseStrategy == ReuseStrategy.NEW_DISK) {
disk = createDisk();
}
return RegularFile.create(0, disk);
}
public void tearDown(RegularFile file) {
switch (reuseStrategy) {
case DELETE_FILES:
file.deleted();
break;
case KEEP_OR_DELETE_FILES:
if (new Random().nextBoolean()) {
file.deleted();
}
break;
case KEEP_FILES:
break;
default:
break;
}
}
@Override
public String toString() {
return reuseStrategy + " [" + blockSize + ", " + cacheSize + "]";
}
}
/**
* Actual test cases for testing RegularFiles.
*/
public static class RegularFileTestRunner extends TestCase {
private final TestConfiguration configuration;
protected RegularFile file;
public RegularFileTestRunner(String methodName, TestConfiguration configuration) {
super(methodName);
this.configuration = configuration;
}
@Override
public String getName() {
return super.getName() + " [" + configuration + "]";
}
@Override
public void setUp() {
file = configuration.createRegularFile();
}
@Override
public void tearDown() {
configuration.tearDown(file);
}
private void fillContent(String fill) throws IOException {
file.write(0, buffer(fill));
}
public void testEmpty() {
assertEquals(0, file.size());
assertContentEquals("", file);
}
public void testEmpty_read_singleByte() {
assertEquals(-1, file.read(0));
assertEquals(-1, file.read(1));
}
public void testEmpty_read_byteArray() {
byte[] array = new byte[10];
assertEquals(-1, file.read(0, array, 0, array.length));
assertArrayEquals(bytes("0000000000"), array);
}
public void testEmpty_read_singleBuffer() {
ByteBuffer buffer = ByteBuffer.allocate(10);
int read = file.read(0, buffer);
assertEquals(-1, read);
assertEquals(0, buffer.position());
}
public void testEmpty_read_multipleBuffers() {
ByteBuffer buf1 = ByteBuffer.allocate(5);
ByteBuffer buf2 = ByteBuffer.allocate(5);
long read = file.read(0, ImmutableList.of(buf1, buf2));
assertEquals(-1, read);
assertEquals(0, buf1.position());
assertEquals(0, buf2.position());
}
public void testEmpty_write_singleByte_atStart() throws IOException {
file.write(0, (byte) 1);
assertContentEquals("1", file);
}
public void testEmpty_write_byteArray_atStart() throws IOException {
byte[] bytes = bytes("111111");
file.write(0, bytes, 0, bytes.length);
assertContentEquals(bytes, file);
}
public void testEmpty_write_partialByteArray_atStart() throws IOException {
byte[] bytes = bytes("2211111122");
file.write(0, bytes, 2, 6);
assertContentEquals("111111", file);
}
public void testEmpty_write_singleBuffer_atStart() throws IOException {
file.write(0, buffer("111111"));
assertContentEquals("111111", file);
}
public void testEmpty_write_multipleBuffers_atStart() throws IOException {
file.write(0, buffers("111", "111"));
assertContentEquals("111111", file);
}
public void testEmpty_write_singleByte_atNonZeroPosition() throws IOException {
file.write(5, (byte) 1);
assertContentEquals("000001", file);
}
public void testEmpty_write_byteArray_atNonZeroPosition() throws IOException {
byte[] bytes = bytes("111111");
file.write(5, bytes, 0, bytes.length);
assertContentEquals("00000111111", file);
}
public void testEmpty_write_partialByteArray_atNonZeroPosition() throws IOException {
byte[] bytes = bytes("2211111122");
file.write(5, bytes, 2, 6);
assertContentEquals("00000111111", file);
}
public void testEmpty_write_singleBuffer_atNonZeroPosition() throws IOException {
file.write(5, buffer("111"));
assertContentEquals("00000111", file);
}
public void testEmpty_write_multipleBuffers_atNonZeroPosition() throws IOException {
file.write(5, buffers("111", "222"));
assertContentEquals("00000111222", file);
}
public void testEmpty_write_noBytesArray_atStart() throws IOException {
file.write(0, bytes(), 0, 0);
assertContentEquals(bytes(), file);
}
public void testEmpty_write_noBytesArray_atNonZeroPosition() throws IOException {
file.write(5, bytes(), 0, 0);
assertContentEquals(bytes("00000"), file);
}
public void testEmpty_write_noBytesBuffer_atStart() throws IOException {
file.write(0, buffer(""));
assertContentEquals(bytes(), file);
}
public void testEmpty_write_noBytesBuffer_atNonZeroPosition() throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(0);
file.write(5, buffer);
assertContentEquals(bytes("00000"), file);
}
public void testEmpty_write_noBytesBuffers_atStart() throws IOException {
file.write(0, ImmutableList.of(buffer(""), buffer(""), buffer("")));
assertContentEquals(bytes(), file);
}
public void testEmpty_write_noBytesBuffers_atNonZeroPosition() throws IOException {
file.write(5, ImmutableList.of(buffer(""), buffer(""), buffer("")));
assertContentEquals(bytes("00000"), file);
}
public void testEmpty_transferFrom_fromStart_countEqualsSrcSize() throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("111111")), 0, 6);
assertEquals(6, transferred);
assertContentEquals("111111", file);
}
public void testEmpty_transferFrom_fromStart_countLessThanSrcSize() throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("111111")), 0, 3);
assertEquals(3, transferred);
assertContentEquals("111", file);
}
public void testEmpty_transferFrom_fromStart_countGreaterThanSrcSize() throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("111111")), 0, 12);
assertEquals(6, transferred);
assertContentEquals("111111", file);
}
public void testEmpty_transferFrom_fromBeyondStart_countEqualsSrcSize() throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("111111")), 4, 6);
assertEquals(6, transferred);
assertContentEquals("0000111111", file);
}
public void testEmpty_transferFrom_fromBeyondStart_countLessThanSrcSize() throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("111111")), 4, 3);
assertEquals(3, transferred);
assertContentEquals("0000111", file);
}
public void testEmpty_transferFrom_fromBeyondStart_countGreaterThanSrcSize()
throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("111111")), 4, 12);
assertEquals(6, transferred);
assertContentEquals("0000111111", file);
}
public void testEmpty_transferFrom_fromStart_noBytes_countEqualsSrcSize() throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("")), 0, 0);
assertEquals(0, transferred);
assertContentEquals(bytes(), file);
}
public void testEmpty_transferFrom_fromStart_noBytes_countGreaterThanSrcSize()
throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("")), 0, 10);
assertEquals(0, transferred);
assertContentEquals(bytes(), file);
}
public void testEmpty_transferFrom_fromBeyondStart_noBytes_countEqualsSrcSize()
throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("")), 5, 0);
assertEquals(0, transferred);
assertContentEquals(bytes("00000"), file);
}
public void testEmpty_transferFrom_fromBeyondStart_noBytes_countGreaterThanSrcSize()
throws IOException {
long transferred = file.transferFrom(new ByteBufferChannel(buffer("")), 5, 10);
assertEquals(0, transferred);
assertContentEquals(bytes("00000"), file);
}
public void testEmpty_transferTo() throws IOException {
ByteBufferChannel channel = new ByteBufferChannel(100);
assertEquals(0, file.transferTo(0, 100, channel));
}
public void testEmpty_copy() throws IOException {
RegularFile copy = file.copyWithoutContent(1);
assertContentEquals("", copy);
}
public void testEmpty_truncate_toZero() throws IOException {
file.truncate(0);
assertContentEquals("", file);
}
public void testEmpty_truncate_sizeUp() throws IOException {
file.truncate(10);
assertContentEquals("", file);
}
public void testNonEmpty() throws IOException {
fillContent("222222");
assertContentEquals("222222", file);
}
public void testNonEmpty_read_singleByte() throws IOException {
fillContent("123456");
assertEquals(1, file.read(0));
assertEquals(2, file.read(1));
assertEquals(6, file.read(5));
assertEquals(-1, file.read(6));
assertEquals(-1, file.read(100));
}
public void testNonEmpty_read_all_byteArray() throws IOException {
fillContent("222222");
byte[] array = new byte[6];
assertEquals(6, file.read(0, array, 0, array.length));
assertArrayEquals(bytes("222222"), array);
}
public void testNonEmpty_read_all_singleBuffer() throws IOException {
fillContent("222222");
ByteBuffer buffer = ByteBuffer.allocate(6);
assertEquals(6, file.read(0, buffer));
assertBufferEquals("222222", 0, buffer);
}
public void testNonEmpty_read_all_multipleBuffers() throws IOException {
fillContent("223334");
ByteBuffer buf1 = ByteBuffer.allocate(3);
ByteBuffer buf2 = ByteBuffer.allocate(3);
assertEquals(6, file.read(0, ImmutableList.of(buf1, buf2)));
assertBufferEquals("223", 0, buf1);
assertBufferEquals("334", 0, buf2);
}
public void testNonEmpty_read_all_byteArray_largerThanContent() throws IOException {
fillContent("222222");
byte[] array = new byte[10];
assertEquals(6, file.read(0, array, 0, array.length));
assertArrayEquals(bytes("2222220000"), array);
array = new byte[10];
assertEquals(6, file.read(0, array, 2, 6));
assertArrayEquals(bytes("0022222200"), array);
}
public void testNonEmpty_read_all_singleBuffer_largerThanContent() throws IOException {
fillContent("222222");
ByteBuffer buffer = ByteBuffer.allocate(16);
assertBufferEquals("0000000000000000", 16, buffer);
assertEquals(6, file.read(0, buffer));
assertBufferEquals("2222220000000000", 10, buffer);
}
public void testNonEmpty_read_all_multipleBuffers_largerThanContent() throws IOException {
fillContent("222222");
ByteBuffer buf1 = ByteBuffer.allocate(4);
ByteBuffer buf2 = ByteBuffer.allocate(8);
assertEquals(6, file.read(0, ImmutableList.of(buf1, buf2)));
assertBufferEquals("2222", 0, buf1);
assertBufferEquals("22000000", 6, buf2);
}
public void testNonEmpty_read_all_multipleBuffers_extraBuffers() throws IOException {
fillContent("222222");
ByteBuffer buf1 = ByteBuffer.allocate(4);
ByteBuffer buf2 = ByteBuffer.allocate(8);
ByteBuffer buf3 = ByteBuffer.allocate(4);
assertEquals(6, file.read(0, ImmutableList.of(buf1, buf2, buf3)));
assertBufferEquals("2222", 0, buf1);
assertBufferEquals("22000000", 6, buf2);
assertBufferEquals("0000", 4, buf3);
}
public void testNonEmpty_read_partial_fromStart_byteArray() throws IOException {
fillContent("222222");
byte[] array = new byte[3];
assertEquals(3, file.read(0, array, 0, array.length));
assertArrayEquals(bytes("222"), array);
array = new byte[10];
assertEquals(3, file.read(0, array, 1, 3));
assertArrayEquals(bytes("0222000000"), array);
}
public void testNonEmpty_read_partial_fromMiddle_byteArray() throws IOException {
fillContent("22223333");
byte[] array = new byte[3];
assertEquals(3, file.read(3, array, 0, array.length));
assertArrayEquals(bytes("233"), array);
array = new byte[10];
assertEquals(3, file.read(3, array, 1, 3));
assertArrayEquals(bytes("0233000000"), array);
}
public void testNonEmpty_read_partial_fromEnd_byteArray() throws IOException {
fillContent("2222222222");
byte[] array = new byte[3];
assertEquals(2, file.read(8, array, 0, array.length));
assertArrayEquals(bytes("220"), array);
array = new byte[10];
assertEquals(2, file.read(8, array, 1, 3));
assertArrayEquals(bytes("0220000000"), array);
}
public void testNonEmpty_read_partial_fromStart_singleBuffer() throws IOException {
fillContent("222222");
ByteBuffer buffer = ByteBuffer.allocate(3);
assertEquals(3, file.read(0, buffer));
assertBufferEquals("222", 0, buffer);
}
public void testNonEmpty_read_partial_fromMiddle_singleBuffer() throws IOException {
fillContent("22223333");
ByteBuffer buffer = ByteBuffer.allocate(3);
assertEquals(3, file.read(3, buffer));
assertBufferEquals("233", 0, buffer);
}
public void testNonEmpty_read_partial_fromEnd_singleBuffer() throws IOException {
fillContent("2222222222");
ByteBuffer buffer = ByteBuffer.allocate(3);
assertEquals(2, file.read(8, buffer));
assertBufferEquals("220", 1, buffer);
}
public void testNonEmpty_read_partial_fromStart_multipleBuffers() throws IOException {
fillContent("12345678");
ByteBuffer buf1 = ByteBuffer.allocate(2);
ByteBuffer buf2 = ByteBuffer.allocate(2);
assertEquals(4, file.read(0, ImmutableList.of(buf1, buf2)));
assertBufferEquals("12", 0, buf1);
assertBufferEquals("34", 0, buf2);
}
public void testNonEmpty_read_partial_fromMiddle_multipleBuffers() throws IOException {
fillContent("12345678");
ByteBuffer buf1 = ByteBuffer.allocate(2);
ByteBuffer buf2 = ByteBuffer.allocate(2);
assertEquals(4, file.read(3, ImmutableList.of(buf1, buf2)));
assertBufferEquals("45", 0, buf1);
assertBufferEquals("67", 0, buf2);
}
public void testNonEmpty_read_partial_fromEnd_multipleBuffers() throws IOException {
fillContent("123456789");
ByteBuffer buf1 = ByteBuffer.allocate(2);
ByteBuffer buf2 = ByteBuffer.allocate(2);
assertEquals(3, file.read(6, ImmutableList.of(buf1, buf2)));
assertBufferEquals("78", 0, buf1);
assertBufferEquals("90", 1, buf2);
}
public void testNonEmpty_read_fromPastEnd_byteArray() throws IOException {
fillContent("123");
byte[] array = new byte[3];
assertEquals(-1, file.read(3, array, 0, array.length));
assertArrayEquals(bytes("000"), array);
assertEquals(-1, file.read(3, array, 0, 2));
assertArrayEquals(bytes("000"), array);
}
public void testNonEmpty_read_fromPastEnd_singleBuffer() throws IOException {
fillContent("123");
ByteBuffer buffer = ByteBuffer.allocate(3);
file.read(3, buffer);
assertBufferEquals("000", 3, buffer);
}
public void testNonEmpty_read_fromPastEnd_multipleBuffers() throws IOException {
fillContent("123");
ByteBuffer buf1 = ByteBuffer.allocate(2);
ByteBuffer buf2 = ByteBuffer.allocate(2);
assertEquals(-1, file.read(6, ImmutableList.of(buf1, buf2)));
assertBufferEquals("00", 2, buf1);
assertBufferEquals("00", 2, buf2);
}
public void testNonEmpty_write_partial_fromStart_singleByte() throws IOException {
fillContent("222222");
assertEquals(1, file.write(0, (byte) 1));
assertContentEquals("122222", file);
}
public void testNonEmpty_write_partial_fromMiddle_singleByte() throws IOException {
fillContent("222222");
assertEquals(1, file.write(3, (byte) 1));
assertContentEquals("222122", file);
}
public void testNonEmpty_write_partial_fromEnd_singleByte() throws IOException {
fillContent("222222");
assertEquals(1, file.write(6, (byte) 1));
assertContentEquals("2222221", file);
}
public void testNonEmpty_write_partial_fromStart_byteArray() throws IOException {
fillContent("222222");
assertEquals(3, file.write(0, bytes("111"), 0, 3));
assertContentEquals("111222", file);
assertEquals(2, file.write(0, bytes("333333"), 0, 2));
assertContentEquals("331222", file);
}
public void testNonEmpty_write_partial_fromMiddle_byteArray() throws IOException {
fillContent("22222222");
assertEquals(3, file.write(3, buffer("111")));
assertContentEquals("22211122", file);
assertEquals(2, file.write(5, bytes("333333"), 1, 2));
assertContentEquals("22211332", file);
}
public void testNonEmpty_write_partial_fromBeforeEnd_byteArray() throws IOException {
fillContent("22222222");
assertEquals(3, file.write(6, bytes("111"), 0, 3));
assertContentEquals("222222111", file);
assertEquals(2, file.write(8, bytes("333333"), 2, 2));
assertContentEquals("2222221133", file);
}
public void testNonEmpty_write_partial_fromEnd_byteArray() throws IOException {
fillContent("222222");
assertEquals(3, file.write(6, bytes("111"), 0, 3));
assertContentEquals("222222111", file);
assertEquals(2, file.write(9, bytes("333333"), 3, 2));
assertContentEquals("22222211133", file);
}
public void testNonEmpty_write_partial_fromPastEnd_byteArray() throws IOException {
fillContent("222222");
assertEquals(3, file.write(8, bytes("111"), 0, 3));
assertContentEquals("22222200111", file);
assertEquals(2, file.write(13, bytes("333333"), 4, 2));
assertContentEquals("222222001110033", file);
}
public void testNonEmpty_write_partial_fromStart_singleBuffer() throws IOException {
fillContent("222222");
assertEquals(3, file.write(0, buffer("111")));
assertContentEquals("111222", file);
}
public void testNonEmpty_write_partial_fromMiddle_singleBuffer() throws IOException {
fillContent("22222222");
assertEquals(3, file.write(3, buffer("111")));
assertContentEquals("22211122", file);
}
public void testNonEmpty_write_partial_fromBeforeEnd_singleBuffer() throws IOException {
fillContent("22222222");
assertEquals(3, file.write(6, buffer("111")));
assertContentEquals("222222111", file);
}
public void testNonEmpty_write_partial_fromEnd_singleBuffer() throws IOException {
fillContent("222222");
assertEquals(3, file.write(6, buffer("111")));
assertContentEquals("222222111", file);
}
public void testNonEmpty_write_partial_fromPastEnd_singleBuffer() throws IOException {
fillContent("222222");
assertEquals(3, file.write(8, buffer("111")));
assertContentEquals("22222200111", file);
}
public void testNonEmpty_write_partial_fromStart_multipleBuffers() throws IOException {
fillContent("222222");
assertEquals(4, file.write(0, buffers("11", "33")));
assertContentEquals("113322", file);
}
public void testNonEmpty_write_partial_fromMiddle_multipleBuffers() throws IOException {
fillContent("22222222");
assertEquals(4, file.write(2, buffers("11", "33")));
assertContentEquals("22113322", file);
}
public void testNonEmpty_write_partial_fromBeforeEnd_multipleBuffers() throws IOException {
fillContent("22222222");
assertEquals(6, file.write(6, buffers("111", "333")));
assertContentEquals("222222111333", file);
}
public void testNonEmpty_write_partial_fromEnd_multipleBuffers() throws IOException {
fillContent("222222");
assertEquals(6, file.write(6, buffers("111", "333")));
assertContentEquals("222222111333", file);
}
public void testNonEmpty_write_partial_fromPastEnd_multipleBuffers() throws IOException {
fillContent("222222");
assertEquals(4, file.write(10, buffers("11", "33")));
assertContentEquals("22222200001133", file);
}
public void testNonEmpty_write_overwrite_sameLength() throws IOException {
fillContent("2222");
assertEquals(4, file.write(0, buffer("1234")));
assertContentEquals("1234", file);
}
public void testNonEmpty_write_overwrite_greaterLength() throws IOException {
fillContent("2222");
assertEquals(8, file.write(0, buffer("12345678")));
assertContentEquals("12345678", file);
}
public void testNonEmpty_transferTo_fromStart_countEqualsSize() throws IOException {
fillContent("123456");
ByteBufferChannel channel = new ByteBufferChannel(10);
assertEquals(6, file.transferTo(0, 6, channel));
assertBufferEquals("1234560000", 4, channel.buffer());
}
public void testNonEmpty_transferTo_fromStart_countLessThanSize() throws IOException {
fillContent("123456");
ByteBufferChannel channel = new ByteBufferChannel(10);
assertEquals(4, file.transferTo(0, 4, channel));
assertBufferEquals("1234000000", 6, channel.buffer());
}
public void testNonEmpty_transferTo_fromMiddle_countEqualsSize() throws IOException {
fillContent("123456");
ByteBufferChannel channel = new ByteBufferChannel(10);
assertEquals(2, file.transferTo(4, 6, channel));
assertBufferEquals("5600000000", 8, channel.buffer());
}
public void testNonEmpty_transferTo_fromMiddle_countLessThanSize() throws IOException {
fillContent("12345678");
ByteBufferChannel channel = new ByteBufferChannel(10);
assertEquals(4, file.transferTo(3, 4, channel));
assertBufferEquals("4567000000", 6, channel.buffer());
}
public void testNonEmpty_transferFrom_toStart_countEqualsSrcSize() throws IOException {
fillContent("22222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("11111"));
assertEquals(5, file.transferFrom(channel, 0, 5));
assertContentEquals("11111222", file);
}
public void testNonEmpty_transferFrom_toStart_countLessThanSrcSize() throws IOException {
fillContent("22222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("11111"));
assertEquals(3, file.transferFrom(channel, 0, 3));
assertContentEquals("11122222", file);
}
public void testNonEmpty_transferFrom_toStart_countGreaterThanSrcSize() throws IOException {
fillContent("22222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("11111"));
assertEquals(5, file.transferFrom(channel, 0, 10));
assertContentEquals("11111222", file);
}
public void testNonEmpty_transferFrom_toMiddle_countEqualsSrcSize() throws IOException {
fillContent("22222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("1111"));
assertEquals(4, file.transferFrom(channel, 2, 4));
assertContentEquals("22111122", file);
}
public void testNonEmpty_transferFrom_toMiddle_countLessThanSrcSize() throws IOException {
fillContent("22222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("11111"));
assertEquals(3, file.transferFrom(channel, 2, 3));
assertContentEquals("22111222", file);
}
public void testNonEmpty_transferFrom_toMiddle_countGreaterThanSrcSize() throws IOException {
fillContent("22222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("1111"));
assertEquals(4, file.transferFrom(channel, 2, 100));
assertContentEquals("22111122", file);
}
public void testNonEmpty_transferFrom_toMiddle_transferGoesBeyondContentSize()
throws IOException {
fillContent("222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("111111"));
assertEquals(6, file.transferFrom(channel, 4, 6));
assertContentEquals("2222111111", file);
}
public void testNonEmpty_transferFrom_toEnd() throws IOException {
fillContent("222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("111111"));
assertEquals(6, file.transferFrom(channel, 6, 6));
assertContentEquals("222222111111", file);
}
public void testNonEmpty_transferFrom_toPastEnd() throws IOException {
fillContent("222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("111111"));
assertEquals(6, file.transferFrom(channel, 10, 6));
assertContentEquals("2222220000111111", file);
}
public void testNonEmpty_transferFrom_hugeOverestimateCount() throws IOException {
fillContent("222222");
ByteBufferChannel channel = new ByteBufferChannel(buffer("111111"));
assertEquals(6, file.transferFrom(channel, 6, 1024 * 1024 * 10));
assertContentEquals("222222111111", file);
}
public void testNonEmpty_copy() throws IOException {
fillContent("123456");
RegularFile copy = file.copyWithoutContent(1);
file.copyContentTo(copy);
assertContentEquals("123456", copy);
}
public void testNonEmpty_copy_multipleTimes() throws IOException {
fillContent("123456");
RegularFile copy = file.copyWithoutContent(1);
file.copyContentTo(copy);
RegularFile copy2 = copy.copyWithoutContent(2);
copy.copyContentTo(copy2);
assertContentEquals("123456", copy);
}
public void testNonEmpty_truncate_toZero() throws IOException {
fillContent("123456");
file.truncate(0);
assertContentEquals("", file);
}
public void testNonEmpty_truncate_partial() throws IOException {
fillContent("12345678");
file.truncate(5);
assertContentEquals("12345", file);
}
public void testNonEmpty_truncate_sizeUp() throws IOException {
fillContent("123456");
file.truncate(12);
assertContentEquals("123456", file);
}
public void testDeletedStoreRemainsUsableWhileOpen() throws IOException {
byte[] bytes = bytes("1234567890");
file.write(0, bytes, 0, bytes.length);
file.opened();
file.opened();
file.deleted();
assertContentEquals(bytes, file);
byte[] moreBytes = bytes("1234");
file.write(bytes.length, moreBytes, 0, 4);
byte[] totalBytes = concat(bytes, bytes("1234"));
assertContentEquals(totalBytes, file);
file.closed();
assertContentEquals(totalBytes, file);
file.closed();
// don't check anything else; no guarantee of what if anything will happen once the file is
// deleted and completely closed
}
private static void assertBufferEquals(String expected, ByteBuffer actual) {
assertEquals(expected.length(), actual.capacity());
assertArrayEquals(bytes(expected), actual.array());
}
private static void assertBufferEquals(String expected, int remaining, ByteBuffer actual) {
assertBufferEquals(expected, actual);
assertEquals(remaining, actual.remaining());
}
private static void assertContentEquals(String expected, RegularFile actual) {
assertContentEquals(bytes(expected), actual);
}
protected static void assertContentEquals(byte[] expected, RegularFile actual) {
assertEquals(expected.length, actual.sizeWithoutLocking());
byte[] actualBytes = new byte[(int) actual.sizeWithoutLocking()];
actual.read(0, ByteBuffer.wrap(actualBytes));
assertArrayEquals(expected, actualBytes);
}
}
}
| [
"cgdecker@google.com"
] | cgdecker@google.com |
3bc2442261eef69e47f0a411d369a3b162f38b64 | adc238ed73e97eb197ac26b8d7994e4062c676ca | /CollectionsSessions/src/HackerRank/Sorting/BubbleSort.java | c2538fe44b9c8468ed1207fb0ada7093ee5645e1 | [] | no_license | Bhavyasri-1395/MyFirstCommitInGitHub | 8d6734541410e2392d32243ffb493d787096259e | 8b1b0e13c847d43ceb06bb367775dfca30b5cb07 | refs/heads/master | 2022-12-28T16:18:00.098197 | 2019-06-29T07:28:00 | 2019-06-29T07:28:00 | 194,374,934 | 0 | 0 | null | 2022-12-16T01:53:45 | 2019-06-29T06:57:32 | Java | UTF-8 | Java | false | false | 763 | java | package HackerRank.Sorting;
import java.util.Scanner;
public class BubbleSort {
// Complete the countSwaps function below.
static void countSwaps(int[] a) {
int numberOfExchanges = 0;
for(int i=1;i<a.length;i++) {
int check = 0;
for(int j = 0;j<a.length-i;j++) {
if(a[j]>a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
numberOfExchanges++;
check++;
}
}
if(check == 0) {
break;
}
}
System.out.println("Array is sorted in "+numberOfExchanges+" swaps.");
System.out.println("First Element: "+a[0]);
System.out.println("Last Element: "+a[a.length-1]);
}
public static void main(String[] args) {
int[] arr = {1,3,5,2,4,6,7};
countSwaps(arr);
}
}
| [
"bhavyasri koora@bhavyasri"
] | bhavyasri koora@bhavyasri |
eb678b9c67be426154f1e36f8a17f7e012f435c2 | 3da92102512bbeed7449a269030fd1956ca0163b | /app/src/main/java/com/example/timz/belajarlist/MainActivity.java | f7e68a6622980e483195f06b7975bd03e6fce74b | [] | no_license | asidosibuea/BelajarList | 9d86cf9cb77dac66c51a4c36292e764ae1b5c139 | 033d92b89b1e270a7b5b8ae4ab3381da17caa722 | refs/heads/master | 2021-08-14T16:32:05.173783 | 2017-11-16T06:58:59 | 2017-11-16T06:58:59 | 110,935,357 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,639 | java | package com.example.timz.belajarlist;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//data yang harus ditampilkan dibentuk objeknya
//dimasukan ke dalam array list
final ArrayList<Makanan> daftar_makanan = new ArrayList<>();
// Makanan m1 = new Makanan(R.drawable.ic_thumb_up_black_48dp,"Rendang",1200);
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_up_black_48dp, "Rendang", 12000));
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_up_black_48dp, "Ayam Geprek Pedas", 14000));
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_down_black_48dp, "Mir Sedap White Curry", 6000));
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_up_black_48dp, "Ayam Suwir", 1000));
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_up_black_48dp, "Ayam Nuklir", 14000));
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_up_black_48dp, "Nasi Kolor", 8000));
daftar_makanan.add(new Makanan(R.drawable.ic_thumb_down_black_48dp, "Mie Indomie Cabe Ijo", 6000));
//bentuk makanan adapter
MakananAdapter adapter = new MakananAdapter(this, daftar_makanan);
ListView lv_makanan = (ListView) findViewById(R.id.lv_makanan);
lv_makanan.setAdapter(adapter);
//tambahkan onItemClickListener kepada List View
lv_makanan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Makanan m = daftar_makanan.get(i);
String nama_makanan = m.getNama();
Toast.makeText(getApplicationContext(), nama_makanan, Toast.LENGTH_LONG).show();
}
});
public void keluar (View view) {
SharedPreferences sharedPreferences = getSharedPreferences("data_login", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = sharedPreferences.edit();
spEditor.clear();
spEditor.commit();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
| [
"sibuea.asido@gmail.com"
] | sibuea.asido@gmail.com |
1a4925cb55d1ac58bc2f4bcf9a2fec86ae09cfbc | 81b0bb3cfb2e9501f53451e7f03ec072ee2b0e13 | /src/me/lyft/android/services/DriverShortcutService.java | ead66037e98ff3f2d8087746d96a433fedc1fb9c | [] | no_license | reverseengineeringer/me.lyft.android | 48bb85e8693ce4dab50185424d2ec51debf5c243 | 8c26caeeb54ffbde0711d3ce8b187480d84968ef | refs/heads/master | 2021-01-19T02:32:03.752176 | 2016-07-19T16:30:00 | 2016-07-19T16:30:00 | 63,710,356 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,964 | java | package me.lyft.android.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Binder;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import com.lyft.scoop.Screen;
import java.lang.ref.WeakReference;
import javax.inject.Inject;
import me.lyft.android.ILyftPreferences;
import me.lyft.android.LyftApplication;
import me.lyft.android.analytics.studies.DriverAnalytics;
import me.lyft.android.application.IUserProvider;
import me.lyft.android.application.payment.IPricingService;
import me.lyft.android.application.ride.IUserUiService;
import me.lyft.android.common.AppFlow;
import me.lyft.android.common.Unit;
import me.lyft.android.domain.User;
import me.lyft.android.domain.driver.UiState;
import me.lyft.android.domain.passenger.ridetypes.Pricing;
import me.lyft.android.rx.IRxBinder;
import me.lyft.android.rx.RxUIBinder;
import me.lyft.android.ui.MainActivity;
import me.lyft.android.ui.MainScreens.DriverRideScreen;
import me.lyft.android.ui.driver.shortcut.ChatheadView;
import me.lyft.android.ui.driver.shortcut.FloatingViewListener;
import me.lyft.android.ui.driver.shortcut.FloatingViewManager;
import me.lyft.android.ui.driver.shortcut.FloatingViewManager.Options;
import me.lyft.android.utils.MetricsUtils;
import rx.Observable;
import rx.functions.Action1;
public class DriverShortcutService
extends Service
implements FloatingViewListener
{
@Inject
AppFlow appFlow;
private final IRxBinder binder = new RxUIBinder();
private IBinder chatheadServiceBinder;
private ChatheadView chatheadView;
private FloatingViewManager floatingViewManager;
@Inject
ILyftPreferences lyftPreferences;
private Action1<Unit> onPrimeTimeChanged = new Action1()
{
public void call(Unit paramAnonymousUnit)
{
paramAnonymousUnit = userProvider.getUser();
Pricing localPricing = primeTimeService.getPricing();
if (paramAnonymousUnit.isDispatchable())
{
chatheadView.showDispatchable();
floatingViewManager.setExtraCenterY(getResources().getDimension(2131230872));
return;
}
if (localPricing.hasDynamicPricing())
{
chatheadView.showPrimeTime(getResources().getString(2131165668, new Object[] { localPricing.getDynamicPricing() }));
floatingViewManager.setExtraCenterY(getResources().getDimension(2131230872));
return;
}
chatheadView.hidePrimetime();
floatingViewManager.setExtraCenterY(getResources().getDimension(2131230855));
}
};
private Action1<User> onUserChanged = new Action1()
{
public void call(User paramAnonymousUser)
{
DriverShortcutService.this.setFixedActionIconImage();
}
};
@Inject
IPricingService primeTimeService;
@Inject
IUserProvider userProvider;
@Inject
IUserUiService userUiService;
private void bringAppToForeground(String paramString)
{
MainActivity.foregroundActivity(this, paramString);
}
private void destroy()
{
if (floatingViewManager != null)
{
floatingViewManager.removeAllViewToWindow();
floatingViewManager = null;
}
}
private void setFixedActionIconImage()
{
if (userProvider.getUser().isDispatchable())
{
floatingViewManager.updateModeToggleView(2130838195, getResources().getString(2131165734));
return;
}
floatingViewManager.updateModeToggleView(2130838382, getResources().getString(2131165735));
}
public static void startService(Context paramContext)
{
paramContext.startService(new Intent(paramContext, DriverShortcutService.class));
}
public static void stopService(Context paramContext)
{
paramContext.stopService(new Intent(paramContext, DriverShortcutService.class));
}
protected LyftApplication getLyftApplication()
{
return (LyftApplication)getApplication();
}
public IBinder onBind(Intent paramIntent)
{
return chatheadServiceBinder;
}
public void onCreate()
{
super.onCreate();
binder.attach();
getLyftApplication().inject(this);
}
public void onDestroy()
{
destroy();
binder.detach();
super.onDestroy();
}
public void onFinishFloatingView()
{
stopSelf();
}
public void onModeToggleActionUp()
{
User localUser = userProvider.getUser();
userUiService.updateUiState(new UiState(true));
MainScreens.DriverRideScreen localDriverRideScreen = new MainScreens.DriverRideScreen();
if (localUser.isDispatchable()) {
localDriverRideScreen.enableGoOffline();
}
for (;;)
{
appFlow.replaceAllWith(new Screen[] { localDriverRideScreen });
bringAppToForeground("switch_mode");
return;
localDriverRideScreen.enableGoOnline();
}
}
public void onSingleTapUp(MotionEvent paramMotionEvent)
{
DriverAnalytics.trackDriverDefenseButtonTap();
bringAppToForeground("driver_toggle_tap");
stopSelf();
}
public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2)
{
if (floatingViewManager != null) {
return 1;
}
paramIntent = MetricsUtils.fromContext(this);
chatheadServiceBinder = new DriverShortcutServiceBinder(this);
chatheadView = ((ChatheadView)LayoutInflater.from(this).inflate(2130903093, null, false));
floatingViewManager = new FloatingViewManager(this, this);
floatingViewManager.setFixedActionIconImage(2130838145);
floatingViewManager.setModeToggleViewIcon(2130838044);
floatingViewManager.setTrashViewIcon(2130837665);
setFixedActionIconImage();
FloatingViewManager.Options localOptions = new FloatingViewManager.Options();
shape = 1.0F;
overMargin = paramIntent.dpToPixels(getResources().getDimension(2131230863));
floatingViewManager.addViewToWindow(chatheadView, localOptions);
new IntentFilter("android.intent.action.SCREEN_OFF").addAction("android.intent.action.USER_PRESENT");
binder.bindAction(userProvider.observeUserUpdates(), onUserChanged);
binder.bindAction(Observable.combineLatest(primeTimeService.observePricingUpdates(), userProvider.observeUserUpdates(), Unit.func2()), onPrimeTimeChanged);
return 3;
}
public void onTrashActionUp()
{
lyftPreferences.setDriverShortcutEnabled(false);
}
public static class DriverShortcutServiceBinder
extends Binder
{
private final WeakReference<DriverShortcutService> service;
DriverShortcutServiceBinder(DriverShortcutService paramDriverShortcutService)
{
service = new WeakReference(paramDriverShortcutService);
}
public DriverShortcutService getService()
{
return (DriverShortcutService)service.get();
}
}
}
/* Location:
* Qualified Name: me.lyft.android.services.DriverShortcutService
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"reverseengineeringer@hackeradmin.com"
] | reverseengineeringer@hackeradmin.com |
ba4e8beb1583e994fbc726c54bb492b13cd86e46 | a2882bf846726b4b36193afad8566f1af4807893 | /app/src/main/java/com/tubes/sandangin/CameraOperation.java | 0cf66631d1618b330602f3969e21c2a4c59d1764 | [] | no_license | simositus/PBP_UTS_B_KelK | 480547aa3fbe7ee03b7804d4642d42e47d3e5c3b | f92be12989c432eba5cfeb5c0425ad4aaeca9427 | refs/heads/master | 2022-12-28T12:11:08.094774 | 2020-10-12T14:58:42 | 2020-10-12T14:58:42 | 303,425,472 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,069 | java | package com.tubes.sandangin;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
public class CameraOperation extends AppCompatActivity implements SensorEventListener, EasyPermissions.PermissionCallbacks{
//Accelerometer
private long lastUpdate=0;
private float last_x,last_y,last_z;
private static final int SHAKE_THRESHOLD=600;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private static final String TAG = "Camera Operation";
private static final int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_operation);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
CameraPermission();
}
@Override
public void onSensorChanged(@NonNull SensorEvent sensorEvent){
Sensor mySensor = sensorEvent.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER){
float x = sensorEvent.values[0];
float y = sensorEvent.values[0];
float z = sensorEvent.values[0];
long curTime = System.currentTimeMillis();
if ((curTime-lastUpdate)>100){
long diffTime = (curTime-lastUpdate);
lastUpdate = curTime;
float speed = Math.abs(x+y+z-last_x-last_y-last_z)/diffTime*10000;
if (speed>SHAKE_THRESHOLD){
Toast.makeText(getApplicationContext(), "SHAKE", Toast.LENGTH_SHORT).show();
Log.d("key", "asd");
Intent i = new Intent(CameraOperation.this, CameraActivity.class);
startActivity(i);
}
last_x=x;
last_y=y;
last_z=z;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy){
}
public void onResume(){
super.onResume();
mSensorManager.registerListener(this,mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onPause(){
super.onPause();
mSensorManager.unregisterListener(this);
}
// @SuppressLint("MissingPermission")
@AfterPermissionGranted(REQUEST_CODE)
private void CameraPermission(){
// Log.d(TAG, "cameraPermission: asking user for permission");
String[] permission = {Manifest.permission.CAMERA};
if(EasyPermissions.hasPermissions(this, permission)){
Toast.makeText(this, "Kamera Siap Pakai", Toast.LENGTH_SHORT).show();
}else {
EasyPermissions.requestPermissions(this, "Kamera Gagal Diakses",
REQUEST_CODE, permission);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(REQUEST_CODE, permissions,grantResults,this);
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)){
new AppSettingsDialog.Builder(this).build().show();
}
}
}
| [
"timotiust9@gmail.com"
] | timotiust9@gmail.com |
a368f6badfdb87647d975e41c8216fb9a414d445 | 9ef8a81c8c9bfedb0169293eff241a8a4e51207f | /java/Thread/T2.java | 98985896c9d494f2eebd4e7faf273ba19d1305a7 | [] | no_license | raghvendru/MY-PROGRAMS | 5b20938c22a491fa67dd5b5bc27b57f448f03095 | e9562311187b5f031f2a44569cf40b4523fb704f | refs/heads/master | 2023-06-25T12:38:47.715653 | 2021-07-25T12:09:29 | 2021-07-25T12:09:29 | 389,329,098 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 277 | java | import java.lang.Thread;
public class T2 extends Thread {
public void run() {
System.out.println("In thread class T2");
for (int i = 1 ; i < 5 ; i++) {
System.out.println("t2 i is " + i);
}
System.out.println("Exit T2");
}
}
| [
"raghavendruppar@gmail.com"
] | raghavendruppar@gmail.com |
ec2c240f039cbd92fdcd831dfb6881131b818da5 | 2ab596ab4fa057a143deeac5e38215ee2d70dc0d | /src/main/java/ru/jakimenko/tool/task/RabbitTask.java | 61779df88b314f1fc8c941b41940a6d78ce9dfc5 | [] | no_license | konstantin-yakimenko/rabbit-test-utils | 9cf759e5d46af3213959d0389329495b9ff9f004 | e8c88e363218c0e2ee2eb718885b097668a4d2ba | refs/heads/master | 2021-01-11T15:21:12.461843 | 2017-01-29T10:41:13 | 2017-01-29T10:41:13 | 80,340,138 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,694 | java | package ru.jakimenko.tool.task;
import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import com.rabbitmq.client.Channel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
/**
*
* @author kyyakime
*/
public class RabbitTask extends Task {
private final static Logger LOG = LogManager.getLogger();
private final RabbitTemplate taskTemplate;
private final RabbitTemplate waitTemplate;
private final RabbitTemplate rejectTemplate;
private final String waitQueueName;
private volatile boolean running = false;
public RabbitTask(RabbitTemplate taskTemplate, RabbitTemplate waitTemplate, String waitQueueName,
String name, String cron, boolean autoStart, RabbitTemplate rejectTemplate) {
super(name, cron, autoStart);
this.taskTemplate = taskTemplate;
this.waitTemplate = waitTemplate;
this.waitQueueName = waitQueueName;
this.rejectTemplate = rejectTemplate;
}
@Override
public void run() {
if (isActive() && !running) {
start();
}
}
public void process() {
if (running) {
stop();
} else {
start();
}
}
public boolean isRunning() {
return running;
}
private void start() {
try {
running = true;
int count = getMessageCount();
for (int i=0; running && i<count; i++) {
Object message = waitTemplate.receiveAndConvert(waitQueueName);
if (message==null) {
break;
}
taskTemplate.convertAndSend(message);
}
} catch (Exception ex) {
LOG.error("Error in rabbit task", ex);
} finally {
running = false;
}
}
private void stop() {
running = false;
}
private int getMessageCount() {
DeclareOk declareOk = waitTemplate.execute((Channel channel) -> channel.queueDeclarePassive(waitQueueName));
return declareOk.getMessageCount();
}
private int getMessageCountReject() {
DeclareOk declareOk = rejectTemplate.execute((Channel channel) -> channel.queueDeclarePassive("queue.mytest.wait.reject"));
return declareOk.getMessageCount();
}
private void clearReject() throws Exception {
int count = getMessageCountReject();
for (int i=0; running && i<count; i++) {
Object message = rejectTemplate.receiveAndConvert("queue.mytest.wait.reject");
}
}
}
| [
"jakimenko.k@gmail.com"
] | jakimenko.k@gmail.com |
ecde972aaee28a607089d4be08d61911e10c6119 | bc5e147708d3961b09458cc3d3cc0916c3d9fb2d | /src/moduls/gestioUsuaris/model/bll/GUBLL.java | a0bda25640d96a433a87168fbd7def581f766a82 | [] | no_license | vicentlozada/programacio | c5648d7af0a0ad5b5e8e2d8c6cac33c93b6372b6 | 77e584e3ac62814de3aea2cc94c53f1bc243be50 | refs/heads/master | 2021-01-02T08:47:06.625549 | 2015-06-04T17:57:37 | 2015-06-04T17:57:37 | 35,835,576 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,999 | java | /*
* 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 moduls.gestioUsuaris.model.bll;
import classes.Connexio;
import java.sql.Connection;
import llibreries.Encriptar;
import static moduls.gestioInici.controlador.ControladorInici.frmMail;
import static moduls.gestioInici.controlador.ControladorInici.frmSignIn;
import static moduls.gestioUsuaris.controlador.ControladorUsuaris.frmUsuari;
import moduls.gestioUsuaris.model.classes.SingletonUsuari;
import moduls.gestioUsuaris.model.dao.GUDAOBd;
import moduls.gestioUsuaris.model.dao.GUDAOGrafic;
import utils.Funcions;
import utils.Menus;
/**
*
* @author Vicent
*/
public class GUBLL {
public static void cercarUsuari() {
int pos = buscarLoginUsuari();
if (pos != -1) {
SingletonUsuari.us = SingletonUsuari.usAl.get(pos);
}
}
public static int buscarLoginUsuari() {
int pos = -1;
for (int i = 0; i < SingletonUsuari.usAl.size(); i++) {
if ((SingletonUsuari.usAl.get(i)).equals(SingletonUsuari.us)) {
pos = i;
}
}
return pos;
}
public static void omplirCampsMBLL(){
GUDAOGrafic.omplirCampsMDAO();
}
public static void activaUsuariBLL(byte estat) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.activaUsuariDAO(estat, conn) == 1) {
Connexio.desconnectar(conn);
}
}
}
public static boolean cercarDniBLL(String dni) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.cercarDniDAO(dni, conn)) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean cercarUsuariBLL(String usuari) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.cercarUsuariDAO(usuari, conn)) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean cercarEmailBLL(String email) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.cercarEmailDAO(email, conn)) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
// 0
public static void validarUsuari_0BLL() {
GUDAOGrafic.validarUsuari_0DAO();
}
public static void validarContrassenya_0BLL() {
GUDAOGrafic.validarContrassenya_0DAO();
}
public static void demanaUsuari_0BLL() {
if (GUDAOGrafic.validarUsuari_0DAO()) {
frmSignIn.txtPassword.requestFocus();
}
}
public static void demanaContrassenya_0BLL() {
if (GUDAOGrafic.validarContrassenya_0DAO()) {
frmSignIn.btnIniciSessio.requestFocus();
}
}
public static boolean validaUsuariPasswordBLL(String usuari, String pass) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.validarUsuariPasswordDAO(usuari, pass, conn)) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean validarEmailRecordarPass() {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.validarUsuariEmailDAO(frmMail.txtEmail.getText(), conn)) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean recordarDadesBLL() {
if (validarEmailRecordarPass()) {
String novaContrassenaya = Funcions.getCadenaAleatoria1(9);
String Token = Funcions.getCadenaAleatoria3(24);
String missatge = "Contrassenya: " + novaContrassenaya + " " + "Token: " + Token;
String passEncriptat = Encriptar.encriptarTokenMD5(novaContrassenaya);
modificarPassBLL(passEncriptat);
//new Thread(new Job(SingletonInici.user_mail, SingletonInici.pass_mail,
// frmMail.txtEmail.getText(), SingletonInici.assumpte, missatge)).start();
//new Thread(new JcThread(frmMail.barProgressBar, 50)).start();
Menus.information(missatge, Token);
return true;
} else {
Menus.warning("Correu electrònic no registrat!", "Recordar dades");
}
return false;
}
public static boolean modificarPassBLL(String pass) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.modificarPassDAO(pass, conn) == 1) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean modificarPass() {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.updateUsuariDAOBd(conn) == 1) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean eliminarUS() {
int pos = buscarLoginUsuari();
String login = SingletonUsuari.usAl.get(pos).getLogin();
Boolean correcte = Menus.confirmar("Eliminar\n" + login + "?", "Eliminar Usuari");
if (correcte) {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.eliminarUsuariDAOBd(login, conn) == 1) {
Connexio.desconnectar(conn);
return true;
}
}
}
return false;
}
public static int posicioAbsolutaBLL(){
return GUDAOGrafic.posicioAbsolutaDAOGrafic();
}
//-------------------------------------------------------------------
public static boolean validarUsuariBLL() {
return GUDAOGrafic.validarUsuariDAO();
}
public static boolean validarContrassenyaBLL() {
return GUDAOGrafic.validarContrassenyaDAO();
}
public static boolean validarDniBLL() {
return GUDAOGrafic.validarDniDAO();
}
public static boolean validarNomBLL() {
return GUDAOGrafic.validarNomDAO();
}
public static boolean validarEmailBLL() {
return GUDAOGrafic.validarEmailDAO();
}
public static void demanaUsuariBLL() {
if (validarUsuariBLL()) {
if (GUDAOGrafic.demanaUsuariDAO()) {
frmUsuari.txtPassword.requestFocus();
}
}
}
public static void demanaContrassenyaBLL() {
if (validarContrassenyaBLL()) {
frmUsuari.txtDni.requestFocus();
}
}
public static void demanaDniBLL() {
if (validarDniBLL()) {
if (GUDAOGrafic.demanaDniDAO()) {
frmUsuari.txtNom.requestFocus();
}
}
}
public static void demanaNomBLL() {
if (validarNomBLL()) {
frmUsuari.txtEmail.requestFocus();
}
}
public static void demanaEmailBLL() {
if (validarEmailBLL()) {
frmUsuari.cmbTipusUsuari.requestFocus();
}
}
public static boolean modificarUsuariBLL() {
if (GUDAOGrafic.modificarUsuariDAOGrafic()) {
if (updateUsuariBLL()) {
return true;
}
}
return false;
}
public static boolean updateUsuariBLL() {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.updateUsuariDAOBd(conn) == 1) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static boolean afegirUsuariBLL() {
if (GUDAOGrafic.afegirUsuariDAOGrafic()) {
if (insertUsuariBLL()) {
return true;
}
}
return false;
}
public static boolean insertUsuariBLL() {
Connection conn = Connexio.connectar();
if (conn != null) {
if (GUDAOBd.insertUsuariDAOBd(conn) == 1) {
Connexio.desconnectar(conn);
return true;
}
}
return false;
}
public static void setAmpleColumnesBLL(){
GUDAOGrafic.setAmpleColumnesDAOGrafic();
}
}
| [
"vicentlozada@gmail.com"
] | vicentlozada@gmail.com |
fecae7181afd734e24187fc77d545ac0813103ae | a5d01febfd8d45a61f815b6f5ed447e25fad4959 | /Source Code/5.5.1/sources/com/google/android/gms/analytics/zzd.java | df2b94aa6d87967ef9279650ce5ed34867daafd0 | [] | no_license | kkagill/Decompiler-IQ-Option | 7fe5911f90ed2490687f5d216cb2940f07b57194 | c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6 | refs/heads/master | 2020-09-14T20:44:49.115289 | 2019-11-04T06:58:55 | 2019-11-04T06:58:55 | 223,236,327 | 1 | 0 | null | 2019-11-21T18:17:17 | 2019-11-21T18:17:16 | null | UTF-8 | Java | false | false | 1,611 | java | package com.google.android.gms.analytics;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.common.internal.Hide;
import com.google.android.gms.internal.zzatc;
@Hide
public final class zzd {
public static String zzai(int i) {
return zzc("&cd", i);
}
public static String zzaj(int i) {
return zzc("cd", i);
}
public static String zzak(int i) {
return zzc("&cm", i);
}
public static String zzal(int i) {
return zzc("cm", i);
}
public static String zzam(int i) {
return zzc("&pr", i);
}
public static String zzan(int i) {
return zzc("pr", i);
}
public static String zzao(int i) {
return zzc("&promo", i);
}
public static String zzap(int i) {
return zzc(NotificationCompat.CATEGORY_PROMO, i);
}
public static String zzaq(int i) {
return zzc("pi", i);
}
public static String zzar(int i) {
return zzc("&il", i);
}
public static String zzas(int i) {
return zzc("il", i);
}
public static String zzat(int i) {
return zzc("cd", i);
}
public static String zzau(int i) {
return zzc("cm", i);
}
private static String zzc(String str, int i) {
if (i <= 0) {
zzatc.zzf("index out of range for prefix", str);
return "";
}
StringBuilder stringBuilder = new StringBuilder(String.valueOf(str).length() + 11);
stringBuilder.append(str);
stringBuilder.append(i);
return stringBuilder.toString();
}
}
| [
"yihsun1992@gmail.com"
] | yihsun1992@gmail.com |
63693072fe5802ee689b014a58029d8de4bb60f8 | dc614b1b35a67fdb3f6daaa72e7c41c7bca52245 | /app/src/main/java/com/sunc/view/TouchIndicator.java | 088132e5c9879304e719dc62023c8ceefb655c09 | [] | no_license | wukongGit/lovecar | d9289dd9979a5402198ae76c508d1a21f4a5467d | 959136c0492ff8de52d3fde88438093fe43a7067 | refs/heads/master | 2021-09-05T21:40:17.442979 | 2018-01-31T06:29:28 | 2018-01-31T06:29:28 | 116,206,051 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 866 | java | package com.sunc.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by Administrator on 2017/9/23.
*/
public class TouchIndicator extends View {
TouchIndicatorListener mTouchIndicatorListener;
public TouchIndicator(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public void setTouchIndicatorListener(TouchIndicatorListener listener) {
mTouchIndicatorListener = listener;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if(mTouchIndicatorListener != null) {
mTouchIndicatorListener.touched();
}
return false;
}
public interface TouchIndicatorListener {
void touched();
}
}
| [
"sunchenggx@163.com"
] | sunchenggx@163.com |
e6af15e01bd3582f55ece49faa328a91fc80c38f | edf3bb1d980b0ae983cdae5156a4ab6ca8918f18 | /app/src/main/java/com/sonymobile/dronecontrol/utils/Notifier.java | 872e08cd1ee3b345590b21b474c6d365323f47f0 | [
"BSD-3-Clause"
] | permissive | sonyxperiadev/DroneControl | 2c0fbb17d6f390084fa2de094141d8a68f096af9 | f447d712d32ad2a492dc10dbb8684bccd8779a95 | refs/heads/master | 2020-04-09T16:26:19.448382 | 2015-08-31T04:31:40 | 2015-09-02T11:55:52 | 41,371,349 | 9 | 6 | null | null | null | null | UTF-8 | Java | false | false | 2,818 | java | /*
* Copyright (C) 2015 Sony Mobile Communications Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sonymobile.dronecontrol.utils;
import com.sonymobile.dronecontrol.controller.DeviceControllerListener;
import com.sonymobile.dronecontrol.controller.DeviceListenerHandler;
import android.os.Handler;
import android.os.Looper;
import java.util.ArrayList;
import java.util.List;
/**
* Class to notify all listeners registered in a specified list. This is
* prepared to iterate while the list is being modified.
*/
public abstract class Notifier {
protected abstract void onNotify(final DeviceControllerListener listener);
public Notifier() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
notifyListeners();
}
});
}
private void notifyListeners() {
List<DeviceControllerListener> listenersList = new ArrayList<DeviceControllerListener>(DeviceListenerHandler.sRegisteredListeners);
if ((listenersList != null) && !listenersList.isEmpty()) {
for (DeviceControllerListener object : listenersList) {
if (object != null) {
onNotify(object);
}
}
}
}
}
| [
"sylviojalves@gmail.com"
] | sylviojalves@gmail.com |
034e857df3f33b5e74ed75272c90336684af2f0e | ca7a8d435c5e169edad8a707ff7bccf7d6f68928 | /src/classes/BarraDeProgresso.java | e6c3d293caf6106488c27538eccdeb499042a0e4 | [] | no_license | cafeamerica/CafeAmerica3 | bef342e7c0acd940b874e578e065aef747cf24a1 | 068e0ffe1ee57696f2db25ab932d1a2af7f695a1 | refs/heads/master | 2016-09-01T20:11:40.942636 | 2014-12-12T16:56:00 | 2014-12-12T16:56:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,390 | java | /*
* 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 classes;
import javax.swing.JProgressBar;
/**
*
* @author Rafael
*/
public class BarraDeProgresso implements Runnable {
private static JProgressBar jpb;
private boolean interrupted = false;
private static boolean valor;
public BarraDeProgresso() {
}
public void setProgressBar(JProgressBar jpb) {
this.jpb = jpb;
}
public void setInterrupted (boolean interrupted) {
this.interrupted = interrupted;
}
public static void setValor(boolean valor) {
BarraDeProgresso.valor = valor;
}
public static void zeraJpb(){
jpb.setString("");
jpb.setValue(0);
}
public void run() {
valor = false;
jpb.setStringPainted(true);
for (int i = 0; i<10000; ++i) {
try { Thread.sleep (100); } catch (InterruptedException ex) {}
jpb.setValue (i);
jpb.setString(i+"%");
if(valor == true){
jpb.setString("100%");
jpb.setValue(100);
break;
}
}
}
}
| [
""
] | |
2b6baf4848ad1f9682e24eb61cc0469ffe73cdbf | 34ee973e1747402742b2678d2f665cfb256f930a | /src/Mercury/Controllers/Controller.java | 3db1398fe046adc564e8b31c8e2d2f4bae8afd24 | [] | no_license | rphlmnbt/mercury-app | bfc75fe43b1b8f0d3d3409d4bf472e7a46a3c360 | 7733015acf7d78314155899a045763d34586e8e8 | refs/heads/master | 2022-12-13T16:36:46.631333 | 2020-09-09T05:50:52 | 2020-09-09T05:50:52 | 294,015,051 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,884 | java | package Mercury.Controllers;
import Mercury.Model.User;
import Mercury.Services.UserServices;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.stage.*;
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ResourceBundle;
public class Controller implements Initializable{
@FXML
private Pane regPane;
@FXML
private Pane loginPane;
@FXML
private TextField userReg;
@FXML
private TextField nameReg;
@FXML
private PasswordField passReg;
@FXML
private TextField userField;
@FXML
private PasswordField passField;
@FXML
private Pane mainMenu;
@FXML
private Pane updateScreen;
@FXML
private TextField updateUserField;
@FXML
private PasswordField updatePassField;
@FXML
private TextField updateNameField;
@FXML
private TextField userCredentials;
@FXML
private PasswordField passCredentials;
@FXML
private TitledPane deleteScreen;
@FXML
private TextField deleteUserCred;
@FXML
private PasswordField deletePassCred;
@FXML
private TextField searchID;
@FXML
private Label ID;
@FXML
private Label username;
@FXML
private Label name;
@FXML
private Pane searchScreen;
@FXML
private Label currentId;
@FXML
private Label currentUser;
@FXML
private Pane listScreen;
@FXML
private ListView<User> listView;
@FXML
private ImageView userPic;
@FXML
private ImageView userPicUpdate;
@FXML
private ImageView userPicSearch;
private ObservableList<User> userObservableList;
private String filePath;
private File defaultPicFile = new File("./src/Mercury/MercuryResources/UserIcon.png");
private Image defaultPic = new Image(defaultPicFile.toURI().toString(),150,150,false,true,true);
public Controller() {
try {
UserServices us = new UserServices();
userObservableList = FXCollections.observableArrayList();
for (User user : us.listUsers()){
userObservableList.add(user);
}
} catch (Exception e) {
System.out.println("E Controller");
e.printStackTrace();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
listView.setItems(userObservableList);
listView.setCellFactory(userListView -> new UserListViewCell(currentUser.getText()));
}
public void refresh() {
try {
UserServices us = new UserServices();
userObservableList = FXCollections.observableArrayList();
for (User user : us.listUsers()){
userObservableList.add(user);
}
listView.setItems(userObservableList);
listView.setCellFactory(userListView -> new UserListViewCell(currentUser.getText()));
} catch (Exception e) {
System.out.println("E refresh");
e.printStackTrace();
}
}
public void openInbox() {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("../Mercury_Inbox.fxml"));
Parent root = loader.load();
InboxController inboxController = loader.getController();
inboxController.setReceiver(currentUser.getText());
Stage stage = new Stage();
stage.getIcons().add(new Image("Mercury/MercuryResources/logo.png"));
stage.setScene(new Scene(root));
stage.setTitle("Inbox");
stage.show();
} catch (IOException e) {
System.out.println("IOE openInbox");
e.printStackTrace();
}
}
public void openOutbox() {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("../Mercury_Outbox.fxml"));
Parent root = loader.load();
OutboxController outboxController = loader.getController();
outboxController.setSender(currentUser.getText());
Stage stage = new Stage();
stage.getIcons().add(new Image("Mercury/MercuryResources/logo.png"));
stage.setScene(new Scene(root));
stage.setTitle("Outbox");
stage.show();
} catch (IOException e) {
System.out.println("IOE openInbox");
e.printStackTrace();
}
}
public void attachFile() {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extensionPng = new FileChooser.ExtensionFilter("PNG FILES (*.png", ".png");
File file = fileChooser.showOpenDialog(null);
this.filePath = file.getAbsolutePath();
Image image = new Image(file.toURI().toString(), 150, 150, false, true,true);
userPic.setImage(image);
userPicUpdate.setImage(image);
userPicSearch.setImage(image);
}
public void showList() {
mainMenu.setVisible(false);
listScreen.setVisible(true);
}
public void showSendScreen() {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("../Mercury_Send.fxml"));
Parent root = loader.load();
SendMessageController sendMessageController = loader.getController();
sendMessageController.setMsgSender(currentUser.getText());
Stage stage = new Stage();
stage.getIcons().add(new Image("Mercury/MercuryResources/logo.png"));
stage.setScene(new Scene(root));
stage.setTitle("Send Message");
stage.show();
} catch (IOException e) {
System.out.println("IOE sendMessage");
e.printStackTrace();
}
}
public void showRegScreen() {
regPane.setVisible(true);
loginPane.setVisible(false);
}
public void showDeleteScreen() {
deleteScreen.setVisible(true);
}
public void showSearch() {
mainMenu.setVisible(false);
searchScreen.setVisible(true);
}
public void showUpdateScreen() {
try {
UserServices us = new UserServices();
Image image = new Image(us.getUserById(Integer.parseInt(currentId.getText())).getPicture(),150,150,false,true);
userPicUpdate.setImage(image);
updateScreen.setVisible(true);
mainMenu.setVisible(false);
} catch (Exception e) {
System.out.println("E showUpdateScreen");
e.printStackTrace();
}
}
public String encrypt(String password) {
String generatedPassword = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] bytes = md.digest();
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
generatedPassword = sb.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return generatedPassword;
}
public void regUser() {
UserServices us = new UserServices();
String username = userReg.getText();
String password = encrypt(passReg.getText());
String name = nameReg.getText();
User user = new User(username, password, name);
try {
if (this.filePath == null) {
us.addUser(user);
} else {
us.addUser(user, filePath);
}
} catch (ClassNotFoundException e) {
System.out.println("CNFE regUser");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SE regUser");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("FNFE regUser");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE regUser");
e.printStackTrace();
}
userReg.clear();
passReg.clear();
nameReg.clear();
userPic.setImage(defaultPic);
userPicUpdate.setImage(defaultPic);
userPicSearch.setImage(defaultPic);
filePath = null;
regPane.setVisible(false);
loginPane.setVisible(true);
}
public void loginUser() {
boolean isLoggedIn = false;
UserServices us = new UserServices();
ArrayList<User> userList = null;
try {
userList = us.listUsers();
} catch (ClassNotFoundException e) {
System.out.println("CNFE loginUser");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SE loginUser");
e.printStackTrace();
}
for (User user : userList) {
if (userField.getText().equals(user.getUsername()) && encrypt(passField.getText()).equals(user.getPassword())) {
userField.clear();
passField.clear();
currentId.setText(Integer.toString(user.getId()));
currentUser.setText(user.getUsername());
loginPane.setVisible(false);
mainMenu.setVisible(true);
isLoggedIn = true;
}
}
if (isLoggedIn != true) {
JOptionPane.showMessageDialog(null, "Invalid Credentials", "ALERT", 2);
}
}
public void updateUser() {
boolean isVerified = false;
UserServices us = new UserServices();
ArrayList<User> userList = null;
try {
userList = us.listUsers();
} catch (ClassNotFoundException e) {
System.out.println("CNFE updateUser");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SE updateUser");
e.printStackTrace();
}
for (User user : userList) {
if (userCredentials.getText().equals(user.getUsername()) && encrypt(passCredentials.getText()).equals(user.getPassword())) {
isVerified = true;
User updatedUser = new User();
if (updateUserField.getText().isEmpty() != true) {
updatedUser.setUsername(updateUserField.getText());
}
if (updatePassField.getText().isEmpty() != true) {
updatedUser.setPassword(updatePassField.getText());
}
if (updateNameField.getText().isEmpty() != true) {
updatedUser.setName(updateNameField.getText());
}
try {
if (filePath == null) {
updatedUser.setId(user.getId());
us.updateUser(updatedUser);
} else {
updatedUser.setId(user.getId());
us.updateUser(updatedUser, filePath);
}
} catch (Exception e) {
System.out.println("E updateUser");
e.printStackTrace();
}
userCredentials.clear();
passCredentials.clear();
updateUserField.clear();
updatePassField.clear();
updateNameField.clear();
userPicUpdate.setImage(defaultPic);
userPic.setImage(defaultPic);
userPicSearch.setImage(defaultPic);
updateScreen.setVisible(false);
mainMenu.setVisible(true);
}
}
if (isVerified != true) {
JOptionPane.showMessageDialog(null, "Invalid Credentials", "ALERT", 2);
}
}
public void deleteUser() {
boolean isVerified = false;
UserServices us = new UserServices();
ArrayList<User> userList = null;
try {
userList = us.listUsers();
} catch (ClassNotFoundException e) {
System.out.println("CNFE deleteUser");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SE deleteUser");
e.printStackTrace();
}
for (User user : userList) {
if (deleteUserCred.getText().equals(user.getUsername()) && encrypt(deletePassCred.getText()).equals(user.getPassword())) {
try {
us.deleteUserById(user);
} catch (ClassNotFoundException e) {
System.out.println("CNFE deleteUser");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SE deleteUser");
e.printStackTrace();
}
isVerified = true;
deleteUserCred.clear();
deletePassCred.clear();
deleteScreen.setVisible(false);
updateScreen.setVisible(false);
loginPane.setVisible(true);
}
}
if (isVerified != true) {
JOptionPane.showMessageDialog(null, "Invalid Credentials", "ALERT", 2);
}
}
public void logOut() {
currentUser.setText("");
currentId.setText("");
mainMenu.setVisible(false);
loginPane.setVisible(true);
}
public void searchUser() {
User user = new User();
UserServices us = new UserServices();
try {
user = us.getUserById(Integer.parseInt(searchID.getText()));
ID.setText(Integer.toString(user.getId()));
username.setText(user.getUsername());
name.setText(user.getName());
Image image = new Image(us.getUserById(Integer.parseInt(searchID.getText())).getPicture(), 150, 150, false, true);
userPicSearch.setImage(image);
searchID.clear();
} catch (Exception e) {
System.out.println("E searchUser");
e.printStackTrace();
}
}
public void backToMainList() {
mainMenu.setVisible(true);
listScreen.setVisible(false);
}
public void backToMainSearch() {
searchScreen.setVisible(false);
mainMenu.setVisible(true);
ID.setText("ID");
username.setText("Username");
name.setText("Name");
userPicUpdate.setImage(defaultPic);
userPic.setImage(defaultPic);
userPicSearch.setImage(defaultPic);
}
public void backToLogin() {
regPane.setVisible(false);
mainMenu.setVisible(true);
userReg.clear();
passReg.clear();
nameReg.clear();
}
public void backToMainUpdate() {
updateScreen.setVisible(false);
mainMenu.setVisible(true);
updateUserField.clear();
updatePassField.clear();
updateNameField.clear();
userCredentials.clear();
passCredentials.clear();
}
public void backToMainDelete() {
deleteScreen.setVisible(false);
}
public void keyPressedLogin(KeyEvent enter) {
if (enter.getCode()== KeyCode.ENTER) {
loginUser();
}
}
public void keyPressedReg(KeyEvent enter) {
if (enter.getCode()== KeyCode.ENTER) {
regUser();
}
}
public void keyPressedDel(KeyEvent enter) {
if (enter.getCode()== KeyCode.ENTER) {
deleteUser();
}
}
public void keyPressedSearch(KeyEvent enter) {
if (enter.getCode()== KeyCode.ENTER) {
searchUser();
}
}
public void keyPressedUpdate(KeyEvent enter) {
if (enter.getCode()== KeyCode.ENTER) {
updateUser();
}
}
}
| [
"rphlmnbt@gmail.com"
] | rphlmnbt@gmail.com |
a438bf323860549480d9684af2562bfb1e435704 | 109966ece075c80fe84bb3bc87a5fec04b7651e1 | /src/test/java/com/jerolba/bikey/IntKeyMapTest.java | 549aeea6ebe046c6b62adbb40617363ea68c3b7f | [
"Apache-2.0"
] | permissive | jerolba/bikey | 58aa366dabc54a45163bda93272d4facf891a0ca | 2fe78dc28add5a2272afd34b548a9e8224556029 | refs/heads/master | 2021-06-10T12:34:37.083457 | 2019-06-22T19:28:21 | 2019-06-22T19:28:21 | 182,254,896 | 15 | 0 | Apache-2.0 | 2021-05-17T04:25:27 | 2019-04-19T11:32:23 | Java | UTF-8 | Java | false | false | 23,411 | java | /**
* Copyright 2019 Jerónimo López Bezanilla
*
* 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 com.jerolba.bikey;
import static java.util.stream.Collectors.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
public abstract class IntKeyMapTest {
IntKeyMap<String> map = getNewIntKeyMap();
public abstract IntKeyMap<String> getNewIntKeyMap();
@Test
public void justCreatedIsEmpty() {
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
@Test
public void withAnElementIsNotEmpty() {
map.put(1, "one");
assertFalse(map.isEmpty());
}
@Test
public void doesNotAcceptNullValues() {
assertThrows(NullPointerException.class, () -> {
map.put(0, null);
});
}
@Test
public void inAnEmptyMapCanAddAnInexistentElement() {
assertNull(map.put(1, "one"));
assertEquals(1, map.size());
}
@Test
public void anNonAddedElementIsNotCointaned() {
map.put(1, "one");
assertFalse(map.containsKey(2));
}
@Test
public void anAddedElementIsCointaned() {
map.put(1, "one");
assertTrue(map.containsKey(1));
}
@Test
public void canGetValue() {
assertNull(map.put(1, "one"));
assertEquals(new String("one"), map.get(1));
}
@Test
public void canNotGetValueIfItDoesNotExists() {
assertNull(map.put(1, "one"));
assertNull(map.get(2));
}
@Test
public void ifKeyExistsThePreviousValueIsReturned() {
map.put(1, "one");
assertEquals("one", map.put(1, "1"));
assertEquals(1, map.size());
}
@Test
public void ifKeyExistsTheValueIsReplaced() {
map.put(1, "one");
map.put(1, "1");
assertEquals("1", map.get(1));
}
@Test
public void aClearedMapHasNoElements() {
map.put(1, "one");
map.put(132, "one hundred thirty two");
map.clear();
assertTrue(map.isEmpty());
assertFalse(map.containsKey(1));
assertFalse(map.containsKey(132));
}
@Test
public void canRemoveAnElement() {
map.put(1, "one");
map.remove(1);
assertTrue(map.isEmpty());
}
@Test
public void canNotRemoveAnEmptyMap() {
assertNull(map.remove(1));
assertTrue(map.isEmpty());
}
//Implementation detail tests for RadixHamTrie version
@Test
public void testNoNextNodeBranchRemoveMap() {
map.put(12, "12");
map.put(32, "32");
assertNull(map.remove(128));
}
@Test
public void testNotRemovedRecursiveBranchRemoveMap() {
map.put(12, "12");
map.put(32, "32");
assertNull(map.remove(2));
}
@Test
public void ifKeyExistsRemoveReturnsTheValue() {
map.put(1, "one");
assertEquals("one", map.remove(1));
}
@Test
public void canNoRemoveAnUnexistentElement() {
map.put(20, "twenty");
assertNull(map.remove(50));
assertNull(map.remove(4));
assertEquals(1, map.size());
}
@Test
public void canAddAnElementAfterBeingEmpty() {
map.put(1023, "1023");
map.remove(1023);
assertTrue(map.isEmpty());
map.put(1, "1");
assertFalse(map.isEmpty());
}
@Test
public void getOrDefaultReturnsValueIfExists() {
map.put(7890, "7890");
assertEquals("7890", map.getOrDefault(7890, "other"));
}
@Test
public void getOrDefaultReturnsDefaultIfNotExists() {
assertEquals("other", map.getOrDefault(120341, "other"));
}
@Test
public void putIfAbsentPutsIfNotExists() {
assertNull(map.putIfAbsent(132, "132"));
assertEquals("132", map.get(132));
}
@Test
public void putIfAbsentDoesNotPutIfExists() {
map.put(132, "132");
assertEquals("132", map.putIfAbsent(132, "othervalue"));
assertEquals("132", map.get(132));
}
@Test
public void removeValueDoesNotRemoveIfKeyDoesntExists() {
assertFalse(map.remove(56, "56"));
}
@Test
public void removeValueDoesNotRemoveIfKeyAndValueAreNotEquals() {
map.put(56, "56");
assertFalse(map.remove(56, "fifty six"));
assertTrue(map.containsKey(56));
}
@Test
public void removeValueRemovesIfKeyAndValueAreEquals() {
map.put(56, "56");
assertTrue(map.remove(56, "56"));
assertFalse(map.containsKey(56));
}
@Test
public void replaceValueDoesNotReplaceIfKeyDoesntExists() {
assertFalse(map.replace(56, "56", "fifty six"));
}
@Test
public void replaceValueDoesNotReplaceIfKeyAndOldValueAreNotEquals() {
map.put(56, "56");
assertFalse(map.replace(56, "+56", "fifty six"));
assertEquals("56", map.get(56));
}
@Test
public void replaceValueReplacesIfKeyAndValueAreEquals() {
map.put(56, "56");
assertTrue(map.replace(56, "56", "fifty six"));
assertEquals("fifty six", map.get(56));
}
@Test
public void replaceDoesNotReplaceIfKeyDoesntExists() {
assertNull(map.replace(56, "fifty six"));
assertFalse(map.containsKey(56));
}
@Test
public void replaceReplacesIfKeyAndValueExists() {
map.put(56, "56");
assertNotNull(map.replace(56, "fifty six"));
assertEquals("fifty six", map.get(56));
}
@Test
public void computeIfAbsentDoesNothingIfValuePresent() {
map.put(33, "33");
assertEquals("33", map.computeIfAbsent(33, key -> Integer.toString(key + 1)));
assertEquals("33", map.get(33));
}
@Test
public void computeIfAbsentComputesIfValueNotPresent() {
assertEquals("34", map.computeIfAbsent(33, key -> Integer.toString(key + 1)));
assertEquals("34", map.get(33));
}
@Test
public void computeIfPresentComputesIfValuePresent() {
map.put(33, "33");
assertEquals("3334", map.computeIfPresent(33, (key, value) -> value + Integer.toString(key + 1)));
assertEquals("3334", map.get(33));
}
@Test
public void computeIfPresentDoesNothingIfValueNotPresent() {
assertNull(map.computeIfPresent(33, (key, value) -> value + Integer.toString(key + 1)));
assertFalse(map.containsKey(33));
}
@Test
public void computeRemovesKeyIfMappingIsNull() {
map.put(67, "67");
assertNull(map.compute(67, (key, value) -> null));
assertFalse(map.containsKey(67));
}
@Test
public void computeDoesNothingIfMappingIsNullAndKeyDoeNotExists() {
assertNull(map.compute(67, (key, value) -> null));
assertFalse(map.containsKey(67));
}
@Test
public void computePutsValueIfMappingIsNotNull() {
map.put(67, "67");
assertEquals("671", map.compute(67, (key, value) -> value + "1"));
assertEquals("671", map.get(67));
}
@Test
public void mergeRemovesKeyIfMappingIsNull() {
map.put(72, "72");
assertNull(map.merge(72, "1", (oldValue, value) -> null));
assertFalse(map.containsKey(72));
}
@Test
public void mergePutsMappingIfMappingIsNotNull() {
map.put(72, "72");
assertEquals("721", map.merge(72, "1", (oldValue, value) -> oldValue + value));
assertEquals("721", map.get(72));
}
@Test
public void nonPresentValueIsNotContained() {
map.put(1, "one");
map.put(48, "forty eight");
assertFalse(map.containsValue("two"));
assertFalse(map.containsValue("six"));
}
@Test
public void presentValueIsContained() {
map.put(1, "one");
map.put(48, "forty eight");
assertTrue(map.containsValue("one"));
assertTrue(map.containsValue("forty eight"));
}
@Nested
class SimpleIteration {
@Test
public void iterateEmptyMap() {
assertFalse(map.keySet().iterator().hasNext());
assertFalse(map.values().iterator().hasNext());
assertFalse(map.entrySet().iterator().hasNext());
}
@Test
public void onIteratinEndLaunchException() {
map.put(0, "0");
Iterator<IntObjectEntry<String>> it = map.iterator();
it.next();
assertFalse(it.hasNext());
assertThrows(NoSuchElementException.class, () -> {
it.next();
});
}
@Test
public void singleItemIteration() {
map.put(0, "0");
Iterator<IntObjectEntry<String>> iterator = map.iterator();
assertTrue(iterator.hasNext());
IntObjectEntry<String> next = iterator.next();
assertEquals(0, next.getIntKey());
assertEquals("0", next.getValue());
assertFalse(iterator.hasNext());
}
@Test
public void singleItemSecondNodeIteration() {
map.put(32, "32");
Iterator<IntObjectEntry<String>> iterator = map.iterator();
assertTrue(iterator.hasNext());
IntObjectEntry<String> next = iterator.next();
assertEquals(32, next.getIntKey());
assertEquals("32", next.getValue());
assertFalse(iterator.hasNext());
}
@Test
public void singleItemThirdNodeIteration() {
map.put(64, "64");
Iterator<IntObjectEntry<String>> iterator = map.iterator();
assertTrue(iterator.hasNext());
IntObjectEntry<String> next = iterator.next();
assertEquals(64, next.getIntKey());
assertEquals("64", next.getValue());
assertFalse(iterator.hasNext());
}
@Test
public void twoItemInSameNodeIteration() {
map.put(0, "0");
map.put(2, "2");
Iterator<IntObjectEntry<String>> iterator = map.iterator();
assertTrue(iterator.hasNext());
IntObjectEntry<String> next = iterator.next();
assertEquals(0, next.getIntKey());
assertEquals("0", next.getValue());
assertTrue(iterator.hasNext());
next = iterator.next();
assertEquals(2, next.getIntKey());
assertEquals("2", next.getValue());
assertFalse(iterator.hasNext());
}
@Test
public void twoItemInSiblingNodeIteration() {
map.put(31, "31");
map.put(32, "32");
Iterator<IntObjectEntry<String>> iterator = map.iterator();
assertTrue(iterator.hasNext());
IntObjectEntry<String> next = iterator.next();
assertEquals(31, next.getIntKey());
assertEquals("31", next.getValue());
assertTrue(iterator.hasNext());
next = iterator.next();
assertEquals(32, next.getIntKey());
assertEquals("32", next.getValue());
assertFalse(iterator.hasNext());
}
@Test
public void twoItemInCousinNodeIteration() {
map.put(1023, "1023");
map.put(1024, "1024");
Iterator<IntObjectEntry<String>> iterator = map.iterator();
assertTrue(iterator.hasNext());
IntObjectEntry<String> next = iterator.next();
assertEquals(1023, next.getIntKey());
assertEquals("1023", next.getValue());
assertTrue(iterator.hasNext());
next = iterator.next();
assertEquals(1024, next.getIntKey());
assertEquals("1024", next.getValue());
assertFalse(iterator.hasNext());
}
}
@Nested
class Iteration {
@BeforeEach
void beforeEachTest() {
map.put(0, "0");
map.put(1, "1");
map.put(3, "3");
map.put(35, "35");
map.put(127, "127");
map.put(5432, "5432");
}
@Test
public void iteratorHasAllElements() {
Set<String> found = new HashSet<>();
Iterator<IntObjectEntry<String>> iterator = map.iterator();
while (iterator.hasNext()) {
found.add(toString(iterator.next()));
}
assertContainsAll(found);
}
@Test
public void foreachWithBiConsumerHasAllElements() {
Set<String> found = new HashSet<>();
map.forEach((r, c) -> found.add(toString(r, c)));
assertContainsAll(found);
}
@Test
public void foreachWithConsumerHasAllElements() {
Set<String> found = new HashSet<>();
map.forEach(bikey -> found.add(toString(bikey)));
assertContainsAll(found);
}
@Test
public void forLoopHasAllElements() {
Set<String> found = new HashSet<>();
for (IntObjectEntry<String> bikey : map) {
found.add(toString(bikey));
}
assertContainsAll(found);
}
@Test
public void streamHasAllElements() {
Set<String> found = map.stream().map(bikey -> toString(bikey)).collect(toSet());
assertContainsAll(found);
}
@Test
public void iterateWithoutCallingHashNext() {
Iterator<IntObjectEntry<String>> iterator = map.iterator();
Set<String> found = new HashSet<>();
for (int i = 0; i < map.size(); i++) {
found.add(toString(iterator.next()));
}
assertFalse(iterator.hasNext());
assertContainsAll(found);
}
@Test
public void keySetContainsKeys() {
assertContainsAllKeys(map.keySet());
assertContainsAllKeys(new HashSet<>(map.keySet()));
}
@Test
public void iteratedKeySetContainsKeys() {
Set<Integer> keys = new HashSet<>();
for (Integer key : map.keySet()) {
keys.add(key);
}
assertContainsAllKeys(keys);
}
@Test
public void forEachInKeySetContainsKeys() {
Set<Integer> keys = new HashSet<>();
map.keySet().forEach(keys::add);
assertContainsAllKeys(keys);
}
@Test
public void foreachKeyContainsKeys() {
Set<Integer> keys = new HashSet<>();
map.forEachKey(keys::add);
assertContainsAllKeys(keys);
}
@Test
public void streamingKeySetContainsKeys() {
Set<Integer> keys = map.keySet().stream().collect(toSet());
assertContainsAllKeys(keys);
}
@Test
public void clearingKeySetModifiesTheMap() {
map.keySet().clear();
assertTrue(map.isEmpty());
}
@Test
public void valuesContainsValues() {
assertContainsAllValues(map.values());
assertContainsAllValues(new ArrayList<>(map.values()));
}
@Test
public void iteratedValuesContainsValues() {
List<String> values = new ArrayList<>();
for (String value : map.values()) {
values.add(value);
}
assertContainsAllValues(values);
}
@Test
public void forEachInValuesContainsValues() {
List<String> values = new ArrayList<>();
map.values().forEach(values::add);
assertContainsAllValues(values);
}
@Test
public void streamingValuesContainsValues() {
List<String> values = map.values().stream().collect(toList());
assertContainsAllValues(values);
}
@Test
public void clearingValuesModifiesTheMap() {
map.values().clear();
assertTrue(map.isEmpty());
}
@Test
public void entrySetContainsAllEntries() {
assertContainsAllEntries(map.entrySet());
assertContainsAllEntries(new ArrayList<>(map.entrySet()));
}
@Test
public void iteratedEntrySetContainsEntries() {
List<IntObjectEntry<String>> entries = new ArrayList<>();
for (IntObjectEntry<String> entry : map.entrySet()) {
entries.add(entry);
}
assertContainsAllEntries(entries);
}
@Test
public void forEachInEntrySetContainsEntries() {
List<IntObjectEntry<String>> entries = new ArrayList<>();
map.entrySet().forEach(entries::add);
assertContainsAllEntries(entries);
}
@Test
public void streamingEntrySetContainsValues() {
List<IntObjectEntry<String>> entries = map.entrySet().stream().collect(toList());
assertContainsAllEntries(entries);
}
@Test
public void clearingEntrySetModifiesTheMap() {
map.entrySet().clear();
assertTrue(map.isEmpty());
}
void assertContainsAll(Set<String> found) {
assertTrue(found.contains("0 - 0"));
assertTrue(found.contains("1 - 1"));
assertTrue(found.contains("3 - 3"));
assertTrue(found.contains("35 - 35"));
assertTrue(found.contains("127 - 127"));
assertTrue(found.contains("5432 - 5432"));
assertFalse(found.contains("NONE"));
assertEquals(6, found.size());
}
void assertContainsAllKeys(Set<Integer> keySet) {
assertTrue(keySet.contains(0));
assertTrue(keySet.contains(1));
assertTrue(keySet.contains(3));
assertTrue(keySet.contains(35));
assertTrue(keySet.contains(127));
assertTrue(keySet.contains(5432));
assertFalse(keySet.contains(1234567));
assertEquals(6, keySet.size());
}
void assertContainsAllValues(Collection<String> values) {
assertTrue(values.contains("0"));
assertTrue(values.contains("1"));
assertTrue(values.contains("3"));
assertTrue(values.contains("35"));
assertTrue(values.contains("127"));
assertTrue(values.contains("5432"));
assertFalse(values.contains("NONE"));
assertEquals(6, values.size());
}
void assertContainsAllEntries(Collection<IntObjectEntry<String>> found) {
assertTrue(found.contains(new IntObjectEntry<>(0, "0")));
assertTrue(found.contains(new IntObjectEntry<>(1, "1")));
assertTrue(found.contains(new IntObjectEntry<>(3, "3")));
assertTrue(found.contains(new IntObjectEntry<>(35, "35")));
assertTrue(found.contains(new IntObjectEntry<>(127, "127")));
assertTrue(found.contains(new IntObjectEntry<>(5432, "5432")));
assertEquals(6, found.size());
}
String toString(IntObjectEntry<String> entry) {
return toString(entry.getIntKey(), entry.getValue());
}
String toString(int key, String value) {
return key + " - " + value;
}
}
public void randomlyAddAndRemoveValues(int maxValue, int number) {
Random rnd = new Random();
Set<Integer> present = new HashSet<>();
for (int i = 0; i < number; i++) {
int nextInt = maxValue != 0 ? rnd.nextInt(maxValue) : rnd.nextInt();
String put = map.put(nextInt, Integer.toString(nextInt));
if (put != null) {
assertTrue(present.contains(nextInt));
}
present.add(nextInt);
}
List<IntObjectEntry<String>> collected = map.stream().collect(toList());
assertEquals(present.size(), collected.size());
for (IntObjectEntry<String> item : collected) {
assertEquals(Integer.toString(item.getIntKey()), item.getValue());
assertTrue(present.contains(item.getIntKey()));
}
List<Integer> toRemove = new ArrayList<>(present);
Collections.shuffle(toRemove);
int size = map.size();
for (Integer remove : toRemove) {
String value = map.remove(remove);
assertEquals(Integer.toString(remove), value);
assertFalse(map.containsKey(remove));
size--;
assertEquals(size, map.size());
}
assertTrue(map.isEmpty());
}
@Test
public void iterationIsSorted() {
Random rnd = new Random();
for (int i = 0; i < 5_000; i++) {
int nextInt = rnd.nextInt(10_000);
map.put(nextInt, Integer.toString(nextInt));
}
int last = -1;
for (IntObjectEntry<String> tuple : map) {
int key = tuple.getIntKey();
assertTrue(last < key);
last = key;
}
}
@Test
public void hasHashCode() {
int hashCode0 = map.hashCode();
map.put(1, "one");
int hashCode1 = map.hashCode();
map.put(2, "two");
int hashCode2 = map.hashCode();
map.put(3, "three");
int hashCode3 = map.hashCode();
assertNotEquals(hashCode0, hashCode1);
assertNotEquals(hashCode0, hashCode2);
assertNotEquals(hashCode0, hashCode3);
assertNotEquals(hashCode1, hashCode2);
assertNotEquals(hashCode1, hashCode3);
assertNotEquals(hashCode2, hashCode3);
}
@Test
public void twoEmtpyMapsAreEquals() {
assertTrue(map.equals(getNewIntKeyMap()));
}
@Test
public void isEqualsOfItsSelf() {
assertTrue(map.equals(map));
map.put(1, "one");
assertTrue(map.equals(map));
}
@Test
public void hasEquals() {
IntKeyMap<String> other = getNewIntKeyMap();
map.put(1, "one");
assertFalse(map.equals(other));
other.put(1, "one");
assertTrue(map.equals(other));
map.put(2, "two");
assertFalse(map.equals(other));
other.put(22, "two");
assertFalse(map.equals(other));
other.remove(22);
other.put(2, "two");
assertTrue(map.equals(other));
map.put(11, "one");
assertFalse(map.equals(other));
other.put(11, "one");
assertTrue(map.equals(other));
map.equals(null);
}
@Test
public void testToStringEmpty() {
assertEquals("{}", map.toString());
}
@Test
public void testToStringOneElement() {
map.put(1, "one");
assertEquals("{1=one}", map.toString());
}
@Test
public void toStringMultipleElementsAreSorted() {
map.put(35, "thirtyfive");
map.put(1, "one");
assertEquals("{1=one, 35=thirtyfive}", map.toString());
}
}
| [
"jerolba@gmail.com"
] | jerolba@gmail.com |
9bcfe505a39c579d8056b06f0355f1d818eaf2a8 | b63ea40490cf3982de743ce278fca5b7d88e2015 | /spring-core/src/test/java/org/springframework/core/codec/AbstractDecoderTestCase.java | 613cabfdd0e10d40691eb3c5edbc8be6b6faf8c3 | [
"Apache-2.0"
] | permissive | standByMe68/spring | ef71ad7d3210e3bfeb9b428eec9581794a2809f6 | 89bc8d08ce3946ebfadf0c9606aea100c6bb0743 | refs/heads/master | 2022-12-30T09:27:16.091089 | 2020-10-21T07:06:09 | 2020-10-21T07:06:09 | 304,566,572 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,831 | java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.codec;
import java.time.Duration;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.AbstractLeakCheckingTestCase;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import static org.junit.Assert.*;
/**
* Abstract base class for {@link Decoder} unit tests. Subclasses need to implement
* {@link #canDecode()}, {@link #decode()} and {@link #decodeToMono()}, possibly using the wide
* variety of helper methods like {@link #testDecodeAll} or {@link #testDecodeToMonoAll}.
*
* @author Arjen Poutsma
* @since 5.1.3
*/
@SuppressWarnings("ProtectedField")
public abstract class AbstractDecoderTestCase<D extends Decoder<?>>
extends AbstractLeakCheckingTestCase {
/**
* The decoder to test.
*/
protected D decoder;
/**
* Construct a new {@code AbstractDecoderTestCase} for the given decoder.
* @param decoder the decoder
*/
protected AbstractDecoderTestCase(D decoder) {
Assert.notNull(decoder, "Encoder must not be null");
this.decoder = decoder;
}
/**
* Subclasses should implement this method to test {@link Decoder#canDecode}.
*/
@Test
public abstract void canDecode() throws Exception;
/**
* Subclasses should implement this method to test {@link Decoder#decode}, possibly using
* {@link #testDecodeAll} or other helper methods.
*/
@Test
public abstract void decode() throws Exception;
/**
* Subclasses should implement this method to test {@link Decoder#decodeToMono}, possibly using
* {@link #testDecodeToMonoAll}.
*/
@Test
public abstract void decodeToMono() throws Exception;
// Flux
/**
* Helper methods that tests for a variety of {@link Flux} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecodeAll(Publisher<DataBuffer> input, Class<? extends T> outputClass,
Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecodeAll(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* Helper methods that tests for a variety of {@link Flux} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
protected <T> void testDecodeAll(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
testDecode(input, outputType, stepConsumer, mimeType, hints);
testDecodeError(input, outputType, mimeType, hints);
testDecodeCancel(input, outputType, mimeType, hints);
testDecodeEmpty(outputType, mimeType, hints);
}
/**
* com.Test a standard {@link Decoder#decode decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
*
* Flux<DataBuffer> input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -> step
* .consumeNextWith(expectBytes(bytes1))
* .consumeNextWith(expectBytes(bytes2))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecode(Publisher<DataBuffer> input, Class<? extends T> outputClass,
Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecode(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* com.Test a standard {@link Decoder#decode decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
*
* Flux<DataBuffer> input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -> step
* .consumeNextWith(expectBytes(bytes1))
* .consumeNextWith(expectBytes(bytes2))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
@SuppressWarnings("unchecked")
protected <T> void testDecode(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<T> result = (Flux<T>) this.decoder.decode(input, outputType, mimeType, hints);
StepVerifier.FirstStep<T> step = StepVerifier.create(result);
stepConsumer.accept(step);
}
/**
* com.Test a {@link Decoder#decode decode} scenario where the input stream contains an error.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by an {@link InputException}.
* The result is expected to contain one "normal" element, followed by the error.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @see InputException
*/
protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
input = Mono.from(input).concatWith(Flux.error(new InputException()));
try {
this.decoder.decode(input, outputType, mimeType, hints).blockLast(Duration.ofSeconds(5));
fail();
}
catch (InputException ex) {
// expected
}
}
/**
* com.Test a {@link Decoder#decode decode} scenario where the input stream is canceled.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by a cancel signal.
* The result is expected to contain one "normal" element.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeCancel(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<?> result = this.decoder.decode(input, outputType, mimeType, hints);
StepVerifier.create(result).expectNextCount(1).thenCancel().verify();
}
/**
* com.Test a {@link Decoder#decode decode} scenario where the input stream is empty.
* The output is expected to be empty as well.
*
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeEmpty(ResolvableType outputType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
Flux<DataBuffer> input = Flux.empty();
Flux<?> result = this.decoder.decode(input, outputType, mimeType, hints);
StepVerifier.create(result).verifyComplete();
}
// Mono
/**
* Helper methods that tests for a variety of {@link Mono} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecodeToMono(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecodeToMonoAll(Publisher<DataBuffer> input,
Class<? extends T> outputClass, Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecodeToMonoAll(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* Helper methods that tests for a variety of {@link Mono} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecodeToMono(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
protected <T> void testDecodeToMonoAll(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
testDecodeToMono(input, outputType, stepConsumer, mimeType, hints);
testDecodeToMonoError(input, outputType, mimeType, hints);
testDecodeToMonoCancel(input, outputType, mimeType, hints);
testDecodeToMonoEmpty(outputType, mimeType, hints);
}
/**
* com.Test a standard {@link Decoder#decodeToMono) decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
* byte[] allBytes = ... // bytes1 + bytes2
*
* Flux<DataBuffer> input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -> step
* .consumeNextWith(expectBytes(allBytes))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecodeToMono(Publisher<DataBuffer> input,
Class<? extends T> outputClass, Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecodeToMono(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* com.Test a standard {@link Decoder#decodeToMono) decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
* byte[] allBytes = ... // bytes1 + bytes2
*
* Flux<DataBuffer> input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -> step
* .consumeNextWith(expectBytes(allBytes))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
@SuppressWarnings("unchecked")
protected <T> void testDecodeToMono(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Mono<T> result = (Mono<T>) this.decoder.decodeToMono(input, outputType, mimeType, hints);
StepVerifier.FirstStep<T> step = StepVerifier.create(result);
stepConsumer.accept(step);
}
/**
* com.Test a {@link Decoder#decodeToMono decode} scenario where the input stream contains an error.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by an {@link InputException}.
* The result is expected to contain the error.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @see InputException
*/
protected void testDecodeToMonoError(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
input = Mono.from(input).concatWith(Flux.error(new InputException()));
Mono<?> result = this.decoder.decodeToMono(input, outputType, mimeType, hints);
StepVerifier.create(result).expectError(InputException.class).verify();
}
/**
* com.Test a {@link Decoder#decodeToMono decode} scenario where the input stream is canceled.
* This test method will immediately cancel the output stream.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeToMonoCancel(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Mono<?> result = this.decoder.decodeToMono(input, outputType, mimeType, hints);
StepVerifier.create(result).thenCancel().verify();
}
/**
* com.Test a {@link Decoder#decodeToMono decode} scenario where the input stream is empty.
* The output is expected to be empty as well.
*
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeToMonoEmpty(ResolvableType outputType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
Mono<?> result = this.decoder.decodeToMono(Flux.empty(), outputType, mimeType, hints);
StepVerifier.create(result).verifyComplete();
}
/**
* Creates a deferred {@link DataBuffer} containing the given bytes.
* @param bytes the bytes that are to be stored in the buffer
* @return the deferred buffer
*/
protected Mono<DataBuffer> dataBuffer(byte[] bytes) {
return Mono.fromCallable(() -> {
DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(bytes.length);
dataBuffer.write(bytes);
return dataBuffer;
});
}
/**
* Exception used in {@link #testDecodeError} and {@link #testDecodeToMonoError}
*/
@SuppressWarnings("serial")
public static class InputException extends RuntimeException {}
}
| [
"jianchengfeng@haocang.com"
] | jianchengfeng@haocang.com |
b2217f71e902e5163ca8f590085d000b02f49b08 | 622259e01d8555d552ddeba045fafe6624d80312 | /edu.harvard.i2b2.eclipse.plugins.query/gensrc/edu/harvard/i2b2/common/datavo/pdo/ObservationSet.java | 30030a0a7304246c3821e5719785c063006ec686 | [] | no_license | kmullins/i2b2-workbench-old | 93c8e7a3ec7fc70b68c4ce0ae9f2f2c5101f5774 | 8144b0b62924fa8a0e4076bf9672033bdff3b1ff | refs/heads/master | 2021-05-30T01:06:11.258874 | 2015-11-05T18:00:58 | 2015-11-05T18:00:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,105 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.2-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.21 at 10:39:06 AM EDT
//
package edu.harvard.i2b2.common.datavo.pdo;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="observation" type="{http://www.i2b2.org/xsd/hive/pdo/1.1/}observationType" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="panel_name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"observation"
})
@XmlRootElement(name = "observation_set")
public class ObservationSet {
@XmlElement(required = true)
protected List<ObservationType> observation;
@XmlAttribute(name = "panel_name")
protected String panelName;
/**
* Gets the value of the observation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the observation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getObservation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ObservationType }
*
*
*/
public List<ObservationType> getObservation() {
if (observation == null) {
observation = new ArrayList<ObservationType>();
}
return this.observation;
}
/**
* Gets the value of the panelName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPanelName() {
return panelName;
}
/**
* Sets the value of the panelName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPanelName(String value) {
this.panelName = value;
}
}
| [
"Janice@phs000774.partners.org"
] | Janice@phs000774.partners.org |
8e09877125bae6cc4a417428bea1c771fac050d3 | 8fe2412bd6cc304cf36a508a0a0eda595d548301 | /app/src/main/java/com/shosen/max/presenter/ContributionPresenter.java | b77788986778332f91b3d9ffb360e315ca1129a7 | [] | no_license | champion311/fork | 1508d793b8f73d3d786a3034e39514237aae68b1 | d9688ae2ec24a37d6e1f8a866ed70ae3eb9af4ff | refs/heads/master | 2020-04-15T21:29:38.479797 | 2019-01-10T11:28:40 | 2019-01-10T11:28:40 | 165,034,375 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,123 | java | package com.shosen.max.presenter;
import com.shosen.max.api.ApiService;
import com.shosen.max.base.RxPresenter;
import com.shosen.max.constant.TimeConstants;
import com.shosen.max.network.RetrofitClient;
import com.shosen.max.presenter.contract.ContributeContract;
import com.shosen.max.utils.RxUtils;
import io.reactivex.disposables.Disposable;
public class ContributionPresenter extends RxPresenter<ContributeContract.View> implements
ContributeContract.Presenter {
@Override
public void getContributeToday(String phone) {
Disposable di = RetrofitClient.getInstance().create(ApiService.class).
getContributeToday(phone).
compose(RxUtils.ToMain()).compose(RxUtils.handleResult()).subscribe(
accept -> {
if (mView != null) {
mView.showContributeToday(accept);
}
}, throwable -> {
if (mView != null) {
mView.showErrorMessage(throwable);
}
}
);
addSubscribe(di);
}
}
| [
"champion_311@qq.com"
] | champion_311@qq.com |
d4e8afff6d8f68d93dbb25d3b0dd8db4199199b9 | 5cf8a69987b7a3f6688038df795b3b1b0cd9bec4 | /src/test/java/org/jmeterplugins/repository/PluginTest.java | 6d5d11f35a8755e76dbab4b12bd9d210c0dc219f | [
"Apache-2.0"
] | permissive | ptrd/jmeter-plugins-manager | b65d8783ee1a4db0ffa4ddcc3aa10ee394373787 | 2464f2a1e461ca7a6cead7e5f15222023aa106d6 | refs/heads/master | 2021-01-19T19:39:45.291838 | 2017-04-16T18:23:52 | 2017-04-16T18:23:52 | 88,434,066 | 0 | 0 | null | 2017-04-16T18:24:28 | 2017-04-16T18:24:27 | null | UTF-8 | Java | false | false | 3,412 | java | package org.jmeterplugins.repository;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.jmeter.engine.JMeterEngine;
import org.junit.Test;
import java.util.HashSet;
import static org.junit.Assert.*;
public class PluginTest {
@Test
public void testVerFromPath() throws Exception {
assertEquals("0.1", Plugin.getVersionFromPath("/tmp/plugins-manager-0.1.jar"));
assertEquals("0.1-BETA", Plugin.getVersionFromPath("/tmp/plugins-manager-0.1-BETA.jar"));
assertEquals("0.1-SNAPSHOT", Plugin.getVersionFromPath("/tmp/plugins-manager-0.1-SNAPSHOT.jar"));
}
@Test
public void testLibInstallPath() throws Exception {
assertNotNull(Plugin.getLibPath("hector-core", new String[]{"/tmp/hector-core-1.1-2.jar"}));
assertNotNull(Plugin.getLibPath("kafka_2.8.2", new String[]{"/tmp/kafka_2.8.2-0.8.0.jar"}));
assertNotNull(Plugin.getLibPath("websocket-api", new String[]{"/tmp/websocket-api-9.1.1.v20140108.jar"}));
assertNotNull(Plugin.getLibPath("cglib-nodep", new String[]{"/tmp/cglib-nodep-2.1_3.jar"}));
}
@Test
public void testVersionComparator() throws Exception {
PluginMock obj = new PluginMock();
obj.setMarkerClass(JMeterEngine.class.getCanonicalName());
obj.detectInstalled(new HashSet<Plugin>());
assertEquals("2.13", obj.getCandidateVersion());
}
@Test
public void testVirtual() throws Exception {
PluginMock obj = new PluginMock("virtual");
obj.setCandidateVersion("0");
obj.setVersions(JSONObject.fromObject("{\"0\": {\"downloadUrl\": null}}", new JsonConfig()));
assertTrue(obj.isVirtual());
HashSet<String> depends = new HashSet<>();
depends.add("mock");
obj.setDepends(depends);
HashSet<Plugin> others = new HashSet<>();
PluginMock e = new PluginMock();
e.setMarkerClass(JMeterEngine.class.getCanonicalName());
e.detectInstalled(new HashSet<Plugin>());
others.add(e);
obj.detectInstalled(others);
assertTrue(obj.isInstalled());
obj.download(new JARSourceEmul(), new GenericCallback<String>() {
@Override
public void notify(String s) {
}
});
}
@Test
public void testInstallerClass() {
String str = "{\"id\": 0, \"markerClass\": 0, \"name\": 0, \"description\": 0, \"helpUrl\": 0, \"vendor\": 0, \"installerClass\": \"test\"}";
Plugin p = Plugin.fromJSON(JSONObject.fromObject(str, new JsonConfig()));
assertEquals("test", p.getInstallerClass());
}
@Test
public void testVersionChanges() {
String str = "{\"id\": 0, \"markerClass\": 0, \"name\": 0, \"description\": 0, \"helpUrl\": 0, \"vendor\": 0, \"installerClass\": \"test\", " +
"\"versions\" : { \"0.1\" : { \"changes\": \"fix verified exception\" } }}";
Plugin p = Plugin.fromJSON(JSONObject.fromObject(str, new JsonConfig()));
assertEquals("fix verified exception", p.getVersionChanges("0.1"));
str = "{\"id\": 0, \"markerClass\": 0, \"name\": 0, \"description\": 0, \"helpUrl\": 0, \"vendor\": 0, \"installerClass\": \"test\", " +
"\"versions\" : { \"0.1\" : { } }}";
p = Plugin.fromJSON(JSONObject.fromObject(str, new JsonConfig()));
assertNull(p.getVersionChanges("0.1"));
}
} | [
"apc4@ya.ru"
] | apc4@ya.ru |
da29b01318fef4fae2f0967dbfb02979ea908404 | 5a817aa233704ca8286307116ce764948c212584 | /app-starter/app-starter-rest/src/main/java/com/brlouk/starter/rest/MonitoringService.java | fc277d2dc5476c11bbe7106221cf21e3424c81d0 | [] | no_license | brlouk/app-starter | 92d00f546f2ea610ff595a79dcd9a24a5559fe0b | a123e1063e95ed447897f60a97acc0e64e66dc5f | refs/heads/master | 2021-01-20T17:23:47.265646 | 2016-06-04T23:11:37 | 2016-06-04T23:11:37 | 60,433,769 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 445 | java | package com.brlouk.starter.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.http.ResponseEntity;
@Path("/monitoring")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface MonitoringService {
@GET
@Path("/ping")
public ResponseEntity<String> ping();
}
| [
"loukil.brahim@gmail.com"
] | loukil.brahim@gmail.com |
3648b058c13efea976de44c5693f8c060c6cd934 | dbbd9d0e333649b68acf388ba9ff57a6946eb210 | /service/src/main/java/io/redkite/music/analyzer/controller/filters/BaseFilter.java | 4b79dbd70a6ab98bd4c217920bd7c95d661b3646 | [] | no_license | Kirill380/MusicAnalyzer | 55f23d86dcf5afebdef1358e22f7ee8bd6f8639f | 1914b6877870b67f5e67f630114a55ad2f1bee28 | refs/heads/master | 2021-08-22T18:07:54.875925 | 2017-11-30T22:02:00 | 2017-11-30T22:02:00 | 105,506,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,008 | java | package io.redkite.music.analyzer.controller.filters;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class BaseFilter implements Pageable {
protected int offset;
protected int limit;
protected String sort;
@Override
public int getPageNumber() {
return 0;
}
@Override
public int getPageSize() {
return limit == 0 ? 20 : limit;
}
@Override
public int getOffset() {
return offset;
}
@Override
public Sort getSort() {
return new Sort(sort != null ? sort : "email");
}
@Override
public Pageable next() {
return null;
}
@Override
public Pageable previousOrFirst() {
return null;
}
@Override
public Pageable first() {
return null;
}
@Override
public boolean hasPrevious() {
return false;
}
}
| [
"kliubun@kaaiot.io"
] | kliubun@kaaiot.io |
280670cc99d7b0b17f660e34042a93554b41e93e | 003a9020ff53127939694ab148d4005ef69fb0ab | /sandbox/src/main/java/ru/stqa/pft/sandbox/Square.java | 2a437ba6a9d544e1621d71b284272c39f735cfef | [
"Apache-2.0"
] | permissive | tmarmuzevich/java_for_testers | 0cfbc98b5662aaed85fad9fc2380b2fecb7023ea | f528c15452be69e2f9ef14a3f0cabaf2c521dd39 | refs/heads/master | 2020-03-25T07:16:49.061461 | 2018-10-16T14:52:10 | 2018-10-16T14:52:10 | 143,551,814 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 177 | java | package ru.stqa.pft.sandbox;
public class Square {
public double l;
public Square (double l) {
this.l=l;
}
public double area() {
return this.l *this.l;
}
}
| [
"42098155+tmarmuzevich@users.noreply.github.com"
] | 42098155+tmarmuzevich@users.noreply.github.com |
c1fddf62706b2a9c63cdb21b40bce6fa3023ce34 | 932e22c8935578e2da9d2c9ee39a2993a98a2bc0 | /nuxeo-runtime/nuxeo-stream/src/main/java/org/nuxeo/lib/stream/computation/Settings.java | a09919952ffdbbd64f9422759b6255377cfeb25e | [
"Apache-2.0"
] | permissive | JamesLinus/nuxeo | 5a37d67ddbc956033a8d894e570fdc7cc96ea009 | b096d664dafb4006bbacf8b7b2d9649478ea8f63 | refs/heads/master | 2021-07-24T10:59:10.755413 | 2017-11-04T16:10:38 | 2017-11-05T00:39:12 | 109,601,735 | 1 | 1 | null | 2017-11-05T17:46:03 | 2017-11-05T17:46:02 | null | UTF-8 | Java | false | false | 2,101 | java | /*
* (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* bdelbosc
*/
package org.nuxeo.lib.stream.computation;
import java.util.HashMap;
import java.util.Map;
/**
* Settings defines stream's partitions and computation's concurrency.
*
* @since 9.3
*/
public class Settings {
protected final int defaultConcurrency;
protected final int defaultPartitions;
protected final Map<String, Integer> concurrencies = new HashMap<>();
protected final Map<String, Integer> partitions = new HashMap<>();
/**
* Default concurrency and partition to use if not specified explicitly
*/
public Settings(int defaultConcurrency, int defaultPartitions) {
this.defaultConcurrency = defaultConcurrency;
this.defaultPartitions = defaultPartitions;
}
/**
* Set the computation thread pool size.
*/
public Settings setConcurrency(String computationName, int concurrency) {
concurrencies.put(computationName, concurrency);
return this;
}
public int getConcurrency(String computationName) {
return concurrencies.getOrDefault(computationName, defaultConcurrency);
}
/**
* Set the number of partitions for a stream.
*/
public Settings setPartitions(String streamName, int partitions) {
this.partitions.put(streamName, partitions);
return this;
}
public int getPartitions(String streamName) {
return partitions.getOrDefault(streamName, defaultPartitions);
}
}
| [
"bdelbosc@nuxeo.com"
] | bdelbosc@nuxeo.com |
4b1abf4bf2effc06fd5d6a1f3dc67356320c4c59 | 6ade30e92747d9df3b3a75183f9b1bb451e60fc2 | /src/com/scxh/java/ex023/io/file/reader/FileBufferWriterDemo.java | 27bc6d81e7be2fd4f61493eaa469a46b11b0cc78 | [] | no_license | yihu0817/Java_oneclass | 1a4d048291c8a0ed1a572e2d5a911389627ba3a8 | 991cab6695bfb2cc48a16432d4239d9f7f50b449 | refs/heads/master | 2020-12-24T16:34:36.150379 | 2016-04-18T03:02:21 | 2016-04-18T03:02:21 | 35,150,008 | 0 | 1 | null | null | null | null | GB18030 | Java | false | false | 961 | java | package com.scxh.java.ex023.io.file.reader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileBufferWriterDemo {
/**
* @param args
*/
public static void main(String[] args) {
BufferedWriter bufWriter = null;
try {
String str1 = "1.任何容器类,都必须有某种方式可以将东西放进去,然后由某种方式将东西取出来.";
String str2 = "2.存放事物是容器最基本的工作。对于ArrayList,add()是插入对象的方法.";
bufWriter = new BufferedWriter(new FileWriter("E:/writerFile.txt"));
bufWriter.write(str1);
bufWriter.newLine();
// bufWriter.write("\r\n"); //windows下写文件换行符用 "\r\n"
// bufWriter.write(str2);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufWriter != null) {
try {
bufWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| [
"2915858910@qq.com"
] | 2915858910@qq.com |
d0431682367646bc1e513e3789fbec31c7b80363 | c18be07ec556585747ae52f1769313a020060dc2 | /src/test/java/data/Environment.java | 5f32e596a82393393b20f0fa8071711431726ebd | [] | no_license | dengsw0227/interface_auto_test | a52c8853fee31977629de418f9748bd4dc81b314 | 0f5838f785c6a48b66270cc5e799e0fc2857192b | refs/heads/master | 2023-07-18T21:11:42.119897 | 2021-09-10T07:20:16 | 2021-09-10T07:20:16 | 404,694,133 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 435 | java | package data;
import java.util.HashMap;
import java.util.Map;
/**
* 环境变量
* @author balala
* @data 2021/8/25
**/
public class Environment {
// public static String token;
// public static int memberid;
//用Map作为环境变量,而不是具体的变量,
// 因为Map可以存很多键值对,用的时候取出来即可
public static Map<String,Object> envData = new HashMap<String,Object>();
}
| [
"735120730@qq.com"
] | 735120730@qq.com |
64e06bf1aa3c3eb3450b017cc2e4944777aee14a | aa41ce2f2de77370b8d55cd1fb9d5dfa9ce352d4 | /maven-plugin/src/main/java/io/quarkus/bom/decomposer/maven/MojoMessageWriter.java | 241129016247c77b01c0ab54d63e322a02d20312 | [
"Apache-2.0"
] | permissive | gsmet/quarkus-platform-bom-generator | 35a017c2cb07c4125d040e39d175328d083b4aaf | 4ecb78ca26ecd86d0c16e9162f69e5970970a342 | refs/heads/master | 2023-07-14T13:30:10.224553 | 2020-12-05T07:41:01 | 2020-12-05T07:41:01 | 318,777,610 | 0 | 0 | Apache-2.0 | 2020-12-05T12:02:39 | 2020-12-05T12:02:39 | null | UTF-8 | Java | false | false | 892 | java | package io.quarkus.bom.decomposer.maven;
import io.quarkus.bom.decomposer.MessageWriter;
import java.util.Objects;
import org.apache.maven.plugin.logging.Log;
public class MojoMessageWriter implements MessageWriter {
private final Log log;
public MojoMessageWriter(Log log) {
this.log = Objects.requireNonNull(log);
}
@Override
public void info(Object msg) {
log.info(toStr(msg));
}
@Override
public void error(Object msg) {
log.error(toStr(msg));
}
@Override
public boolean debugEnabled() {
return log.isDebugEnabled();
}
@Override
public void debug(Object msg) {
log.debug(toStr(msg));
}
@Override
public void warn(Object msg) {
log.warn(toStr(msg));
}
private CharSequence toStr(Object msg) {
return msg == null ? "null" : msg.toString();
}
}
| [
"olubyans@redhat.com"
] | olubyans@redhat.com |
c6d113a3f736adf235bf6de1d1513815481ef70f | 70cbaeb10970c6996b80a3e908258f240cbf1b99 | /WiFi万能钥匙dex1-dex2jar.jar.src/com/alibaba/fastjson/parser/deserializer/StringFieldDeserializer.java | 0ecbc79534d91dcc38ef69a1cd9ea9b8b6ddb11c | [] | no_license | nwpu043814/wifimaster4.2.02 | eabd02f529a259ca3b5b63fe68c081974393e3dd | ef4ce18574fd7b1e4dafa59318df9d8748c87d37 | refs/heads/master | 2021-08-28T11:11:12.320794 | 2017-12-12T03:01:54 | 2017-12-12T03:01:54 | 113,553,417 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,821 | java | package com.alibaba.fastjson.parser.deserializer;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.util.FieldInfo;
import java.lang.reflect.Type;
import java.util.Map;
public class StringFieldDeserializer
extends FieldDeserializer
{
private final ObjectDeserializer fieldValueDeserilizer;
public StringFieldDeserializer(ParserConfig paramParserConfig, Class<?> paramClass, FieldInfo paramFieldInfo)
{
super(paramClass, paramFieldInfo);
this.fieldValueDeserilizer = paramParserConfig.getDeserializer(paramFieldInfo);
}
public int getFastMatchToken()
{
return this.fieldValueDeserilizer.getFastMatchToken();
}
public void parseField(DefaultJSONParser paramDefaultJSONParser, Object paramObject, Type paramType, Map<String, Object> paramMap)
{
paramType = paramDefaultJSONParser.getLexer();
if (paramType.token() == 4)
{
paramDefaultJSONParser = paramType.stringVal();
paramType.nextToken(16);
if (paramObject != null) {
break label73;
}
paramMap.put(this.fieldInfo.getName(), paramDefaultJSONParser);
}
for (;;)
{
return;
paramDefaultJSONParser = paramDefaultJSONParser.parse();
if (paramDefaultJSONParser == null)
{
paramDefaultJSONParser = null;
break;
}
paramDefaultJSONParser = paramDefaultJSONParser.toString();
break;
label73:
setValue(paramObject, paramDefaultJSONParser);
}
}
}
/* Location: /Users/hanlian/Downloads/WiFi万能钥匙dex1-dex2jar.jar!/com/alibaba/fastjson/parser/deserializer/StringFieldDeserializer.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"lianh@jumei.com"
] | lianh@jumei.com |
f78ea4d98c79fb5ad11ec2731cd774e0297c38f3 | cb6bd697560d94c200fcf4de8db888208134972f | /cs2420 project8/src/FlowGraph.java | 4eef1a9a673ce6c7964cf32bc2e3c54b67793f2d | [] | no_license | 19sblanco/cs3-projects | 493e81078c43b99bb4004edae59df4b6e9669d05 | 937d7fec13a73345326d2d5775e71f58ac834f76 | refs/heads/main | 2023-01-30T17:56:18.844898 | 2020-12-08T07:31:32 | 2020-12-08T07:31:32 | 319,560,184 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,783 | java | import java.io.File;
import java.util.Iterator;
import java.util.Scanner;
public class FlowGraph {
int vertexCt; // Number of vertices in the graph.
GraphNode[] G; // Adjacency list for graph.
String graphName; //The file from which the graph was created.
int maxFlowFromSource;
int maxFlowIntoSink;
GraphNode source;
GraphNode sink;
public FlowGraph() {
this.vertexCt = 0;
this.graphName = "";
this.maxFlowFromSource = 0;
this.maxFlowIntoSink = 0;
}
/**
* create a graph with vertexCt nodes
* @param vertexCt
*/
public FlowGraph(int vertexCt) {
this.vertexCt = vertexCt;
G = new GraphNode[vertexCt];
for (int i = 0; i < vertexCt; i++) {
G[i] = new GraphNode(i);
}
this.maxFlowFromSource = 0;
this.maxFlowIntoSink = 0;
}
public int getVertexCt() {
return vertexCt;
}
public int getMaxFlowFromSource() {
return maxFlowFromSource;
}
public int getMaxFlowIntoSink() {
return maxFlowIntoSink;
}
/**
* @param source
* @param destination
* @param cap capacity of edge
* @param cost cost of edge
* @return create an edge from source to destination with capacation
*/
public boolean addEdge(int source, int destination, int cap, int cost) {
System.out.println("addEdge " + source + "->" + destination + "(" + cap + ", " + cost + ")");
if (source < 0 || source >= vertexCt) return false;
if (destination < 0 || destination >= vertexCt) return false;
//add edge
G[source].addEdge(source, destination, cap, cost);
return true;
}
/**
* @param source
* @param destination
* @return return the capacity between source and destination
*/
public int getCapacity(int source, int destination) {
return G[source].getCapacity(destination);
}
/**
* @param source
* @param destination
* @return the cost of the edge from source to destination
*/
public int getCost(int source, int destination) {
return G[source].getCost(destination);
}
/**
* @return string representing the graph
*/
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("The Graph " + graphName + " \n");
sb.append("Total input " + maxFlowIntoSink + " : Total output " + maxFlowFromSource + "\n");
for (int i = 0; i < vertexCt; i++) {
sb.append(G[i].toString());
}
return sb.toString();
}
/**
* prints all edges that have flow along them
*/
public void printEdges() {
for (GraphNode node: G) {
Iterator<EdgeInfo> itr = node.succ.iterator();
while (itr.hasNext()) {
EdgeInfo e = itr.next();
if (e.flow > 0) {
System.out.println("Edge (" + node.nodeID + "," + e.to + ") assigned " + e.flow + "(" + e.cost + ")");
}
}
}
}
/**
* gets cost of paths taken
*/
public int getCost() {
int cost = 0;
for (GraphNode node: G) {
Iterator<EdgeInfo> itr = node.succ.iterator();
while(itr.hasNext()) {
EdgeInfo e = itr.next();
if (e.flow > 0 && !e.marked) {
e.marked = true;
cost += e.cost;
}
}
}
return cost;
}
/**
* Builds a graph from filename. It automatically inserts backward edges needed for mincost max flow.
* @param filename
*/
public void makeGraph(String filename) {
try {
graphName = filename;
Scanner reader = new Scanner(new File(filename));
vertexCt = reader.nextInt();
G = new GraphNode[vertexCt];
for (int i = 0; i < vertexCt; i++) {
G[i] = new GraphNode(i);
if (i == 0) {
source = G[i];
} else if (i == vertexCt -1) {
sink = G[i];
}
}
while (reader.hasNextInt()) {
int v1 = reader.nextInt();
int v2 = reader.nextInt();
int cap = reader.nextInt();
int cost = reader.nextInt();
G[v1].addEdge(v1, v2, cap, cost);
G[v2].addEdge(v2, v1, 0, -cost);
if (v1 == 0) maxFlowFromSource += cap;
if (v2 == vertexCt - 1) maxFlowIntoSink += cap;
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | [
"73669114+19sblanco@users.noreply.github.com"
] | 73669114+19sblanco@users.noreply.github.com |
595aaa4460c45e62e2b754056e506b7a71501ca4 | 0b75dfbdd449c68c2e215b1c12fcf7445320a53c | /src/main/java/com/tuo/gitproject/util/result/PromptMsg.java | fb1bf7f740dbab42570567348d408079f2bb8341 | [] | no_license | tuo123/gitproject | 3a7dfea963ce201d6edce7dba3a3cb492f6fd06d | 89538c956c9a09c91dc6d1a6c67ca6cbde880d01 | refs/heads/master | 2020-05-02T06:04:47.138769 | 2019-03-30T13:52:51 | 2019-03-30T13:52:51 | 177,786,503 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 988 | java | package com.tuo.gitproject.util.result;
public class PromptMsg {
// 提示消息
public final static String LOGIN_SUCC = "登陆成功!";
public final static String UNLOGIN_USER = "用户未登录!";
public final static String LOGIN_ERROR = "用户不存在或密码错误!";
public final static String OPERATE_SUCC = "操作成功!";
public final static String OPERATE_FAIL = "操作失败!";
public final static String OPERATE_ERROR = "操作出现错误!";
public final static String UNKNOW_ERROR = "未知错误!";
public final static String UNAUTH = "未授权此操作";
public final static String PWD_NOTSAME = "两次密码不一致!!!";
public final static String HASFOREIGNKEY = "存在外键关联!";
public final static String USERISLIMIT = "此用户被禁用!!!";
public final static String TIMEERROR = "操作失败,时间设置出现交叉!";
public final static String INCOMPLETEINFORMATION = "信息未完整!!";
}
| [
"865077142@qq.com"
] | 865077142@qq.com |
b178eceeb16019360b28aa4dc379ad24e9a716af | c1e51495046183a54e6b5333e65acc11a5c5051c | /TrabES/src/swing/action/JConsultarMenuAction.java | 07f6e0d4f064e1f33cd82afcc1c552c9aa45e401 | [] | no_license | gabriacm/massive-nemesis | f477d6f1645acf5649b764e3a25a7386bef7f23a | 025ff300f53e97a3f560dc62ddbbd9073706e316 | refs/heads/master | 2021-01-23T09:27:30.775590 | 2012-12-14T12:57:54 | 2012-12-14T12:57:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 648 | java | package swing.action;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class JConsultarMenuAction extends AbstractAction {
public static final String CONSULTAR1 = "CONSULTAR1";
private JPanel principal;
private CardLayout cards;
public JConsultarMenuAction(JPanel principal, CardLayout cards) {
super("Consultar Programas");
this.principal = principal;
this.cards = cards;
}
@Override
public void actionPerformed(ActionEvent e) {
cards.show(principal, CONSULTAR1);
}
}
| [
"gabriacm@mail.com"
] | gabriacm@mail.com |
77049a5d7f9d23c462c995fd66d28840b8833248 | 2e91f8079e3f00d6bd197fc05cb3ec5146319e39 | /src/main/java/com/ctl/springmongoquerydsl/dao/PersonRepository.java | dc5a1e6da016cb585afd30fe6ccaab8e584ea20b | [] | no_license | cesartl/spring-mongo-querydsl | f8bb68c7546aab43a92a41d7ac9cb28f8fa99a22 | 430091967ebe605387c380b4237c51436b82c44c | refs/heads/master | 2020-03-15T06:27:49.355578 | 2018-05-04T13:51:22 | 2018-05-04T13:51:22 | 132,008,133 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.ctl.springmongoquerydsl.dao;
import com.ctl.springmongoquerydsl.model.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
public interface PersonRepository extends MongoRepository<Person, String>, QuerydslPredicateExecutor<Person> {
}
| [
"cesar.tronlozai@gmail.com"
] | cesar.tronlozai@gmail.com |
e79b12c19172a1980b55098a26fe1139a4a3da1b | ff029c08770594255e7f587246c832edb4d1bb8e | /src/CountDistinctElementWindow.java | 17bc9b15ebed6d2f3f716b806985b6944a59e642 | [] | no_license | kmrsumeet/MustDo150 | c4e9575b0764eb2a1a16ea770c1e2b085e153229 | 79bbc5191977aa3263fd2729c89770f9fe697707 | refs/heads/master | 2020-04-06T14:15:22.184810 | 2018-11-14T10:49:50 | 2018-11-14T10:49:50 | 157,532,972 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,060 | java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class CountDistinctElementWindow {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int n,k;
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = sc.nextInt();
}
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;i<n;i++){
HashMap<Integer, Integer> hmap = new HashMap<Integer,Integer>();
int c = 0;
if((k+i) > n)
break;
for(int j = i;j<(k+i);j++){
Integer val = hmap.get(arr[j]);
if(val!=null){
hmap.put(arr[j],new Integer(val+1));
}
else
{
hmap.put(arr[j],1);
c++;
}
}
list.add(c);
}
Object[] objects = list.toArray();
// Printing array of objects
for (Object obj : objects)
System.out.print(obj + " ");
//System.out.println(list);
}
}
}
| [
"Sumeet.kumar@247-inc.com"
] | Sumeet.kumar@247-inc.com |
84de33194bdadd7929f33c14699df68065215f3b | aa0b5c2a531ac0a8cfbcd47ebdcfdfd40013a071 | /jambeth/jambeth-xml/src/main/java/com/koch/ambeth/xml/pending/ArraySetterCommand.java | 7b3c4f42db7b74a2daedd3db802723f344bb8bd9 | [
"Apache-2.0"
] | permissive | vogelb/ambeth | 7efb73444c4451913d4be30966f2af3596230aaa | 4b842b2648b33657018fc3b31c5d5b2f33a7b929 | refs/heads/master | 2020-04-03T06:32:19.433909 | 2017-07-10T20:49:40 | 2017-07-11T08:03:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,386 | java | package com.koch.ambeth.xml.pending;
/*-
* #%L
* jambeth-xml
* %%
* Copyright (C) 2017 Koch Softwaredevelopment
* %%
* 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.
* #L%
*/
import java.lang.reflect.Array;
import com.koch.ambeth.ioc.IInitializingBean;
import com.koch.ambeth.util.ParamChecker;
import com.koch.ambeth.xml.IReader;
public class ArraySetterCommand extends AbstractObjectCommand
implements IObjectCommand, IInitializingBean {
protected Integer index;
@Override
public void afterPropertiesSet() throws Throwable {
super.afterPropertiesSet();
ParamChecker.assertTrue(parent.getClass().isArray(), "Parent has to be an array");
ParamChecker.assertNotNull(index, "Index");
}
public void setIndex(Integer index) {
this.index = index;
}
@Override
public void execute(IReader reader) {
Object value = objectFuture.getValue();
Array.set(parent, index, value);
}
}
| [
"dennis.koch@bruker.com"
] | dennis.koch@bruker.com |
f103a0df7f70a5dd8b704fadc6c2a74f35c2f716 | 53d7b36188a6b888833d0ebb7fb3f7e105b79af9 | /Project4_2/app/src/test/java/com/cookandroid/project4_2/ExampleUnitTest.java | ca667d59d8f818ea8d089934cd8d8700357f0589 | [] | no_license | gpwi970725/EmbeddedLecture | 6856aa5b12f73cfa22e091f964cd46e4c43aa71a | 8aaf564919f66e2c52343f5c12100b9ed0e9db5a | refs/heads/master | 2020-04-29T21:52:40.565325 | 2019-06-11T04:56:33 | 2019-06-11T04:56:33 | 176,428,001 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package com.cookandroid.project4_2;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"hengzizng@kangwon.ac.kr"
] | hengzizng@kangwon.ac.kr |
588348cb4617ec2bd33756371056d20d94aa45d4 | 806f76edfe3b16b437be3eb81639d1a7b1ced0de | /src/com/huawei/ui/main/stories/nps/interactors/mode/QstnSurveyCommitParam.java | 71b9748cb96b5c86026ca15c7c4bb0bf3d0f261b | [] | no_license | magic-coder/huawei-wear-re | 1bbcabc807e21b2fe8fe9aa9d6402431dfe3fb01 | 935ad32f5348c3d8c8d294ed55a5a2830987da73 | refs/heads/master | 2021-04-15T18:30:54.036851 | 2018-03-22T07:16:50 | 2018-03-22T07:16:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 771 | java | package com.huawei.ui.main.stories.nps.interactors.mode;
public class QstnSurveyCommitParam {
public static final String answers = "answers";
public static final String appID = "appID";
public static final String deviceName = "deviceName";
public static final String firmware = "firmware";
public static final String language = "language";
public static final String model = "model";
public static final String os = "os";
public static final String phoneId = "phoneId";
public static final String questionnaireId = "questionnaireId";
public static final String reqTimes = "reqTimes";
public static final String sn = "sn";
public static final String surveyID = "surveyID";
public static final String times = "times";
}
| [
"lebedev1537@gmail.com"
] | lebedev1537@gmail.com |
74fa3dbbf9def7b817fa184c7528906a25a13f46 | 1d5fb9c487b7421de81fcac257285675453b8874 | /src/main/java/com/stat/store/dao/ReviewAndroidHistoryDAO.java | 990b0a1fd6fffe98010d93ede392e22a461a33ca | [] | no_license | luhonghai/StoreStats | 10a5c860902325478808bd6d935609697af081b1 | e8a38d9abdcdc6412b64f756ee833f57f48811f5 | refs/heads/master | 2021-01-22T12:34:13.981590 | 2015-04-20T10:32:47 | 2015-04-20T10:32:47 | 33,515,991 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package com.stat.store.dao;
import com.stat.store.entity.ReviewAndroidHistory;
import javax.ejb.Remote;
import java.util.List;
/**
* Created by longnguyen on 4/18/15.
*/
@Remote
public interface ReviewAndroidHistoryDAO extends IDAO<ReviewAndroidHistory, Integer>{
public List<ReviewAndroidHistory> getByPackageName(String packageName);
}
| [
"long.nguyen@c-mg.com"
] | long.nguyen@c-mg.com |
9439a2cc0b5d6a499231a0fef9eb96c27917be77 | 36bbde826ff3e123716dce821020cf2a931abf6e | /plugin/core/src/main/gen/com/perl5/lang/perl/psi/impl/PsiPerlPostDerefExprImpl.java | dca5b58ac14605f2519d3c29235071371bfd9df9 | [
"Apache-2.0"
] | permissive | Camelcade/Perl5-IDEA | 0332dd4794aab5ed91126a2c1ecd608f9c801447 | deecc3c4fcdf93b4ff35dd31b4c7045dd7285407 | refs/heads/master | 2023-08-08T07:47:31.489233 | 2023-07-27T05:18:40 | 2023-07-27T06:17:04 | 33,823,684 | 323 | 79 | NOASSERTION | 2023-09-13T04:36:15 | 2015-04-12T16:09:15 | Java | UTF-8 | Java | false | true | 885 | java | // This is a generated file. Not intended for manual editing.
package com.perl5.lang.perl.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.perl5.lang.perl.lexer.PerlElementTypesGenerated.*;
import com.perl5.lang.perl.psi.*;
public class PsiPerlPostDerefExprImpl extends PsiPerlExprImpl implements PsiPerlPostDerefExpr {
public PsiPerlPostDerefExprImpl(ASTNode node) {
super(node);
}
@Override
public void accept(@NotNull PsiPerlVisitor visitor) {
visitor.visitPostDerefExpr(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof PsiPerlVisitor) accept((PsiPerlVisitor)visitor);
else super.accept(visitor);
}
}
| [
"hurricup@gmail.com"
] | hurricup@gmail.com |
10c5932dd401fb17fa7755a87d8fdc18df2f4822 | 7f36eab88af02c91f91561892a5661ad10c0f5fc | /src/main/java/acp/ssb/combobox/CbModelClass.java | 9286624d6dadd4308528950ad9631287a9c59a2a | [] | no_license | sbshab1969/mss04 | 030c662db7dba66d4bb8fa05b8f22d3d83f8d457 | 562e5789687fcb5c30cd0a0a9fbbe8d421889787 | refs/heads/master | 2022-12-04T00:43:31.461205 | 2020-08-10T15:57:33 | 2020-08-10T15:57:33 | 286,512,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,395 | java | package acp.ssb.combobox;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
public class CbModelClass extends AbstractListModel<CbClass> implements
ComboBoxModel<CbClass> {
private static final long serialVersionUID = 1L;
private ArrayList<CbClass> anArrayList = new ArrayList<>();
private CbClass selectedObject = null;
private boolean needNullItem = false;
public CbModelClass() {
}
public CbModelClass(ArrayList<CbClass> arrayList) {
this(arrayList,false);
}
public CbModelClass(ArrayList<CbClass> arrayList, boolean needNull) {
needNullItem = needNull;
setArrayList(arrayList);
}
public void setArrayList(ArrayList<CbClass> arrayList) {
anArrayList = arrayList;
if (getSize() > 0) {
selectedObject = anArrayList.get(0);
}
if (needNullItem) {
anArrayList.add(null);
}
}
// public boolean isNeedNullItem() {
// return needNullItem;
// }
public void setNeedNullItem(boolean needNull) {
needNullItem = needNull;
}
public int getSize() {
return anArrayList.size();
}
public CbClass getElementAt(int index) {
if (index < 0 || index >= getSize()) {
return null;
}
return anArrayList.get(index);
}
public Object getSelectedItem() {
return selectedObject;
}
public void setSelectedItem(Object newValue) {
if ((selectedObject != null && !selectedObject.equals(newValue))
|| (selectedObject == null && newValue != null)) {
selectedObject = (CbClass) newValue;
fireContentsChanged(this, -1, -1);
}
}
public String getKeyStringAt(int index) {
if (index < 0 || index >= getSize()) {
return null;
}
CbClass item = anArrayList.get(index);
String key = item.getKey();
return key;
}
public void setKeyString(String key) {
CbClass selObject = null;
for (CbClass item : anArrayList) {
String itemKey = item.getKey();
if (itemKey.equals(key)) {
selObject = item;
break;
}
}
setSelectedItem(selObject);
}
public int getKeyIntAt(int index) {
int keyInt = -1;
String key = getKeyStringAt(index);
if (key != null) {
keyInt = Integer.valueOf(key);
}
return keyInt;
}
public void setKeyInt(int keyInt) {
String key = String.valueOf(keyInt);
setKeyString(key);
}
}
| [
"sbshab1969@gmail.com"
] | sbshab1969@gmail.com |
5a337aeff7495437760d620e9d4234364a287682 | 3a3e6980119806f9897d3492da3e7857c85eb7e7 | /Spring/springcoreaop/src/main/java/com/parth/aopdemo/MainDemoApp.java | d585dfb6f015ba071c7a2e54ce84a811fa8055bb | [] | no_license | parthfloyd/Training | 7255981c53301fdf1ae41a13d16a46ce0203c2ed | 63cdc104464ba05ec2a9cdceb8a9ef63af61bb2b | refs/heads/master | 2023-04-16T01:03:22.292003 | 2023-04-08T02:08:26 | 2023-04-08T02:08:26 | 277,459,438 | 0 | 1 | null | 2023-04-08T02:08:30 | 2020-07-06T06:22:20 | Java | UTF-8 | Java | false | false | 819 | java | package com.parth.aopdemo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.parth.aopdemo.dao.AccountDAO;
import com.parth.aopdemo.dao.MembershipDAO;
public class MainDemoApp {
public static void main(String[] args) {
//read spring config java class
AnnotationConfigApplicationContext context=
new AnnotationConfigApplicationContext(DemoConfig.class);
//get the bean from spring container
AccountDAO theAccountDAO = context.getBean("accountDAO",AccountDAO.class);
MembershipDAO theMembershipDAO = context.getBean("membershipDAO", MembershipDAO.class);
//call the business method
Account myAccount = new Account();
theAccountDAO.addAccount(myAccount,true);
theMembershipDAO.addMember();
//close the context
context.close();
}
}
| [
"parth6606@gmail.com"
] | parth6606@gmail.com |
c67ea72a6156200a0c8c395756978c23017a4452 | 40d844c1c780cf3618979626282cf59be833907f | /src/testcases/CWE23_Relative_Path_Traversal/CWE23_Relative_Path_Traversal__listen_tcp_14.java | af33faccab0eb706b8e339670b7c86bb77f9faa7 | [] | no_license | rubengomez97/juliet | f9566de7be198921113658f904b521b6bca4d262 | 13debb7a1cc801977b9371b8cc1a313cd1de3a0e | refs/heads/master | 2023-06-02T00:37:24.532638 | 2021-06-23T17:22:22 | 2021-06-23T17:22:22 | 379,676,259 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,688 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__listen_tcp_14.java
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-14.tmpl.java
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: listen_tcp Read data using a listening tcp connection
* GoodSource: A hardcoded string
* BadSink: readFile no validation
* Flow Variant: 14 Control flow: if(IO.staticFive==5) and if(IO.staticFive!=5)
*
* */
package testcases.CWE23_Relative_Path_Traversal;
import testcasesupport.*;
import java.io.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.logging.Level;
public class CWE23_Relative_Path_Traversal__listen_tcp_14 extends AbstractTestCase
{
/* uses badsource and badsink */
public void bad() throws Throwable
{
String data;
if (IO.staticFive == 5)
{
data = ""; /* Initialize data */
/* Read data using a listening tcp connection */
{
ServerSocket listener = null;
Socket socket = null;
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
/* Read data using a listening tcp connection */
try
{
listener = new ServerSocket(39543);
socket = listener.accept();
/* read input from socket */
readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
/* POTENTIAL FLAW: Read data using a listening tcp connection */
data = readerBuffered.readLine();
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* Close stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
/* Close socket objects */
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing Socket", exceptIO);
}
try
{
if (listener != null)
{
listener.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing ServerSocket", exceptIO);
}
}
}
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
String root;
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
{
/* running on Windows */
root = "C:\\uploads\\";
}
else
{
/* running on non-Windows */
root = "/home/user/uploads/";
}
if (data != null)
{
/* POTENTIAL FLAW: no validation of concatenated value */
File file = new File(root + data);
FileInputStream streamFileInputSink = null;
InputStreamReader readerInputStreamSink = null;
BufferedReader readerBufferdSink = null;
if (file.exists() && file.isFile())
{
try
{
streamFileInputSink = new FileInputStream(file);
readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
readerBufferdSink = new BufferedReader(readerInputStreamSink);
IO.writeLine(readerBufferdSink.readLine());
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* Close stream reading objects */
try
{
if (readerBufferdSink != null)
{
readerBufferdSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStreamSink != null)
{
readerInputStreamSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
try
{
if (streamFileInputSink != null)
{
streamFileInputSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
}
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing IO.staticFive==5 to IO.staticFive!=5 */
private void goodG2B1() throws Throwable
{
String data;
if (IO.staticFive != 5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
else
{
/* FIX: Use a hardcoded string */
data = "foo";
}
String root;
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
{
/* running on Windows */
root = "C:\\uploads\\";
}
else
{
/* running on non-Windows */
root = "/home/user/uploads/";
}
if (data != null)
{
/* POTENTIAL FLAW: no validation of concatenated value */
File file = new File(root + data);
FileInputStream streamFileInputSink = null;
InputStreamReader readerInputStreamSink = null;
BufferedReader readerBufferdSink = null;
if (file.exists() && file.isFile())
{
try
{
streamFileInputSink = new FileInputStream(file);
readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
readerBufferdSink = new BufferedReader(readerInputStreamSink);
IO.writeLine(readerBufferdSink.readLine());
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* Close stream reading objects */
try
{
if (readerBufferdSink != null)
{
readerBufferdSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStreamSink != null)
{
readerInputStreamSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
try
{
if (streamFileInputSink != null)
{
streamFileInputSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
}
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing statements in if */
private void goodG2B2() throws Throwable
{
String data;
if (IO.staticFive == 5)
{
/* FIX: Use a hardcoded string */
data = "foo";
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run
* but ensure data is inititialized before the Sink to avoid compiler errors */
data = null;
}
String root;
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
{
/* running on Windows */
root = "C:\\uploads\\";
}
else
{
/* running on non-Windows */
root = "/home/user/uploads/";
}
if (data != null)
{
/* POTENTIAL FLAW: no validation of concatenated value */
File file = new File(root + data);
FileInputStream streamFileInputSink = null;
InputStreamReader readerInputStreamSink = null;
BufferedReader readerBufferdSink = null;
if (file.exists() && file.isFile())
{
try
{
streamFileInputSink = new FileInputStream(file);
readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
readerBufferdSink = new BufferedReader(readerInputStreamSink);
IO.writeLine(readerBufferdSink.readLine());
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* Close stream reading objects */
try
{
if (readerBufferdSink != null)
{
readerBufferdSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStreamSink != null)
{
readerInputStreamSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
try
{
if (streamFileInputSink != null)
{
streamFileInputSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
}
}
}
}
}
public void good() throws Throwable
{
goodG2B1();
goodG2B2();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"you@example.com"
] | you@example.com |
cf92f44cb522484eb6625094de14418b2c0c1190 | 2a3e67031266cfa7c09d7075afdc74d0fed594fe | /src/model/dao/dataConnection.java | d75a8124dd4a3b7cf0c8b8228c91b86cbe6662df | [] | no_license | garganish/expenses_project | cc9fd64069658cd9be4d934b1f4819a18aceb03e | 3104629da9c49a5dc9a8f924c0e793e3fa0a09e8 | refs/heads/master | 2020-03-22T20:42:59.084605 | 2018-07-11T20:36:49 | 2018-07-11T20:36:49 | 140,625,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,287 | java | /*
* 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 model.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import utility.configration;
/**
*
* @author anishgarg
*/
public class dataConnection {
private static Connection cc;
private dataConnection()
{
}
public static Connection getConnection() throws Exception
{
if(cc==null)
{
Class.forName(configration.driver_name);
cc= DriverManager.getConnection(configration.db_url, configration.db_user, configration.db_pass);
}
return cc;
}
public static void closeConnection()
{
try
{
if(cc!=null)
{
cc.close();
}
cc=null;
}
catch(SQLException ex)
{
System.out.println(ex);
}
}
public static PreparedStatement getStatement(String query) throws Exception
{
return getConnection().prepareStatement(query);
}
}
| [
"garganish@outlook.com"
] | garganish@outlook.com |
813c9c8bf7c5e161d037c917e1a765df7ff876ba | f730a5e3d97d0c8a862d0917e493172d12c39267 | /src/Gun61OCASorulari/S71.java | 2434e1761d3d9fe7ac4886423ceb3d5e74d67bc0 | [] | no_license | maolukpinar/JavaKursu | 4c77fef063f61132868ed106ba9a64326f209a42 | 842c6ab1851ab95833965eea0e2a0b5b5e97f8d3 | refs/heads/master | 2023-01-02T14:12:48.785421 | 2020-10-30T20:39:29 | 2020-10-30T20:39:29 | 308,738,592 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 763 | java | package Gun61OCASorulari;
public class S71 {
public static void main(String[] args) {
int [][] arr = new int [2][4];
arr[0] = new int[]{1,3,5,7};
arr[1] = new int[]{1,3};
for (int[] a: arr ) { // 0.satırı ve 1.satırı
for (int i = 0; i < arr.length; i++) {
// sınır 2 : arr.length: arr nin kaç satır olduğunu gösterir, a.leng ise o satırdaki sütun sayısını
System.out.print(a[i]+ " "); // a[0], a[1] 1 ve 3 ü yazacak 1.satırdan
// 2.Satıra geçtiğinde yine a[0] ve a[1] yani 2satırın 1 ve 3 ünü yazacak
}System.out.println();
}
}
}
//
//1 3
// 1 3
| [
"maolukpinar@gmail.com"
] | maolukpinar@gmail.com |
85172774c6b3816599e28b3e62e276aaf5b65bbd | ddbf5f19782b1fd96f69bdb23242934d38e2fbd1 | /codigoFonte/ListagemTV/app/src/main/java/br/com/indt/susan/listagemtv/model/bean/Produto.java | d6697f36479ca3355d387ad840cda3347c8cb3a3 | [] | no_license | SusanConde/Avaliacao-Pratica-Susan | 21a9f5f32cfc12b9a5d3a9e286b9e8db4800f223 | 1eee02eb4da905a97e1eb11c9ceb87e270208eb8 | refs/heads/master | 2021-01-23T02:58:51.517805 | 2017-03-27T04:47:08 | 2017-03-27T04:47:08 | 86,036,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 801 | java | package br.com.indt.susan.listagemtv.model.bean;
import java.io.Serializable;
/**
* Created by susan on 23/03/17.
*/
public class Produto implements Serializable {
private Long id;
private String nome;
private double preco;
private String urlFoto;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
public String getUrlFoto() {
return urlFoto;
}
public void setUrlFoto(String urlFoto) {
this.urlFoto = urlFoto;
}
}
| [
"suh.conde@gmail.com"
] | suh.conde@gmail.com |
536d36f37bef4f2749a91b0ae6246b4de8a2860b | 45c3ae4fdd179d6f16f26ee2fd8b75f11c127618 | /src/main/java/edu/javacourse/city/dao/PersonCheckDao.java | f2f9fa8698353d88f18de284f8c4d80b48362c90 | [] | no_license | OschepkovSA/ext-systems-city-register | a24ef4660de7ace1d438474f987070a2c28bde78 | 69802923b3bf30952ffcef43bd81578d79f829c7 | refs/heads/main | 2023-01-08T21:27:10.784726 | 2020-11-13T08:06:07 | 2020-11-13T08:06:07 | 312,511,315 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,525 | java | package edu.javacourse.city.dao;
import edu.javacourse.city.domain.PersonRequest;
import edu.javacourse.city.domain.PersonResponse;
import edu.javacourse.city.exception.PersonCheckException;
import java.sql.*;
public class PersonCheckDao {
private static final String SQL_REQUEST =
"select temporal from cr_address_person ap "
+ "inner join cr_person p on p.person_id = ap.person_id "
+ "inner join cr_address a on a.address_id = ap.address_id "
+ "where "
+ "CURRENT_DATE >= ap.start_date and (CURRENT_DATE <= ap.end_date or ap.end_date is null)"
+ "and upper(p.sur_name) = upper(?) "
+ "and upper(p.given_name) = upper(?) "
+ "and upper(p.patronymic) = upper(?) "
+ "and p.date_of_birth = ? "
+ "and a.street_code = ? "
+ "and upper(a.building) = upper(?) ";
private ConnectionBuilder connectionBuilder;
public void setConnectionBuilder(ConnectionBuilder connectionBuilder) {
this.connectionBuilder = connectionBuilder;
}
private Connection getConnection() throws SQLException {
return connectionBuilder.getConnection();
}
public PersonResponse checkPerson (PersonRequest request) throws PersonCheckException {
PersonResponse response = new PersonResponse();
String sql = SQL_REQUEST;
if (request.getExtension() != null) {
sql += " and upper(a.extension) = upper(?) ";
} else {
sql += " and extension is null ";
}
if (request.getAppartment() != null) {
sql += " and upper(a.apartment) = upper(?) ";
} else {
sql += " and apartment is null ";
}
try (Connection con = getConnection();
PreparedStatement stmt = con.prepareStatement(sql)
) {
int count = 1;
stmt.setString(count++, request.getSurName());
stmt.setString(count++, request.getGivenName());
stmt.setString(count++,request.getPatronomic());
stmt.setDate(count++, java.sql.Date.valueOf(request.getDateOfBirth()));
stmt.setLong(count++, request.getStreetCode());
stmt.setString(count++, request.getBuilding());
if (request.getExtension() != null) {
stmt.setString(count++ , request.getExtension());
}
if (request.getAppartment() != null) {
stmt.setString(count++ , request.getAppartment());
}
ResultSet resultSet = stmt.executeQuery();
if (resultSet.next()) {
response.setRegistered(true);
response.setTemporal(resultSet.getBoolean("temporal"));
}
} catch (SQLException e) {
throw new PersonCheckException(e);
}
return response;
}
}
| [
"70422885+OschepkovSA@users.noreply.github.com"
] | 70422885+OschepkovSA@users.noreply.github.com |
6736bdcb4e1a5875d775117aeab30e9fe445e92f | 3a9c2f1151fe814f8c7b47335aaa06b5480f839f | /lib/src/main/java/com/example/lib/LogCollection.java | d69518005e4c837a7e092ef8ae673f8b820fa631 | [] | no_license | lgthunder/image-download-server | eff0fee15e1c790833520a98286ec44eebae344b | ea2026383b53cbedf1b1915214077fdbf4c4ad0f | refs/heads/master | 2022-12-14T09:40:51.243490 | 2020-08-22T05:09:21 | 2020-08-22T05:09:21 | 287,139,016 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 624 | java | package com.example.lib;
import java.util.concurrent.LinkedBlockingQueue;
public class LogCollection {
static LogCollection INSTANCE = new LogCollection();
private LinkedBlockingQueue<ServerLogData> queue = new LinkedBlockingQueue();
public static LogCollection getInstance() {
return INSTANCE;
}
public LinkedBlockingQueue<ServerLogData> getQueue() {
return queue;
}
public void sendLog(ServerLogData data) {
try {
queue.put(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| [
"lgthundera@gmail.com"
] | lgthundera@gmail.com |
8d735deeebe8d6e4389e3428e70c1e2f1ee972d6 | 6789889233ca24043e82c01728f2d8c5570a58b3 | /src/daoInterfaces/MotivoEntradasInterface.java | 25cf169975250c926cf7113bf0780f2d7d514f97 | [
"Apache-2.0"
] | permissive | dev-alexandre/acal-2000 | fbe58f236440fddcc0cd13ca39a4914998f7dac6 | bc3919695498ad1cb531136aeddeda4654617c26 | refs/heads/master | 2021-02-13T04:59:53.751722 | 2020-03-03T14:55:54 | 2020-03-03T14:55:54 | 244,663,851 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 714 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package daoInterfaces;
import entidades.Motivoentrada;
import java.util.List;
/**
*
* @author netservidor
*/
public interface MotivoEntradasInterface {
public void AdicionarMotivoEntrada (Motivoentrada motivo);
public void ApagarMotivoEntrada (Motivoentrada motivo);
public void AlterarMotivoEntrada (Motivoentrada motivo);
public List<Motivoentrada> BuscarMotivo (String nome);
public List<Motivoentrada> BuscarTodosMotivos ();
public List<Motivoentrada> BuscarMotivoEntradaLikeNome(String nome);
public Motivoentrada BuscarMotivoEntradaId(int id);
}
| [
"alexandre.queiroz@solutis.com.br"
] | alexandre.queiroz@solutis.com.br |
0c9bc976c07ec205ee5c0e07951f2d9e08e55214 | 3b481b302b02edf57b816acac9e5ff3b7ec602e2 | /src/aio.java | 5a820849fd9ebfa7bd3a8d048393e65d83a0752b | [] | no_license | reverseengineeringer/com.twitter.android | 53338ae009b2b6aa79551a8273875ec3728eda99 | f834eee04284d773ccfcd05487021200de30bd1e | refs/heads/master | 2021-04-15T04:35:06.232782 | 2016-07-21T03:51:19 | 2016-07-21T03:51:19 | 63,835,046 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 304 | java | import android.widget.TextView;
import com.twitter.util.object.b;
final class aio
implements b<TextView, aik>
{
public aik a(TextView paramTextView)
{
return new aik(paramTextView);
}
}
/* Location:
* Qualified Name: aio
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"reverseengineeringer@hackeradmin.com"
] | reverseengineeringer@hackeradmin.com |
143b229e6b3544f782a704750744065713663a9e | 7375c088b70e816c428034e1cf7936d85d68e91a | /src/main/java/app/party/Party.java | 6b43dc595ef79f3f26587e239afbbebe1fa8a9d3 | [] | no_license | micke239/socialapolitiker-indexer | 6b4b05b951dd4f22ae751f1ec759aadeca466776 | 8065fc21ac42d1d60ba8532848c213ed4e01e06f | refs/heads/master | 2016-09-05T14:13:54.863977 | 2015-08-04T20:59:47 | 2015-08-04T20:59:47 | 33,794,171 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,748 | java | package app.party;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import app.politician.Politician;
@Entity
@Table(name = "party")
public class Party {
private Long id;
private String name;
private String urlName;
private Date createdAt;
private Date updatedAt;
private Integer displayOrder;
private List<Politician> politicians;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrlName() {
return urlName;
}
public void setUrlName(String urlName) {
this.urlName = urlName;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
@OneToMany(mappedBy = "party")
public List<Politician> getPoliticians() {
return politicians;
}
public void setPoliticians(List<Politician> politicians) {
this.politicians = politicians;
}
}
| [
"micke239@gmail.com"
] | micke239@gmail.com |
861fced283ff4d831ab81ee9d1c20cc8b7db45fd | c5abd3ea80712080fd136e812f78d256b86b2472 | /01.project/03.module/01.web/src/com/newswatch/LoginAction.java | 324cb506e49e25ee90bd43c974e7cd9355e2e188 | [] | no_license | GuanXianghui/newswatch | a25ec34eaaf41a2d4516cd3259e9d1b206dbb9de | c48297e118aee8e96ca6e64ff8fa1364e971709d | refs/heads/master | 2020-05-19T09:26:57.720044 | 2015-06-03T09:40:06 | 2015-06-03T09:40:06 | 34,969,407 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,161 | java | package com.newswatch;
import org.apache.commons.lang.StringUtils;
import com.newswatch.dao.UserDao;
import com.newswatch.entities.User;
import com.newswatch.interfaces.UserInterface;
/**
* 管理员登录
*
* @author Gxx
* @module oa
* @datetime 14-5-10 19:20
*/
public class LoginAction extends BaseAction implements UserInterface{
private static final long serialVersionUID = 1L;
private String name;
private String password;
private String jumpUrl;
/**
* 入口
* @return
*/
public String execute() throws Exception {
logger.info("name:[" + name + "],password:[" + password + "],jumpUrl:[" + jumpUrl + "]");
//判字段为空
if(StringUtils.isBlank(name) || StringUtils.isBlank(password)){
message = "请输入必输项";
return ERROR;
}
//判图片验证码是否正确
if(!checkSecurityCode()){
message = "图片验证码输入错误";
return ERROR;
}
//判名字存在
if(!UserDao.isNameExist(name)){
message = "该用户名不存在";
return ERROR;
}
User user = UserDao.getUserByName(name);
//判密码是否一致
if(!StringUtils.equals(password, user.getPassword())){
message = "你的密码输入有误";
return ERROR;
}
//普通用户 登录成功
//刷新session缓存中的user
refreshSessionUser(user);
message = "登录成功!";
if(StringUtils.isNotBlank(jumpUrl)){
response.sendRedirect(jumpUrl);
} else {
response.sendRedirect("newsSearch.jsp");
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getJumpUrl() {
return jumpUrl;
}
public void setJumpUrl(String jumpUrl) {
this.jumpUrl = jumpUrl;
}
}
| [
"419066357@163.com"
] | 419066357@163.com |
e9d4f16fe5cedb5953af56e3f888b7587f2c405c | 311f3e8d2ba9a82f9083196b7c5dd3e701f76713 | /src/com/bukkit/systexpro/blockpatrol/commands/CommandHandler.java | 88fbbff03af5be44230ea631039828762599edeb | [] | no_license | SystexPro/BlockPatrol | 9938b2daa907977882a137f2a9652de790d68424 | 4ac2bb7b13920aa6b1b3e7c0dc34d4d501e02fd7 | refs/heads/master | 2016-09-05T22:39:21.829254 | 2011-10-14T02:28:44 | 2011-10-14T02:28:44 | 2,550,892 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,073 | java | /**
* THIS JAVA CLASS WAS TAKEN FROM BIGBROTHER.
* ALL COPYRIGHTS GOES TO THE ORIGINAL OWNER
* AND THE DEV THAT HAS TAKEN OVER THAT PLUGIN.
*/
package com.bukkit.systexpro.blockpatrol.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import com.bukkit.systexpro.blockpatrol.BlockPatrolPlugin;
public class CommandHandler implements CommandExecutor {
private HashMap<String, CommandExecutor> executors = new HashMap<String, CommandExecutor>();
private BlockPatrolPlugin plugin;
public CommandHandler(BlockPatrolPlugin core) {
plugin = core;
}
public void registerExecutor(String subcmd, CommandExecutor cmd) {
executors.put(subcmd.toLowerCase(), cmd);
}
/**
* OnCommand
*/
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String commandName = command.getName().toLowerCase();
args = groupArgs(args);
if (sender instanceof Player) {
if (commandName.equalsIgnoreCase("bp")) {
if (args.length == 0)
return help(sender);
String subcommandName = args[0].toLowerCase();
if (!executors.containsKey(subcommandName))
return false;
return executors.get(subcommandName).onCommand(sender, command, commandLabel, args);
}
} else if (sender instanceof ConsoleCommandSender) {
if (commandName.equals("bp")) {
ConsoleCommandSender console = (ConsoleCommandSender) sender;
if (args.length == 0) {
return false;
} else if (args[0].equalsIgnoreCase("version")) {
console.sendMessage("Running BlockPatrol v" + plugin.getDescription().getVersion() + " for Build: " + plugin.settings.build);
} else if(args[0].equalsIgnoreCase("reload")) {
console.sendMessage(ChatColor.GREEN + "Reloaded Configuration File");
plugin.settings.loadConfig();
}
return true;
}
return false;
}
return false;
}
private boolean help(CommandSender sender) {
Player p = (Player) sender;
p.sendMessage("[===Block Patrol===]");
p.sendMessage("Command Triggers - /bp, /b");
p.sendMessage("/bp wand - Gives BlockPatrol Wand(Set in Config)");
return true;
}
public static String[] groupArgs(String[] preargs) {
List<String> args = new ArrayList<String>();
String currentArg = "";
boolean inQuotes = false;
for (String arg : preargs) {
if (inQuotes) {
currentArg += " " + arg;
if (arg.endsWith("\"")) {
args.add(currentArg.substring(0, currentArg.lastIndexOf("\"")));
inQuotes = false;
}
} else {
if (arg.startsWith("\"")) {
inQuotes = true;
currentArg = arg.substring(1, arg.length());
} else {
args.add(arg);
}
}
}
String[] gargs = new String[args.size()];
return args.toArray(gargs);
}
}
| [
"christian@tweakuniverse.com"
] | christian@tweakuniverse.com |
67818d0e124db15e1c9c206fc283b89c52686bf7 | f916e79e8d44942bcdb62be568b9d6f4e6ad1c09 | /v-chat/src/main/java/me/linx/vchat/constants/CodeMap.java | 851741dc29bed94671a06b1814b6af06185161c7 | [] | no_license | qinglok/vChat | a80cef6e3f05f14b013e4df73ca3de247d66cd3a | 4e63eac098b2253fa40138a0ab3c7edd45590396 | refs/heads/master | 2020-04-19T21:19:26.569671 | 2019-03-07T09:57:38 | 2019-03-07T09:57:38 | 168,438,379 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 731 | java | package me.linx.vchat.constants;
public enum CodeMap {
Yes(0, ""),
ErrorSys(1, "系统错误"),
ErrorParameter(2, "参数错误"),
ErrorEmailWasUsed(3, "邮箱已被注册"),
ErrorEmailUnUsed(4, "该邮箱尚未注册"),
ErrorPassword(5, "邮箱或密码错误"),
ErrorTokenFailed(6, "请登录后操作"),
ErrorFileEmpty(7, "文件为空"),
ErrorFileUploadFailure(8, "上传失败"),
ErrorLoggedOther(9, "已经在其他设备登录"),
ErrorVerifySecret(10, "验证密保失败"),
ErrorUserNotFound(10, "找不到该用户");
public int value;
public String msg;
CodeMap(int value, String msg) {
this.value = value;
this.msg = msg;
}
}
| [
"32668325@qq.com"
] | 32668325@qq.com |
03dc505af1c6071ae9f88378ccf22643df7c7665 | a623a6773fc66bd314eec78dd67b4986f1174e50 | /shared/src/main/java/com/jyothi/shared/AutowiringRemoteServiceServlet.java | dadf9fb75c105deef8913880af4d3f16252492cb | [] | no_license | kjyothirani/GWTExample1 | 51bfb7591fb649dfba5027e989fd3e06bf703587 | 4c2fd995aff8aeba883cd35104c3dbb195366bb7 | refs/heads/master | 2021-08-28T01:21:23.361289 | 2017-12-11T02:21:35 | 2017-12-11T02:21:35 | 112,736,771 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,093 | java | package com.jyothi.shared;
import javax.servlet.ServletException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public abstract class AutowiringRemoteServiceServlet extends RemoteServiceServlet {
@Override
public void init() throws ServletException {
super.init();
final WebApplicationContext ctx =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
if (ctx == null) {
throw new IllegalStateException("No Spring web application context found");
}
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
WebApplicationContextUtils.
getRequiredWebApplicationContext(getServletContext()).
getAutowireCapableBeanFactory().
autowireBean(this);
}
} | [
"katajyothi.rani@gmail.com"
] | katajyothi.rani@gmail.com |
f4ec54ccbbd2d5ac79d96d3a09696b36daa91cf0 | 79378de7f97a5be5d0777f55e7a4f267e51cb841 | /java/AULAS/src/lista2exerciciosjava/Exercicio6.java | 9a54ebf10171a34396658e33239a1056d1849578 | [] | no_license | MarlonSilva21/Bootcamp-Generation-turma27 | 6298b3f94701727f9f1fe2e275460aec2681d874 | dd759f88ee759ccab9d69d18839c0bd9638b6373 | refs/heads/main | 2023-07-27T21:36:33.093040 | 2021-09-05T01:21:13 | 2021-09-05T01:21:13 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 591 | java | package lista2exerciciosjava;
import java.util.Locale;
import java.util.Scanner;
public class Exercicio6 {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner leia = new Scanner(System.in);
int multiplo3 = 0, cont = 0, num;
double media = 0.0;
do {
System.out.print("Digite um numero: ");
num = leia.nextInt();
if(num % 3 == 0) {
multiplo3 += num;
cont++;
}
}while(num != 0);
media = multiplo3 / cont;
System.out.printf("Média dos números múltiplos de 3 = %.2f\n", media);
leia.close();
}
}
| [
"josemarlondasilva48@gmail.com"
] | josemarlondasilva48@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.