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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ef43714838a74433331de462f782b28e89ae878 | 42a265ffa03ddd33d10eec6422016a20bc492ba4 | /spring-framework/spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java | 0643ab41d27eff6e4c19c291ad04d8178dff54f0 | [] | no_license | KyrieLSH/Spring | af12751240759e0bc27be05e3bb7227d8869e6ee | 399b836e2d2b571ba70a5e2dfb16a34208afe983 | refs/heads/master | 2020-06-19T23:29:01.251398 | 2019-08-07T05:54:31 | 2019-08-07T05:54:31 | 196,912,473 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,776 | java | /*
* Copyright 2002-2018 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.context.annotation;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.event.DefaultEventListenerFactory;
import org.springframework.context.event.EventListenerMethodProcessor;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
/**
* Utility class that allows for convenient registration of common
* {@link org.springframework.beans.factory.config.BeanPostProcessor} and
* {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor}
* definitions for annotation-based configuration. Also registers a common
* {@link org.springframework.beans.factory.support.AutowireCandidateResolver}.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
* @author Phillip Webb
* @author Stephane Nicoll
* @since 2.5
* @see ContextAnnotationAutowireCandidateResolver
* @see ConfigurationClassPostProcessor
* @see CommonAnnotationBeanPostProcessor
* @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
* @see org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
*/
public abstract class AnnotationConfigUtils {
/**
* The bean name of the internally managed Configuration annotation processor.
*/
public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalConfigurationAnnotationProcessor";
/**
* The bean name of the internally managed BeanNameGenerator for use when processing
* {@link Configuration} classes. Set by {@link AnnotationConfigApplicationContext}
* and {@code AnnotationConfigWebApplicationContext} during bootstrap in order to make
* any custom name generation strategy available to the underlying
* {@link ConfigurationClassPostProcessor}.
* @since 3.1.1
*/
public static final String CONFIGURATION_BEAN_NAME_GENERATOR =
"org.springframework.context.annotation.internalConfigurationBeanNameGenerator";
/**
* The bean name of the internally managed Autowired annotation processor.
*/
public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalAutowiredAnnotationProcessor";
/**
* The bean name of the internally managed Required annotation processor.
* @deprecated as of 5.1, since no Required processor is registered by default anymore
*/
@Deprecated
public static final String REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalRequiredAnnotationProcessor";
/**
* The bean name of the internally managed JSR-250 annotation processor.
*/
public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalCommonAnnotationProcessor";
/**
* The bean name of the internally managed JPA annotation processor.
*/
public static final String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalPersistenceAnnotationProcessor";
private static final String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME =
"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor";
/**
* The bean name of the internally managed @EventListener annotation processor.
*/
public static final String EVENT_LISTENER_PROCESSOR_BEAN_NAME =
"org.springframework.context.event.internalEventListenerProcessor";
/**
* The bean name of the internally managed EventListenerFactory.
*/
public static final String EVENT_LISTENER_FACTORY_BEAN_NAME =
"org.springframework.context.event.internalEventListenerFactory";
private static final boolean jsr250Present;
private static final boolean jpaPresent;
static {
ClassLoader classLoader = AnnotationConfigUtils.class.getClassLoader();
jsr250Present = ClassUtils.isPresent("javax.annotation.Resource", classLoader);
jpaPresent = ClassUtils.isPresent("javax.persistence.EntityManagerFactory", classLoader) &&
ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, classLoader);
}
/**
* Register all relevant annotation post processors in the given registry.
* @param registry the registry to operate on
*/
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
/**
* Register all relevant annotation post processors in the given registry.
* @param registry the registry to operate on
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return a Set of BeanDefinitionHolders, containing all bean definitions
* that have actually been registered by this call
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
/**
* 获取IOC容器
*/
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
/**
* 注册一个配置类解析器的bean定义(ConfigurationClassPostProcessor)
*/
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/**
* 设置AutoWired注解解析器的bean定义信息
*/
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
/**
* 检查是否支持JSR250规范,如何支持注册 解析JSR250规范的注解
*/
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
/**
* 检查是否支持jpa,若支持注册解析jpa规范的注解
*/
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/**
* 注册解析@EventListener的注解
*/
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
private static BeanDefinitionHolder registerPostProcessor(
BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(beanName, definition);
return new BeanDefinitionHolder(definition, beanName);
}
@Nullable
private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {
if (registry instanceof DefaultListableBeanFactory) {
return (DefaultListableBeanFactory) registry;
}
else if (registry instanceof GenericApplicationContext) {
return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();
}
else {
return null;
}
}
public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {
processCommonDefinitionAnnotations(abd, abd.getMetadata());
}
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
else if (abd.getMetadata() != metadata) {
lazy = attributesFor(abd.getMetadata(), Lazy.class);
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
}
if (metadata.isAnnotated(Primary.class.getName())) {
abd.setPrimary(true);
}
AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);
if (dependsOn != null) {
abd.setDependsOn(dependsOn.getStringArray("value"));
}
AnnotationAttributes role = attributesFor(metadata, Role.class);
if (role != null) {
abd.setRole(role.getNumber("value").intValue());
}
AnnotationAttributes description = attributesFor(metadata, Description.class);
if (description != null) {
abd.setDescription(description.getString("value"));
}
}
static BeanDefinitionHolder applyScopedProxyMode(
ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
return definition;
}
boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
}
@Nullable
static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationClass) {
return attributesFor(metadata, annotationClass.getName());
}
@Nullable
static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationClassName) {
return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClassName, false));
}
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
Class<?> containerClass, Class<?> annotationClass) {
return attributesForRepeatable(metadata, containerClass.getName(), annotationClass.getName());
}
@SuppressWarnings("unchecked")
static Set<AnnotationAttributes> attributesForRepeatable(
AnnotationMetadata metadata, String containerClassName, String annotationClassName) {
Set<AnnotationAttributes> result = new LinkedHashSet<>();
// Direct annotation present?
addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));
// Container annotation present?
Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
if (container != null && container.containsKey("value")) {
for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
addAttributesIfNotNull(result, containedAttributes);
}
}
// Return merged result
return Collections.unmodifiableSet(result);
}
private static void addAttributesIfNotNull(
Set<AnnotationAttributes> result, @Nullable Map<String, Object> attributes) {
if (attributes != null) {
result.add(AnnotationAttributes.fromMap(attributes));
}
}
}
| [
"KyrieLSH@163.com"
] | KyrieLSH@163.com |
b9f866890ecf50a553770c2b71d2073b6c5e268f | 08a4360e83a3192ab14542224e6b0b47d8b2b2a6 | /src/java/minhnlt/controller/AddToCartServlet.java | ad9481dfe0d5492d1065ecb8b36f1cb2c9dc2c72 | [] | no_license | Thienminh1999/libraryProject | 9650ca07c0cfab674fced5b7bf1dcd9deacce330 | dd4ee524a73cdc286195c0d004b04f1c610104c3 | refs/heads/master | 2022-11-28T00:27:01.387659 | 2020-08-12T02:09:27 | 2020-08-12T02:09:27 | 286,892,587 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,275 | 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 minhnlt.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import minhnlt.cart.CartObj;
import minhnlt.tblBook.BookDAO;
import minhnlt.tblBook.BookDTO;
/**
*
* @author ADMIN
*/
public class AddToCartServlet extends HttpServlet {
private final String DETAIL_BOOK_SERVLET = "showDetailBookServlet";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String bookId = request.getParameter("txtBookId");
int quantity =Integer.parseInt(request.getParameter("txtQuantity"));
boolean checkAdd = false;
String url;
try {
HttpSession session = request.getSession(true);
if(quantity <= 0){
checkAdd = false;
url = "showDetailBookServlet?txtBookID=" + bookId;
session.setAttribute("checkAddComplete", checkAdd);
request.getRequestDispatcher(url).forward(request, response);
}
BookDAO dao = new BookDAO();
BookDTO book = dao.loadBookDetail(bookId);
CartObj cart = (CartObj) session.getAttribute("CART");
if (cart == null) {
cart = new CartObj();
}
int quantityInDB = dao.getQuantityInDB(bookId);
if(quantity < quantityInDB){
checkAdd = cart.addToCart(book, quantity);
} else {
checkAdd = false;
}
session.setAttribute("checkAddComplete", checkAdd);
session.setAttribute("CART", cart);
} catch (NamingException e) {
log("AddToCartServlet_NamingException" + e.getMessage());
} catch (SQLException e) {
log("AddToCartServlet_SQLException" + e.getMessage());
} finally {
url = "showDetailBookServlet?txtBookID=" + bookId;
request.getRequestDispatcher(url).forward(request, response);
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"56019088+Thienminh1999@users.noreply.github.com"
] | 56019088+Thienminh1999@users.noreply.github.com |
cc4169cf53f8ca8fda738a3ae43b8d1fc9d32d1b | 8abdc7916b578f1feb1d9e448d3b5576456a3bb7 | /src/main/java/cn/DeepBlue/pojo/Course.java | 8b6e06c821672d665f89b36cf9a6a4e0434fe32c | [] | no_license | JavaAR/Member-Management-System | 2f2abf6481ff760e93c7cfbe83d4c8d1d7dd26c1 | 37c7b72a0ee927b3ecc990dd4af8d978222080d8 | refs/heads/master | 2022-12-24T09:34:15.234560 | 2019-10-12T06:36:06 | 2019-10-12T06:36:06 | 210,534,587 | 0 | 0 | null | 2022-12-16T02:23:19 | 2019-09-24T07:03:17 | JavaScript | UTF-8 | Java | false | false | 6,603 | java | package cn.DeepBlue.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Column;
import javax.persistence.Id;
import java.util.Date;
public class Course {
/**
* 课程Id
*/
@Id
@Column(name = "CId")
private Integer cid;
/**
* 课程名称
*/
@Column(name = "CourseName")
private String coursename;
/**
* 课程分类 课程分类表的主键
*/
@Column(name = "CourseClassify")
private Integer courseclassify;
/**
* 上课地址 地址表的主键
*/
@Column(name = "AddressId")
private Integer addressid;
/**
* 开课时间
*/
@DateTimeFormat(pattern = "YYYY-MM-DD hh:mm")
@Column(name = "CourseStartTime")
private Date coursestarttime;
/**
* 下课时间
*/
@DateTimeFormat(pattern = "YYYY-MM-DD hh:mm")
@Column(name = "CourseEndTime")
private Date courseendtime;
/**
* 课时费用
*/
@Column(name = "CourseMoney")
private String coursemoney;
/**
* 创建人
*/
@Column(name = "CREATED_BY")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "CREATED_TIME")
private Date createdTime;
/**
* 更新人
*/
@Column(name = "UPDATED_BY")
private String updatedBy;
/**
* 更新时间
*/
@Column(name = "UPDATED_TIME")
private Date updatedTime;
/**
* 教练 用户表教练id
*/
@Column(name = "CoachId")
private Integer coachid;
/**
* 课程强度
*/
private String courseclassfyname;
public String getCourseclassfyname() {
return courseclassfyname;
}
public void setCourseclassfyname(String courseclassfyname) {
this.courseclassfyname = courseclassfyname;
}
public String getAddname() {
return addname;
}
public void setAddname(String addname) {
this.addname = addname;
}
public String getCoachname() {
return coachname;
}
public void setCoachname(String coachname) {
this.coachname = coachname;
}
/**
* 训练地址
*/
private String addname;
/**
* 教练姓名
*/
private String coachname;
/**
* 获取课程Id
*
* @return CId - 课程Id
*/
public Integer getCid() {
return cid;
}
/**
* 设置课程Id
*
* @param cid 课程Id
*/
public void setCid(Integer cid) {
this.cid = cid;
}
/**
* 获取课程名称
*
* @return CourseName - 课程名称
*/
public String getCoursename() {
return coursename;
}
/**
* 设置课程名称
*
* @param coursename 课程名称
*/
public void setCoursename(String coursename) {
this.coursename = coursename;
}
/**
* 获取课程分类 课程分类表的主键
*
* @return CourseClassify - 课程分类 课程分类表的主键
*/
public Integer getCourseclassify() {
return courseclassify;
}
/**
* 设置课程分类 课程分类表的主键
*
* @param courseclassify 课程分类 课程分类表的主键
*/
public void setCourseclassify(Integer courseclassify) {
this.courseclassify = courseclassify;
}
/**
* 获取上课地址 地址表的主键
*
* @return AddressId - 上课地址 地址表的主键
*/
public Integer getAddressid() {
return addressid;
}
/**
* 设置上课地址 地址表的主键
*
* @param addressid 上课地址 地址表的主键
*/
public void setAddressid(Integer addressid) {
this.addressid = addressid;
}
/**
* 获取开课时间
*
* @return CourseStartTime - 开课时间
*/
public Date getCoursestarttime() {
return coursestarttime;
}
/**
* 设置开课时间
*
* @param coursestarttime 开课时间
*/
public void setCoursestarttime(Date coursestarttime) {
this.coursestarttime = coursestarttime;
}
/**
* 获取下课时间
*
* @return CourseEndTime - 下课时间
*/
public Date getCourseendtime() {
return courseendtime;
}
/**
* 设置下课时间
*
* @param courseendtime 下课时间
*/
public void setCourseendtime(Date courseendtime) {
this.courseendtime = courseendtime;
}
/**
* 获取课时费用
*
* @return CourseMoney - 课时费用
*/
public String getCoursemoney() {
return coursemoney;
}
/**
* 设置课时费用
*
* @param coursemoney 课时费用
*/
public void setCoursemoney(String coursemoney) {
this.coursemoney = coursemoney;
}
/**
* 获取创建人
*
* @return CREATED_BY - 创建人
*/
public String getCreatedBy() {
return createdBy;
}
/**
* 设置创建人
*
* @param createdBy 创建人
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* 获取创建时间
*
* @return CREATED_TIME - 创建时间
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置创建时间
*
* @param createdTime 创建时间
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取更新人
*
* @return UPDATED_BY - 更新人
*/
public String getUpdatedBy() {
return updatedBy;
}
/**
* 设置更新人
*
* @param updatedBy 更新人
*/
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
/**
* 获取更新时间
*
* @return UPDATED_TIME - 更新时间
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置更新时间
*
* @param updatedTime 更新时间
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
/**
* 获取教练 用户表教练id
*
* @return CoachId - 教练 用户表教练id
*/
public Integer getCoachid() {
return coachid;
}
/**
* 设置教练 用户表教练id
*
* @param coachid 教练 用户表教练id
*/
public void setCoachid(Integer coachid) {
this.coachid = coachid;
}
} | [
"3"
] | 3 |
32779823c5b43c0f5f14579c27b54378ca504f69 | 1a784eb6310702ec208aa71035baad3a59220a21 | /Calculation.java | b416b2b1db690a61950fc6352bdeda766ddcffd0 | [] | no_license | kamiyarinshu/emmmm | 5734955d8fdb1381f9d161d646c337465a1a2b04 | ea4801f43f41378487c16d51b692856b6d8410e9 | refs/heads/master | 2020-05-15T21:28:15.275744 | 2019-04-21T06:47:35 | 2019-04-21T06:47:35 | 182,499,690 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | package Page162;
interface Shape {
abstract double area(double number);
}
class Circle implements Shape{
public double area(double number) {
return number*3.1415926;
}
}
class Square implements Shape{
public double area(double number) {
return number*number;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
12849a000a0b690bebe3d22b5754889192e7c4bf | 6dd0af4748bc3db1176e638819f3089f0b26e918 | /hi-ws/src/com/hh/xml/internal/bind/v2/model/impl/RuntimeEnumConstantImpl.java | 3c4d3f19b357477121dc564b81ab2e312cf69f3f | [] | no_license | ngocdon0127/core-hiendm | df13debcc8f1d3dfc421b57bd149a95d2a4cd441 | 46421fbd1868625b0a1c7b1447d4f882e37e6257 | refs/heads/master | 2022-11-17T11:50:16.145719 | 2020-07-14T10:55:22 | 2020-07-14T10:55:22 | 279,256,530 | 0 | 0 | null | 2020-07-13T09:24:43 | 2020-07-13T09:24:42 | null | UTF-8 | Java | false | false | 742 | java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.hh.xml.internal.bind.v2.model.impl;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
/**
* @author Kohsuke Kawaguchi
*/
final class RuntimeEnumConstantImpl extends EnumConstantImpl<Type,Class,Field,Method> {
public RuntimeEnumConstantImpl(
RuntimeEnumLeafInfoImpl owner, String name, String lexical,
EnumConstantImpl<Type,Class,Field,Method> next) {
super(owner, name, lexical, next);
}
}
| [
"truongnx25@viettel.com.vn"
] | truongnx25@viettel.com.vn |
14fa9ba300a3ec7394656a3ddf1ead5ed7d586d4 | a06f9e4a794ba5da8eaa6a150944d10566dd0259 | /Week_05/JDBC-demo/src/main/java/com/geektime/Main.java | d2f556b4cf3ad4cbff8a3a7c6b21dc445b624448 | [] | no_license | william9755/JAVA-000 | 2719bd744a0522852bdba02ae64a5911e8ca585c | c2504dd57908896430429cdc8e2aea7dab24aa9c | refs/heads/main | 2023-02-16T16:23:45.033634 | 2021-01-13T14:39:21 | 2021-01-13T14:39:21 | 303,095,470 | 0 | 0 | null | 2020-10-11T10:31:13 | 2020-10-11T10:31:12 | null | UTF-8 | Java | false | false | 796 | java | package com.geektime;
import com.geektime.app.TestApplication;
import com.geektime.util.ConnectionManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author YangMin
* @time 2020-11-15 20:57
*/
public class Main {
// spring 自动注入
// spring boot 自动配置和 start
// jdbc 原生增删改查、事务、PrepareStatement、批处理
// Hikari
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
TestApplication testApplication = (TestApplication) applicationContext.getBean("testApplication");
testApplication.test();
}
}
| [
"william97@foxmail.com"
] | william97@foxmail.com |
271eec5ea15b64ede0adde06f7c8344c46626424 | 7776ec88ed4fdf029deccdfd24b3eb282a2eb13b | /app/src/main/java/com/graduation/ui/home/question_detail/QuestionDetailActivity.java | fa51e69b0b6616e17b0b8f45198244e34de675a1 | [] | no_license | haitunSasa/Graduation | 13f01181802b1fc616867beb0fbf0e10ad287ffa | b87a00421098dd9df5f8c6487f74762abf66328d | refs/heads/master | 2021-01-20T02:38:27.430450 | 2017-06-17T09:03:26 | 2017-06-17T09:03:26 | 89,435,193 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,292 | java | package com.graduation.ui.home.question_detail;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.graduation.R;
import com.graduation.base.BaseActivity;
import com.graduation.bean.AnswerUser;
import com.graduation.bean.BaseResponse;
import com.graduation.bean.QuestionUser;
import com.graduation.bean.UsersInfo;
import com.graduation.ui.adapter.AnswerAdapter;
import com.graduation.ui.adapter.listener.AnswerListener;
import com.graduation.ui.answer.answer_text.AnswerActivity;
import com.graduation.ui.recycler.IRecyclerView;
import com.graduation.ui.recycler.LoadMoreFooterView;
import com.graduation.ui.recycler.OnRefreshListener;
import com.graduation.utils.SharedPreUtil;
import java.util.List;
import static com.graduation.bean.ErrCode.printErrCause;
public class QuestionDetailActivity extends BaseActivity<QuestionDetailPresenter,QuestionDetailModel> implements QuestionDetailContact.IView ,OnRefreshListener{
private Context context;
private String userName;
private String questionContent;
private int reward;
private int questionIsAnswer;
private QuestionUser questionUser;
private ImageView iv_user_img;
private List<AnswerUser> mData;
private int position;
private IRecyclerView irc;
private AnswerAdapter mAdapter;
private TextView tv_question;
private TextView tv_user_name;
private TextView tv_reward;
private UsersInfo usersInfo;
private Button btn_answer;
public static void startAction(Context context, QuestionUser questionUser){
Intent intent = new Intent(context,QuestionDetailActivity.class);
intent.putExtra("questionUser",questionUser);
context.startActivity(intent);
}
@Override
public int getLayoutId() {
return R.layout.activity_question_detail;
}
@Override
public void initView() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
usersInfo=SharedPreUtil.getInstance().getUser();
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
irc = (IRecyclerView) findViewById(R.id.irc);
iv_user_img = (ImageView) findViewById(R.id.iv_answer_img);
tv_user_name = (TextView) findViewById(R.id.tv_name);
tv_reward = (TextView) findViewById(R.id.tv_reward);
tv_question = (TextView) findViewById(R.id.tv_question);
btn_answer = (Button) findViewById(R.id.btn_answer);
questionUser=(QuestionUser) getIntent().getSerializableExtra("questionUser");
questionContent=questionUser.getQuestionContent();
questionIsAnswer=questionUser.getQuestionIsAnswer();
userName=questionUser.getUserName();
reward=questionUser.getQuestionReward();
if(usersInfo.getRole()==0){
btn_answer.setText("认证专家");
btn_answer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: 2017/5/11 认证专家
}
});
}else {
btn_answer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: 2017/5/11 回答问题
AnswerActivity.starAction(mContext,questionUser);
}
});
}
mAdapter = new AnswerAdapter(this, new AnswerListener() {
@Override
public void eavesdropper(int pos) {
position=pos;
JSONObject jsonObject=new JSONObject();
jsonObject.put("userId", usersInfo.getUserId());
jsonObject.put("questionId", questionUser.getQuestionId());
jsonObject.put("answerId",mData.get(pos).getAnswerId());
mPresenter.eavesdropper(JSON.toJSONString(jsonObject));
}
@Override
public void userDetail(int pos) {
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
irc.setLayoutManager(linearLayoutManager);
irc.setAdapter(mAdapter);
irc.setOnRefreshListener(this);
tv_user_name.setText(userName);
tv_question.setText(questionContent);
tv_reward.setText("¥"+reward);
/*if(questionIsAnswer==1){*/
getAnswer();
mPresenter.getUserAction(usersInfo.getUserId(),questionUser.getQuestionId());
}
private void getAnswer() {
mPresenter.getAnswer(usersInfo.getUserId(),questionUser.getQuestionId());
}
@Override
public void initPresenter() {
mPresenter.setVM(this,mModel);
}
@Override
public void showLoading(String title) {
}
@Override
public void stopLoading() {
irc.setRefreshing(false);
}
@Override
public void showErrorTip(String msg) {
irc.setLoadMoreStatus(LoadMoreFooterView.Status.ERROR);
}
@Override
public void onRefresh() {
mAdapter.getPageBean().setRefresh(true);
//发起请求
irc.setRefreshing(true);
getAnswer();
}
@Override
public void displayAnswer(BaseResponse<List<AnswerUser>> response) {
if(response.flag==1) {
mData = response.data;
mAdapter.reset(mData);
}else {
Toast.makeText(this, printErrCause(response.errCode), Toast.LENGTH_SHORT).show();
}
}
@Override
public void display(BaseResponse<AnswerUser> response) {
if(response.flag==1) {
mData.set(position,response.data);
mAdapter.reset(mData);
}else {
Toast.makeText(this, printErrCause(response.errCode), Toast.LENGTH_SHORT).show();
}
}
}
| [
"947299531@qq.com"
] | 947299531@qq.com |
2f6377f4e08250b46bf2b7cad5549d975e39ba32 | 383952547d8147093afcc8c83e3a4c8cd0912fa8 | /gmall-manage-web/src/main/java/com/atguigu/gamll/manage/util/MyFileUploader.java | ff0a02a059eb4b364e29af2daa5da180396b4424 | [] | no_license | wJ-noName/Gmall1015 | 6849a872e1a21cd9c5140f2ba3ea5bfb4bf0a50e | a11566143d8372a3a7c4790e1968987f08cf91e4 | refs/heads/master | 2020-04-25T08:27:23.326406 | 2019-03-08T00:55:04 | 2019-03-08T00:55:18 | 172,647,783 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,321 | java | package com.atguigu.gamll.manage.util;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;
public class MyFileUploader {
public static String uploadImage(MultipartFile multipartFile){
String url = "http://192.168.85.19";
try {
String path = MyFileUploader.class.getClassLoader().getResource("tracker.conf").getPath();
ClientGlobal.init(path);
TrackerClient trackerClient = new TrackerClient();
TrackerServer connection = trackerClient.getConnection();
StorageClient storageClient = new StorageClient(connection, null);
byte[] bytes = multipartFile.getBytes();
String originalFilename = multipartFile.getOriginalFilename();
int i = originalFilename.lastIndexOf(".");
String substring = originalFilename.substring(i + 1);
String[] strings = storageClient.upload_file(bytes, substring, null);
for (String string : strings) {
url = url + "/" + string;
}
} catch (Exception e) {
e.printStackTrace();
}
return url;
}
}
| [
"wuyaowang@163.com"
] | wuyaowang@163.com |
59514413b6709588c2035501830aea6575606271 | 09459aad9b35cf89ba2c176d629968bba3a8b20d | /src/br/com/declau/hellrider/screens/ScreenBackground.java | 9acd48fb956f22984e739380a04ea941679a512a | [] | no_license | declau/demo_jogo_android_hell_rider | 7b10e4bd945dceddd04bee3d6bc3e8f7c6908187 | 490b44bd3ef79e5f752e898bf8aa2ac662cd57bb | refs/heads/master | 2020-05-29T16:22:39.198186 | 2015-03-23T18:10:22 | 2015-03-23T18:10:22 | 32,750,639 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | package br.com.declau.hellrider.screens;
import org.cocos2d.nodes.CCSprite;
public class ScreenBackground extends CCSprite {
public ScreenBackground(String image) {
super(image);
}
}
| [
"dec82@hotmail.com"
] | dec82@hotmail.com |
31f2dea6229ae37184a356ade704932f9d273a23 | ff22760b31b46dd41d19b50251b64d68659b2fec | /wenda-admin/src/main/java/com/nevada/admin/validator/FlagValidatorClass.java | 2808afb842f66092dcfeabd87e3aa1b96422dee6 | [] | no_license | MissMinFu/wenda | 77d49228b9c353394b5ab76ab4ede8c71302f1f9 | 63c389ea72eaf4a08662155867425bceb23bcc81 | refs/heads/master | 2022-06-28T17:19:37.085330 | 2020-04-14T12:47:38 | 2020-04-14T12:47:38 | 249,633,401 | 0 | 0 | null | 2022-06-21T03:03:14 | 2020-03-24T06:47:33 | Java | UTF-8 | Java | false | false | 826 | java | package com.nevada.admin.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Integer> {
private String[] values;
public void initialize(FlagValidator constraintAnnotation) {
this.values=constraintAnnotation.value();
}
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
boolean isValid = false;
if(value==null){
//当状态为空时使用默认值
return true;
}
for(int i=0;i<values.length;i++){
if(values[i].equals(String.valueOf(value))){
isValid = true;
break;
}
}
return isValid;
}
}
| [
"1583540302@qq.com"
] | 1583540302@qq.com |
ab6f148c84cd3525bde9156df36a3c2126ee22e3 | 5d202cca39068b818717fbbd4d8676d4438c3851 | /app/src/main/java/com/java/demo/test/sort/InsertSort.java | 9f83fee59f629b4bb1eb899bf203b84b4ef8ccdb | [] | no_license | ljzjohnliu/StudyJavaDemo | 4db0eee6a283a313d1a6a274380e8eda2b25f413 | 962e56c727e6665966a16b1c32936d7d0f9b4071 | refs/heads/master | 2023-01-02T17:58:31.113300 | 2020-10-30T09:07:32 | 2020-10-30T09:07:32 | 306,253,600 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,412 | java | package com.java.demo.test.sort;
import java.util.Arrays;
/**
* 直接插入排序的基本思想是:
* 将数组中的所有元素依次跟前面已经排好的元素相比较,如果选择的元素比已排序的元素小,则交换,直到全部元素都比较过为止。
*/
public class InsertSort {
/**
* 算法描述
* 一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
* ①. 从第一个元素开始,该元素可以认为已经被排序
* ②. 取出下一个元素,在已经排序的元素序列中从后向前扫描
* ③. 如果该元素(已排序)大于新元素,将该元素移到下一位置
* ④. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
* ⑤. 将新元素插入到该位置后
* ⑥. 重复步骤②~⑤
*/
/**
* ①. 移位法:
*
* @param array
*/
public static void sort(int[] array) {
if (array == null || array.length == 0) {
return;
}
for (int i = 1; i < array.length; i++) {
int j = i - 1;
int temp = array[i]; // 先取出待插入数据保存,因为向后移位过程中会把覆盖掉待插入数
while (j >= 0 && array[j] > temp) { // 如果待是比待插入数据大,就后移
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp; // 找到比待插入数据小的位置,将待插入数据插入
}
}
/**
* 而交换法不需求额外的保存待插入数据,通过不停的向前交换待插入数据,类似冒泡法,直到找到比它小的值,也就是待插入数据找到了自己的位置。
* ②. 交换法:
*/
public static void sort2(int[] array) {
if (array == null || array.length == 0) {
return;
}
for (int i = 1; i < array.length; i++) {
int j = i - 1;
while (j >= 0 && array[j] > array[j + 1]) { //只要大就交换操作
array[j + 1] = array[j] + array[j + 1];
array[j] = array[j + 1] - array[j];
array[j + 1] = array[j + 1] - array[j];
j--;
System.out.println("Sorting: j = " + j + ", array : " + Arrays.toString(array));
}
}
}
}
| [
"liujianzhang@qiyi.com"
] | liujianzhang@qiyi.com |
8ed15abea37678c6518bdf7bc6a00f6b503a2883 | 65221ef294326b3f158af3474cc375661c46da04 | /src/main/java/com/mook/tomcat/RequestFacade.java | 1de6d1c0a728a873bb979119de10b80935929cf3 | [] | no_license | Dreamroute/tomcat | 6ee77dea90890fa191b351cdde8c5370fe63fa53 | f371103c3205b33f98e48968bbd4ae90715c4ddd | refs/heads/master | 2021-01-17T12:43:07.237707 | 2017-03-08T04:12:10 | 2017-03-08T04:12:10 | 84,072,512 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,286 | java | package com.mook.tomcat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
public class RequestFacade implements ServletRequest {
private Request request;
public RequestFacade(Request request) {
this.request = request;
}
@Override
public Object getAttribute(String name) {
return request.getAttribute(name);
}
@Override
public Enumeration getAttributeNames() {
return null;
}
@Override
public String getCharacterEncoding() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
}
@Override
public int getContentLength() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getContentType() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getParameter(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getParameterNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getParameterValues(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map getParameterMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getProtocol() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getScheme() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerName() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getServerPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public BufferedReader getReader() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRemoteAddr() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRemoteHost() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAttribute(String name, Object o) {
// TODO Auto-generated method stub
}
@Override
public void removeAttribute(String name) {
// TODO Auto-generated method stub
}
@Override
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getLocales() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isSecure() {
// TODO Auto-generated method stub
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRealPath(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getRemotePort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getLocalAddr() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getLocalPort() {
// TODO Auto-generated method stub
return 0;
}
}
| [
"342252328@qq.com"
] | 342252328@qq.com |
98ac545e87f08ad45b24a22301dabd4815807ed6 | 2d9716466bf534c6a22b7320a8fbc26a3fb5bd56 | /011. E-Talk/eTalk/app/src/main/java/com/example/cpu11398_local/etalk/presentation/custom/VerticalClockView.java | 30714a4aef2f755e99031f8cf9861690fd15c89b | [] | no_license | nvhung97/internship | 277a32d65fc66dc9dfd5d93f185deeb24b82a11d | f30b852689e50fe983ef23c5d1ad5cb99c8f4de7 | refs/heads/master | 2020-03-18T23:27:48.180159 | 2019-06-27T10:59:55 | 2019-06-27T10:59:55 | 135,404,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package com.example.cpu11398_local.etalk.presentation.custom;
import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
public class VerticalClockView extends ClockView {
public VerticalClockView(Context context) {
super(context);
}
public VerticalClockView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public VerticalClockView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setTranslationX((getMeasuredHeight() - getMeasuredWidth()) / 2);
setRotation(-90);
}
}
| [
"nvhung1401@gmail.com"
] | nvhung1401@gmail.com |
301ee4303781751b9391b143f907c12df4889631 | f3fe49fc8b6bcd60af915a91ec0d219d05141a11 | /app/common/core/src/main/java/com/uhomed/entrance/core/utils/queue/LockFreeQueue.java | 70a7cc77985947b5fb5f89d590b92ea93907d7b0 | [] | no_license | uhomed/uhomed-entrance | f3d4a915d9416810780f95a37e904823e073efca | 1429d175453a8dc3b8665cdaa9c767f5e25021da | refs/heads/master | 2021-03-30T15:48:34.219052 | 2018-01-11T10:39:20 | 2018-01-11T10:39:20 | 102,097,971 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,150 | java | /**
* mario.com Inc.
* Copyright (c) 2014-2015 All Rights Reserved.
*/
package com.uhomed.entrance.core.utils.queue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* <p>
* A free lock queue,based on linked list
* </p>
*/
public class LockFreeQueue<V> {
// the queue node
@SuppressWarnings("hiding")
private class Node<V> {
public V value = null;
public AtomicReference<Node<V>> next = null;
@SuppressWarnings({ "rawtypes", "unchecked" })
public Node(V value, Node next) {
this.value = value;
this.next = new AtomicReference<Node<V>>(next);
}
}
private AtomicReference<Node<V>> head = null; // queue head
private AtomicReference<Node<V>> tail = null; // queue tail
private AtomicInteger queueSize = new AtomicInteger(0); // size of the queue
public LockFreeQueue() {
Node<V> dummy = new Node<V>(null, null); // init an dummy node
// init head and tail,reference to the same dummy node
head = new AtomicReference<Node<V>>(dummy);
tail = new AtomicReference<Node<V>>(dummy);
}
/**
* <p>
* Add an value to the end of the queue
* </p>
* <p>
* This method is based on CAP operation,and is thread safe.
* </p>
* <p>
* It guarantee the value will eventually add into the queue
* </p>
*
* @param value
* the value to be added into the queue
*/
public void enQueue(V value) {
Node<V> newNode = new Node<V>(value, null);
Node<V> oldTail = null;
while (true) {
oldTail = tail.get();
AtomicReference<Node<V>> nextNode = oldTail.next;
if (nextNode.compareAndSet(null, newNode)) {
break;
} else {
tail.compareAndSet(oldTail, oldTail.next.get());
}
}
queueSize.getAndIncrement();
tail.compareAndSet(oldTail, oldTail.next.get());
}
/**
* <p>
* Get an Value from the queue
* </p>
* <p>
* This method is based on CAP operation,thread safe
* </p>
* <p>
* It guarantees return an value or null if queue is empty eventually
* </p>
*
* @return value on the head of the queue,or null when queue is empty
*/
public V deQueue() {
while (true) {
Node<V> oldHead = head.get();
Node<V> oldTail = tail.get();
AtomicReference<Node<V>> next = oldHead.next;
if (next.get() == null) {
return null; // /queue is empty
}
if (oldHead == tail.get()) {
tail.compareAndSet(oldTail, oldTail.next.get()); // move the
// tail to
// last node
continue;
}
if (head.compareAndSet(oldHead, oldHead.next.get())) {
queueSize.getAndDecrement();
return oldHead.next.get().value;
}
}
}
/**
* <p>
* Get the size of the stack
* </p>
* <p>
* This method doesn't reflect timely state when used in concurrency
* environment
* </p>
*
* @return size of the stack
*/
public int size() {
return queueSize.get();
}
/**
* <p>
* Check if the stack is empty
* </p>
* <p>
* This method doesn't reflect timely state when used in concurrency
* environment
* </p>
*
* @return false unless stack is empty
*/
public boolean isEmpty() {
return queueSize.get() == 0;
}
}
| [
"liming@limingdeMacintosh.local"
] | liming@limingdeMacintosh.local |
9efdd27b37c7f52ef642f9f83aad05a1a29c34a7 | 206a4a8d87d13d325576afe152318db658c27bcc | /src/lavesdk/algorithm/AlgorithmRTE.java | 0a91cda365e9094f4b1dfa8dc03daa5ad4f5c848 | [] | no_license | LavesHSU/Laves-sdk | eed858f862eb02b6536c3aa3575341cd9969fb23 | c25e2fb1a09053c64eb8ed1d82f317cbffe1a749 | refs/heads/master | 2023-03-30T04:46:12.508537 | 2021-03-26T21:14:18 | 2021-03-26T21:14:18 | 319,662,438 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 77,921 | java | /**
* This is part of the LAVESDK - Logistics Algorithms Visualization and Education Software Development Kit.
*
* Copyright (C) 2020 Jan Dornseifer & Department of Management Information Science, University of Siegen &
* Department for Management Science and Operations Research, Helmut Schmidt University
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See license/LICENSE.txt for further information.
*/
package lavesdk.algorithm;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import lavesdk.algorithm.AlgorithmExercise.ExamResult;
import lavesdk.algorithm.enums.AlgorithmStartOption;
import lavesdk.algorithm.plugin.AlgorithmPlugin;
import lavesdk.algorithm.plugin.PluginHost;
import lavesdk.algorithm.plugin.security.HostSecurity;
import lavesdk.algorithm.plugin.views.GraphView;
import lavesdk.algorithm.plugin.views.TextAreaView;
import lavesdk.algorithm.plugin.views.View;
import lavesdk.algorithm.text.AlgorithmStep;
import lavesdk.algorithm.text.AlgorithmText;
import lavesdk.gui.EDT;
import lavesdk.gui.GuiJob;
import lavesdk.gui.GuiRequest;
import lavesdk.logging.enums.LogType;
/**
* The runtime environment of an algorithm.
* <br><br>
* Implement your algorithm by inherit from this class and override the methods {@link #executeStep(int, AlgorithmStateAttachment)},
* {@link #createInitialState(AlgorithmState)}, {@link #storeState(AlgorithmState)}, {@link #restoreState(AlgorithmState)},
* {@link #rollBackStep(int, int)} and {@link #adoptState(int, AlgorithmState)}.<br>
* For information about implementing the algorithm step-by-step look at {@link #executeStep(int, AlgorithmStateAttachment)}.
* <br><br>
* To increase/decrease the execution speed of the algorithm set the factor ({@link #setExecSpeedFactor(float)}) to a greater/smaller
* value than <code>1.0f</code>. Skip/ignore all breakpoints by using {@link #setSkipBreakpoints(boolean)}.
* <br><br>
* Use {@link #setMinStepDwellTime(long)} to specify the execution time that a step should have at least. This prevents from overrunning
* steps especially if the user steps back in the algorithm.
* <br><br>
* <b>Listener</b>:<br>
* Use {@link #addListener(RTEListener)} to add a {@link RTEListener} to listen to runtime events like:
* <ul>
* <li>when does the algorithm start? ({@link RTEListener#beforeStart(RTEvent)})</li>
* <li>when does the algorithm resume? ({@link RTEListener#beforeResume(RTEvent)})</li>
* <li>when does the algorithm pause? ({@link RTEListener#beforePause(RTEvent)})</li>
* <li>when does the algorithm stop? ({@link RTEListener#onStop()})</li>
* </ul>
* <b>The plugin is automatically added as a listener of runtime events</b>.
* <br><br>
* <b>Attention</b>:<br>
* The algorithm runtime environment is only functioning if the host application is registered using
* {@link #registerHost(lavesdk.algorithm.plugin.PluginHost)}. <b>This must only be done by the host application</b>!
* <br><br>
* <b>Exercise mode</b>:<br>
* The algorithm can be executed in two different modes, the normal mode on the one hand which allows the user to
* start, resume, pause, stop and go the previous or next step and the exercise mode on the other hand. In the exercise mode
* it is only possible to start and stop the algorithm, the execution is done fully automatic so the user can only give right answers
* to the questions to go one step further. If the user cannot solve an exercise he can give it up to continue.<br>
* Use {@link #setExerciseModeEnabled(boolean)} to change the mode of the runtime environment.
* <br><br>
* <b>Visualization Policy (please note)</b>:<br>
* The LAVESDK uses the Swing framework to display the graphical user interface of algorithms or in general to display the GUI.
* Furthermore each algorithm has its own runtime environment (RTE) that runs in an own thread. This brings us a hazard of
* unpredictable behavior (like thread interference or memory consistency errors) when a RTE thread updates the GUI. That's because
* the GUI is handled by another thread (the event dispatch thread, EDT) and moreover the Swing GUI is especially not thread-safe.<br>
* But the thread-safe modification of the GUI must be possible because the visualization of an algorithm is done in the RTE thread,
* meaning another thread as the EDT.
* <br><br>
* Therefore it is stated that each visual component that is part of the LAVESDK has to be thread-safe and should be tagged as one.
* If this is not the case it is up to you to ensure that all the <b>thread-unsafe calls</b> you make to modify the GUI of
* your algorithm plugin are shifted to the EDT.<br>
* You can shift a GUI action to the EDT from the RTE thread by using a {@link GuiJob} or a {@link GuiRequest}.<br>
* <u>Example</u>: you have a <code>TextView</code> component that has a thread-unsafe <code>setText(...)</code> method and a <code>ListView</code> component
* that has a thread-unsafe <code>getEntry(...)</code> method
* <pre>
* ...
* protected void executeStep(int stepID, AlgorithmStateAttachment asa) throws Exception {
* ...
* switch(stepID) {
* case 3:
* // a step that changes a specific set
*
* // visualize the changed set but the setText()-method of the TextView is not thread-safe
* // so shift the call to the EDT
* EDT.execute(new GuiJob() {
* protected void execute() throws Throwable {
* textView.setText(set);
* }
* });
*
* nextStepID = 4;
* break;
* case 7:
* // a step that has to modify an entry of a ListView component its getEntry() method is not thread-safe
* final Entry e = EDT.execute(new GuiRequest<Entry>() {
* protected Entry execute() throws Throwable {
* return listView.getEntry(index);
* }
* });
*
* // modify the entry
* ...
* break;
* }
*
* return nextStepID;
* }
* ...
* </pre>
*
* @author jdornseifer
* @version 1.3
* @since 1.0
*/
public abstract class AlgorithmRTE extends HostSecurity {
/** the thread in which the runtime environment of the algorithm is running or <code>null</code> if currently no thread is existing */
private Thread thread;
/** the runtime environment */
private final RuntimeEnvironment rte;
/** the algorithm plugin that uses the runtime environment */
private final AlgorithmPlugin plugin;
/** the initial state of the algorithm */
private final AlgorithmState initialState;
/** the listeners of the rte */
private final List<RTEListener> listeners;
/** a custom exercise provider or <code>null</code> if there is no custom provider */
private final AlgorithmExerciseProvider customExerciseProvider;
/** flag for the {@link RTEListener#beforeStart(RTEvent)} event */
private static final short RTEVENT_BEFORESTART = 1;
/** flag for the {@link RTEListener#beforeResume(RTEvent)} event */
private static final short RTEVENT_BEFORERESUME = 2;
/** flag for the {@link RTEListener#beforePause(RTEvent)} event */
private static final short RTEVENT_BEFOREPAUSE = 3;
/** flag for the {@link RTEListener#onStop()} event */
private static final short RTEVENT_ONSTOP = 4;
/** flag for the {@link RTEListener#onRunning()} event */
private static final short RTEVENT_ONRUNNING = 5;
/** flag for the {@link RTEListener#onPause()} event */
private static final short RTEVENT_ONPAUSE = 6;
/**
* Creates a new algorithm runtime environment.
*
* @param plugin the algorithm plugin that uses the runtime environment
* @param text the algorithm text that is executed in the runtime environment
* @throws IllegalArgumentException
* <ul>
* <li>if plugin is null</code>
* <li>if text is null</code>
* </ul>
* @since 1.0
*/
public AlgorithmRTE(final AlgorithmPlugin plugin, final AlgorithmText text) throws IllegalArgumentException {
this(plugin, text, null);
}
/**
* Creates a new algorithm runtime environment.
*
* @param plugin the algorithm plugin that uses the runtime environment
* @param text the algorithm text that is executed in the runtime environment
* @param provider a custom provider that handles and displays exercises of the algorithm or <code>null</code> if the default provider of the host should be used
* @throws IllegalArgumentException
* <ul>
* <li>if plugin is null</code>
* <li>if text is null</code>
* </ul>
* @since 1.0
*/
public AlgorithmRTE(final AlgorithmPlugin plugin, final AlgorithmText text, final AlgorithmExerciseProvider provider) throws IllegalArgumentException {
if(plugin == null)
throw new IllegalArgumentException("No valid argument!");
this.thread = null;
this.rte = new RuntimeEnvironment(text);
this.plugin = plugin;
this.listeners = new ArrayList<RTEListener>();
this.customExerciseProvider = provider;
// create the initial state of the algorithm
initialState = new AlgorithmState(plugin, RuntimeEnvironment.INITIALSTATE_STEPID);
createInitialState(initialState);
// very important: freeze the initial state and DO NOT add this one to the history!!!
initialState.freeze();
// add the plugin as the first listener of runtime events
listeners.add(plugin);
}
/**
* Adds a new listener to listen to runtime events of the algorithm.
*
* @see RTEAdapter
* @param listener the listener
* @since 1.0
*/
public final void addListener(final RTEListener listener) {
if(listener == null || listeners.contains(listener))
return;
listeners.add(listener);
}
/**
* Removes the listener from the algorithm runtime environment.
*
* @param listener the listener
* @since 1.0
*/
public final void removeListener(final RTEListener listener) {
if(listener == null || listener == plugin)
return;
listeners.remove(listener);
}
/**
* Starts or resumes the execution of the algorithm.<br>
* This triggers the {@link RTEListener#beforeStart(RTEvent)} or {@link RTEListener#beforeResume(RTEvent)} and the
* {@link RTEListener#onRunning()} event.
*
* @see #pause()
* @see #stop()
* @since 1.0
*/
public final void start() {
start(AlgorithmStartOption.NORMAL);
}
/**
* Starts or resumes the execution of the algorithm.<br>
* This triggers the {@link RTEListener#beforeStart(RTEvent)} or {@link RTEListener#beforeResume(RTEvent)} and the
* {@link RTEListener#onRunning()} event.
* <br><br>
* <b>Notice</b>:<br>
* Each step of the algorithm has a specific dwell time (either a custom one determined by the algorithm developer or a predefined one determined by {@link #setMinStepDwellTime(long)}).
* This dwell time can be ignored using the {@link AlgorithmStartOption#START_TO_FINISH} option. This means that only breakpoints are regarded.
* <br><br>
* If the runtime environment is in exercise mode it is not possible to pause and resume the work. The execution of the algorithm
* is performed fully automatic by the runtime environment during the exercise.
*
* @see #pause()
* @see #stop()
* @param option the start option of the algorithm
* @throws IllegalArgumentException
* <ul>
* <li>if option is null</li>
* </ul>
* @since 1.0
*/
public final void start(final AlgorithmStartOption option) throws IllegalArgumentException {
if(option == null)
throw new IllegalArgumentException("No valid argument!");
// only the active plugin has permission to start the rte
if(!isActivePlugin(plugin)) {
writeLogMessage(plugin, "Plugin tries to start its algorithm runtime environment but is not active!", LogType.WARNING);
return;
}
// rte is running? then break up
if(isRunning())
return;
if(!isStarted()) {
// fire runtime event and break up if the event is canceled
if(!fireRuntimeEvent(RTEVENT_BEFORESTART))
return;
// we start from the beginning
rte.restart(option);
// restore the initial data of the time of freezing
initialState.unfreeze();
// restore the initial state
restoreState(initialState);
// start a new thread if rte is stopped or not started yet
synchronized(this) {
thread = new Thread(rte);
thread.start();
}
}
else if(rte.isPaused()) {
// fire runtime event and break up if the event is canceled
if(!fireRuntimeEvent(RTEVENT_BEFORERESUME))
return;
/*
* INFO:
* If the rte is in exercise mode then it is not possible to resume its work. Because of the rte
* cannot be paused, isRunning() returns true which means that the work cannot be resumed because
* of the check above so we to do anything here.
*/
// let the runtime environment resume its work
rte.resume(option);
}
fireRuntimeEvent(RTEVENT_ONRUNNING);
}
/**
* Pauses the runtime environment of the algorithm until it is resumed by calling {@link #start()}.<br>
* This triggers the {@link RTEListener#beforePause(RTEvent)} and the {@link RTEListener#onPause()} event.
* <br><br>
* <b>Notice</b>:<br>
* If the runtime environment is in exercise mode it is not possible to pause and resume the work. The execution of the algorithm
* during the exercise is performed fully automatic by the runtime environment.
*
* @see #start()
* @see #stop()
* @since 1.0
*/
public final void pause() {
// only the active plugin has permission to pause the rte
if(!isActivePlugin(plugin)) {
writeLogMessage(plugin, "Plugin tries to pause its algorithm runtime environment but is not active!", LogType.WARNING);
return;
}
if(isStarted() && !isExerciseModeEnabled()) {
// fire runtime event and break up if the event is canceled
if(!fireRuntimeEvent(RTEVENT_BEFOREPAUSE))
return;
rte.pause();
// pause is done so notify the listeners
fireRuntimeEvent(RTEVENT_ONPAUSE);
}
}
/**
* Stops the runtime environment of the algorithm. This means that the rte has to be restarted by calling
* {@link #start()}.<br>
* This triggers the {@link RTEListener#onStop()} event.
*
* @see #pause()
* @since 1.0
*/
public final void stop() {
// only the active plugin has permission to stop the rte
if(!isActivePlugin(plugin)) {
writeLogMessage(plugin, "Plugin tries to stop its algorithm runtime environment but is not active!", LogType.WARNING);
return;
}
if(!isStarted())
return;
// interrupt runtime thread
// (important: further actions are done in the onStop() method which is invoked automatically by the rte -> see run())
synchronized(this) {
if(thread != null)
thread.interrupt();
}
}
/**
* Goes to the next step of the algorithm. This is only possible if the runtime environment was started once
* and not stopped until yet.
* <br><br>
* <b>Notice</b>:<br>
* If the exercise mode is enabled ({@link #isExerciseModeEnabled()}) then it is not possible to go to the next step.
*
* @since 1.0
*/
public final void nextStep() {
// only the active plugin has permission to go to the next step
if(!isActivePlugin(plugin)) {
writeLogMessage(plugin, "Plugin tries to go to the next step in its algorithm runtime environment but is not active!", LogType.WARNING);
return;
}
if(!isStarted())
return;
// skips the execution of the current step (this is only possible if the rte is not in exercise mode)
rte.skipStep();
}
/**
* Goes to the previous step of the algorithm. This is only possible if the runtime environment was started once
* and not stopped until yet.
* <br><br>
* <b>Notice</b>:<br>
* If the exercise mode is enabled ({@link #isExerciseModeEnabled()}) then it is not possible to go to the previous step.
*
* @since 1.0
*/
public final void prevStep() {
// only the active plugin has permission to go to the previous step
if(!isActivePlugin(plugin)) {
writeLogMessage(plugin, "Plugin tries to go to the previous step in its algorithm runtime environment but is not active!", LogType.WARNING);
return;
}
if(!isStarted())
return;
// go one step back (this is only possible if the rte is not in exercise mode)
rte.goStepBack();
}
/**
* Indicates if the runtime environment is started.
*
* @return <code>true</code> if the rte is started otherwise <code>false</code>
* @since 1.0
*/
public final boolean isStarted() {
return rte.isStarted();
}
/**
* Indicates if the algorithm runtime environment is currently in running mode. This means that
* it is started and not paused.
*
* @return <code>true</code> if the rte is running otherwise <code>false</code>
*/
public final boolean isRunning() {
return isStarted() && !rte.isPaused();
}
/**
* Gets the execution speed factor of the rte.
* <br><br>
* <b>Notice</b>:<br>
* A value smaller <code>1.0f</code> means a <b>slower</b> and a value greater <code>1.0f</code> a
* <b>faster execution</b>. For example a factor of <code>2.0f</code> means that the execution of the
* algorithm is two times faster as normal and a factor of <code>0.5f</code> means that the execution is only
* half as fast as normal (<code>0.1f</code> means ten times slower as normal).
*
* @return the execution speed factor (a value <code>> 0.0f</code>)
* @since 1.0
*/
public final float getExecSpeedFactor() {
return rte.getExecSpeedFactor();
}
/**
* Sets the execution speed factor of the rte.
* <br><br>
* <b>Notice</b>:<br>
* A value smaller <code>1.0f</code> means a <b>slower</b> and a value greater <code>1.0f</code> a
* <b>faster execution</b>. For example a factor of <code>2.0f</code> means that the execution of the
* algorithm is two times faster as normal and a factor of <code>0.5f</code> means that the execution is only
* half as fast as normal (<code>0.1f</code> means ten times slower as normal).
*
* @param factor the execution speed factor (a value <code>> 0.0f</code>)
* @since 1.0
*/
public final void setExecSpeedFactor(final float factor) {
rte.setExecSpeedFactor(factor);
}
/**
* Gets the minimal dwell time that a step must have.
* <br><br>
* <b>Notice</b>:<br>
* If a step has no dwell time it is hard to go back over this step ("go to previous step") because it is always transition into the next step.
* So if a step does not have the minimal dwell time the runtime environment is automatically paused for the remaining time and
* an overrun of the step is prevented.<br>
* The default value is <code>500</code> milliseconds.
*
* @return the minimal execution time in milliseconds
* @since 1.0
*/
public final long getMinStepDwellTime() {
return rte.getMinDwellTime();
}
/**
* Sets the minimal dwell time that a step must have.
* <br><br>
* <b>Notice</b>:<br>
* If a step has no dwell time it is hard to go back over this step ("go to previous step") because it is always transition into the next step.
* So if a step does not have the minimal dwell time the runtime environment is automatically paused for the remaining time and
* an overrun of the step is prevented.<br>
* The default value is <code>500</code> milliseconds.
*
* @param millis the minimal dwell time in milliseconds
* @throws IllegalArgumentException
* <ul>
* <li>if millis is <code>< 0</code></li>
* </ul>
* @since 1.0
*/
public final void setMinStepDwellTime(final long millis) throws IllegalArgumentException {
rte.setMinDwellTime(millis);
}
/**
* Indicates if the breakpoints will currently be skipped/ignored.
*
* @return <code>true</code> if breakpoints are ignored otherwise <code>false</code>
* @since 1.0
*/
public final boolean getSkipBreakpoints() {
return rte.getSkipBreakpoints();
}
/**
* Sets if the breakpoints should currently be skipped/ignored.
*
* @param skip <code>true</code> if breakpoints are ignored otherwise <code>false</code>
* @since 1.0
*/
public final void setSkipBreakpoints(final boolean skip) {
rte.setSkipBreakpoints(skip);
}
/**
* Indicates whether the runtime environment should be paused before it transitions into stop.
*
* @return <code>true</code> if the runtime environment pauses the execution before it transitions into stop otherwise <code>false</code>
* @since 1.0
*/
public final boolean getPauseBeforeStop() {
return rte.getPauseBeforeTerminate();
}
/**
* Sets whether the runtime environment should be paused before it transitions into stop.
*
* @param pause <code>true</code> if the environment should pause the execution before it transitions into stop otherwise <code>false</code>
* @since 1.0
*/
public final void setPauseBeforeTerminate(final boolean pause) {
rte.setPauseBeforeTerminate(pause);
}
/**
* Indicates whether the exercise mode of the runtime environment is enabled.
* <br><br>
* Exercises of the algorithm are only presented to the user when the exercise mode is enabled.
*
* @return <code>true</code> if the exercise mode is enabled otherwise <code>false</code>
* @since 1.0
*/
public final boolean isExerciseModeEnabled() {
return rte.isExerciseModeEnabled();
}
/**
* Sets whether the exercise mode of the runtime environment should be enabled.
* <br><br>
* Exercises of the algorithm are only presented to the user when the exercise mode is enabled.
* <br><br>
* <b>Notice</b>:<br>
* This is only possible if the plugin has this mode ({@link AlgorithmPlugin#hasExerciseMode()} and the rte is not started yet (meaning
* the exercise mode can only be activated if the rte is stopped).
* The {@link PluginHost} is notified about the changed mode by {@link PluginHost#rteModeChanged()}.
*
* @param enabled <code>true</code> if the exercise mode should be enabled otherwise <code>false</code>
* @since 1.0
*/
public final void setExerciseModeEnabled(final boolean enabled) {
// if the plugin does not have an exercise mode then it is not possible to enable this mode
if(!plugin.hasExerciseMode())
return;
rte.setExerciseModeEnabled(enabled);
}
/**
* Allows the runtime environment to sleep for a specific amount of time.
*
* @param millis the sleeping time in milliseconds
* @since 1.0
*/
protected final void sleep(final long millis) {
if(!isStarted() || millis <= 0)
return;
/*
* INFO:
* It may not be checked against isRunning() otherwise a step is completely
* processed although he has inner steps in the following scenario:
* The user pauses the rte and goes to the next step.
* That means if the execution of the next step uses multiple sleeps for inner steps
* all these invocations are ignored because the rte is in pause mode which means isRunning()
* is false.
*/
rte.sleep(millis);
}
/**
* Executes a step of the algorithm.
* <br><br>
* <b>Visualize a step</b>:<br>
* Use {@link #sleep(long)} to let the algorithm sleep for a specific amount of time to visualize the current step.<br>
* Please note that if you modify a GUI component (for example a {@link GraphView}) you should invoke the <i>repaint</i> method after
* you make the modification.<br>
* <u>Example</u>: Change the background color of a vertex with the caption "v".
* <pre>
* ...
* // get the visual component of the vertex
* GraphView<Vertex, Edge>.VisualVertex vv = graphView.getVisualVertexByCaption("v");
* // change the background and afterwards repaint the graph view
* vv.setBackground(Color.yellow);
* graphView.repaint();
* </pre>
* <b>Important (please note)</b>:<br>
* The execution of algorithm steps runs in an own thread of the runtime environment. Because the Swing framework is
* not thread-safe this brings us a hazard of unpredictable behavior if you update the GUI (meaning you visualize something)
* from the inside of this method because the method is executed in another thread then the GUI (the GUI is executed in a thread
* called the event dispatch thread, EDT).<br>
* To avoid this hazard of unpredictable behavior you have to consider the following: if you invoke a method of a visual component
* that is not tagged as <b>thread-safe</b> then you have to implement it on your own<br>
* <u>Example</u>: the method <code>setText(...)</code> of a component <code>TextView</code> is <b>not tagged as thread-safe</b>:
* <pre>
* final Set<Integer> set;
* ...
* // visualize the current set
* EDT.execute(new GuiJob() {
* protected void execute() {
* textView.setText(set.toString());
* }
* });
* ...
* </pre>
* If a method is <b>tagged as thread-safe</b> (like "This method is thread-safe!") then you can invoke the method directly in the runtime environment without shift it
* to the EDT.
*
* @param stepID the id of the step that should be executed
* @param asa the attachment of the current algorithm state that can be used to attach data that is available only during the execution of the current step
* @return the id of the following step or <code>< 0</code> if the algorithm is terminated
* @throws Exception
* <ul>
* <li>a step can throw an exception while the step is in execution which results in a breakup of the whole algorithm execution but prevents from a crash -<br>
* the exception will be logged (via the connected host) but this is an <b>unusual behavior</b> of the algorithm and should be avoided</li>
* </ul>
* @since 1.0
*/
protected abstract int executeStep(final int stepID, final AlgorithmStateAttachment asa) throws Exception;
/**
* Stores the current state of the algorithm.
* <br><br>
* Use the <i>add</i> methods ({@link AlgorithmState#addInt(String, int)}/{@link AlgorithmState#addSet(String, lavesdk.math.Set)}/...) to
* store the current content of the variables you use in your algorithm implementation.
* <br><br>
* <b>Example</b>:
* <pre>
* public class MyAlgorithm extends AlgorithmRTE {
* ...
* private int k;
* private float B;
* private List<Integer> indices;
* ...
*
* protected void storeState(AlgorithmState state) {
* state.addInt("k", k);
* state.addFloat("B", B);
* state.addList("indices", indices);
* }
*
* protected void restoreState(AlgorithmState state) {
* k = state.getInt("k");
* B = state.getFloat("B");
* indices = state.getList("indices");
* }
*
* ...
*
* protected int executeStep(int stepID, AlgorithmStateAttachment asa) {
* ...
* // implement each step of the algorithm
* switch(stepID) {
* case ...: k = indices.get(i); indices.remove(i); ...
* case ...: B = 0.5*k*i; ...
* }
*
* return nextStep;
* }
*
* ...
* }
* </pre>
* <b>Attention</b>:<br>
* If you want to store custom objects in an algorithm state ensure that these objects implement {@link Serializable}
* and are <code>public</code> and independent classes.<br>
* If a state cannot be frozen (error message: "Algorithm state could not be frozen!") a reason might be that you try to store
* custom objects that are not <code>public</code> or not independent (like nested classes).
*
* @param state the state where the algorithm variables/data should be stored
* @since 1.0
*/
protected abstract void storeState(final AlgorithmState state);
/**
* Restores a state of the algorithm.
* <br><br>
* Use the <i>get</i> methods ({@link AlgorithmState#addInt(String, int)}/{@link AlgorithmState#addSet(String, lavesdk.math.Set)}/...) to
* assign the data of the state to the variables you use in your algorithm implementation.
* <br><br>
* <b>Example</b>:
* <pre>
* public class MyAlgorithm extends AlgorithmRTE {
* ...
* private int k;
* private float B;
* private List<Integer> indices;
* ...
*
* protected void storeState(AlgorithmState state) {
* state.addInt("k", k);
* state.addFloat("B", B);
* state.addList("indices", indices);
* }
*
* protected void restoreState(AlgorithmState state) {
* k = state.getInt("k");
* B = state.getFloat("B");
* indices = state.getList("indices");
* }
*
* ...
*
* protected int executeStep(int stepID, AlgorithmStateAttachment asa) {
* ...
* // implement each step of the algorithm
* switch(stepID) {
* case ...: k = indices.get(i); indices.remove(i); ...
* case ...: B = 0.5*k*i; ...
* }
*
* return nextStep;
* }
*
* ...
* }
* </pre>
* <b>Attention</b>:<br>
* If a state cannot be made unfrozen (error message: "Algorithm state could not be unfrozen!") a reason might be that you try to restore
* custom objects that are not <code>public</code> or not independent (like nested classes).
*
* @param state the state where the algorithm variables/data should be stored
* @since 1.0
*/
protected abstract void restoreState(final AlgorithmState state);
/**
* Creates the initial state of the algorithm meaning the initial values of the variables
* which are used in your algorithm.
* <br><br>
* This state is used to restore the initial state of the algorithm if for example the runtime environment is stopped ({@link #stop()})
* and the algorithm should start from scratch.
* <br><br>
* <b>Notice</b>:<br>
* This method is invoked at creation time of the algorithm runtime environment which means in the constructor (see example) so it is
* only called once.
* <br><br>
* <b>Example</b>:
* <pre>
* public class MyAlgorithm extends AlgorithmRTE {
* ...
* private int k;
* private float B;
* private List<Integer> indices;
* ...
*
* public MyAlgorithm(AlgorithmPlugin plugin) {
* super(plugin);
* ...
* // the variables of the algorithm are initialized through createInitialState(...)
* }
*
* protected void createInitialState(AlgorithmState state) {
* k = state.addInt("k", 0);
* B = state.addFloat("B", 0.0f);
* indices = state.addList("indices", new ArrayList<>());
* }
*
* ...
* }
* </pre>
*
* @see #storeState(AlgorithmState)
* @see #restoreState(AlgorithmState)
* @param state the state where the algorithm variables/data should be stored
* @since 1.0
*/
protected abstract void createInitialState(final AlgorithmState state);
/**
* Rolls back the specified step.
* <br><br>
* This method is triggered if a state is popped from the state history meaning that the algorithm is set
* to a previous step so that an earlier state of the algorithm is restored.<br>
* It is invoked {@link #restoreState(AlgorithmState)} before a step is rolled back meaning it is possible to access the
* state the algorithm had before the given step was executed.
* <br><br>
* <b>Use this method to undo the visualization of a step</b>.
* <br><br>
* <u>Example</u>:
* <pre>
* protected void rollBackStep(int stepID) {
* switch(stepID) {
* ...
* case StepIDs.INITIALIZE_SETS:
* // the step to initialize the sets of the algorithm (like "Let A:={v1}, B:={v | v in V and (v, v1) in E} ...")
* // should be rolled back meaning we delete the text in the specific view that shows the sets
* textAreaView.setText("");
* break;
* ...
* }
* }
* </pre>
* <b>Important (please note)</b>:<br>
* The execution of algorithm steps runs in an own thread of the runtime environment. Because the Swing framework is
* not thread-safe this brings us a hazard of unpredictable behavior if you update the GUI (meaning you visualize something)
* from the inside of this method because the method is executed in another thread then the GUI (the GUI is executed in a thread
* called the event dispatch thread, EDT).<br>
* To avoid this hazard of unpredictable behavior you have to consider the following: if you invoke a method of a visual component
* that is not tagged as <b>thread-safe</b> then you have to implement it on your own<br>
* Example: the method <code>setText(...)</code> of a component <code>TextView</code> is <b>not tagged as thread-safe</b>:
* <pre>
* final Set<Integer> set;
* ...
* // visualize the current set
* EDT.execute(new GuiJob() {
* protected void execute() {
* textView.setText(set.toString());
* }
* });
* ...
* </pre>
* If a method is <b>tagged as thread-safe</b> (like "This method is thread-safe!") then you can invoke the method directly in the runtime environment without shift it
* to the EDT.
*
* @param stepID the id of the step to roll back
* @param nextStepID the id of the next step that would have been executed if the current step were not rolled back (this information is useful when a step has several execution branches with each doing different visualization work); might be <code>< 0</code> if no further step follows and the algorithm terminates
* @since 1.0
*/
protected abstract void rollBackStep(final int stepID, final int nextStepID);
/**
* Lets the algorithm adopt the given state.
* <br><br>
* This has to be performed <b>if and only if</b> an exercise of an {@link AlgorithmStep} overrides {@link AlgorithmExercise#getApplySolutionToAlgorithm()} meaning
* that it returns <code>true</code>.<br>
* A state is adopted directly before the related step is executed.<br>
* Request the solution(s) by use of the associated key(s) defined in {@link AlgorithmExercise#applySolutionToAlgorithm(AlgorithmState, Object[])}.
* <br><br>
* Applying the solution to the algorithm is useful when a step can be executed in several ways so adopting a solution lets the
* algorithm continue with the way the user has chosen.
* <br><br>
* <u>Example</u>: The user has to select a path in a graph from a specific vertex to another one which means in general that their
* are more than one correct paths. The algorithm can choose any path too, that is the path must not be equal to the user's choice.
* Applying the solution of the user to the algorithm let the algorithm take the same path as the user has specified and it ensures
* a synchronous execution.
*
* @param stepID the id of the step for whom this adoption is done
* @param state the state the algorithm should adopt (<b>in general this state is not equal a state stored or restored with {@link #storeState(AlgorithmState)}/{@link #restoreState(AlgorithmState)}</b>)
* @since 1.0
*/
protected abstract void adoptState(final int stepID, final AlgorithmState state);
/**
* Gets the views that are used in the runtime environment to visualize the algorithm.
* <br><br>
* <b>Example</b>:<br>
* The algorithm uses a {@link GraphView} <code>graphView</code> and a {@link TextAreaView} <code>textAreaView</code> to visualize the algorithm,
* so the method should return them as follows:
* <pre>
* protected View[] getViews() {
* return new View[] { graphView, textAreaView };
* }
* </pre>
* These view information are used to disable the repaint mechanism of the views when an algorithm step is skipped by use of {@link #nextStep()}
* or {@link #prevStep()}. Disabling the repaint mechanism might enhance the performance during a step is skipped.
*
* @return the array of views that are used to visualize the algorithm or <code>null</code>
* @since 1.0
*/
protected abstract View[] getViews();
@Override
protected final void hostAccepted() {
// there is set a secured host system for the runtime environment? then set the exercise provider that should be used
rte.setExerciseProvider((customExerciseProvider != null) ? customExerciseProvider : getDefaultExerciseProvider());
}
/**
* Stops and resets the runtime environment of the algorithm meaning that the current runtime environment
* thread is terminated if necessary and the executing step of the {@link AlgorithmText}
* is set to the initial one.
* <br><br>
* Furthermore the runtime event "on stop" is fired.
* <br><br>
* <b>Attention</b>:<br>
* This method may only be invoked by the {@link RuntimeEnvironment#run()} method!
*
* @since 1.0
*/
private void onStop() {
// clear the runtime thread
synchronized(this) {
thread = null;
}
// notify the listeners
fireRuntimeEvent(RTEVENT_ONSTOP);
}
/**
* Fires the declared runtime event for each listener.
*
* @see #RTEVENT_BEFORESTART
* @see #RTEVENT_BEFORERESUME
* @see #RTEVENT_BEFOREPAUSE
* @see #RTEVENT_ONSTOP
* @see #RTEVENT_ONRUNNING
* @param event the event
* @return <code>true</code> if the event should be done otherwise <code>false</code>
* @since 1.0
*/
private boolean fireRuntimeEvent(final int event) {
for(int i = 0; i < listeners.size(); i++) {
final RTEListener l = listeners.get(i);
final RTEvent e = new RTEvent(rte.getExecutingStepID());
EDT.execute(new GuiJob(getClass().getSimpleName() + ".fireRuntimeEvent", true) {
@Override
protected void execute() throws Throwable {
switch(event) {
case RTEVENT_BEFORESTART:
l.beforeStart(e);
break;
case RTEVENT_BEFORERESUME:
l.beforeResume(e);
break;
case RTEVENT_BEFOREPAUSE:
l.beforePause(e);
break;
case RTEVENT_ONSTOP:
l.onStop();
break;
case RTEVENT_ONRUNNING:
l.onRunning();
break;
case RTEVENT_ONPAUSE:
l.onPause();;
break;
}
}
});
if(!e.doit)
return false;
}
return true;
}
/**
* The runtime environment (rte) is responsible for controlling the schedule of an algorithm step-by-step.
* <br><br>
* <b>Attention</b>:<br>
* This is only possible from the inside of the LAVESDK or more precisely from the inside of this class!<br>
* <i>DO NOT REMOVE THE PRIVATE VISIBILITY OF THIS CLASS</i>!
*
* @author jdornseifer
* @version 1.3
* @since 1.0
*/
private final class RuntimeEnvironment implements Runnable, AlgorithmExerciseController {
/** monitor to lock for synchronization */
private final Object monitor;
/** the algorithm text that is executed in the runtime environment */
private final AlgorithmText text;
/** the history of the algorithm states */
private final Stack<AlgorithmState> stateHistory;
/** the provider of the exercises or <code>null</code> */
private AlgorithmExerciseProvider exerciseProvider;
/** flag that indicates whether the exercise mode is enabled */
private boolean exerciseModeEnabled;
/** flag that indicates whether the runtime environment is started or not */
private boolean started;
/** the step id of the current step which is executed */
private int executingStepID;
/** flag that indicates whether the rte is paused */
private boolean paused;
/** a runtime-wide flag that indicates whether the rte should be terminated (this is done at the end of the step that is in execution at this time) */
private boolean terminateRTE;
/** flag that indicates whether the step that is currently in execution should be skipped (see also {@link #enableSkipStepFlag()} and {@link #disableSkipStepFlag()}) */
private boolean skipCurrStep;
/** flag that indicates whether the last step should be restored */
private boolean stepBack;
/** factor to increase or decrease the speeding of the rte */
private float sleepFactor;
/** flag that indicates whether the breakpoints should be skipped */
private boolean skipBreakpoints;
/** the minimal dwell time that a step must have to prevent from overrunning steps especially when the user steps back in the algorithm */
private long minDwellTime;
/** the current start option of the algorithm */
private AlgorithmStartOption currStartOpt;
/** flag that indicates whether the schedule should be paused before it is terminated */
private boolean pauseBeforeTerminate;
/** the step id of the initial state which is an invalid step id related to the algorithm steps and only be supposed to identify the initial algorithm state */
private static final int INITIALSTATE_STEPID = -1;
/**
* Creates a new rte based on the properties of the specified one.
*
* @param text the algorithm text
* @throws IllegalArgumentException
* <ul>
* <li>if text is null</code>
* </ul>
* @since 1.0
*/
public RuntimeEnvironment(final AlgorithmText text) throws IllegalArgumentException {
if(text == null)
throw new IllegalArgumentException("No valid argument!");
this.monitor = new Object();
this.text = text;
this.stateHistory = new Stack<AlgorithmState>();
this.exerciseProvider = null;
this.exerciseModeEnabled = false;
this.started = false;
this.executingStepID = INITIALSTATE_STEPID;
this.paused = false;
this.terminateRTE = false;
this.skipCurrStep = false;
this.stepBack = false;
this.sleepFactor = 1.0f;
this.skipBreakpoints = false;
this.minDwellTime = 500;
this.currStartOpt = AlgorithmStartOption.NORMAL;
this.pauseBeforeTerminate = false;
// currently there is no step in execution
text.setExecutingStepID(executingStepID);
}
/**
* Restarts the rte meaning that the rte is set to its initial state before the algorithm is executed.
*
* @param option the start option
* @since 1.0
*/
public synchronized void restart(final AlgorithmStartOption option) {
// already started? then break up
if(started)
return;
this.currStartOpt = !exerciseModeEnabled ? option : AlgorithmStartOption.NORMAL;
this.started = true;
this.executingStepID = text.getFirstStepID();
this.paused = false;
this.terminateRTE = false;
this.skipCurrStep = false;
this.stepBack = false;
this.stateHistory.clear();
}
/**
* Indicates whether the rte is started.
*
* @see #restart()
* @return <code>true</code> if the rte is started otherwise <code>false</code>
* @since 1.0
*/
public boolean isStarted() {
return started;
}
/**
* Resumes the work of the runtime environment but only if the rte was started previously and it is not enabled the exercise mode.
* <br><br>
* If the rte is in exercise mode it is not possible to pause and resume the rte. The execution of the algorithm during the exercise is
* performed fully automatic.
*
* @see #pause()
* @param option the start option
* @since 1.0
*/
public void resume(final AlgorithmStartOption option) {
// the rte cannot resume its work when it is not started yet or is in exercise mode
// if the algorithm is in exercise mode then it is only possible to start and stop the algorithm,
// resume/pause/prevStep/nextStep are inactive
if(!started || exerciseModeEnabled)
return;
synchronized(this) {
this.currStartOpt = !exerciseModeEnabled ? option : AlgorithmStartOption.NORMAL;
this.paused = false;
}
wakeUp();
}
/**
* Wakes up the runtime environment that it can resume its work.
* <br><br>
* <b>Notice</b>:<br>
* To resume the work of the rte please use {@link #resume(boolean)} instead of this method because this method is part of
* the {@link AlgorithmExerciseController} and should only be used by exercises.
*
* @since 1.0
*/
public void wakeUp() {
synchronized(monitor) {
monitor.notify();
}
}
/**
* {@inheritDoc}
*
* @since 1.0
*/
@Override
public AlgorithmExerciseProvider getExerciseProvider() {
return exerciseProvider;
}
/**
* Sets the provider of the exercises.
*
* @param provider the provider
* @since 1.0
*/
public synchronized void setExerciseProvider(final AlgorithmExerciseProvider provider) {
exerciseProvider = provider;
}
/**
* Pauses the runtime environment but only if the rte is not in exercise mode.
* <br><br>
* If the rte is in exercise mode it is not possible to pause and resume the rte. The execution of the algorithm during the exercise is
* performed fully automatic.
*
* @see #resume()
* @since 1.0
*/
public synchronized void pause() {
// if the algorithm is in exercise mode then it is only possible to start and stop the algorithm,
// resume/pause/prevStep/nextStep are inactive
if(exerciseModeEnabled)
return;
paused = true;
}
/**
* Indicates whether the runtime environment is paused.
*
* @return <code>true</code> if rte is paused otherwise <code>false</code>
* @since 1.0
*/
public boolean isPaused() {
return paused;
}
/**
* Lets the runtime sleep for a specific amount of time.
* <br><br>
* <b>Notice</b>:<br>
* If {@link #skipStep()} is invoked all sleep invocations are suppress for the current step in execution.
*
* @param millis time in milliseconds
* @since 1.0
*/
public void sleep(final long millis) {
if(skipCurrStep || terminateRTE)
return;
try {
// sleep if possible (notice: wait(0); does not have the effect that waiting is ignored (it needs
// also a notify()))
if(sleepFactor > 0.0f) {
synchronized(monitor) {
monitor.wait((long)(millis * sleepFactor));
}
}
// if rte is paused in the meanwhile wait after sleeping until rte is unpaused
checkPause();
}
catch(InterruptedException e) {
terminateRTE = true;
enableSkipStepFlag();
}
}
/**
* Suppresses all sleep and pause invocations for the current run.
* <br><br>
* <b>Notice</b>:<br>
* {@link #wakeUp()} is invoked automatically to wake up the rte from its current state (sleep or pause).<br>
* <b>If the exercise mode is enabled ({@link #isExerciseModeEnabled()}) then it is not possible to skip steps.</b>
*
* @since 1.0
*/
public void skipStep() {
synchronized(this) {
// if the algorithm is in exercise mode then it is only possible to start and stop the algorithm,
// resume/pause/prevStep/nextStep are inactive
if(exerciseModeEnabled)
return;
enableSkipStepFlag();
}
// wake up the rte
wakeUp();
}
/**
* Goes one step back in the execution of the algorithm and restores the step's state.
* <br><br>
* <b>Notice</b>:<br>
* {@link #skipStep()} is automatically invoked which means additionally that {@link #wakeUp()} is also called
* to wake up the rte from its current state (sleep or pause).<br>
* <b>If the exercise mode is enabled ({@link #isExerciseModeEnabled()}) then it is not possible to step back.</b>
*
* @since 1.0
*/
public void goStepBack() {
synchronized(this) {
// if the algorithm is in exercise mode then it is only possible to start and stop the algorithm,
// resume/pause/prevStep/nextStep are inactive
if(exerciseModeEnabled)
return;
stepBack = true;
}
// skip the current step and wake up the rte
skipStep();
}
/**
* Gets the identifier of the step that is currently in execution.
*
* @return the step id or {@link #INITIALSTATE_STEPID} if the rte is not started yet
* @since 1.0
*/
public int getExecutingStepID() {
return executingStepID;
}
/**
* Indicates if the breakpoints will currently be skipped/ignored.
*
* @return <code>true</code> if breakpoints are ignored otherwise <code>false</code>
* @since 1.0
*/
public boolean getSkipBreakpoints() {
return skipBreakpoints;
}
/**
* Sets if the breakpoints should currently be skipped/ignored.
*
* @param skip <code>true</code> if breakpoints are ignored otherwise <code>false</code>
* @since 1.0
*/
public synchronized void setSkipBreakpoints(final boolean skip) {
skipBreakpoints = skip;
}
/**
* Gets the execution speed factor of the rte.
* <br><br>
* <b>Notice</b>:<br>
* A value smaller <code>1.0f</code> means a <b>slower</b> and a value greater <code>1.0f</code> a
* <b>faster execution</b>. For example a factor of <code>2.0f</code> means that the execution of the
* algorithm is two times faster as normal and a factor of <code>0.5f</code> means that the execution is only
* half as fast as normal (<code>0.1f</code> means ten times slower as normal).
*
* @return the execution speed factor (a value <code>> 0.0f</code>)
* @since 1.0
*/
public float getExecSpeedFactor() {
return 1.0f / sleepFactor;
}
/**
* Sets the execution speed factor of the rte.
* <br><br>
* <b>Notice</b>:<br>
* A value smaller <code>1.0f</code> means a <b>slower</b> and a value greater <code>1.0f</code> a
* <b>faster execution</b>. For example a factor of <code>2.0f</code> means that the execution of the
* algorithm is two times faster as normal and a factor of <code>0.5f</code> means that the execution is only
* half as fast as normal (<code>0.1f</code> means ten times slower as normal).
*
* @param factor the execution speed factor (a value <code>> 0.0f</code>)
* @since 1.0
*/
public synchronized void setExecSpeedFactor(final float factor) {
if(factor > 0.0f)
sleepFactor = 1.0f / factor;
}
/**
* Gets the minimal dwell time that a step must have.
* <br><br>
* <b>Notice</b>:<br>
* If a step has no dwell time it is hard to go back over this step ("go to previous step") because it is always transition into the next step.
* So if a step does not have the minimal dwell time the runtime environment is automatically paused for the remaining time and
* an overrun of the step is prevented.<br>
* The default value is <code>500</code> milliseconds.
*
* @return the minimal dwell time in milliseconds
* @since 1.0
*/
public long getMinDwellTime() {
return minDwellTime;
}
/**
* Sets the minimal dwell time that a step must have.
* <br><br>
* <b>Notice</b>:<br>
* If a step has no dwell time it is hard to go back over this step ("go to previous step") because it is always transition into the next step.
* So if a step does not have the minimal dwell time the runtime environment is automatically paused for the remaining time and
* an overrun of the step is prevented.<br>
* The default value is <code>500</code> milliseconds.
*
* @param millis the minimal dwell time in milliseconds
* @throws IllegalArgumentException
* <ul>
* <li>if millis is <code>< 0</code></li>
* </ul>
* @since 1.0
*/
public synchronized void setMinDwellTime(final long millis) throws IllegalArgumentException {
if(millis < 0)
throw new IllegalArgumentException("No valid argument!");
minDwellTime = millis;
}
/**
* Indicates whether the runtime environment should be paused before it transitions into terminate state.
*
* @return <code>true</code> if the rte pauses the execution before it transitions into terminate state otherwise <code>false</code>
* @since 1.0
*/
public boolean getPauseBeforeTerminate() {
return pauseBeforeTerminate;
}
/**
* Sets whether the runtime environment should be paused before it transitions into terminate state.
*
* @param pause <code>true</code> if the rte pauses the execution before it transitions into terminate state otherwise <code>false</code>
* @since 1.0
*/
public synchronized void setPauseBeforeTerminate(final boolean pause) {
pauseBeforeTerminate = pause;
}
/**
* Indicates whether the exercise mode of the rte is enabled.
* <br><br>
* Exercises of the algorithm are only presented to the user when the exercise mode is enabled.
*
* @return <code>true</code> if the exercise mode is enabled otherwise <code>false</code>
* @since 1.0
*/
public boolean isExerciseModeEnabled() {
return exerciseModeEnabled;
}
/**
* Sets whether the exercise mode of the rte should be enabled.
* <br><br>
* Exercises of the algorithm are only presented to the user when the exercise mode is enabled.
* <br><br>
* <b>Notice</b>:<br>
* This is only possible if the rte is not started yet (meaning the exercise mode can only be activated if the rte is stopped).
* The {@link PluginHost} is notified about the changed mode by {@link PluginHost#rteModeChanged()}.
*
* @param enabled <code>true</code> if the exercise mode should be enabled otherwise <code>false</code>
* @since 1.0
*/
public void setExerciseModeEnabled(final boolean enabled) {
AlgorithmExerciseProvider provider = null;
synchronized(this) {
// if the rte is already started or the flag does not changed then it is not possible that the
// exercution mode is switched
if(started || exerciseModeEnabled == enabled)
return;
exerciseModeEnabled = enabled;
provider = exerciseProvider;
}
// if the state of the exercise mode is changed then we have to update the handler of the provider because
// a provider can be used in multiple runtime environments
if(provider != null)
provider.setHandler(this);
if(getHost() != null)
getHost().rteModeChanged();
// switch the visibility state of the provider
if(provider != null) {
final AlgorithmExerciseProvider ep = provider;
EDT.execute(new GuiJob(getClass().getSimpleName() + ".setExerciseModeEnabled") {
@Override
protected void execute() throws Throwable {
ep.setVisible(enabled);
}
});
}
}
@Override
public PluginHost getHost() {
return AlgorithmRTE.this.getHost();
}
/**
* Does the schedule of the algorithm in the background.
*
* @since 1.0
*/
@Override
public void run() {
final Thread rteThread = AlgorithmRTE.this.thread;
int nextStepID = -1;
long dwellTimeStart;
long dwellTime;
boolean processed = false;
AlgorithmExercise<?> exercise = null;
boolean playAndPauseAllowed = false;
terminateRTE = false;
// notify the exercise provider that the exam begins but only if the exercise mode is enabled
if(exerciseModeEnabled) {
EDT.execute(new GuiJob(getClass().getSimpleName() + ".run") {
@Override
protected void execute() throws Throwable {
if(RuntimeEnvironment.this.exerciseProvider != null)
RuntimeEnvironment.this.exerciseProvider.beginExam();
}
});
}
while(!processed && !rteThread.isInterrupted()) {
try {
// set the step that is currently in execution
text.setExecutingStepID(executingStepID);
// cache the state of the current executing step
pushStateHistory(executingStepID);
// check for a breakpoint before the step is executed (if the step has a breakpoint then the rte is paused)
if(!checkBreakpoint(executingStepID)) {
// if a step has a breakpoint it is not necessary to pause again
// if the play and pause start option is enabled then we pause the algorithm before the current step is executed
// meaning if the user presses play and pause the current step is executed and the next step is activated but not performed
// (play and pause is allowed after one step is executed otherwise the rte will pause before the first step is executed)
if(playAndPauseAllowed && currStartOpt == AlgorithmStartOption.PLAY_AND_PAUSE) {
AlgorithmRTE.this.pause();
checkPause();
}
}
// if the current start option is "run until the algorithm ends" then enable the skip step flag before each step is executed
if(currStartOpt == AlgorithmStartOption.START_TO_FINISH)
enableSkipStepFlag();
// get the exercise of the current step
exercise = getCurrentExercise();
// execute the current step normally when the rte is not in exercise mode or the step does not have
// an exercise otherwise communicate with the exercise for execution
if(!exerciseModeEnabled || exercise == null) {
dwellTimeStart = System.currentTimeMillis();
// execute the current step
nextStepID = executeCurrentStep();
// measure the dwell time of the step
dwellTime = System.currentTimeMillis() - dwellTimeStart;
// step does not achieve the minimal dwell time? then sleep the remaining time
if(dwellTime < minDwellTime)
sleep(minDwellTime - dwellTime);
}
else
nextStepID = processExercise(exercise, text.getStepByID(executingStepID));
// valid next step?
if(nextStepID > 0 && !terminateRTE) {
// pause the rte if necessary
checkPause();
if(stepBack) {
// go to the predecessor state of the executing step
nextStepID = popStateHistory(executingStepID, nextStepID);
// the state is restored
stepBack = false;
}
}
else
processed = true; // no more steps? that means the process is done!
}
catch(InterruptedException e) {
terminateRTE = true;
}
// reset flags that are supposed to manipulate the current step in execution
disableSkipStepFlag();
stepBack = false;
// schedule is done?
if(processed && !terminateRTE) {
exercise = text.getFinalExercise();
try {
// if the exercise mode is enabled and there is a final exercise then
if(exerciseModeEnabled && exercise != null)
processExercise(exercise, null);
// pause the algorithm before it terminates but only if the exercise mode is not enabled
// (this has to be done after the skip step flag is reset otherwise it has no effect)
if(!exerciseModeEnabled && pauseBeforeTerminate) {
AlgorithmRTE.this.pause();
checkPause();
// give the user the possibility to step back from the end of the algorithm schedule
if(stepBack) {
// go to the predecessor state of the executing step
nextStepID = popStateHistory(executingStepID, nextStepID);
// reset the flags
disableSkipStepFlag();
stepBack = false;
processed = false;
}
}
}
catch(InterruptedException e) {
terminateRTE = true;
}
}
// terminate the runtime environment?
if(terminateRTE)
rteThread.interrupt();
// important: set the algorithm to the next step
executingStepID = nextStepID;
// after the first step is executed play and pause option is enabled
playAndPauseAllowed = true;
}
// if runtime thread is not interrupted yet then do it first
if(!rteThread.isInterrupted())
rteThread.interrupt();
// notify the exercise provider that the exam ends but only if the exercise mode is enabled
if(exerciseModeEnabled) {
EDT.execute(new GuiJob(getClass().getSimpleName() + ".run") {
@Override
protected void execute() throws Throwable {
if(RuntimeEnvironment.this.exerciseProvider != null)
RuntimeEnvironment.this.exerciseProvider.endExam(RuntimeEnvironment.this.terminateRTE);
}
});
}
done();
}
/**
* Enables the {@link #skipCurrStep} flag and disables the repaint mechansim of each view of {@link AlgorithmRTE#getViews()}.
*
* @since 1.0
*/
private void enableSkipStepFlag() {
final boolean oldState = skipCurrStep;
skipCurrStep = true;
if(skipCurrStep != oldState) {
// disable the repaint mechanism of the algorithm views
final View[] views = AlgorithmRTE.this.getViews();
if(views != null) {
for(View view : views) {
if(view != null)
view.setRepaintDisabled(true);
}
}
}
}
/**
* Disables the {@link #skipCurrStep} flag and enables the repaint mechansim of each view of {@link AlgorithmRTE#getViews()}.
* Furthermore each view is repainted automatically.
*
* @since 1.0
*/
private void disableSkipStepFlag() {
final boolean oldState = skipCurrStep;
skipCurrStep = false;
if(skipCurrStep != oldState) {
// enable the repaint mechanism of the algorithm views (the views are repainted automatically in setRepaintDisabled(...))
final View[] views = AlgorithmRTE.this.getViews();
if(views != null) {
for(View view : views) {
if(view != null)
view.setRepaintDisabled(false);
}
}
}
}
/**
* Processes the specified exercise.
*
* @param exercise the exercise
* @param the related step or <code>null</code>
* @return the id of the next step
* @throws InterruptedException
* <ul>
* <li>if the processing is interrupted</li>
* </ul>
* @since 1.0
*/
private int processExercise(final AlgorithmExercise<?> exercise, final AlgorithmStep step) throws InterruptedException {
final AlgorithmState oldState = stateHistory.peek();
ExamResult examResult = ExamResult.FAILED;
int nextStepID = -1;
InterruptedException ex = null;
// enter the processing of the exercise
exercise.enter(this, step);
try {
do {
// a solution is requested and entered by the user while the rte sleeps
oldState.unfreeze();
EDT.execute(new GuiJob() {
@Override
protected void execute() throws Throwable {
exercise.beforeRequestSolution(oldState);
}
});
// catch an InterruptedException from sleep so that we can execute the afterRequestSolution event
try {
// let the rte sleep for an undefinite period of time until the exercise wakes up the rte
sleep();
// if the user has input a solution for the exercise then skip the current execution to compare only
// the results
if(!exercise.isOmitted())
enableSkipStepFlag();
}
catch(InterruptedException e) {
ex = e;
}
// a solution is requested and entered by the user while the rte sleeps, the request ends before
// the step is execute so that their could be removed objects that were added in beforeRequestSolution()
final boolean omitted = exercise.isOmitted();
EDT.execute(new GuiJob() {
@Override
protected void execute() throws Throwable {
exercise.afterRequestSolution(omitted);
}
});
// after executed the event rethrow the exception so that the further execution is skipped
if(ex != null)
throw ex;
// a solution can only be applied if the exercise is not omitted
if(exercise.getApplySolutionToAlgorithm() && !exercise.isOmitted()) {
// firtsly check whether the solution is correct
examResult = exercise.examine(oldState);
// exercise succeeded?
if(examResult == ExamResult.SUCCEEDED) {
// transfer the solution of the user in a state so that this state can be adopted by the algorithm
final AlgorithmState transferState = new AlgorithmState(plugin, executingStepID);
exercise.transferSolution(transferState);
// let the algorithm adopt the state
AlgorithmRTE.this.adoptState(executingStepID, transferState);
// only execute the step if the exercise was solved correct
nextStepID = executeCurrentStep();
}
}
else {
// if the exercise does not applys a solution to the algorithm execute the current step
// so that the exercise can request the algorithm state after this step or visualizes the way to solve the step
nextStepID = executeCurrentStep();
}
// if the solution of the exercise is applied to the algorithm the examination is already done;
// do further checking but only if the rte was not terminated during the execution of the current step
if(!terminateRTE && !exercise.getApplySolutionToAlgorithm()) {
// examine the exercise with the current state of the algorithm
examResult = exercise.examine(requestState(executingStepID));
// if the exercise failed the state before the step must be restored and rolled back so that the exercise
// can be solved once again
if(examResult == ExamResult.FAILED && !exercise.isOmitted()) {
oldState.unfreeze();
AlgorithmRTE.this.restoreState(oldState);
AlgorithmRTE.this.rollBackStep(executingStepID, nextStepID);
}
}
// reset the skip flag for a next run
disableSkipStepFlag();
} while(examResult != ExamResult.SUCCEEDED && !terminateRTE && !exercise.isOmitted());
}
catch(InterruptedException e) {
throw e;
}
finally {
// we always have to exit the exercise although the rte is interrupted because
// the user stops the algorithm or something like that
exercise.exit(examResult);
}
return nextStepID;
}
/**
* Checks if the rte should be paused and if so, transfers the rte in pause mode.
*
* @return <code>true</code> if the rte was paused otherwise <code>false</code>
* @throws InterruptedException
* <ul>
* <li>if pause is interrupted by the thread meaning that the thread is interrupted and should be terminated</li>
* </ul>
* @since 1.0
*/
private boolean checkPause() throws InterruptedException {
// in exercise mode pausing is not allowed because the execution flow is fully automatic
if(exerciseModeEnabled || skipCurrStep || terminateRTE)
return false;
// to set the monitor in synchronized mode costs time so do this only if
// the flag is set
if(paused) {
synchronized(monitor) {
// attention: pause could be suppressed although the paused flag is set so
// the skip flag has to be checked each time too
while(paused && !skipCurrStep)
monitor.wait();
}
return true;
}
return false;
}
/**
* Checks if the specified step has a breakpoint. If so then the rte is paused and must be resumed using {@link #work()}.
* <br><br>
* <b>Notice</b>:<br>
* If {@link #skipBreakpoints} is <code>true</code> then the method does nothing and returns.
*
* @param stepID the step id
* @return <code>true</code> if the rte was paused because the current step had a breakpoint otherwise <code>false</code>
* @throws InterruptedException
* <ul>
* <li>if pause is interrupted by the thread meaning that the thread is interrupted and should be terminated</li>
* </ul>
* @since 1.0
*/
private boolean checkBreakpoint(final int stepID) throws InterruptedException {
// in exercise mode breakpoints are not allowed because the execution flow is fully automatic
if(exerciseModeEnabled || skipBreakpoints || terminateRTE)
return false;
final AlgorithmStep step = text.getStepByID(stepID);
// step has a breakpoint? then go into pause mode
if(step != null && step.hasBreakpoint())
AlgorithmRTE.this.pause();
return checkPause();
}
/**
* Lets the runtime environment sleep for an indefinite period of time.
*
* @throws InterruptedException
* <ul>
* <li>if the runtime thread is interrupted</li>
* </ul>
* @since 1.0
*/
private void sleep() throws InterruptedException {
if(skipCurrStep || terminateRTE)
return;
synchronized(monitor) {
monitor.wait();
}
}
/**
* Requests the current state of the algorithm.
* <br><br>
* <b>Notice</b>:<br>
* The state is frozen!
*
* @param stepID the id of the current step
* @return the state
* @since 1.0
*/
private AlgorithmState requestState(final int stepID) {
// save the current state of the algorithm
final AlgorithmState state = new AlgorithmState(plugin, stepID);
AlgorithmRTE.this.storeState(state);
// very important: freeze the state against changes after the state is queried
state.freeze();
return state;
}
/**
* Stores the current algorithm state and pushes it to the history stack.
*
* @param nextStepID the id of the next step which state is stored
* @since 1.0
*/
private void pushStateHistory(final int nextStepID) {
// save the current state of the algorithm add it to the stack
stateHistory.push(requestState(nextStepID));
}
/**
* Restores the algorithm state before the specified step and rolls back all steps up to the one that
* is restored.
*
* @see AlgorithmRTE#rollBackStep(int)
* @param stepID the id of the step which predecessor state should be restored
* @param nextStepID the id of the next step
* @return the id of the step that has to be executed next
* @since 1.0
*/
private int popStateHistory(final int stepID, final int nextStepID) {
AlgorithmState state = null;
boolean predStepFound = false;
boolean currStepFound = false;
int lastNextStepID = nextStepID;
// find the step of the given step id and roll back all steps until the required step is found
while(stateHistory.size() > 0 && !predStepFound) {
state = stateHistory.pop();
currStepFound = currStepFound || (state.getStepID() == stepID);
// we have found the predecessor step of the current (given) step if the given step was found
// and the current popped state has another id then the one from the given state
predStepFound = currStepFound && (state.getStepID() != stepID);
state.unfreeze();
AlgorithmRTE.this.restoreState(state);
AlgorithmRTE.this.rollBackStep(state.getStepID(), lastNextStepID);
lastNextStepID = state.getStepID();
}
// no valid state then execute the first step next
if(state == null)
return text.getFirstStepID();
else
return state.getStepID();
}
/**
* Executes the current step meaning the step with the id {@link #executingStepID}.
* <br><br>
* <b>Notice</b>:<br>
* This method invokes the {@link AlgorithmRTE#executeStep(int, AlgorithmStateAttachment)} method. If their occur an exception then this exception is logged
* and the {@link #terminateRTE} flag is set.
*
* @return the step id of the next step that has to be executed or <code>-1</code> if the algorithm is finished
* @since 1.0
*/
private int executeCurrentStep() {
try {
return AlgorithmRTE.this.executeStep(executingStepID, stateHistory.peek());
}
catch(Exception e) {
AlgorithmRTE.this.writeLogMessage(AlgorithmRTE.this.plugin, "execution of step id " + executingStepID + " failed", e, LogType.ERROR);
terminateRTE = true;
}
return -1;
}
/**
* Gets the exercise of the step that is currently in execution.
* <br><br>
* <b>Notice</b>:<br>
* The method returns <code>null</code> automatically if the exercise mode is not enabled!
*
* @return the exercise of the current step or <code>null</code> if there is no exercise
* @since 1.0
*/
private AlgorithmExercise<?> getCurrentExercise() {
// if the rte is not in exercise mode then the current step must not be checked for a valid exercise
if(!exerciseModeEnabled)
return null;
final AlgorithmStep step = text.getStepByID(executingStepID);
return (step != null) ? step.getExercise() : null;
}
/**
* Indicates that the runtime job is done meaning that the rte is reset and {@link AlgorithmRTE#onStop()}
* is invoked.
*
* @since 1.0
*/
private void done() {
started = false;
skipCurrStep = false;
// release the state history because the algorithm is finished
stateHistory.clear();
// currently no step is in execution
text.setExecutingStepID(INITIALSTATE_STEPID);
// important: reset the algorithm runtime environment
AlgorithmRTE.this.onStop();
}
}
} | [
"jan.dornseifer@t-online.de"
] | jan.dornseifer@t-online.de |
a0f26a1778823bebd4b80605e0262c9cddbc0105 | 7454576f6f6d5ea2b95cccf4c14be3f794f0e5fd | /widgetlib/src/test/java/com/zhoujiulong/widgetlib/ExampleUnitTest.java | 1720734a63b2760f0698500322a3ecae2f439321 | [] | no_license | yangkai987/Project | 23ce1533670ae7c04be0279d7df39efa901e66a1 | f4a1c326089ad81989a598e028e7a376e81a3888 | refs/heads/master | 2020-09-05T18:51:17.961557 | 2019-11-12T06:33:24 | 2019-11-12T06:33:24 | 220,184,841 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package com.membership_score.widgetlib;
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);
}
} | [
"kai.yang@xfxb.net"
] | kai.yang@xfxb.net |
253bd142be170cf1428538065ce8db08db15acdb | 2775d4bed59bf9543097f9a35e29f5d12e666c0b | /javalab2/src/pm5/MenuOrder.java | 716aeb24433d2a87ced0868d7805c2708bef997c | [] | no_license | Hyun2gi/java | b87ddbc2b62d56b2c22697a3ab6c44b3bef4bb31 | 22f27b7a75e32b0f33d0073d0b33d068071e5627 | refs/heads/main | 2023-03-27T05:05:21.838572 | 2021-03-30T00:40:06 | 2021-03-30T00:40:06 | 344,002,258 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,487 | java | // 1971040 이현정
// 실습5 : 음료수 자판기
package pm5;
public class MenuOrder {
private int cokePrice;
private int lemonPrice;
private int coffeePrice;
int change;
int menu;
public int getCokePrice() {
return cokePrice;
}
public int getLemonPrice() {
return lemonPrice;
}
public int getCoffeePrice() {
return coffeePrice;
}
public void setCokePrice(int m) {
cokePrice = m;
}
public void setLemonPrice(int m) {
lemonPrice = m;
}
public void setCoffeePrice(int m) {
coffeePrice = m;
}
public void showMenu() {
System.out.println("---Select Drink---");
System.out.println("0 : Coke." + getCokePrice());
System.out.println("1 : Lemonade." + getLemonPrice());
System.out.println("2 : Coffee." + getCoffeePrice());
}
public void drinkCost(int menu, int inmoney) {
switch(menu) {
case 0 :
change = inmoney-cokePrice;
break;
case 1 :
change = inmoney-lemonPrice;
break;
case 2 :
change = inmoney-coffeePrice;
break;
}
}
public void showResult() {
switch(menu) {
case 0 :
System.out.println("You selected Coke");
System.out.printf("Your change is %d won.\n", change);
break;
case 1 :
System.out.println("You selected Lemonade");
System.out.printf("Your change is %d won.", change);
break;
case 2 :
System.out.println("You selected Coffee");
System.out.printf("Your change is %d won.", change);
break;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
0e515b386a9230db9008d55f196bee5558c44da7 | 470b391cd4c0cd40c713b0d9875741349f521107 | /lib/src/main/java/com/steve/lib/basic/BaseBuilder.java | 1bf9dccbbba3f16badd208fe6d4c8a6dea5823df | [
"Apache-2.0"
] | permissive | tinggengyan/DatePicker | edb986916379cd66b98ba253f3ae621718026205 | 31756308843be3a8d2e20d6586cdbcc49b71b1b2 | refs/heads/master | 2021-01-13T03:36:31.185621 | 2017-01-03T13:11:49 | 2017-01-03T13:11:49 | 77,321,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,892 | java | package com.steve.lib.basic;
import android.text.TextUtils;
import com.steve.lib.DatePriceAdapterBuilder;
/**
* Created by yantinggeng on 2016/10/25.
*/
public abstract class BaseBuilder {
protected DatePriceAdapterBuilder.DateYearMonth getYearMonth(String date) {
if (TextUtils.isEmpty(date)) {
return null;
}
DatePriceAdapterBuilder.DateYearMonth dateYearMonth = new DatePriceAdapterBuilder.DateYearMonth();
String[] strings = date.split("-");
if (strings.length < 2) {
return null;
}
String year = strings[0];
String month = strings[1];
if (TextUtils.isEmpty(year) || TextUtils.isEmpty(month)) {
return null;
}
dateYearMonth.setYear(Integer.valueOf(year));
dateYearMonth.setMonth(Integer.valueOf(month));
return dateYearMonth;
}
protected static class DateYearMonth {
private int year;
private int month;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (object == this) {
return true;
}
if (!(object instanceof DateYearMonth)) {
return false;
}
DateYearMonth other = (DateYearMonth) object;
return other.getYear() == this.getYear() && other.getMonth() == this.getMonth();
}
@Override
public int hashCode() {
return this.getYear() + this.getMonth();
}
}
}
| [
"tinggengyan@gmail.com"
] | tinggengyan@gmail.com |
b3cecd3fa57514588549dae9f6d951b3150c1e15 | ebff31214a3a675428fcf00fa1136945257d6734 | /src/main/java/Week2/FromOneToAHundred.java | e230202fc1755dba8d46f2ffb952615090dab519 | [] | no_license | sorynel24/ProiectConcurs | 5b7885de5f11968d67413f1b0af0bd56f8939957 | dcb210d9cb0bacaab8d99012f449b671045bee43 | refs/heads/master | 2020-11-24T15:20:54.929152 | 2020-01-09T18:12:53 | 2020-01-09T18:12:53 | 228,213,464 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 324 | java | package Week2;
public class FromOneToAHundred {
//Exercises 3 of Week 2
public static void main(String[] args){
int number = 0;
while(number <= 100){
number++;
System.out.println(number);
if(number == 100){
break;
}
}
}
}
| [
"sorynel255yahoo.com"
] | sorynel255yahoo.com |
4b80e2bd6a5997b080d049648ebfa34a10bcd16e | a8870b3179379ac53df690eb3da48953413d26a2 | /hnote-bk/hnote-facade/src/main/java/me/mingshan/hnote/facade/model/Trash.java | b9884bac88c3d6b5a0f9e2110944e7d87a2f8f14 | [] | no_license | mstao/hnote | 6a676913c39b508b1f9635753b65c510b0973e3f | c4532598e7045f861cfa0958a4296bfa9c4f7470 | refs/heads/master | 2021-04-18T19:32:14.279650 | 2018-07-28T03:39:48 | 2018-07-28T03:39:48 | 126,829,875 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 851 | java | package me.mingshan.hnote.facade.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* @Author: mingshan
* @Date: Created in 16:41 2018/4/27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Trash implements Serializable {
private static final long serialVersionUID = -1715340505113819658L;
private Long id;
private Long noteId;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date gmtCreate;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date gmtModified;
}
| [
"499445428@qq.com"
] | 499445428@qq.com |
0f363c3278354d8760f1b42b515d4a3880c0fbb4 | c813f4edd9e7dc549b9d3d3afd097b09e61dac8d | /src/preprocess/jflexcrf/Element.java | 2c05bd655810bb1070f2fe77522c69dd12387d1e | [] | no_license | duyet/islab-phantichcamxuc | 2d512f0b2ab4cbda5c6725a9079a00b4d46f5974 | a1da6be448f4cc4499fcd39595342bb600fa69bd | refs/heads/master | 2021-05-29T16:49:04.856379 | 2015-10-02T10:35:59 | 2015-10-02T10:35:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 831 | java | /*
Copyright (C) 2006, Xuan-Hieu Phan
Email: hieuxuan@ecei.tohoku.ac.jp
pxhieu@gmail.com
URL: http://www.hori.ecei.tohoku.ac.jp/~hieuxuan
Graduate School of Information Sciences,
Tohoku University
*/
package preprocess.jflexcrf;
import java.io.*;
import java.util.*;
public class Element {
public int count = 0; // the number of occurrences of this context predicate
public int chosen = 0; // indicating whether or not it is incorporated into the model
Map lbCntFidxes = null; // map of labels to CountFeatureIdxes
List cpFeatures = null; // features associated with this context predicates
boolean isScanned = false; // be scanned or not
public Element() {
lbCntFidxes = new HashMap();
cpFeatures = new ArrayList();
}
} // end of class Element
| [
"lvduit08@gmail.com"
] | lvduit08@gmail.com |
9a0efbce1565cb86b2b6413818caf641df75c5e8 | 40f971f0f0014490f0cfd4205003e5ca2ff620a0 | /src/main/java/com/spittr/utils/convert/UserConvert.java | 745be0a82d751d71fa41da3b957e91dd04cb485a | [] | no_license | duanxg/spring-boot-demo | 55cc4d2fedcee8c7d09cd6102cd02e14c8e040cc | 343da013b0dfc40412103fd3bad1118eca05415a | refs/heads/master | 2020-03-28T20:56:18.410278 | 2017-06-12T09:38:02 | 2017-06-12T09:38:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,272 | java | package com.spittr.utils.convert;
import java.util.Date;
import java.util.Map;
import com.google.gson.JsonObject;
import com.spittr.model.User;
/**
* 用户对象模型转换
*
* @author chufei
* @date 2017年4月13日
*/
public class UserConvert {
/**
* Map对象转化Uesr对象
*
* @param map
* @param user
* @return
*/
public static User map2User(Map<String, String> map, User user) {
if (user != null) {
if (map.get("nickname") != null) {
user.setNickname(map.get("nickname"));
}
if (map.get("password") != null) {
user.setPassword(map.get("password"));
}
if (map.get("gender") != null) {
user.setGender(Integer.parseInt(map.get("gender")));
}
if (map.get("age") != null) {
user.setAge(Integer.parseInt(map.get("age")));
}
if (map.get("birthDay") != null) {
user.setBirthDay(map.get("birthDay"));
}
if (map.get("location") != null) {
user.setLocation(map.get("location"));
}
if (map.get("phoneNum") != null) {
user.setPhoneNum(map.get("phoneNum"));
}
if (map.get("profile") != null) {
user.setProfile(map.get("profile"));
}
if (map.get("registeredTime") != null) {
user.setRegisteredTime(new Date(Long.parseLong(map.get("registeredTime"))));
}
}
return user;
}
/**
* User对象转化Json对象
*
* @param user
* @param jsonObject
* @return
*/
public static JsonObject user2Json(User user) {
JsonObject jsonObject = new JsonObject();
if (user != null) {
if (user.getNickname() != null) {
jsonObject.addProperty("nickname", user.getNickname());
}
jsonObject.addProperty("gender", user.getGender());
jsonObject.addProperty("age", user.getAge());
if (user.getBirthDay() != null) {
jsonObject.addProperty("birthDay", user.getBirthDay());
}
if (user.getLocation() != null) {
jsonObject.addProperty("location", user.getLocation());
}
if (user.getPhoneNum() != null) {
jsonObject.addProperty("phoneNum", user.getPhoneNum());
}
if (user.getProfile() != null) {
jsonObject.addProperty("profile", user.getProfile());
}
if (user.getRegisteredTime() != null) {
jsonObject.addProperty("registeredTime", user.getRegisteredTime().getTime());
}
}
return jsonObject;
}
}
| [
"cf2093043@126.com"
] | cf2093043@126.com |
e0cf3b47da9d6417d3c7697b740c68a5ad5c0965 | edf62a35ed35831093316497d754323e80be792b | /005SeleniumWebDriverforArrchanaMohan/Backup/Traning/.metadata/.plugins/org.eclipse.core.resources/.history/ea/408b9995de580015172da124c5ce41cd | 0e9c29fa237954cd7060e12c90c7520d981875da | [] | no_license | lavanyarichard/testautomation | 602423df431ce9707f8b00047275e70f4ee85161 | f24f50622cdca81f4297250b0c73c82e7946948d | refs/heads/master | 2021-01-19T05:31:06.154109 | 2015-09-13T18:38:16 | 2015-09-13T18:38:16 | 42,582,789 | 1 | 0 | null | 2015-09-16T11:20:24 | 2015-09-16T11:20:24 | null | UTF-8 | Java | false | false | 5,862 | package com.stta.SuiteOne;
import java.io.IOException;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import com.stta.utility.Read_XLS;
import com.stta.utility.SuiteUtility;
//SuiteOneCaseTwo Class Inherits From SuiteOneBase Class.
//So, SuiteOneCaseTwo Class Is Child Class Of SuiteOneBase Class And SuiteBase Class.
public class SuiteOneCaseTwo extends SuiteOneBase{
Read_XLS FilePath = null;
String SheetName = null;
String TestCaseName = null;
String ToRunColumnNameTestCase = null;
String ToRunColumnNameTestData = null;
String TestDataToRun[]=null;
static boolean TestCasePass=true;
static int DataSet=-1;
static boolean Testskip=false;
static boolean Testfail=false;
SoftAssert s_assert =null;
@BeforeTest
public void checkCaseToRun() throws IOException{
//Called init() function from SuiteBase class to Initialize .xls Files
init();
//To set SuiteOne.xls file's path In FilePath Variable.
FilePath = TestCaseListExcelOne;
TestCaseName = this.getClass().getSimpleName();
//SheetName to check CaseToRun flag against test case.
SheetName = "TestCasesList";
//Name of column In TestCasesList Excel sheet.
ToRunColumnNameTestCase = "CaseToRun";
//Name of column In Test Case Data sheets.
ToRunColumnNameTestData = "DataToRun";
//To check test case's CaseToRun = Y or N In related excel sheet.
//If CaseToRun = N or blank, Test case will skip execution. Else It will be executed.
if(!SuiteUtility.checkToRunUtility(FilePath, SheetName,ToRunColumnNameTestCase,TestCaseName)){
//To report result as skip for test cases In TestCasesList sheet.
SuiteUtility.WriteResultUtility(FilePath, SheetName, "Pass/Fail/Skip", TestCaseName, "SKIP");
//To throw skip exception for this test case.
throw new SkipException(TestCaseName+"'s CaseToRun Flag Is 'N' Or Blank. So Skipping Execution Of "+TestCaseName);
}
//To retrieve DataToRun flags of all data set lines from related test data sheet.
TestDataToRun = SuiteUtility.checkToRunUtilityOfData(FilePath, TestCaseName, ToRunColumnNameTestData);
}
//Accepts 4 column's String data In every Iteration.
@Test(dataProvider="SuiteOneCaseTwoData")
public void SuiteOneCaseTwoTest(String DataCol1,String DataCol2,String DataCol3,String ExpectedResult){
DataSet++;
//Created object of testng SoftAssert class.
s_assert = new SoftAssert();
//If found DataToRun = "N" for data set then execution will be skipped for that data set.
if(!TestDataToRun[DataSet].equalsIgnoreCase("Y")){
//If DataToRun = "N", Set Testskip=true.
Testskip=true;
throw new SkipException("DataToRun for row number "+DataSet+" Is No Or Blank. So Skipping Its Execution.");
}
//If found DataToRun = "Y" for data set then bellow given lines will be executed.
//To Convert data from String to Integer
int ValueOne = Integer.parseInt(DataCol1);
int ValueTwo = Integer.parseInt(DataCol2);
int ValueThree = Integer.parseInt(DataCol3);
int ExpectedResultInt = Integer.parseInt(ExpectedResult);
//Subtract the values.
int ActualResult = ValueOne-ValueTwo-ValueThree;
//Compare actual and expected values.
if(!(ActualResult==ExpectedResultInt)){
//If expected and actual results not match, Set flag Testfail=true.
Testfail=true;
//If result Is fail then test failure will be captured Inside s_assert object reference.
//This soft assertion will not stop your test execution.
s_assert.assertEquals(ActualResult, ExpectedResultInt, ActualResult+" And "+ExpectedResultInt+" Not Match");
}
if(Testfail){
//At last, test data assertion failure will be reported In testNG reports and It will mark your test data, test case and test suite as fail.
s_assert.assertAll();
}
}
//@AfterMethod method will be executed after execution of @Test method every time.
@AfterMethod
public void reporterDataResults(){
if(Testskip){
//If found Testskip = true, Result will be reported as SKIP against data set line In excel sheet.
SuiteUtility.WriteResultUtility(FilePath, TestCaseName, "Pass/Fail/Skip", DataSet+1, "SKIP");
}
else if(Testfail){
//To make object reference null after reporting In report.
s_assert = null;
//Set TestCasePass = false to report test case as fail In excel sheet.
TestCasePass=false;
//If found Testfail = true, Result will be reported as FAIL against data set line In excel sheet.
SuiteUtility.WriteResultUtility(FilePath, TestCaseName, "Pass/Fail/Skip", DataSet+1, "FAIL");
}
else{
//If found Testskip = false and Testfail = false, Result will be reported as PASS against data set line In excel sheet.
SuiteUtility.WriteResultUtility(FilePath, TestCaseName, "Pass/Fail/Skip", DataSet+1, "PASS");
}
//At last make both flags as false for next data set.
Testskip=false;
Testfail=false;
}
//This data provider method will return 4 column's data one by one In every Iteration.
@DataProvider
public Object[][] SuiteOneCaseTwoData(){
//To retrieve data from Data 1 Column,Data 2 Column,Data 3 Column and Expected Result column of SuiteOneCaseTwo data Sheet.
//Last two columns (DataToRun and Pass/Fail/Skip) are Ignored programatically when reading test data.
return SuiteUtility.GetTestDataUtility(FilePath, TestCaseName);
}
//To report result as pass or fail for test cases In TestCasesList sheet.
@AfterTest
public void closeBrowser(){
if(TestCasePass){
SuiteUtility.WriteResultUtility(FilePath, SheetName, "Pass/Fail/Skip", TestCaseName, "PASS");
}
else{
SuiteUtility.WriteResultUtility(FilePath, SheetName, "Pass/Fail/Skip", TestCaseName, "FAIL");
}
}
} | [
"arrchanamohan@yahoo.co.uk"
] | arrchanamohan@yahoo.co.uk | |
91dd01e8cd64892d68d5c696fb60d5f9e75af9f2 | ea296be7e0a3be487c08dd08809054cf5b978d52 | /src/cn/ucai/kind/applib/model/GroupRemoveListener.java | 76ec015c3732fa0b74b80dea04c7cca4f960c952 | [] | no_license | SuJiang007/ucai-git-Kind | 18238c6be324706227eb84c1e0c9bc331eda6201 | a5e03d19c4b7978ef578598fc113224838d93caa | refs/heads/master | 2021-01-17T16:20:24.379615 | 2016-06-08T10:04:27 | 2016-06-08T10:04:27 | 60,239,718 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,221 | java | package cn.ucai.kind.applib.model;
import com.easemob.EMGroupChangeListener;
/**
* 群组被解散或者被T监听
*
*/
public abstract class GroupRemoveListener implements EMGroupChangeListener{
@Override
public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
// TODO Auto-generated method stub
}
@Override
public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
// TODO Auto-generated method stub
}
@Override
public void onApplicationAccept(String groupId, String groupName, String accepter) {
// TODO Auto-generated method stub
}
@Override
public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
// TODO Auto-generated method stub
}
@Override
public void onInvitationAccpted(String groupId, String inviter, String reason) {
// TODO Auto-generated method stub
}
@Override
public void onInvitationDeclined(String groupId, String invitee, String reason) {
// TODO Auto-generated method stub
}
}
| [
"402034990@qq.com"
] | 402034990@qq.com |
10af8273ba0ac500b533a8e5d028ae805734fa29 | 92156a2c72321b144f9e53fb3b3e3cf57d761184 | /src/main/java/inacap/webcomponent/prueba3/repository/TipoVehiculoRepository.java | 07fcb0585bf1f7c60d075c8aa3ce66641d44d005 | [] | no_license | callmedaddy1208/rentacar | 34e5528536a47c1c136c761b71b8631394b140b4 | b6840ea9514e5c323b314993c8721330c9b2d7b2 | refs/heads/master | 2020-03-21T08:08:07.438504 | 2018-06-30T02:07:07 | 2018-06-30T02:07:07 | 138,322,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 499 | 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 inacap.webcomponent.prueba3.repository;
import inacap.webcomponent.prueba3.model.TipoVehiculoModel;
import org.springframework.data.repository.CrudRepository;
/**
*
* @author pablo
*/
public interface TipoVehiculoRepository extends CrudRepository<TipoVehiculoModel, Integer> {
}
| [
"pablo@10.24.9.29"
] | pablo@10.24.9.29 |
beb48a7f07fa2a957b30abcf7cda760861f014f6 | ea33632bd6353aa94290df2b7a8357e9801626a0 | /src/main/java/javax/telephony/events/ProvInServiceEv.java | b5e1d9dbc89e933a42c8f2f062f17145802913c6 | [] | no_license | inkyu/TIL_JTAPI | b5dc049eda4567f7c290841e2925cadc54944a91 | 43539acfff2b0eec70e688299e3d641152eac028 | refs/heads/master | 2020-05-17T05:05:48.468878 | 2019-04-26T06:40:56 | 2019-04-26T06:40:56 | 183,523,767 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 128 | java | package javax.telephony.events;
public abstract interface ProvInServiceEv extends ProvEv {
public static final int ID = 111;
} | [
"inkyu@0566"
] | inkyu@0566 |
eef768bd4fa1255b84dee19936bf6709117117d9 | 9a75a39db6b959874d146a642a0e2524278fb806 | /src/main/java/com/example/demo/util/ManualClient.java | cbf49df1a2996ab6c7db26d2830b14f1a8f6979f | [] | no_license | zuoxiaojiang/captcha_breaker | 61ebdaf64cd6c6e916cb941f175802d3831d544f | eab4b587510547f696d337a51eab46caf4deef81 | refs/heads/master | 2022-12-12T18:44:05.290646 | 2020-09-03T12:37:10 | 2020-09-03T12:37:10 | 292,565,626 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 692 | java | package com.example.demo.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class ManualClient {
public static String resStr = "";
public static String bypass() throws InterruptedException {
String res;
System.out.println("监听接收到的人工打码结果...");
do {
Thread.sleep(1);
} while (resStr.equals(""));
System.out.println("人工打码结束...");
res = resStr;
System.out.println("人工打码结果:" + res);
resStr = "";
return res;
}
public static void main(String[] args) throws InterruptedException {
bypass();
}
}
| [
"691301967@qq.com"
] | 691301967@qq.com |
e75d4a299094fc28d2e9aaef7cf4265000e9f6da | de7bc61f2890c0e564520f74bfc2543fc9904147 | /Programs/Chapter12/Examples/src/examples/Compareit.java | 5783ee716a1f3a75661fd1af42ae7ab724a0314e | [] | no_license | dineshsharma14/JavaBio | e57f48646f77ff783b17eed5a1ec070732ecedac | 3bd18eeccd670ca15092bac15566eb91852ac288 | refs/heads/master | 2022-01-02T15:45:17.550505 | 2018-02-28T02:22:45 | 2018-02-28T02:22:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,695 | java | /*
* Copyright 2013 Peter Garst.
*
* 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 examples;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* @author peterg
*/
public class Compareit {
void tryit(List<DNA> list) {
Collections.sort(list, new Comparator<DNA>() {
@Override
public int compare(DNA o1, DNA o2) {
if (o1.size() < o2.size())
return -1;
if (o1.size() == o2.size())
return 0;
return 1;
}
});
Collections.sort(list, (DNA o1, DNA o2)
-> {
if (o1.size() < o2.size())
return -1;
if (o1.size() == o2.size())
return 0;
return 1;
});
Collections.sort(list, (o1, o2)
-> {
if (o1.size() < o2.size())
return -1;
if (o1.size() == o2.size())
return 0;
return 1;
});
(x, y) -> ((x<y)? -1 : 1);
Comparator cmp = (x, y) -> ((x<y)? -1 : 1);
}
}
| [
"pgarst@gmail.com"
] | pgarst@gmail.com |
0fca423351c45760de21ac5aa670a1893c88afdc | 133caf188b8ff26efbe313e18a315362f5e1b07f | /src/main/java/com/UrbanLadder/Utility/Listeners.java | cdce6b25e34d06d10805d3ec92a4f69805924e8d | [] | no_license | payalpatra567/HybridFramework | 8917f1bf88f68c61595ed60b3f1ecd9af317c51b | ed9de3b511631c7ded45e7732e85862c52c704eb | refs/heads/master | 2023-08-17T08:28:25.493568 | 2021-10-03T13:34:00 | 2021-10-03T13:34:00 | 413,084,414 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 579 | java | package com.UrbanLadder.Utility;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.UrbanLadder.ReusableComponents.reusablecomponent;
public class Listeners implements ITestListener{
WebDriver driver ;
reusablecomponent b = new reusablecomponent();
public void onTestFailure(ITestResult result) {
try {
b.getScreenshot(result.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"ppatra9437@gmail"
] | ppatra9437@gmail |
672bb3c7bd416c13808b0dbdbe3806b160c09f4b | 20fd738d09d438aa1a32a578bbb79a8f907bb895 | /tunnel-server/src/main/java/com/hellobike/base/tunnel/publisher/hbase/HBasePublisher.java | 5010606a3f26b32ebfa332b288d6bd6b7e07238e | [
"Apache-2.0"
] | permissive | Rayeee/tunnel | f35b7846efd807f1da08b42dc53c8f5192acb517 | 7f1aa237b778b75f434b56fb1d9a5a9fcd1523ac | refs/heads/master | 2020-04-13T19:29:25.719833 | 2018-12-28T11:06:44 | 2018-12-28T11:37:11 | 163,404,190 | 1 | 0 | null | 2018-12-28T11:43:48 | 2018-12-28T11:43:48 | null | UTF-8 | Java | false | false | 2,438 | java | /*
* Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd.
*
* 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.hellobike.base.tunnel.publisher.hbase;
import com.hellobike.base.tunnel.config.HBaseConfig;
import com.hellobike.base.tunnel.model.Event;
import com.hellobike.base.tunnel.publisher.BasePublisher;
import com.hellobike.base.tunnel.publisher.IPublisher;
import java.util.List;
import java.util.Objects;
/**
* @author machunxiao create at 2018-11-27
*/
public class HBasePublisher extends BasePublisher implements IPublisher {
private final HBaseClient hBaseClient;
private final List<HBaseConfig> configs;
public HBasePublisher(List<HBaseConfig> configs) {
this.hBaseClient = getHBaseClient(configs);
this.configs = configs;
}
@Override
public void publish(Event event, Callback callback) {
for (HBaseConfig config : configs) {
if (!config.getFilters().stream().allMatch(filter -> filter.filter(event))) {
continue;
}
switch (event.getEventType()) {
case INSERT:
hBaseClient.insert(config, event);
break;
case UPDATE:
hBaseClient.update(config, event);
break;
case DELETE:
hBaseClient.delete(config, event);
break;
default:
break;
}
}
}
@Override
public void close() {
this.hBaseClient.close();
}
private HBaseClient getHBaseClient(List<HBaseConfig> configs) {
String quorum = configs.stream()
.map(HBaseConfig::getQuorum)
.filter(Objects::nonNull)
.findFirst().orElse(null);
return quorum == null ? HBaseClient.getInstance() : HBaseClient.getInstance(quorum);
}
}
| [
"machunxiao04629@hellobike.com"
] | machunxiao04629@hellobike.com |
902f7e67d70b90a1c6a95050fa8fbfed3a9dfd7e | 956a8d2d35e4bb164c2c904fa6a58f1785fa40bf | /src/test/java/com/dzuniga/mancala/business/move/validations/InsideBoardTest.java | 702afb674943aa564f7fa7e979f4f528682d9982 | [] | no_license | douglaszuniga/mancala | a85e69a2cd1610fa3d79176fc9762cccf5960f14 | 50fed2e05c35945c61612bd01b2573ecd5a08b60 | refs/heads/master | 2022-04-19T03:49:04.462656 | 2020-04-21T15:53:53 | 2020-04-21T15:53:53 | 255,724,688 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,065 | java | package com.dzuniga.mancala.business.move.validations;
import com.dzuniga.mancala.business.move.validations.exceptions.OutsideGameboardException;
import com.dzuniga.mancala.domain.Gameboard;
import com.dzuniga.mancala.domain.Move;
import com.dzuniga.mancala.domain.Player;
import com.dzuniga.mancala.domain.Turn;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class InsideBoardTest {
private InsideBoard validation;
@BeforeEach
void setUp() {
validation = new InsideBoard();
}
@Test
public void shouldThrowNullPointerExceptionWhenMoveIsNull() {
assertThrows(NullPointerException.class, () -> validation.validate(null));
}
@Test
public void shouldNotThrowExceptionWhenStartPositionIsInsideTheGameboard() {
Gameboard gameboard = Gameboard.newGameBoard();
int startPosition = 0;
Turn turn =
Turn.builder()
.playerTwo(Player.PLAYER_TWO)
.playerOne(Player.PLAYER_ONE)
.playing(Player.PLAYER_ONE)
.number(1)
.currentBoard(gameboard)
.events(List.of())
.build();
Move move = Move.builder().currentTurn(turn).startPosition(startPosition).build();
assertDoesNotThrow(() -> validation.validate(move));
}
@Test
public void shouldThrowOutsideGameboardExceptionWhenStartPositionIsOutSideTheGameboard() {
Gameboard gameboard = Gameboard.newGameBoard();
int startPosition = 14;
Turn turn =
Turn.builder()
.playerTwo(Player.PLAYER_TWO)
.playerOne(Player.PLAYER_ONE)
.playing(Player.PLAYER_ONE)
.number(1)
.currentBoard(gameboard)
.events(List.of())
.build();
Move move = Move.builder().currentTurn(turn).startPosition(startPosition).build();
assertThrows(OutsideGameboardException.class, () -> validation.validate(move));
}
}
| [
"zuniga.doug@gmail.com"
] | zuniga.doug@gmail.com |
9381907d837af8cbea65187db19c6ac05c92f340 | e903704f314cf937e582bc132885619d35faeee4 | /bitcamp-spring-ioc/src/main/java/bitcamp/java106/step13_AOP/ex6/MyAdvice.java | d4d19b12f6d0912f1b91b36aa5072a5508595c01 | [] | no_license | DonghyounKang/bitcamp | 8e6983487a9195b043f6bf2c06e7ec7249821379 | 59333616150469f36c04d041f874e3fd59da0d8d | refs/heads/master | 2021-01-24T10:28:06.509948 | 2018-08-16T08:20:28 | 2018-08-16T08:20:28 | 123,054,186 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,120 | java | // 특정 메서드 호출 전후에 실행되는 클래스
package bitcamp.java106.step13_AOP.ex6;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAdvice {
// 타겟 객체의 메서드를 호출하기 전에 그 메서드가 받을 파라미터를 먼저 받기
/*
<aop:before
pointcut="execution(* bitcamp.java106.step13.ex4.X.*(..)) and args(a,b)"
method="doBefore"/>
*/
@Before("execution(* bitcamp.java106.step13_AOP.ex5.X.*(..)) and args(a,b)")
public void doBefore(int a, int b) {
System.out.printf("MyAdvice.doBefore(): %d, %d\n", a, b);
}
// 타겟 객체의 메서드를 호출한 후 그 결과를 받기
// => 설정 파일에 정의된 이름을 사용하여 파라미터를 선언해야 한다.
/*
<aop:after-returning
pointcut="execution(* bitcamp.java106.step13.ex4.X.*(..))"
method="doAfterReturning"
returning="returnValue"/>
*/
@AfterReturning(
pointcut="execution(* bitcamp.java106.step13_AOP.ex5.X.*(..))",
returning="returnValue")
public void doAfterReturning(Object returnValue) {
System.out.printf("MyAdvice.doAfterReturning(): %d\n", returnValue);
}
// 타겟 객체의 메서드를 호출할 때 예외가 발생했다면 그 예외 객체를 받기
// => 설정 파일에 정의된 이름을 사용하여 파라미터를 선언해야 한다.
/*
<aop:after-throwing
pointcut="execution(* bitcamp.java106.step13.ex4.X.*(..))"
method="doAfterThrowing"
throwing="error"/>
*/
@AfterThrowing(
pointcut="execution(* bitcamp.java106.step13_AOP.ex5.X.*(..))",
throwing="error")
public void doAfterThrowing(Exception error) {
System.out.printf("MyAdvice.doAfterThrowing(): %s\n", error.getMessage());
}
}
| [
"donghyounkang@gmail.com"
] | donghyounkang@gmail.com |
9417ea06d893f800b7f6641ff575c5eab9be6eba | 5bd9a62fdf9e3c799733e4afcbf52ea48cc1def9 | /src/main/java/com/capgemini/fibonacci/Fibonacci.java | 86f690ed97ad8be3b5bee7c8f3ce963c1e593af6 | [] | no_license | BartoszRatajczak/javaExercises | 1b636c50ce75ebb2cd9564076d4ce93a9f5562cd | 1d8bce034d1ff1c83658f07da038810ebb6be78f | refs/heads/master | 2016-09-01T07:08:22.361544 | 2015-10-30T10:34:16 | 2015-10-30T10:34:16 | 44,964,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 209 | java | package com.capgemini.fibonacci;
public class Fibonacci {
public static long fib(int n) {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
return (fib(n - 2) + fib(n - 1));
}
}
| [
"ratajczak89@gmail.com"
] | ratajczak89@gmail.com |
3839a94c8db796744ac25ddad9ea70b1998ac37c | 619d9787d10914dc753ba4721b4abd8837e41bb8 | /src/javacp.java | f4832be1087d93439cb675d6eb9e0026b25cdb45 | [] | no_license | njoshi727/java4cp | 63922e3b5e3787b37bc12ed326eafd821b7544c4 | 50325bb9b22e1b50df7adde6311c40b9f7f36dab | refs/heads/master | 2023-01-20T17:43:38.874577 | 2020-11-28T07:35:55 | 2020-11-28T07:35:55 | 316,681,804 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,307 | java |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.sql.SQLOutput;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Stack;
import java.util.*;
public class javacp {
static final InputStreamReader it = new InputStreamReader(System.in);
static final BufferedReader br = new BufferedReader(it);
static int sti(String s)
{
return Integer.parseInt(s);
}
static int[] sta(String[] s)
{
int[] b = new int[s.length];
for(int i=0;i<s.length;i++)
{
b[i] = sti(s[i]);
}
return b;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long nCr(int n, int r)
{
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(int n)
{
long res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
static int inputint () throws IOException{
return sti(br.readLine());
}
static int[] inputarr () throws IOException{
return sta(br.readLine().split(" "));
}
public static void main(String[] args) throws IOException {
// no of test case --> t
int t = inputint();
while (t-- >0){
int[] arr = inputarr();
int x = Math.max(arr[0],arr[1]);
int y = Math.min(arr[0],arr[1]);
if(x == y) System.out.println(2*x);
else System.out.println(2*x-1);
}
}
static long maxSubArraySum(int a[])
{
int size = a.length;
long max_so_far = Long.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
static void printArrayList(ArrayList<Integer> a)
{
for(int i=a.size()-1;i>=0;i--)
{
System.out.print(a.get(i)+" ");
}
}
static void maximumInAWindow(int[] a , int k){
Deque<Integer> dq = new ArrayDeque<>(k);
dq.addFirst(0);
//for first K elements
for(int i=1;i<k;i++)
{
while(a[dq.peekLast()] < a[i])
{
dq.removeLast();
if(dq.size()==0)
break;
}
dq.addLast(i);
}
System.out.print(a[dq.peekFirst()]+" ");
//For rest of the elements
for(int i = 1 ; i < a.length - k +1 ; i++){
while(dq.peekFirst() < i) {
dq.removeFirst();
if(dq.size()==0)
break;
}
if(dq.size()>0)
{
while(a[dq.peekLast()] < a[i+k-1])
{
dq.removeLast();
if(dq.size()==0)
break;
}
}
dq.addLast(i+k-1);
System.out.print(a[dq.peekFirst()]+" ");
}
}
} | [
"authornjnikhil@gmail.com"
] | authornjnikhil@gmail.com |
22dea6bafbc2251274c42632c0722ddbdb6d78e9 | 7d53910ec755f02fa8f2a3021956037ded353ce9 | /android/app/src/main/java/com/upsms55/DirectSmsPackage.java | bd4697a3bdca9b399eed3eb49a88d00ba7c67a6f | [] | no_license | HrithikMittal/Girl-Safety | 0659c2e1982b975277a378db32d20d62f94a4f24 | da45d00226028982298d510d015cd6a1d27fe901 | refs/heads/side | 2020-06-25T01:21:04.911450 | 2019-07-28T04:58:42 | 2019-07-28T04:58:42 | 199,153,074 | 0 | 0 | null | 2019-07-30T04:41:32 | 2019-07-27T10:57:26 | Objective-C | UTF-8 | Java | false | false | 868 | java | //DirectSmsPackage.java
package com.upsms55;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
// import com.upsms55.DirectSmsModule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DirectSmsPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
//this is where you register the module
modules.add(new DirectSmsModule(reactContext));
return modules;
}
} | [
"adhikanshmittal@gmail.com"
] | adhikanshmittal@gmail.com |
7db363f6ff810e696e0f10195cd4abf9e6bf1b9e | 5ffb589448461cecb35dedd83ccf3ea969ead039 | /src/main/java/com/upgrad/bookmyconsultation/config/SwaggerConfiguration.java | d5956434a4ec0232dfb743a19c1d995a01c9f56d | [] | no_license | jain-rishabh966/bookmyconsultation | 96634461c0ec262367c0a2b23355fab7e249e684 | d06137b1290497f1a6bd93a432ab9f039a736def | refs/heads/master | 2023-08-10T18:46:37.006771 | 2021-09-28T18:37:58 | 2021-09-28T18:37:58 | 401,070,440 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 911 | java | package com.upgrad.bookmyconsultation.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@ComponentScan("com.upgrad.bookmyconsultation.controller")
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket productsApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.upgrad.bookmyconsultation")).paths(PathSelectors.any())
.build();
}
}
| [
"jain.rishabh966@gmail.com"
] | jain.rishabh966@gmail.com |
f516812077ea006bf8f9cb058de3766f194ac3f6 | 585dbef0f42ce10b5db92e3f3b0d80066df9699c | /src/dev/emax/sortbench/algorithm/container/SortbenchAlgorithmGianlosort.java | cdc22d40a59d812eb87469110a91ecd445a1a8fa | [] | no_license | Gianlo98/Sortbench | 454db510c74e476b18de1d500c9dfbd8179d2562 | cacdfee2f76efec420bbfc2430a14331e40c79e0 | refs/heads/master | 2020-08-04T02:12:27.576459 | 2019-11-05T08:29:47 | 2019-11-05T08:29:47 | 211,966,520 | 0 | 0 | null | 2019-09-30T22:09:40 | 2019-09-30T22:09:39 | null | UTF-8 | Java | false | false | 675 | java | package dev.emax.sortbench.algorithm.container;
import dev.emax.sortbench.algorithm.SortbenchAlgorithm;
import dev.emax.sortbench.algorithm.SortbenchAlgorithmInfo;
import dev.emax.sortbench.dataset.SortbenchDataset;
public class SortbenchAlgorithmGianlosort extends SortbenchAlgorithm {
@Override
public void algorithmCompute(SortbenchDataset algorithmDataset) {
//Non fa un cazzo come me :D
}
@Override
public SortbenchAlgorithmInfo algorithmInfo() {
return SortbenchAlgorithmInfo.builder()
.algorithmName("Gianlo Sort")
.algorithmAuthor("-")
.algorithmYear("-")
.algorithmCaseBest("O(n)")
.algorithmCaseWorst("O(kN)")
.build();
}
}
| [
"gianlorenzo.occhipinti@gmail.com"
] | gianlorenzo.occhipinti@gmail.com |
616b5767e7e8ad8686cb7b8aab10f0c1b310293e | 792e2dc83e2715df4162ad6297bb5685a8491a8c | /src/main/java/com/sleepy/zeo/bean/UserBean.java | 695b876434411265aed9fea70405d575fdc17f75 | [] | no_license | sleepy-zeo/MyBatis | f8a65606d558fc21d46262167e3df9c4d8193a5c | 5a0636a8f803c1979437f724f8088b670747c650 | refs/heads/master | 2023-01-02T18:49:05.943108 | 2020-11-02T07:03:08 | 2020-11-02T07:03:08 | 308,313,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 788 | java | package com.sleepy.zeo.bean;
public class UserBean {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserBean[" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
']';
}
}
| [
"hongwei.wu@grandsun.com"
] | hongwei.wu@grandsun.com |
d06710e662046877a5e1bd74002e08482b3ee095 | df8a54e59d208bd00b74f25ecfbfd1b80cd58207 | /enums-releases/src/ca/mcmaster/magarveylab/enums/Codons.java | 08ceccf6e730329b9d87a852e8b329f1868f64c8 | [] | no_license | magarveylab/enums-releases | b6dc99c83ebda60d953a79374397aaf4971ece25 | a7fca51fc74f6cb2ced224507233bafe0a4e02a0 | refs/heads/master | 2021-01-18T23:43:55.650322 | 2016-10-02T20:51:12 | 2016-10-02T20:51:12 | 63,807,340 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,812 | java | package ca.mcmaster.magarveylab.enums;
import ca.mcmaster.magarveylab.enums.substrates.ProteinogenicAminoAcids;
public enum Codons {
UUU(ProteinogenicAminoAcids.PHENYLALANINE),
UUC(ProteinogenicAminoAcids.PHENYLALANINE),
UUA(ProteinogenicAminoAcids.LEUCINE),
UUG(ProteinogenicAminoAcids.LEUCINE),
UCU(ProteinogenicAminoAcids.SERINE),
UCC(ProteinogenicAminoAcids.SERINE),
UCA(ProteinogenicAminoAcids.SERINE),
UCG(ProteinogenicAminoAcids.SERINE),
UAU(ProteinogenicAminoAcids.TYROSINE),
UAC(ProteinogenicAminoAcids.TYROSINE),
UGU(ProteinogenicAminoAcids.CYSTEINE),
UGC(ProteinogenicAminoAcids.CYSTEINE),
UGG(ProteinogenicAminoAcids.TRYPTOPHAN),
CUU(ProteinogenicAminoAcids.LEUCINE),
CUC(ProteinogenicAminoAcids.LEUCINE),
CUA(ProteinogenicAminoAcids.LEUCINE),
CUG(ProteinogenicAminoAcids.LEUCINE),
CCU(ProteinogenicAminoAcids.PROLINE),
CCC(ProteinogenicAminoAcids.PROLINE),
CCA(ProteinogenicAminoAcids.PROLINE),
CCG(ProteinogenicAminoAcids.PROLINE),
CAU(ProteinogenicAminoAcids.HISTIDINE),
CAC(ProteinogenicAminoAcids.HISTIDINE),
CAA(ProteinogenicAminoAcids.GLUTAMINE),
CAG(ProteinogenicAminoAcids.GLUTAMINE),
CGU(ProteinogenicAminoAcids.ARGININE),
CGC(ProteinogenicAminoAcids.ARGININE),
CGA(ProteinogenicAminoAcids.ARGININE),
CGG(ProteinogenicAminoAcids.ARGININE),
AUU(ProteinogenicAminoAcids.ISOLEUCINE),
AUC(ProteinogenicAminoAcids.ISOLEUCINE),
AUA(ProteinogenicAminoAcids.ISOLEUCINE),
AUG(ProteinogenicAminoAcids.METHIONINE),
ACU(ProteinogenicAminoAcids.THREONINE),
ACC(ProteinogenicAminoAcids.THREONINE),
ACA(ProteinogenicAminoAcids.THREONINE),
ACG(ProteinogenicAminoAcids.THREONINE),
AAU(ProteinogenicAminoAcids.ASPARAGINE),
AAC(ProteinogenicAminoAcids.ASPARAGINE),
AAA(ProteinogenicAminoAcids.LYSINE),
AAG(ProteinogenicAminoAcids.LYSINE),
AGU(ProteinogenicAminoAcids.SERINE),
AGC(ProteinogenicAminoAcids.SERINE),
AGA(ProteinogenicAminoAcids.ARGININE),
AGG(ProteinogenicAminoAcids.ARGININE),
GUU(ProteinogenicAminoAcids.VALINE),
GUC(ProteinogenicAminoAcids.VALINE),
GUA(ProteinogenicAminoAcids.VALINE),
GUG(ProteinogenicAminoAcids.VALINE),
GCU(ProteinogenicAminoAcids.ALANINE),
GCC(ProteinogenicAminoAcids.ALANINE),
GCA(ProteinogenicAminoAcids.ALANINE),
GCG(ProteinogenicAminoAcids.ALANINE),
GAU(ProteinogenicAminoAcids.ASPARTATE),
GAC(ProteinogenicAminoAcids.ASPARTATE),
GAA(ProteinogenicAminoAcids.GLUTAMATE),
GAG(ProteinogenicAminoAcids.GLUTAMATE),
GGU(ProteinogenicAminoAcids.GLYCINE),
GGC(ProteinogenicAminoAcids.GLYCINE),
GGA(ProteinogenicAminoAcids.GLYCINE),
GGG(ProteinogenicAminoAcids.GLYCINE),
;
private ProteinogenicAminoAcids aminoAcid;
private Codons(ProteinogenicAminoAcids aminoAcid) {
this.aminoAcid = aminoAcid;
}
public ProteinogenicAminoAcids getAminoAcid() {
return aminoAcid;
}
// stop: UAA, UAG, UGA
}
| [
"michaelskinnider@gmail.com"
] | michaelskinnider@gmail.com |
4102150a33f8c9f68274b5039cb436d0d68335eb | 97b6b04ea5fe1a85da921fc6e8eea5a88c893a14 | /src/com/day14/day14/关卡三/Title3.java | 5c21c8ce226db7f13a07ed8a0680c86e895c43a2 | [] | no_license | To-chase/JavaPro | a1809b4ea03f80332ac3ea01fb3e2bd0a0cbfd86 | 6b5efa8d75998207a123c8602369db5d35729129 | refs/heads/master | 2020-12-11T10:01:28.179800 | 2020-01-19T08:19:23 | 2020-01-19T08:19:23 | 233,815,240 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 948 | java | package com.day14.day14.关卡三;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
public class Title3 {
public static void main(String[] args){
HashMap<String,String> map=new HashMap<>();
Scanner sc=new Scanner(System.in);
Random random=new Random();
map.put("12345678","西瓜");
map.put("12345679","香蕉");
map.put("12345670","苹果");
map.put("12345687","橘子");
while(true){
System.out.println("请输入商品号(输-1结束):");
String str=sc.next();
if(!str.equals("-1")){
if(map.containsKey(str)){
System.out.println("根据商品号:"+str+",查询到对应的商品为:"+map.get(str));
}else{
System.out.println("查无商品");
}
}else{
break;
}
}
}
}
| [
"1174934578@qq.com"
] | 1174934578@qq.com |
b14abbd188a30cb6138a053bb2d1a4299f4cb479 | c5e3cb259bbd9cc1d732c06664f7efa5ea5b5eda | /pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/patch/TissuePatch.java | 22ebe109e27f5d4f78ae5dd6ba64fb7d3ee9ead7 | [
"BSD-3-Clause"
] | permissive | broadinstitute/ddp-study-server | c7f69a0576f27f0e75955421d8bfc0cb1154b41e | 8709557b32bac942e227eaa1029477771562d47a | refs/heads/develop | 2023-09-01T02:22:28.228891 | 2023-08-31T21:03:45 | 2023-08-31T21:03:45 | 224,263,376 | 12 | 6 | BSD-3-Clause | 2023-09-14T16:55:00 | 2019-11-26T18:49:36 | Java | UTF-8 | Java | false | false | 1,445 | java | package org.broadinstitute.dsm.model.patch;
import java.util.Optional;
import org.broadinstitute.dsm.db.Tissue;
import org.broadinstitute.dsm.model.NameValue;
public class TissuePatch extends BasePatch {
public static final String TISSUE_ID = "tissueId";
private String tissueId;
public TissuePatch(Patch patch) {
super(patch);
}
private void prepare() {
tissueId = Tissue.createNewTissue(patch.getParentId(), patch.getUser());
}
@Override
public Object doPatch() {
return patchNameValuePair();
}
@Override
protected Object patchNameValuePairs() {
return null;
}
@Override
protected Object patchNameValuePair() {
prepare();
Optional<Object> maybeNameValue = processSingleNameValue();
return maybeNameValue.orElse(resultMap);
}
@Override
Object handleSingleNameValue() {
if (Patch.patch(tissueId, patch.getUser(), patch.getNameValue(), dbElement)) {
nameValues = setWorkflowRelatedFields(patch);
resultMap.put(TISSUE_ID, tissueId);
if (!nameValues.isEmpty()) {
resultMap.put(NAME_VALUE, GSON.toJson(nameValues));
}
exportToESWithId(tissueId, patch.getNameValue());
}
return resultMap;
}
@Override
Optional<Object> processEachNameValue(NameValue nameValue) {
return Optional.empty();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fde07e420ba928ad440931a6b8332734e3c4bdb7 | 73afe0210dd332a32860392bec393ca73eaed2b6 | /fkSdk/src/main/java/com/jchou/sdk/view/CustomDialog.java | 9245bad1403f154af0087cb086119657aa439990 | [] | no_license | JohnsonHou/FkLib | 2a2eca401687ed700bd9e9949ba52d1d01692534 | be5452071bf805393510e67e5cd3e9b913b550b0 | refs/heads/master | 2020-05-23T02:29:26.889623 | 2019-05-15T02:01:44 | 2019-05-15T02:01:44 | 186,605,458 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,878 | java | package com.jchou.sdk.view;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.jchou.sdk.R;
public class CustomDialog extends ProgressDialog {
private TextView tvLoad;
CharSequence mMessage;
public CustomDialog(Context context, @Nullable CharSequence message) {
this(context, R.style.CustomDialog, message);
}
public CustomDialog(Context context) {
this(context, R.style.CustomDialog, null);
}
public CustomDialog(Context context, int theme, @Nullable CharSequence message) {
super(context, theme);
mMessage = message;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init(getContext());
}
private void init(Context context) {
//设置不可取消,点击其他区域不能取消,实际中可以抽出去封装供外包设置
setCancelable(false);
setCanceledOnTouchOutside(false);
View view = LayoutInflater.from(context).inflate(R.layout.loadinglayout, null, false);
setContentView(view);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
getWindow().setAttributes(params);
tvLoad = (TextView) view.findViewById(R.id.tv_load_dialog);
if (!TextUtils.isEmpty(mMessage)) {
tvLoad.setVisibility(View.VISIBLE);
tvLoad.setText(mMessage);
}
}
@Override
public void show() {
super.show();
}
} | [
"jc_hou0817@163.com"
] | jc_hou0817@163.com |
b4371209fd48ea2cf0665ebe80e388d23bdad5bd | 2f7a608250c536c7b5af4826146475a6f68ac1b9 | /src/main/java/algorithms/LCS.java | 0779a1cdef253ef7e62e90696ce108cf67746d28 | [] | no_license | tasyrkin/Algorithms | a10369d65ff244ee1ffac39bd0875042e393e4be | 1dc8415a665a3812f715a26b34aa6df4c36d8fce | refs/heads/master | 2020-12-24T16:35:20.600243 | 2019-01-07T01:35:49 | 2019-01-07T01:35:49 | 38,586,047 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,845 | java | package algorithms;
import java.util.Arrays;
public class LCS {
public static int LCS(String a, String b) {
char[] aArr = a.toCharArray();
char[] bArr = b.toCharArray();
int[][] lcsArray = new int[aArr.length][bArr.length];
lcsArray[0][0] = aArr[0] == bArr[0] ? 1 : 0;
for (int I = 0; I < aArr.length; I++) {
for (int J = 0; J < bArr.length; J++) {
int currMax = Integer.MIN_VALUE;
for (int i = 0; i < I; i++) {
for (int j = 0; j < J; j++) {
if (currMax < lcsArray[i][j])
currMax = lcsArray[i][j];
}
}
lcsArray[I][J] = Math.max(lcsArray[I][J],
(currMax == Integer.MIN_VALUE ? 0 : currMax)
+ (aArr[I] == bArr[J] ? 1 : 0));
}
}
// int max = Integer.MIN_VALUE;
// for (int I = 0; I < aArr.length; I++) {
// for (int J = 0; J < bArr.length; J++) {
// if(max < lcsArray[I][J]){
// max = lcsArray[I][J];
// }
// }
// }
return lcsArray[aArr.length - 1][bArr.length - 1];
}
public static int[][] array = null;
public static int LCS2(char[] a, char[] b, int i, int j) {
if (i < 0 || j < 0)
return 0;
if (array[i][j] > 0)
return array[i][j];
int equal = (a[i] == b[j] ? 1 : 0) + LCS2(a, b, i - 1, j - 1);
int lessI = LCS2(a, b, i - 1, j);
int lessJ = LCS2(a, b, i, j - 1);
int res = Math.max(equal, Math.max(lessI, lessJ));
array[i][j] = res;
return array[i][j];
}
/**
* @param args
*/
public static void main(String[] args) {
char[] a = "a1b1c1d1e111".toCharArray();
char[] b = "bcde11111".toCharArray();
array = new int[a.length][b.length];
int lcsNum = LCS2(a, b, a.length - 1, b.length - 1);
System.out.println(lcsNum);
for (int i = 0; i < array.length; i++) {
System.out.println(Arrays.toString(array[i]));
}
char[] result = new char[lcsNum];
int i = a.length - 1;
int j = b.length - 1;
while (lcsNum > 0) {
int curr = array[i][j];
boolean need_i = false;
for (int cnt_i = i - 1; cnt_i >= 0; cnt_i--) {
if (array[i][j] == array[cnt_i][j] + 1) {
i = cnt_i + 1;
need_i = true;
break;
}
}
boolean need_j = false;
for (int cnt_j = j - 1; cnt_j >= 0; cnt_j--) {
if (array[i][j] == array[i][cnt_j] + 1) {
j = cnt_j + 1;
need_j = true;
break;
}
}
result[--lcsNum] = a[i];
if(need_i)i--;
if(need_j)j--;
}
// while (lcsNum > 0) {
// int num = Integer.MAX_VALUE;
// if (i > 0 && j > 0) {
// num = array[i - 1][j - 1];
// }
// int num1 = Integer.MAX_VALUE;
// if (i > 0) {
// num1 = array[i - 1][j];
// }
// int num2 = Integer.MAX_VALUE;
// if (j > 0) {
// num2 = array[i][j - 1];
// }
// if ((num == lcsNum - 1 && num1 == lcsNum - 1 && num2 == lcsNum - 1)
// || (i == 0 && j == 0)) {
// result[--lcsNum] = a[i];
// } else {
// if (lcsNum == num) {
// i--;
// j--;
// } else if (lcsNum == num1) {
// i--;
// } else {
// j--;
// }
// }
// }
// while (lcsNum > 0) {
// int num = array[i - 1][j - 1];
// int num1 = Integer.MIN_VALUE;
// if (j < b.length) {
// num1 = array[i - 1][j];
// }
// int num2 = Integer.MIN_VALUE;
// if (i < a.length) {
// num2 = array[i][j - 1];
// }
// //int max = Math.max(num, Math.max(num1, num2));
// if (lcsNum == num && a[i - 1] == b[j - 1]) {
// result[--lcsNum] = a[i - 1];
// i--;
// j--;
// } else if (lcsNum == num1 && j < b.length && a[i - 1] == b[j]) {
// result[--lcsNum] = a[i - 1];
// i--;
// } else if (lcsNum == num2 && i < a.length && a[i] == b[j - 1]) {
// result[--lcsNum] = a[j - 1];
// j--;
// }
// }
// for (int i = a.length - 1; i > 0; i--) {
// for (int j = b.length - 1; j > 0; j--) {
// int num = array[i][j];
// if (num > array[i - 1][j] && num > array[i][j - 1]){
// result[--lcsNum] = a[i];
// }
// }
// }
System.out.println(Arrays.toString(result));
}
}
| [
"tasyrkin@gmail.com"
] | tasyrkin@gmail.com |
f8e2f28f92381837e9a1ed061ecbb53c0898b44d | 3a88c92b5dc7d5445af7cc7e7bf2c13f1fcfa59b | /appinventor/ai_notifications_eoteam/GROW_game_app/Missions.java | ae41640cb5230a9569c6ba91b047283a2b9711d7 | [] | no_license | greengs/GROW_game_app | d63ee9f7ca1ced6a335c3821db9586877167d847 | 1ded3fe9ee3eee78642632abccf0c70f9326a8e5 | refs/heads/main | 2023-06-11T08:29:25.237968 | 2021-06-20T01:17:05 | 2021-06-20T01:17:05 | 378,533,074 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 31,390 | java | package appinventor.ai_notifications_eoteam.GROW_game_app;
import android.os.Bundle;
import com.google.appinventor.components.runtime.AppInventorCompatActivity;
import com.google.appinventor.components.runtime.Component;
import com.google.appinventor.components.runtime.EventDispatcher;
import com.google.appinventor.components.runtime.Form;
import com.google.appinventor.components.runtime.HandlesEventDispatching;
import com.google.appinventor.components.runtime.HorizontalArrangement;
import com.google.appinventor.components.runtime.Image;
import com.google.appinventor.components.runtime.Label;
import com.google.appinventor.components.runtime.errors.PermissionException;
import com.google.appinventor.components.runtime.errors.YailRuntimeError;
import com.google.appinventor.components.runtime.util.RetValManager;
import com.google.appinventor.components.runtime.util.RuntimeErrorAlert;
import com.google.youngandroid.runtime;
import gnu.expr.Language;
import gnu.expr.ModuleBody;
import gnu.expr.ModuleInfo;
import gnu.expr.ModuleMethod;
import gnu.kawa.functions.Apply;
import gnu.kawa.functions.Format;
import gnu.kawa.functions.GetNamedPart;
import gnu.kawa.functions.IsEqual;
import gnu.kawa.reflect.Invoke;
import gnu.kawa.reflect.SlotGet;
import gnu.kawa.reflect.SlotSet;
import gnu.lists.Consumer;
import gnu.lists.FString;
import gnu.lists.LList;
import gnu.lists.Pair;
import gnu.lists.VoidConsumer;
import gnu.mapping.CallContext;
import gnu.mapping.Environment;
import gnu.mapping.Procedure;
import gnu.mapping.SimpleSymbol;
import gnu.mapping.Symbol;
import gnu.mapping.Values;
import gnu.mapping.WrongType;
import gnu.math.IntNum;
import kawa.lang.Promise;
import kawa.lib.lists;
import kawa.lib.misc;
import kawa.lib.strings;
import kawa.standard.Scheme;
public class Missions extends Form implements Runnable {
static final SimpleSymbol Lit0;
static final SimpleSymbol Lit1;
static final SimpleSymbol Lit10;
static final SimpleSymbol Lit11;
static final SimpleSymbol Lit12;
static final SimpleSymbol Lit13;
static final SimpleSymbol Lit14;
static final FString Lit15;
static final SimpleSymbol Lit16;
static final SimpleSymbol Lit17;
static final IntNum Lit18;
static final SimpleSymbol Lit19;
static final SimpleSymbol Lit2;
static final IntNum Lit20;
static final FString Lit21;
static final FString Lit22;
static final SimpleSymbol Lit23;
static final SimpleSymbol Lit24;
static final SimpleSymbol Lit25;
static final IntNum Lit26;
static final SimpleSymbol Lit27;
static final SimpleSymbol Lit28;
static final IntNum Lit29;
static final SimpleSymbol Lit3;
static final SimpleSymbol Lit30;
static final IntNum Lit31;
static final FString Lit32;
static final FString Lit33;
static final SimpleSymbol Lit34;
static final IntNum Lit35;
static final FString Lit36;
static final FString Lit37;
static final SimpleSymbol Lit38;
static final IntNum Lit39;
static final IntNum Lit4;
static final SimpleSymbol Lit40;
static final IntNum Lit41;
static final FString Lit42;
static final SimpleSymbol Lit43;
static final SimpleSymbol Lit44;
static final SimpleSymbol Lit45;
static final SimpleSymbol Lit46;
static final SimpleSymbol Lit47;
static final SimpleSymbol Lit48;
static final SimpleSymbol Lit49;
static final SimpleSymbol Lit5;
static final SimpleSymbol Lit50;
static final SimpleSymbol Lit51;
static final SimpleSymbol Lit52;
static final SimpleSymbol Lit53;
static final SimpleSymbol Lit54;
static final SimpleSymbol Lit55;
static final SimpleSymbol Lit56 = (SimpleSymbol)(new SimpleSymbol("lookup-handler")).readResolve();
static final SimpleSymbol Lit6;
static final SimpleSymbol Lit7;
static final SimpleSymbol Lit8;
static final IntNum Lit9;
public static Missions Missions;
static final ModuleMethod lambda$Fn1;
static final ModuleMethod lambda$Fn10;
static final ModuleMethod lambda$Fn2;
static final ModuleMethod lambda$Fn3;
static final ModuleMethod lambda$Fn4;
static final ModuleMethod lambda$Fn5;
static final ModuleMethod lambda$Fn6;
static final ModuleMethod lambda$Fn7;
static final ModuleMethod lambda$Fn8;
static final ModuleMethod lambda$Fn9;
public Boolean $Stdebug$Mnform$St;
public final ModuleMethod $define;
public HorizontalArrangement HorizontalArrangement1;
public HorizontalArrangement HorizontalArrangement2;
public Image Image1;
public Label Label1;
public final ModuleMethod add$Mnto$Mncomponents;
public final ModuleMethod add$Mnto$Mnevents;
public final ModuleMethod add$Mnto$Mnform$Mndo$Mnafter$Mncreation;
public final ModuleMethod add$Mnto$Mnform$Mnenvironment;
public final ModuleMethod add$Mnto$Mnglobal$Mnvar$Mnenvironment;
public final ModuleMethod add$Mnto$Mnglobal$Mnvars;
public final ModuleMethod android$Mnlog$Mnform;
public LList components$Mnto$Mncreate;
public final ModuleMethod dispatchEvent;
public final ModuleMethod dispatchGenericEvent;
public LList events$Mnto$Mnregister;
public LList form$Mndo$Mnafter$Mncreation;
public Environment form$Mnenvironment;
public Symbol form$Mnname$Mnsymbol;
public final ModuleMethod get$Mnsimple$Mnname;
public Environment global$Mnvar$Mnenvironment;
public LList global$Mnvars$Mnto$Mncreate;
public final ModuleMethod is$Mnbound$Mnin$Mnform$Mnenvironment;
public final ModuleMethod lookup$Mnhandler;
public final ModuleMethod lookup$Mnin$Mnform$Mnenvironment;
public final ModuleMethod onCreate;
public final ModuleMethod process$Mnexception;
public final ModuleMethod send$Mnerror;
static {
Lit55 = (SimpleSymbol)(new SimpleSymbol("dispatchGenericEvent")).readResolve();
Lit54 = (SimpleSymbol)(new SimpleSymbol("dispatchEvent")).readResolve();
Lit53 = (SimpleSymbol)(new SimpleSymbol("send-error")).readResolve();
Lit52 = (SimpleSymbol)(new SimpleSymbol("add-to-form-do-after-creation")).readResolve();
Lit51 = (SimpleSymbol)(new SimpleSymbol("add-to-global-vars")).readResolve();
Lit50 = (SimpleSymbol)(new SimpleSymbol("add-to-components")).readResolve();
Lit49 = (SimpleSymbol)(new SimpleSymbol("add-to-events")).readResolve();
Lit48 = (SimpleSymbol)(new SimpleSymbol("add-to-global-var-environment")).readResolve();
Lit47 = (SimpleSymbol)(new SimpleSymbol("is-bound-in-form-environment")).readResolve();
Lit46 = (SimpleSymbol)(new SimpleSymbol("lookup-in-form-environment")).readResolve();
Lit45 = (SimpleSymbol)(new SimpleSymbol("add-to-form-environment")).readResolve();
Lit44 = (SimpleSymbol)(new SimpleSymbol("android-log-form")).readResolve();
Lit43 = (SimpleSymbol)(new SimpleSymbol("get-simple-name")).readResolve();
Lit42 = new FString("com.google.appinventor.components.runtime.Image");
Lit41 = IntNum.make(-1080);
Lit40 = (SimpleSymbol)(new SimpleSymbol("Picture")).readResolve();
Lit39 = IntNum.make(-1050);
Lit38 = (SimpleSymbol)(new SimpleSymbol("Image1")).readResolve();
Lit37 = new FString("com.google.appinventor.components.runtime.Image");
Lit36 = new FString("com.google.appinventor.components.runtime.HorizontalArrangement");
Lit35 = IntNum.make(-1005);
Lit34 = (SimpleSymbol)(new SimpleSymbol("HorizontalArrangement2")).readResolve();
Lit33 = new FString("com.google.appinventor.components.runtime.HorizontalArrangement");
Lit32 = new FString("com.google.appinventor.components.runtime.Label");
int[] arrayOfInt = new int[2];
arrayOfInt[0] = -1;
Lit31 = IntNum.make(arrayOfInt);
Lit30 = (SimpleSymbol)(new SimpleSymbol("TextColor")).readResolve();
Lit29 = IntNum.make(1);
Lit28 = (SimpleSymbol)(new SimpleSymbol("TextAlignment")).readResolve();
Lit27 = (SimpleSymbol)(new SimpleSymbol("Text")).readResolve();
Lit26 = IntNum.make(18);
Lit25 = (SimpleSymbol)(new SimpleSymbol("FontSize")).readResolve();
Lit24 = (SimpleSymbol)(new SimpleSymbol("FontBold")).readResolve();
Lit23 = (SimpleSymbol)(new SimpleSymbol("Label1")).readResolve();
Lit22 = new FString("com.google.appinventor.components.runtime.Label");
Lit21 = new FString("com.google.appinventor.components.runtime.HorizontalArrangement");
Lit20 = IntNum.make(-1005);
Lit19 = (SimpleSymbol)(new SimpleSymbol("Width")).readResolve();
Lit18 = IntNum.make(-1005);
Lit17 = (SimpleSymbol)(new SimpleSymbol("Height")).readResolve();
Lit16 = (SimpleSymbol)(new SimpleSymbol("HorizontalArrangement1")).readResolve();
Lit15 = new FString("com.google.appinventor.components.runtime.HorizontalArrangement");
Lit14 = (SimpleSymbol)(new SimpleSymbol("TitleVisible")).readResolve();
Lit13 = (SimpleSymbol)(new SimpleSymbol("Title")).readResolve();
Lit12 = (SimpleSymbol)(new SimpleSymbol("Sizing")).readResolve();
Lit11 = (SimpleSymbol)(new SimpleSymbol("boolean")).readResolve();
Lit10 = (SimpleSymbol)(new SimpleSymbol("ShowListsAsJson")).readResolve();
arrayOfInt = new int[2];
arrayOfInt[0] = -15227642;
Lit9 = IntNum.make(arrayOfInt);
Lit8 = (SimpleSymbol)(new SimpleSymbol("BackgroundColor")).readResolve();
Lit7 = (SimpleSymbol)(new SimpleSymbol("text")).readResolve();
Lit6 = (SimpleSymbol)(new SimpleSymbol("AppName")).readResolve();
Lit5 = (SimpleSymbol)(new SimpleSymbol("number")).readResolve();
Lit4 = IntNum.make(3);
Lit3 = (SimpleSymbol)(new SimpleSymbol("AlignHorizontal")).readResolve();
Lit2 = (SimpleSymbol)(new SimpleSymbol("*the-null-value*")).readResolve();
Lit1 = (SimpleSymbol)(new SimpleSymbol("getMessage")).readResolve();
Lit0 = (SimpleSymbol)(new SimpleSymbol("Missions")).readResolve();
}
public Missions() {
ModuleInfo.register(this);
Missions$frame missions$frame = new Missions$frame();
missions$frame.$main = this;
this.get$Mnsimple$Mnname = new ModuleMethod(missions$frame, 1, Lit43, 4097);
this.onCreate = new ModuleMethod(missions$frame, 2, "onCreate", 4097);
this.android$Mnlog$Mnform = new ModuleMethod(missions$frame, 3, Lit44, 4097);
this.add$Mnto$Mnform$Mnenvironment = new ModuleMethod(missions$frame, 4, Lit45, 8194);
this.lookup$Mnin$Mnform$Mnenvironment = new ModuleMethod(missions$frame, 5, Lit46, 8193);
this.is$Mnbound$Mnin$Mnform$Mnenvironment = new ModuleMethod(missions$frame, 7, Lit47, 4097);
this.add$Mnto$Mnglobal$Mnvar$Mnenvironment = new ModuleMethod(missions$frame, 8, Lit48, 8194);
this.add$Mnto$Mnevents = new ModuleMethod(missions$frame, 9, Lit49, 8194);
this.add$Mnto$Mncomponents = new ModuleMethod(missions$frame, 10, Lit50, 16388);
this.add$Mnto$Mnglobal$Mnvars = new ModuleMethod(missions$frame, 11, Lit51, 8194);
this.add$Mnto$Mnform$Mndo$Mnafter$Mncreation = new ModuleMethod(missions$frame, 12, Lit52, 4097);
this.send$Mnerror = new ModuleMethod(missions$frame, 13, Lit53, 4097);
this.process$Mnexception = new ModuleMethod(missions$frame, 14, "process-exception", 4097);
this.dispatchEvent = new ModuleMethod(missions$frame, 15, Lit54, 16388);
this.dispatchGenericEvent = new ModuleMethod(missions$frame, 16, Lit55, 16388);
this.lookup$Mnhandler = new ModuleMethod(missions$frame, 17, Lit56, 8194);
ModuleMethod moduleMethod = new ModuleMethod(missions$frame, 18, null, 0);
moduleMethod.setProperty("source-location", "/tmp/runtime6993135000179593734.scm:622");
lambda$Fn1 = moduleMethod;
this.$define = new ModuleMethod(missions$frame, 19, "$define", 0);
lambda$Fn2 = new ModuleMethod(missions$frame, 20, null, 0);
lambda$Fn3 = new ModuleMethod(missions$frame, 21, null, 0);
lambda$Fn4 = new ModuleMethod(missions$frame, 22, null, 0);
lambda$Fn5 = new ModuleMethod(missions$frame, 23, null, 0);
lambda$Fn6 = new ModuleMethod(missions$frame, 24, null, 0);
lambda$Fn7 = new ModuleMethod(missions$frame, 25, null, 0);
lambda$Fn8 = new ModuleMethod(missions$frame, 26, null, 0);
lambda$Fn9 = new ModuleMethod(missions$frame, 27, null, 0);
lambda$Fn10 = new ModuleMethod(missions$frame, 28, null, 0);
}
static Object lambda10() {
runtime.setAndCoerceProperty$Ex(Lit38, Lit17, Lit39, Lit5);
runtime.setAndCoerceProperty$Ex(Lit38, Lit40, "Attiki.jpg", Lit7);
return runtime.setAndCoerceProperty$Ex(Lit38, Lit19, Lit41, Lit5);
}
static Object lambda11() {
runtime.setAndCoerceProperty$Ex(Lit38, Lit17, Lit39, Lit5);
runtime.setAndCoerceProperty$Ex(Lit38, Lit40, "Attiki.jpg", Lit7);
return runtime.setAndCoerceProperty$Ex(Lit38, Lit19, Lit41, Lit5);
}
public static SimpleSymbol lambda1symbolAppend$V(Object[] paramArrayOfObject) {
LList lList2 = LList.makeList(paramArrayOfObject, 0);
Apply apply = Scheme.apply;
ModuleMethod moduleMethod = strings.string$Mnappend;
LList lList1 = LList.Empty;
while (true) {
Object object1;
Object object2;
if (lList2 == LList.Empty) {
object1 = apply.apply2(moduleMethod, LList.reverseInPlace(lList1));
try {
CharSequence charSequence = (CharSequence)object1;
return misc.string$To$Symbol(charSequence);
} catch (ClassCastException null) {
throw new WrongType(object2, "string->symbol", 1, object1);
}
}
try {
Pair pair = (Pair)object2;
object2 = pair.getCdr();
Object object = pair.getCar();
try {
Symbol symbol = (Symbol)object;
object1 = Pair.make(misc.symbol$To$String(symbol), object1);
} catch (ClassCastException classCastException) {
throw new WrongType(classCastException, "symbol->string", 1, object);
}
} catch (ClassCastException classCastException) {
throw new WrongType(classCastException, "arg0", -2, object2);
}
}
}
static Object lambda2() {
return null;
}
static Object lambda3() {
runtime.setAndCoerceProperty$Ex(Lit0, Lit3, Lit4, Lit5);
runtime.setAndCoerceProperty$Ex(Lit0, Lit6, "GROW_game_app", Lit7);
runtime.setAndCoerceProperty$Ex(Lit0, Lit8, Lit9, Lit5);
runtime.setAndCoerceProperty$Ex(Lit0, Lit10, Boolean.TRUE, Lit11);
runtime.setAndCoerceProperty$Ex(Lit0, Lit12, "Responsive", Lit7);
runtime.setAndCoerceProperty$Ex(Lit0, Lit13, "Missions", Lit7);
return runtime.setAndCoerceProperty$Ex(Lit0, Lit14, Boolean.FALSE, Lit11);
}
static Object lambda4() {
runtime.setAndCoerceProperty$Ex(Lit16, Lit17, Lit18, Lit5);
return runtime.setAndCoerceProperty$Ex(Lit16, Lit19, Lit20, Lit5);
}
static Object lambda5() {
runtime.setAndCoerceProperty$Ex(Lit16, Lit17, Lit18, Lit5);
return runtime.setAndCoerceProperty$Ex(Lit16, Lit19, Lit20, Lit5);
}
static Object lambda6() {
runtime.setAndCoerceProperty$Ex(Lit23, Lit24, Boolean.TRUE, Lit11);
runtime.setAndCoerceProperty$Ex(Lit23, Lit25, Lit26, Lit5);
runtime.setAndCoerceProperty$Ex(Lit23, Lit27, "Missions", Lit7);
runtime.setAndCoerceProperty$Ex(Lit23, Lit28, Lit29, Lit5);
return runtime.setAndCoerceProperty$Ex(Lit23, Lit30, Lit31, Lit5);
}
static Object lambda7() {
runtime.setAndCoerceProperty$Ex(Lit23, Lit24, Boolean.TRUE, Lit11);
runtime.setAndCoerceProperty$Ex(Lit23, Lit25, Lit26, Lit5);
runtime.setAndCoerceProperty$Ex(Lit23, Lit27, "Missions", Lit7);
runtime.setAndCoerceProperty$Ex(Lit23, Lit28, Lit29, Lit5);
return runtime.setAndCoerceProperty$Ex(Lit23, Lit30, Lit31, Lit5);
}
static Object lambda8() {
return runtime.setAndCoerceProperty$Ex(Lit34, Lit17, Lit35, Lit5);
}
static Object lambda9() {
return runtime.setAndCoerceProperty$Ex(Lit34, Lit17, Lit35, Lit5);
}
public void $define() {
Language.setDefaults((Language)Scheme.getInstance());
try {
run();
} catch (Exception exception) {
androidLogForm(exception.getMessage());
processException(exception);
}
Missions = this;
addToFormEnvironment((Symbol)Lit0, this);
LList lList = this.events$Mnto$Mnregister;
while (true) {
if (lList == LList.Empty)
try {
lList = lists.reverse(this.components$Mnto$Mncreate);
addToGlobalVars(Lit2, lambda$Fn1);
LList lList1 = lists.reverse(this.form$Mndo$Mnafter$Mncreation);
while (true) {
Object object1;
if (lList1 == LList.Empty) {
lList1 = lList;
while (true) {
Object object2;
if (lList1 == LList.Empty) {
lList1 = lists.reverse(this.global$Mnvars$Mnto$Mncreate);
while (true) {
if (lList1 == LList.Empty) {
lList1 = lList;
while (true) {
if (lList1 == LList.Empty)
while (true) {
lList1 = LList.Empty;
if (lList == lList1)
return;
try {
Pair pair = (Pair)lList;
object = pair.getCar();
Object object3 = lists.caddr.apply1(object);
lists.cadddr.apply1(object);
callInitialize(SlotGet.field.apply2(this, object3));
object = pair.getCdr();
} catch (ClassCastException null) {
throw new WrongType(object1, "arg0", -2, object);
}
}
try {
Pair pair = (Pair)object1;
object1 = pair.getCar();
lists.caddr.apply1(object1);
object1 = lists.cadddr.apply1(object1);
if (object1 != Boolean.FALSE)
Scheme.applyToArgs.apply1(object1);
object1 = pair.getCdr();
} catch (ClassCastException null) {
throw new WrongType(object, "arg0", -2, object1);
}
}
break;
}
try {
Pair pair = (Pair)object1;
Object object3 = pair.getCar();
object1 = lists.car.apply1(object3);
object3 = lists.cadr.apply1(object3);
try {
object2 = object1;
addToGlobalVarEnvironment((Symbol)object2, Scheme.applyToArgs.apply1(object3));
object1 = pair.getCdr();
} catch (ClassCastException null) {}
} catch (ClassCastException null) {
throw new WrongType(object, "arg0", -2, object1);
}
throw new WrongType(object, "add-to-global-var-environment", 0, object1);
}
break;
}
try {
Pair pair = (Pair)object1;
object2 = pair.getCar();
object1 = lists.caddr.apply1(object2);
lists.cadddr.apply1(object2);
Object object3 = lists.cadr.apply1(object2);
object2 = lists.car.apply1(object2);
try {
Symbol symbol = (Symbol)object2;
object2 = lookupInFormEnvironment(symbol);
object3 = Invoke.make.apply2(object3, object2);
SlotSet.set$Mnfield$Ex.apply3(this, object1, object3);
try {
object2 = object1;
addToFormEnvironment((Symbol)object2, object3);
object1 = pair.getCdr();
} catch (ClassCastException null) {}
} catch (ClassCastException null) {}
} catch (ClassCastException null) {
throw new WrongType(object, "arg0", -2, object1);
}
throw new WrongType(object, "lookup-in-form-environment", 0, object2);
}
break;
}
try {
Pair pair = (Pair)object1;
misc.force(pair.getCar());
object1 = pair.getCdr();
} catch (ClassCastException null) {
throw new WrongType(object, "arg0", -2, object1);
}
}
continue;
} catch (YailRuntimeError object) {
processException(object);
return;
}
try {
Pair pair = (Pair)object;
Object object1 = pair.getCar();
object = lists.car.apply1(object1);
if (object == null) {
object = null;
} else {
object = object.toString();
}
object1 = lists.cdr.apply1(object1);
if (object1 == null) {
object1 = null;
} else {
object1 = object1.toString();
}
EventDispatcher.registerEventForDelegation((HandlesEventDispatching)this, (String)object, (String)object1);
object = pair.getCdr();
} catch (ClassCastException classCastException) {
throw new WrongType(classCastException, "arg0", -2, object);
}
}
}
public void addToComponents(Object paramObject1, Object paramObject2, Object paramObject3, Object paramObject4) {
this.components$Mnto$Mncreate = (LList)lists.cons(LList.list4(paramObject1, paramObject2, paramObject3, paramObject4), this.components$Mnto$Mncreate);
}
public void addToEvents(Object paramObject1, Object paramObject2) {
this.events$Mnto$Mnregister = (LList)lists.cons(lists.cons(paramObject1, paramObject2), this.events$Mnto$Mnregister);
}
public void addToFormDoAfterCreation(Object paramObject) {
this.form$Mndo$Mnafter$Mncreation = (LList)lists.cons(paramObject, this.form$Mndo$Mnafter$Mncreation);
}
public void addToFormEnvironment(Symbol paramSymbol, Object paramObject) {
androidLogForm(Format.formatToString(0, new Object[] { "Adding ~A to env ~A with value ~A", paramSymbol, this.form$Mnenvironment, paramObject }));
this.form$Mnenvironment.put(paramSymbol, paramObject);
}
public void addToGlobalVarEnvironment(Symbol paramSymbol, Object paramObject) {
androidLogForm(Format.formatToString(0, new Object[] { "Adding ~A to env ~A with value ~A", paramSymbol, this.global$Mnvar$Mnenvironment, paramObject }));
this.global$Mnvar$Mnenvironment.put(paramSymbol, paramObject);
}
public void addToGlobalVars(Object paramObject1, Object paramObject2) {
this.global$Mnvars$Mnto$Mncreate = (LList)lists.cons(LList.list2(paramObject1, paramObject2), this.global$Mnvars$Mnto$Mncreate);
}
public void androidLogForm(Object paramObject) {}
public boolean dispatchEvent(Component paramComponent, String paramString1, String paramString2, Object[] paramArrayOfObject) {
SimpleSymbol simpleSymbol = misc.string$To$Symbol(paramString1);
if (isBoundInFormEnvironment((Symbol)simpleSymbol)) {
if (lookupInFormEnvironment((Symbol)simpleSymbol) == paramComponent) {
object = lookupHandler(paramString1, paramString2);
try {
Scheme.apply.apply2(object, LList.makeList(paramArrayOfObject, 0));
return true;
} catch (PermissionException object) {
boolean bool;
object.printStackTrace();
if (this == paramComponent) {
bool = true;
} else {
bool = false;
}
if (bool ? IsEqual.apply(paramString2, "PermissionNeeded") : bool) {
processException(object);
return false;
}
PermissionDenied(paramComponent, paramString2, object.getPermissionNeeded());
return false;
} catch (Throwable throwable) {
androidLogForm(throwable.getMessage());
throwable.printStackTrace();
processException(throwable);
return false;
}
}
return false;
}
EventDispatcher.unregisterEventForDelegation((HandlesEventDispatching)this, (String)object, paramString2);
return false;
}
public void dispatchGenericEvent(Component paramComponent, String paramString, boolean paramBoolean, Object[] paramArrayOfObject) {
boolean bool = true;
Object object = lookupInFormEnvironment((Symbol)misc.string$To$Symbol((CharSequence)strings.stringAppend(new Object[] { "any$", getSimpleName(paramComponent), "$", paramString })));
if (object != Boolean.FALSE)
try {
Boolean bool1;
Apply apply = Scheme.apply;
if (paramBoolean) {
bool1 = Boolean.TRUE;
} else {
bool1 = Boolean.FALSE;
}
apply.apply2(object, lists.cons(paramComponent, lists.cons(bool1, LList.makeList(paramArrayOfObject, 0))));
return;
} catch (PermissionException permissionException) {
permissionException.printStackTrace();
if (this != paramComponent)
bool = false;
if (bool ? IsEqual.apply(paramString, "PermissionNeeded") : bool) {
processException(permissionException);
return;
}
PermissionDenied(paramComponent, paramString, permissionException.getPermissionNeeded());
return;
} catch (Throwable throwable) {
androidLogForm(throwable.getMessage());
throwable.printStackTrace();
processException(throwable);
}
}
public String getSimpleName(Object paramObject) {
return paramObject.getClass().getSimpleName();
}
public boolean isBoundInFormEnvironment(Symbol paramSymbol) {
return this.form$Mnenvironment.isBound(paramSymbol);
}
public Object lookupHandler(Object paramObject1, Object paramObject2) {
Object object = null;
if (paramObject1 == null) {
paramObject1 = null;
} else {
paramObject1 = paramObject1.toString();
}
if (paramObject2 == null) {
paramObject2 = object;
return lookupInFormEnvironment((Symbol)misc.string$To$Symbol(EventDispatcher.makeFullEventName((String)paramObject1, (String)paramObject2)));
}
paramObject2 = paramObject2.toString();
return lookupInFormEnvironment((Symbol)misc.string$To$Symbol(EventDispatcher.makeFullEventName((String)paramObject1, (String)paramObject2)));
}
public Object lookupInFormEnvironment(Symbol paramSymbol) {
return lookupInFormEnvironment(paramSymbol, Boolean.FALSE);
}
public Object lookupInFormEnvironment(Symbol paramSymbol, Object paramObject) {
if (this.form$Mnenvironment == null) {
i = 1;
} else {
i = 0;
}
int i = i + 1 & 0x1;
if ((i != 0) ? this.form$Mnenvironment.isBound(paramSymbol) : (i != 0))
paramObject = this.form$Mnenvironment.get(paramSymbol);
return paramObject;
}
public void onCreate(Bundle paramBundle) {
AppInventorCompatActivity.setClassicModeFromYail(true);
super.onCreate(paramBundle);
}
public void processException(Object paramObject) {
Object object = Scheme.applyToArgs.apply1(GetNamedPart.getNamedPart.apply2(paramObject, Lit1));
if (object == null) {
object = null;
} else {
object = object.toString();
}
if (paramObject instanceof YailRuntimeError) {
paramObject = ((YailRuntimeError)paramObject).getErrorType();
} else {
paramObject = "Runtime Error";
}
RuntimeErrorAlert.alert(this, (String)object, (String)paramObject, "End Application");
}
public void run() {
CallContext callContext = CallContext.getInstance();
Consumer consumer = callContext.consumer;
callContext.consumer = (Consumer)VoidConsumer.instance;
try {
run(callContext);
throwable = null;
} catch (Throwable throwable) {}
ModuleBody.runCleanup(callContext, throwable, consumer);
}
public final void run(CallContext paramCallContext) {
String str;
Consumer consumer = paramCallContext.consumer;
runtime.$instance.run();
this.$Stdebug$Mnform$St = Boolean.FALSE;
this.form$Mnenvironment = (Environment)Environment.make(misc.symbol$To$String((Symbol)Lit0));
FString fString = strings.stringAppend(new Object[] { misc.symbol$To$String((Symbol)Lit0), "-global-vars" });
if (fString == null) {
fString = null;
} else {
str = fString.toString();
}
this.global$Mnvar$Mnenvironment = (Environment)Environment.make(str);
Missions = null;
this.form$Mnname$Mnsymbol = (Symbol)Lit0;
this.events$Mnto$Mnregister = LList.Empty;
this.components$Mnto$Mncreate = LList.Empty;
this.global$Mnvars$Mnto$Mncreate = LList.Empty;
this.form$Mndo$Mnafter$Mncreation = LList.Empty;
runtime.$instance.run();
if (runtime.$Stthis$Mnis$Mnthe$Mnrepl$St != Boolean.FALSE) {
runtime.setAndCoerceProperty$Ex(Lit0, Lit3, Lit4, Lit5);
runtime.setAndCoerceProperty$Ex(Lit0, Lit6, "GROW_game_app", Lit7);
runtime.setAndCoerceProperty$Ex(Lit0, Lit8, Lit9, Lit5);
runtime.setAndCoerceProperty$Ex(Lit0, Lit10, Boolean.TRUE, Lit11);
runtime.setAndCoerceProperty$Ex(Lit0, Lit12, "Responsive", Lit7);
runtime.setAndCoerceProperty$Ex(Lit0, Lit13, "Missions", Lit7);
Values.writeValues(runtime.setAndCoerceProperty$Ex(Lit0, Lit14, Boolean.FALSE, Lit11), consumer);
} else {
addToFormDoAfterCreation(new Promise((Procedure)lambda$Fn2));
}
this.HorizontalArrangement1 = null;
if (runtime.$Stthis$Mnis$Mnthe$Mnrepl$St != Boolean.FALSE) {
Values.writeValues(runtime.addComponentWithinRepl(Lit0, Lit15, Lit16, lambda$Fn3), consumer);
} else {
addToComponents(Lit0, Lit21, Lit16, lambda$Fn4);
}
this.Label1 = null;
if (runtime.$Stthis$Mnis$Mnthe$Mnrepl$St != Boolean.FALSE) {
Values.writeValues(runtime.addComponentWithinRepl(Lit0, Lit22, Lit23, lambda$Fn5), consumer);
} else {
addToComponents(Lit0, Lit32, Lit23, lambda$Fn6);
}
this.HorizontalArrangement2 = null;
if (runtime.$Stthis$Mnis$Mnthe$Mnrepl$St != Boolean.FALSE) {
Values.writeValues(runtime.addComponentWithinRepl(Lit0, Lit33, Lit34, lambda$Fn7), consumer);
} else {
addToComponents(Lit0, Lit36, Lit34, lambda$Fn8);
}
this.Image1 = null;
if (runtime.$Stthis$Mnis$Mnthe$Mnrepl$St != Boolean.FALSE) {
Values.writeValues(runtime.addComponentWithinRepl(Lit0, Lit37, Lit38, lambda$Fn9), consumer);
} else {
addToComponents(Lit0, Lit42, Lit38, lambda$Fn10);
}
runtime.initRuntime();
}
public void sendError(Object paramObject) {
if (paramObject == null) {
paramObject = null;
} else {
paramObject = paramObject.toString();
}
RetValManager.sendError((String)paramObject);
}
}
/* Location: /home/geo/hackathon/GROW/apk/dex2jar-2.0/classes-dex2jar.jar!/appinventor/ai_notifications_eoteam/GROW_game_app/Missions.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | [
"notifications.eoteam@gmail.com"
] | notifications.eoteam@gmail.com |
d45795e78021f022f5017f82c8a289d61c8c8938 | a6bab661de1fd9c33d1f91eb73576a6cca1fd255 | /app/src/main/java/com/aufthesis/findnearstation/CompassView.java | f528747def4b1b9cbebdb3395c99b214ee758480 | [] | no_license | yoichi75jp/FindNearStation | bf6b8398bb23361d40d8929733da46ed2366c82f | d0843a6332e9b90fca706b12d0649944d58e4f00 | refs/heads/master | 2020-03-16T08:48:54.906780 | 2019-05-15T16:24:05 | 2019-05-15T16:24:05 | 132,602,693 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,315 | java | package com.aufthesis.findnearstation;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.util.AttributeSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import java.math.BigDecimal;
import java.text.NumberFormat;
/**
// Created by yoichi75jp2 on 2015/06/20.
*/
//サーフェイスビューの拡張
public class CompassView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private final static int ONE_FRAME_TICK = 1000 / 25; // 1フレームの時間
private final static int MAX_FRAME_SKIPS = 5; // 時間が余ったとき最大何回フレームをスキップするか
private SurfaceHolder mSurfaceHolder; // サーフェイスホルダー
private Thread mMainLoop; // メインのゲームループの様なモノ
private Context m_context;
private Vibrator m_vibrator;
// 画像を表示するためのモノ
private final Resources mRes = this.getContext().getResources();
private Bitmap mBitmap;
private float m_ArrowDir; // 矢印の方向
private float m_StationDir; // 駅の方向
private float m_swsize;
private float m_shsize;
private float m_bitmapWidth;
private float m_bitmapHeight;
private String m_station = "";
private String m_distance = "";
private final String[] m_Direction = getResources().getStringArray(R.array.direction);
// ////////////////////////////////////////////////////////////
// コンストラクタ
public CompassView(Context context) {
super(context);
m_context = context;
// Bitmapをロードする
this.loadBitmap();
// SurfaceViewの初期化
this.initSurfaceView(context);
}
// ////////////////////////////////////////////////////////////
// コンストラクタ
public CompassView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
m_context = context;
// Bitmapをロードする
this.loadBitmap();
// SurfaceViewの初期化
this.initSurfaceView(context);
}
// ////////////////////////////////////////////////////////////
// コンストラクタ
public CompassView(Context context, AttributeSet attrs) {
super(context, attrs);
m_context = context;
// Bitmapをロードする
this.loadBitmap();
// SurfaceViewの初期化
this.initSurfaceView(context);
}
// ////////////////////////////////////////////////////////////
// Bitmapをロードする
private void loadBitmap() {
// 画像のロード
mBitmap = BitmapFactory.decodeResource(this.mRes, R.drawable.compass);
m_bitmapWidth = mBitmap.getWidth();
m_bitmapHeight = mBitmap.getHeight();
}
// ////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////
// SurfaceViewの初期化
private void initSurfaceView(Context context) {
// サーフェイスホルダーを取り出す
this.mSurfaceHolder = this.getHolder();
// コールバック関数を登録する
this.mSurfaceHolder.addCallback(this);
mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
setDispSize();
m_vibrator = (Vibrator)m_context.getSystemService(Context.VIBRATOR_SERVICE);
setZOrderOnTop(true);
}
private void setDispSize()
{
// スマートフォンの液晶のサイズを取得を開始
// ウィンドウマネージャのインスタンス取得
WindowManager wm = (WindowManager)m_context.getSystemService(Context.WINDOW_SERVICE);
// ディスプレイのインスタンス生成
Display disp = wm.getDefaultDisplay();
// スマートフォンの画面のサイズ
/*
m_swsize = disp.getWidth();
m_shsize = disp.getHeight();
/**/
Point point = new Point();
disp.getSize(point);
m_swsize = point.x;
m_shsize = point.y;
/**/
}
public void onDraw() {
Canvas canvas = this.mSurfaceHolder.lockCanvas();
this.draw(canvas);
this.mSurfaceHolder.unlockCanvasAndPost(canvas);
}
// ////////////////////////////////////////////////////////////
// 描画処理
public void draw(final Canvas canvas) {
super.draw(canvas);
// Arrowを表示
Paint paint = new Paint();
canvas.save();
float fRatio = (m_swsize/m_bitmapWidth)/1.3f;
canvas.rotate(m_ArrowDir, m_swsize/2.f, m_shsize/2.f);
canvas.translate((m_swsize/2.f) - (m_bitmapWidth*fRatio/2.f), (m_shsize/2.f)-(m_bitmapHeight*fRatio/2.f));
canvas.scale(fRatio, fRatio);
canvas.drawBitmap(mBitmap, 0, 0, paint);
canvas.restore();
/*
// 文字を表示
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setTextSize(70);
canvas.save();
canvas.rotate(this.m_ArrowDir, m_swsize/2.f, m_shsize/2.f);
canvas.translate(m_swsize/2.f, m_shsize/2.f - m_bitmapHeight*fRatio/1.75f);
canvas.drawText("駅", 0, 0, paint);
canvas.restore();
/**/
}
//private int[] mScreenCenter = { 0, 0 };
// ////////////////////////////////////////////////////////////
// サーフェイスサイズの変更があったときとかに呼ばれる
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// センター位置
//this.mScreenCenter[0] = width/2;
//this.mScreenCenter[1] = height/2;
setDispSize();
}
// ////////////////////////////////////////////////////////////
// サーフェイスが作られたときに呼ばれる
public void surfaceCreated(SurfaceHolder holder) {
// ワーカースレッドを作る
this.mMainLoop = new Thread(this);
this.mMainLoop.start();
}
// ////////////////////////////////////////////////////////////
// サーフェイスが破棄された時に呼ばれる
public void surfaceDestroyed(SurfaceHolder holder) {
this.mMainLoop = null;
}
// ////////////////////////////////////////////////////////////
// 毎フレーム呼ばれるやつ
public void move() {
}
//////////////////////////////////////////////////////////////
//毎フレーム呼ばれるやつ
//ちょっと上等なメインループ
public void run() {
Canvas canvas;
long beginTime; // 処理開始時間
long pastTick; // 経過時間
int sleep;
int frameSkipped; // 何フレーム分スキップしたか
// フレームレート関連
//int frameCount = 0;
long beforeTick = 0;
long currTime;
//String tmp = "";
// 文字書いたり
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setTextSize(50);
//int count = 0;
// スレッドが消滅していない間はずっと処理し続ける
while (this.mMainLoop != null) {
canvas = null;
// フレームレートの表示
//frameCount++;
currTime = System.currentTimeMillis();
if (beforeTick + 1000 < currTime) {
beforeTick = currTime;
//tmp = "" + frameCount;
//frameCount = 0;
}
try {
synchronized (this.mSurfaceHolder) {
canvas = this.mSurfaceHolder.lockCanvas();
// キャンバスとれなかった
if (canvas == null)
continue;
//canvas.drawColor(Color.parseColor("#CACACA"));
//canvas.drawColor(Color.parseColor("#FFFFEE"));
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
// 現在時刻
beginTime = System.currentTimeMillis();
frameSkipped = 0;
// ////////////////////////////////////////////////////////////
// ↓アップデートやら描画やら
this.move();
canvas.save();
this.draw(canvas);
canvas.restore();
// ////////////////////////////////////////////////////////////
// 経過時間
pastTick = System.currentTimeMillis() - beginTime;
// 余っちゃった時間
sleep = (int)(ONE_FRAME_TICK - pastTick);
// 余った時間があるときは待たせる
if (0 < sleep) {
try {
Thread.sleep(sleep);
} catch (Exception e) {}
}
// 描画に時間係過ぎちゃった場合は更新だけ回す
while (sleep < 0 && frameSkipped < MAX_FRAME_SKIPS) {
// ////////////////////////////////////////////////////////////
// 遅れた分だけ更新をかける
this.move();
// ////////////////////////////////////////////////////////////
sleep += ONE_FRAME_TICK;
frameSkipped++;
}
canvas.drawText(mRes.getString(R.string.toStation, m_station), 1, 100, paint);
canvas.drawText(mRes.getString(R.string.direction, getDirectionString(m_StationDir)), 1, 200, paint);
canvas.drawText(mRes.getString(R.string.distance, m_distance), 1, 300, paint);
}
} finally {
// キャンバスの解放し忘れに注意
if (canvas != null) {
this.mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
//位置情報を設定
public void setLocationInfo(float iDegree1,float iDegree2, float iDistance, String iStation)
{
m_ArrowDir = iDegree1 + iDegree2;
m_StationDir = iDegree2;
m_station = iStation;
BigDecimal bd = new BigDecimal(iDistance);
float fDistance = bd.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); //小数点第2位で四捨五入
NumberFormat nf = NumberFormat.getNumberInstance(); //3桁区切りでカンマ表示するように
m_distance = String.valueOf(nf.format(fDistance));
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX();
float y = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
if((x <= m_swsize/2.f+100f && x >= m_swsize/2.f-100f) && (y <= m_shsize/2.f+100f && y >= m_shsize/2.f-100f))
{
m_vibrator.vibrate(100);
}
break;
}
long lTime = event.getEventTime() - event.getDownTime();
if(lTime >= 1000) {
/*
m_vibrator.vibrate(100);
Toast.makeText(m_context, String.valueOf(lTime), Toast.LENGTH_LONG).show();
Intent intent = new Intent(m_context, CatalogActivity.class);
m_context.startActivity(intent);
**/
}
return true;
}
private String getDirectionString(float ArrowDir)
{
float ratio = 360f/32f;
String sDir = "";
if((ArrowDir >= 360-(ratio) && ArrowDir <= 360 || ArrowDir >= 0 && ArrowDir <= ratio) ||
ArrowDir >= -ratio && ArrowDir <= 0 || ArrowDir <= -(360-ratio) && ArrowDir >= -(360))
{
sDir = m_Direction[0];
}
else {
for (int i = 1; i < 16; i++)
if (ArrowDir >= ratio * (i*2-1) && ArrowDir <= ratio * (i*2+1) ||
ArrowDir >= -(ratio)*(32-(i*2-1)) && ArrowDir <= -(ratio)*(32-(i*2+1)))
{
sDir = m_Direction[i];
break;
}
}
return sDir;
}
}
| [
"yoichi75jp@gmail.com"
] | yoichi75jp@gmail.com |
9ea9fc3d0da4aef1e6626486cef245ea630f0d42 | fc0e653a122b3af2418cc9fa718790d001b474ab | /app/src/main/java/com/example/harshanuwan/signinproject/LoginActivity.java | 7a5ee7116dd203e1c72ea70244e885f1cf0218eb | [] | no_license | RashilaKanchanamali/mobiChat | b7fc62e5c5c6b952534945eb7c6b1afd22b5e188 | f55f53a19f8917b35c49654a1b8ddb0ce23ada2a | refs/heads/master | 2020-04-02T08:56:05.394295 | 2018-10-23T05:38:07 | 2018-10-23T05:38:07 | 154,268,277 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,327 | java | package com.example.harshanuwan.signinproject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar toolbar2;
private FirebaseAuth mAuth;
private EditText etUsername;
private EditText etPassword;
private Button bLogin;
private EditText vtRegisterLink;
private ProgressDialog loadingBar;
private Toolbar mtoolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.tvRegisterLink).setOnClickListener(this);
mtoolbar = (Toolbar) findViewById(R.id.login_toolbar);
setSupportActionBar(mtoolbar);
getSupportActionBar().setTitle("Log In");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView RegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
final Button bLogin = (Button) findViewById(R.id.bLogin);
loadingBar = new ProgressDialog(this);
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
LoginUserAccount(Username,Password);
}
});
RegisterLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, SiginUpActivity.class);
startActivity(registerIntent);
}
});
}
private void LoginUserAccount(String email, String password) {
if (TextUtils.isEmpty(email))
{
Toast.makeText(LoginActivity.this,"Please enter your email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(LoginActivity.this,"Please enter your password", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Login Account");
loadingBar.setMessage("Creating account");
loadingBar.show();
mAuth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
Intent mainpage = new Intent(LoginActivity.this,MainPageActivity.class);
mainpage.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainpage);
finish();
}
else {
Toast.makeText(LoginActivity.this,
"Again write your correct email and password",Toast.LENGTH_SHORT).show();
}
loadingBar.dismiss();
}
});
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bLogin:
// startActivity(new Intent(this, SiginUpActivity.class));
break;
}
}
}
| [
"grkrathnasiri@gmail.com"
] | grkrathnasiri@gmail.com |
466a31e77b3109b4b263f4f40c96cc44a9826c5b | 4ef9d3446f645305e52a19071def98c170d36305 | /src/test/java/com/vladavekin/logic/controller/syntax/TextSyntaxItalicCharTest.java | 1f2462027fe25507f9e5b355dcbef5d1bcb87a4c | [] | no_license | VlAvekin/avenblog | 6e7e0e83d407bf4087ee0fa020b961c076949a7c | 5a1453833f26276d6bd615e6a8d2f27029a5541e | refs/heads/master | 2020-04-06T15:57:45.255807 | 2019-01-28T17:08:07 | 2019-01-28T17:08:07 | 157,599,570 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,483 | java | package com.vladavekin.logic.controller.syntax;
import com.vladavekin.logic.model.TransforAvenTextAtHTML;
import org.junit.Test;
import static org.junit.Assert.*;
public class TextSyntaxItalicCharTest {
private TransforAvenTextAtHTML tatah;
@Test
public void directItalicText1() {
// * курсив текста *
final String inputValue = "~ курсив текста";
final String expectedValue = "<i>курсив текста</i>";
tatah = new TextItalicSyntax();
final String actualValue = tatah.direct(inputValue);
System.out.println(actualValue);
assertEquals(expectedValue, actualValue);
}
@Test
public void directItalicText2() {
// * курсив текста *
final String inputValue = "~курсив текста";
final String expectedValue = "";
tatah = new TextItalicSyntax();
final String actualValue = tatah.direct(inputValue);
System.out.println(actualValue);
assertEquals(expectedValue, actualValue);
}
@Test
public void directItalicText3() {
// * курсив текста *
final String inputValue = "~~ курсив текста";
final String expectedValue = "";
tatah = new TextItalicSyntax();
final String actualValue = tatah.direct(inputValue);
System.out.println(actualValue);
assertEquals(expectedValue, actualValue);
}
} | [
"vladaavekin@gmail.com"
] | vladaavekin@gmail.com |
7a4f4a9c5950c1cb6e7a2118cc2f382304599fb8 | 199a711251a455b4314dcf159b8119b3174b6e97 | /WebServer/Server/src/main/java/com/gjs/taskTimekeeper/webServer/server/validation/sanitize/ObjectWithStringsAnitizer.java | 2a6b68718203c65a6e9bf765b0097cfd30114ad2 | [
"Apache-2.0"
] | permissive | GregJohnStewart/task-timekeeper | c48ad96534d17a5bce7fd513f6d34aad1b2d8be6 | 3ab34400f8744060e3e8f2225ba95b2c89a7c8e3 | refs/heads/master | 2021-07-08T22:24:34.056525 | 2020-07-28T03:56:28 | 2020-07-28T03:56:28 | 178,615,532 | 1 | 1 | Apache-2.0 | 2020-07-28T03:56:29 | 2019-03-30T21:57:40 | Java | UTF-8 | Java | false | false | 1,276 | java | package com.gjs.taskTimekeeper.webServer.server.validation.sanitize;
import lombok.extern.slf4j.Slf4j;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.lang.reflect.Field;
@ApplicationScoped
@Slf4j
public class ObjectWithStringsAnitizer extends Anitizer<Object> {
@Inject
HTMLAnitizer htmlAnitizer;
@Override
public Object anitize(Object object, AnitizeOp operation) {
if(object == null) {
return object;
}
if(object instanceof String) {
object = this.htmlAnitizer.anitize((String)object, operation);
} else {
Field[] fields = object.getClass().getDeclaredFields();
for(Field field : fields) {
Class t = field.getType();
if(t == String.class) {
field.setAccessible(true);
String orig = null;
try {
orig = (String)field.get(object);
} catch(IllegalAccessException e) {
log.error("Failed to get field {} in action request config.", field, e);
continue;
}
try {
field.set(object, this.htmlAnitizer.anitize(orig, operation));
} catch(IllegalAccessException | IllegalArgumentException e) {
log.error("Failed to set field {} in action request config.", field, e);
continue;
}
}
}
}
return object;
}
}
| [
"contact@gjstewart.net"
] | contact@gjstewart.net |
adb4ddd558013f20e9563e4f23d0a41b503260f8 | 39abf2d80b07f4018ca4b01542371c5c351deda3 | /https:/github.com/fanchoop/LP-Int-gration.git/contact-ac/src/main/java/ContactDuplicateException.java | b644a8dc0cf7414b77fd2a92409bef3b9196f76e | [] | no_license | fanchoop/LP-Int-gration | a5497e4f26c590827ce66c0a66e72066eafb5965 | bda5579ced4c106dfa4e7f10c2b3cc6a50c60705 | refs/heads/master | 2020-03-28T22:42:10.296556 | 2018-09-18T13:31:39 | 2018-09-18T13:31:39 | 149,251,888 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 178 | java | public class ContactDuplicateException extends Exception {
public ContactDuplicateException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
} | [
"francois.danet1@gmail.com"
] | francois.danet1@gmail.com |
7638faf5366c91fed63100c5acf078304fe3ab9c | 96e3786c5e03023618e6de9ba075cd00fc339193 | /src/deliver/ReadyOrderSvlt.java | 2a036cf4b94dae78da9255c9a4f71ff03a0cdbe8 | [] | no_license | Piyumi-Hettiarachchi/Food-Delivery-System | 096069a1df89f75513f129ce11dff98e01e01abc | cb9ffa34b70353009052351e4f980060cf08d821 | refs/heads/master | 2023-08-28T06:28:21.232585 | 2021-11-02T12:02:58 | 2021-11-02T12:02:58 | 423,827,170 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 847 | java | package deliver;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ReadyOrderSvlt")
public class ReadyOrderSvlt extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<ReadyOrder> ReadyOrderDetails = EmployeeBDUtil.getDetails();
request.setAttribute("ReadyOrderDetails",ReadyOrderDetails);
RequestDispatcher dis = request.getRequestDispatcher("/pages/ReadyOrder.jsp");
dis.forward(request, response);
}
}
| [
"it20020880@my.sliit.lk"
] | it20020880@my.sliit.lk |
5e91d56c2dfc1cdb6b42ed2c5b2a8db71119aaad | 78f666507a42aeb11ad84c5b83de48cf2bd58df8 | /app/src/main/java/com/example/myapplication/Details.java | 9a29c06a4e9a7c624cdd99cbdea3097d6dac7cef | [] | no_license | Dinesh0000/ConnectISM | c456f1f39885f2cddcb12ba93f6b10ba7a3265d5 | 7980b14179ea406bc79b14abd52c6388ed41f379 | refs/heads/main | 2023-09-04T17:57:33.921586 | 2021-10-26T12:30:40 | 2021-10-26T12:30:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 444 | java | package com.example.myapplication;
public class Details {
private String subject;
private String details;
public Details() {
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
| [
"progyanature723@gmail.com"
] | progyanature723@gmail.com |
18b9c014744d6e005b6ab83b4be2b1395d608f41 | e8f6aef75dab01981270e3c0ff3e59dcee6b0de8 | /com/wang/spring/Student.java | 07cbf9877e19ee5f965878fe2232d8ecb4f8c418 | [] | no_license | asshin/test | d582f9e9aa8d4cb36993c502414e30fd9979582d | 9d609c112c365c88cb497a33d4bb8e847c22cc10 | refs/heads/master | 2023-08-28T17:03:46.634882 | 2021-10-31T09:26:42 | 2021-10-31T09:26:42 | 423,096,544 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 658 | java | package com.wang.spring;
public class Student {
private String name;
private Major major;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Major getMajor() {
return major;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", major=" + major.getMajorName() +
'}';
}
public void setMajor(Major major) {
this.major = major;
}
public static void main(String[] args) {
System.out.println("1111111111");
}
}
| [
"857541619@qq.com"
] | 857541619@qq.com |
f76ddd4d80c6f5e175cb1cf3ca6fd20e6bd5eb22 | db75faf26ed9cb7ba39d458182ba9a6d953cda86 | /SeboSystemWeb/src/com/sebosystem/control/UtilControlBean.java | 1068dfe30fbe14741bf374e500fd7d04b7fbed01 | [] | no_license | lucassabreu/sebosystem | b57ce0bcd5a583aa46f98fd5f54adf931c2c2c60 | 637e1870986c2770a1297b76f5cc45a558c82d33 | refs/heads/master | 2021-01-01T06:55:19.820296 | 2014-11-30T12:31:33 | 2014-11-30T12:31:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,509 | java | package com.sebosystem.control;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.NoneScoped;
import com.sebosystem.control.base.AbstractControlBean;
import com.sebosystem.dao.helper.EnumTypeKey;
@ManagedBean(name = "util")
@NoneScoped
public class UtilControlBean extends AbstractControlBean {
private static final long serialVersionUID = -8414460510053008193L;
/**
* Convert all lines into paragrafhs
*
* @param text
* @return
*/
public String formatText(String text) {
return "<p>".concat(text.replace("\n", "</p><p>")).concat("</p>");
}
/**
* Cut the string by the params
*
* @param text
* @param maxChars
* @return
*/
public String maxLength(String text, int maxChars) {
if (text.length() > maxChars) {
text = text.substring(0, maxChars - 3).concat("...");
}
return text;
}
/**
* Retrives the localized string based on params
*
* @param base
* @param key
* @return
*/
public String returnMessage(String base, EnumTypeKey key) {
if (key == null)
return null;
return this.getLocalizedString(base.concat("_").concat(key.getKey()));
}
/**
* Return the position {@code index} of the array {@code values}
*
* @param index
* @param values
* @return
*/
public String choose(int index, String values) {
return values.split(",")[index];
}
}
| [
"lucas.s.abreu@gmail.com"
] | lucas.s.abreu@gmail.com |
0bde51588fd2a5d2cf685d3d2e89b69b1ecc7a3e | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/Alluxio--alluxio/4cf319e679d290899bfb6c9e5e7148eb0a884bf0/after/CpCommand.java | d8752a095847b032fe12721e9b82c76d71469c45 | [] | 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 | 23,093 | java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.shell.command;
import alluxio.AlluxioURI;
import alluxio.Constants;
import alluxio.client.ReadType;
import alluxio.client.file.FileInStream;
import alluxio.client.file.FileOutStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.client.file.options.CreateFileOptions;
import alluxio.client.file.options.OpenFileOptions;
import alluxio.exception.AlluxioException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.exception.InvalidPathException;
import alluxio.shell.AlluxioShellUtils;
import alluxio.util.io.PathUtils;
import com.google.common.base.Joiner;
import com.google.common.io.Closer;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.concurrent.ThreadSafe;
/**
* Copies a file or a directory in the Alluxio filesystem.
*/
@ThreadSafe
public final class CpCommand extends AbstractShellCommand {
/**
* @param fs the filesystem of Alluxio
*/
public CpCommand(FileSystem fs) {
super(fs);
}
@Override
public String getCommandName() {
return "cp";
}
@Override
protected int getNumOfArgs() {
return 2;
}
@Override
protected Options getOptions() {
return new Options().addOption(RECURSIVE_OPTION);
}
@Override
public void run(CommandLine cl) throws AlluxioException, IOException {
String[] args = cl.getArgs();
AlluxioURI srcPath = new AlluxioURI(args[0]);
AlluxioURI dstPath = new AlluxioURI(args[1]);
if ((dstPath.getScheme() == null || isAlluxio(dstPath.getScheme()))
&& isFile(srcPath.getScheme())) {
List<File> srcFiles = AlluxioShellUtils.getFiles(srcPath.getPath());
if (srcFiles.size() == 0) {
throw new IOException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(srcPath));
}
if (srcPath.containsWildcard()) {
List<AlluxioURI> srcPaths = new ArrayList<>();
for (File srcFile : srcFiles) {
srcPaths.add(
new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()));
}
copyFromLocalWildcard(srcPaths, dstPath);
} else {
copyFromLocal(srcPath, dstPath);
}
} else if ((srcPath.getScheme() == null || isAlluxio(srcPath.getScheme()))
&& isFile(dstPath.getScheme())) {
List<AlluxioURI> srcPaths = AlluxioShellUtils.getAlluxioURIs(mFileSystem, srcPath);
if (srcPaths.size() == 0) {
throw new IOException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(srcPath));
}
if (srcPath.containsWildcard()) {
copyWildcardToLocal(srcPaths, dstPath);
} else {
copyToLocal(srcPath, dstPath);
}
} else if ((srcPath.getScheme() == null || isAlluxio(srcPath.getScheme()))
&& (dstPath.getScheme() == null || isAlluxio(dstPath.getScheme()))) {
List<AlluxioURI> srcPaths = AlluxioShellUtils.getAlluxioURIs(mFileSystem, srcPath);
if (srcPaths.size() == 0) {
throw new FileDoesNotExistException(
ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(srcPath.getPath()));
}
if (srcPath.containsWildcard()) {
copyWildcard(srcPaths, dstPath, cl.hasOption("R"));
} else {
copy(srcPath, dstPath, cl.hasOption("R"));
}
} else {
throw new InvalidPathException(
"Schemes must be either file or alluxio, and at most one file scheme is allowed.");
}
}
/**
* Copies a list of files or directories specified by srcPaths to the destination specified by
* dstPath. This method is used when the original source path contains wildcards.
*
* @param srcPaths a list of files or directories in the Alluxio filesystem
* @param dstPath the destination in the Alluxio filesystem
* @param recursive indicates whether directories should be copied recursively
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyWildcard(List<AlluxioURI> srcPaths, AlluxioURI dstPath, boolean recursive)
throws AlluxioException, IOException {
URIStatus dstStatus = null;
try {
dstStatus = mFileSystem.getStatus(dstPath);
} catch (FileDoesNotExistException e) {
// if the destination does not exist, it will be created
}
if (dstStatus != null && !dstStatus.isFolder()) {
throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage());
}
if (dstStatus == null) {
mFileSystem.createDirectory(dstPath);
System.out.println("Created directory: " + dstPath);
}
List<String> errorMessages = new ArrayList<>();
for (AlluxioURI srcPath : srcPaths) {
try {
copy(srcPath, new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(),
PathUtils.concatPath(dstPath.getPath(), srcPath.getName())), recursive);
} catch (AlluxioException | IOException e) {
errorMessages.add(e.getMessage());
}
}
if (errorMessages.size() != 0) {
throw new IOException(Joiner.on('\n').join(errorMessages));
}
}
/**
* Copies a file or a directory in the Alluxio filesystem.
*
* @param srcPath the source {@link AlluxioURI} (could be a file or a directory)
* @param dstPath the {@link AlluxioURI} of the destination path in the Alluxio filesystem
* @param recursive indicates whether directories should be copied recursively
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copy(AlluxioURI srcPath, AlluxioURI dstPath, boolean recursive)
throws AlluxioException, IOException {
URIStatus srcStatus = mFileSystem.getStatus(srcPath);
URIStatus dstStatus = null;
try {
dstStatus = mFileSystem.getStatus(dstPath);
} catch (FileDoesNotExistException e) {
// if the destination does not exist, it will be created
}
if (!srcStatus.isFolder()) {
if (dstStatus != null && dstStatus.isFolder()) {
dstPath = new AlluxioURI(PathUtils.concatPath(dstPath.getPath(), srcPath.getName()));
}
copyFile(srcPath, dstPath);
} else {
if (!recursive) {
throw new IOException(
srcPath.getPath() + " is a directory, to copy it please use \"cp -R <src> <dst>\"");
}
List<URIStatus> statuses;
statuses = mFileSystem.listStatus(srcPath);
if (dstStatus != null) {
if (!dstStatus.isFolder()) {
throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage());
}
// if copying a directory to an existing directory, the copied directory will become a
// subdirectory of the destination
if (srcStatus.isFolder()) {
dstPath = new AlluxioURI(PathUtils.concatPath(dstPath.getPath(), srcPath.getName()));
mFileSystem.createDirectory(dstPath);
System.out.println("Created directory: " + dstPath);
}
}
if (dstStatus == null) {
mFileSystem.createDirectory(dstPath);
System.out.println("Created directory: " + dstPath);
}
List<String> errorMessages = new ArrayList<>();
for (URIStatus status : statuses) {
try {
copy(new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), status.getPath()),
new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(),
PathUtils.concatPath(dstPath.getPath(), status.getName())), recursive);
} catch (IOException e) {
errorMessages.add(e.getMessage());
}
}
if (errorMessages.size() != 0) {
throw new IOException(Joiner.on('\n').join(errorMessages));
}
}
}
/**
* Copies a file in the Alluxio filesystem.
*
* @param srcPath the source {@link AlluxioURI} (has to be a file)
* @param dstPath the destination path in the Alluxio filesystem
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyFile(AlluxioURI srcPath, AlluxioURI dstPath)
throws AlluxioException, IOException {
try (Closer closer = Closer.create()) {
OpenFileOptions openFileOptions = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
FileInStream is = closer.register(mFileSystem.openFile(srcPath, openFileOptions));
CreateFileOptions createFileOptions = CreateFileOptions.defaults();
FileOutStream os = closer.register(mFileSystem.createFile(dstPath, createFileOptions));
IOUtils.copy(is, os);
System.out.println("Copied " + srcPath + " to " + dstPath);
}
}
/**
* Copies a directory from local to Alluxio filesystem. The destination directory structure
* maintained as local directory. This method is used when input path is a directory.
*
* @param srcPath the {@link AlluxioURI} of the source directory in the local filesystem
* @param dstPath the {@link AlluxioURI} of the destination
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyFromLocalDir(AlluxioURI srcPath, AlluxioURI dstPath)
throws AlluxioException, IOException {
File srcDir = new File(srcPath.getPath());
boolean dstExistedBefore = mFileSystem.exists(dstPath);
createDstDir(dstPath);
List<String> errorMessages = new ArrayList<>();
File[] fileList = srcDir.listFiles();
if (fileList == null) {
String errMsg = String.format("Failed to list files for directory %s", srcDir);
errorMessages.add(errMsg);
fileList = new File[0];
}
int misFiles = 0;
for (File srcFile : fileList) {
AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcFile.getName()));
try {
copyPath(
new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()),
newURI);
} catch (AlluxioException | IOException e) {
errorMessages.add(e.getMessage());
if (!mFileSystem.exists(newURI)) {
misFiles++;
}
}
}
if (errorMessages.size() != 0) {
if (misFiles == fileList.length) {
// If the directory doesn't exist and no files were created, then delete the directory
if (!dstExistedBefore && mFileSystem.exists(dstPath)) {
mFileSystem.delete(dstPath);
}
}
throw new IOException(Joiner.on('\n').join(errorMessages));
}
}
/**
* Copies a list of files or directories specified by srcPaths from the local filesystem to
* dstPath in the Alluxio filesystem space. This method is used when the input path contains
* wildcards.
*
* @param srcPaths a list of files or directories in the local filesystem
* @param dstPath the {@link AlluxioURI} of the destination
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyFromLocalWildcard(List<AlluxioURI> srcPaths, AlluxioURI dstPath)
throws AlluxioException, IOException {
boolean dstExistedBefore = mFileSystem.exists(dstPath);
createDstDir(dstPath);
List<String> errorMessages = new ArrayList<>();
int misFiles = 0;
for (AlluxioURI srcPath : srcPaths) {
AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcPath.getName()));
try {
copyPath(srcPath, newURI);
System.out.println("Copied " + srcPath + " to " + dstPath);
} catch (AlluxioException | IOException e) {
errorMessages.add(e.getMessage());
if (!mFileSystem.exists(newURI)) {
misFiles++;
}
}
}
if (errorMessages.size() != 0) {
if (misFiles == srcPaths.size()) {
// If the directory doesn't exist and no files were created, then delete the directory
if (!dstExistedBefore && mFileSystem.exists(dstPath)) {
mFileSystem.delete(dstPath);
}
}
throw new IOException(Joiner.on('\n').join(errorMessages));
}
}
/**
* Creates a directory in the Alluxio filesystem space. It will not throw any exception if the
* destination directory already exists.
*
* @param dstPath the {@link AlluxioURI} of the destination directory which will be created
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void createDstDir(AlluxioURI dstPath) throws AlluxioException, IOException {
try {
mFileSystem.createDirectory(dstPath);
} catch (FileAlreadyExistsException e) {
// it's fine if the directory already exists
}
URIStatus dstStatus = mFileSystem.getStatus(dstPath);
if (!dstStatus.isFolder()) {
throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage());
}
}
/**
* Copies a file or directory specified by srcPath from the local filesystem to dstPath in the
* Alluxio filesystem space.
*
* @param srcPath the {@link AlluxioURI} of the source in the local filesystem
* @param dstPath the {@link AlluxioURI} of the destination
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyFromLocal(AlluxioURI srcPath, AlluxioURI dstPath)
throws AlluxioException, IOException {
File srcFile = new File(srcPath.getPath());
if (srcFile.isDirectory()) {
copyFromLocalDir(srcPath, dstPath);
} else {
copyPath(srcPath, dstPath);
}
System.out.println("Copied " + srcPath + " to " + dstPath);
}
/**
* Copies a file or directory specified by srcPath from the local filesystem to dstPath in the
* Alluxio filesystem space.
*
* @param srcPath the {@link AlluxioURI} of the source file in the local filesystem
* @param dstPath the {@link AlluxioURI} of the destination
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyPath(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException,
IOException {
File src = new File(srcPath.getPath());
if (!src.isDirectory()) {
// If the dstPath is a directory, then it should be updated to be the path of the file where
// src will be copied to.
if (mFileSystem.exists(dstPath) && mFileSystem.getStatus(dstPath).isFolder()) {
dstPath = dstPath.join(src.getName());
}
FileOutStream os = null;
try (Closer closer = Closer.create()) {
os = closer.register(mFileSystem.createFile(dstPath));
FileInputStream in = closer.register(new FileInputStream(src));
FileChannel channel = closer.register(in.getChannel());
ByteBuffer buf = ByteBuffer.allocate(8 * Constants.MB);
while (channel.read(buf) != -1) {
buf.flip();
os.write(buf.array(), 0, buf.limit());
}
} catch (Exception e) {
// Close the out stream and delete the file, so we don't have an incomplete file lying
// around.
if (os != null) {
os.cancel();
if (mFileSystem.exists(dstPath)) {
mFileSystem.delete(dstPath);
}
}
throw e;
}
} else {
mFileSystem.createDirectory(dstPath);
List<String> errorMessages = new ArrayList<>();
File[] fileList = src.listFiles();
if (fileList == null) {
String errMsg = String.format("Failed to list files for directory %s", src);
errorMessages.add(errMsg);
fileList = new File[0];
}
int misFiles = 0;
for (File srcFile : fileList) {
AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcFile.getName()));
try {
copyPath(
new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()),
newURI);
} catch (IOException e) {
errorMessages.add(e.getMessage());
if (!mFileSystem.exists(newURI)) {
misFiles++;
}
}
}
if (errorMessages.size() != 0) {
if (misFiles == fileList.length) {
// If the directory doesn't exist and no files were created, then delete the directory
if (mFileSystem.exists(dstPath)) {
mFileSystem.delete(dstPath);
}
}
throw new IOException(Joiner.on('\n').join(errorMessages));
}
}
}
/**
* Copies a list of files or directories specified by srcPaths from the Alluxio filesystem to
* dstPath in the local filesystem. This method is used when the input path contains wildcards.
*
* @param srcPaths the list of files in the Alluxio filesystem
* @param dstPath the {@link AlluxioURI} of the destination directory in the local filesystem
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyWildcardToLocal(List<AlluxioURI> srcPaths, AlluxioURI dstPath)
throws AlluxioException, IOException {
File dstFile = new File(dstPath.getPath());
if (dstFile.exists() && !dstFile.isDirectory()) {
throw new InvalidPathException(ExceptionMessage.DESTINATION_CANNOT_BE_FILE.getMessage());
}
if (!dstFile.exists()) {
if (!dstFile.mkdirs()) {
throw new IOException("Fail to create directory: " + dstPath);
} else {
System.out.println("Create directory: " + dstPath);
}
}
List<String> errorMessages = new ArrayList<>();
for (AlluxioURI srcPath : srcPaths) {
try {
File dstSubFile = new File(dstFile.getAbsoluteFile(), srcPath.getName());
copyToLocal(srcPath,
new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), dstSubFile.getPath()));
} catch (IOException e) {
errorMessages.add(e.getMessage());
}
}
if (errorMessages.size() != 0) {
throw new IOException(Joiner.on('\n').join(errorMessages));
}
}
/**
* Copies a file or a directory from the Alluxio filesystem to the local filesystem.
*
* @param srcPath the source {@link AlluxioURI} (could be a file or a directory)
* @param dstPath the {@link AlluxioURI} of the destination in the local filesystem
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException,
IOException {
URIStatus srcStatus = mFileSystem.getStatus(srcPath);
File dstFile = new File(dstPath.getPath());
if (srcStatus.isFolder()) {
// make a local directory
if (!dstFile.exists()) {
if (!dstFile.mkdirs()) {
throw new IOException("mkdir failure for directory: " + dstPath);
} else {
System.out.println("Create directory: " + dstPath);
}
}
List<URIStatus> statuses;
try {
statuses = mFileSystem.listStatus(srcPath);
} catch (AlluxioException e) {
throw new IOException(e.getMessage());
}
List<String> errorMessages = new ArrayList<>();
for (URIStatus status : statuses) {
try {
File subDstFile = new File(dstFile.getAbsolutePath(), status.getName());
copyToLocal(
new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), status.getPath()),
new AlluxioURI(dstPath.getScheme(), dstPath.getAuthority(), subDstFile.getPath()));
} catch (IOException e) {
errorMessages.add(e.getMessage());
}
}
if (errorMessages.size() != 0) {
throw new IOException(Joiner.on('\n').join(errorMessages));
}
} else {
copyFileToLocal(srcPath, dstPath);
}
}
/**
* Copies a file specified by argv from the filesystem to the local filesystem. This is the
* utility function.
*
* @param srcPath The source {@link AlluxioURI} (has to be a file)
* @param dstPath The {@link AlluxioURI} of the destination in the local filesystem
* @throws AlluxioException when Alluxio exception occurs
* @throws IOException when non-Alluxio exception occurs
*/
private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath)
throws AlluxioException, IOException {
File dstFile = new File(dstPath.getPath());
String randomSuffix =
String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8));
File outputFile;
if (dstFile.isDirectory()) {
outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName()));
} else {
outputFile = dstFile;
}
File tmpDst = new File(outputFile.getPath() + randomSuffix);
try (Closer closer = Closer.create()) {
OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
FileInStream is = closer.register(mFileSystem.openFile(srcPath, options));
FileOutputStream out = closer.register(new FileOutputStream(tmpDst));
byte[] buf = new byte[64 * Constants.MB];
int t = is.read(buf);
while (t != -1) {
out.write(buf, 0, t);
t = is.read(buf);
}
if (!tmpDst.renameTo(outputFile)) {
throw new IOException(
"Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath());
}
System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath());
} finally {
tmpDst.delete();
}
}
@Override
public String getUsage() {
return "cp [-R] <src> <dst>";
}
@Override
public String getDescription() {
return "Copies a file or a directory in the Alluxio filesystem or between local filesystem "
+ "and Alluxio filesystem. The -R flag is needed to copy directories in the Alluxio "
+ "filesystem. Local Path with schema \"file\".";
}
private static boolean isAlluxio(String scheme) {
return Constants.SCHEME.equals(scheme);
}
private static boolean isFile(String scheme) {
return "file".equals(scheme);
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
282afa17dcac8f9ed578d8f565bff81a50198512 | fb8729dd9dece6726612c55c21913c3987f1359a | /src/practice_exercises_cop2210/practice_exercise1_17.java | 2e911673deb30f18d882e4a03893312f0fe761e5 | [] | no_license | curbi007/Practice_Exercises_COP2210 | d7f3fc01b5b83d6390531dc2f16a7ebe6837268d | 7422be373210d002fd131f7d9dcab20161ac4608 | refs/heads/master | 2021-01-10T13:19:55.854391 | 2016-01-19T19:41:30 | 2016-01-19T19:41:30 | 49,785,407 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 698 | java | /*
* You are now an entrant to the show. Get ready, it's about to begin!
* And welcome to the show!!
*/
package practice_exercises_cop2210;
import javax.swing.JOptionPane;
import java.net.URL;
import javax.swing.ImageIcon;
/**
*
* @author Carlos
*
*/
public class practice_exercise1_17 {
public static void main(String[] args) throws Exception
{
//this program
URL imageLocation = new URL ("http://i3.kym-cdn.com/photos/images/newsfeed/001/037/049/75d.png");
JOptionPane.showMessageDialog(null, "Hello", "Urgent Message!!!",
JOptionPane.PLAIN_MESSAGE, new ImageIcon(imageLocation));
//la fin.
}
}
| [
"Carlos@10.109.28.219"
] | Carlos@10.109.28.219 |
c4d66d8eaab1fbb41f4ae5090f6f73250a992eb5 | 1dc2c68ecabe64797d3beb8a36c465b50ab37eb0 | /src/main/java/com/example/tbike/Simulate.java | 5e31aedfed5bf6a2173548d9b3f470341361c218 | [] | no_license | choijunghwan/TBike | e0641c5933b9085f2e6c5506c6bee7d4faf3cb0c | f9dca2b2b6978addfe3aac907db4e64af0e4ae1c | refs/heads/master | 2023-08-13T19:10:04.123869 | 2021-09-24T12:59:38 | 2021-09-24T12:59:38 | 409,515,400 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 841 | java | package com.example.tbike;
public class Simulate {
private String status;
private Integer time;
private Integer failed_requests_count;
private String distance;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getTime() {
return time;
}
public void setTime(Integer time) {
this.time = time;
}
public Integer getFailed_requests_count() {
return failed_requests_count;
}
public void setFailed_requests_count(Integer failed_requests_count) {
this.failed_requests_count = failed_requests_count;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
| [
"vkdlxj3562@naver.com"
] | vkdlxj3562@naver.com |
6e995c9d6b3f8f9803cc1057b05b9b807c4fd4ee | d45a0fd55db09321dc6b4a597eca03c0aaa3b8f3 | /app/src/main/java/com/example/user/finalandroid/MoneyAdepter.java | 5093f4bbc67f46bbac78226ba4bdfef00a179b92 | [] | no_license | naypota/FinalAndroid | 8608ba90d5755c26476f0764f6d5ed5b1975722b | cd1958a58c3d00da7ad7b2af2a91eaf2569c5d45 | refs/heads/master | 2021-08-24T15:06:31.539717 | 2017-12-10T05:30:47 | 2017-12-10T05:30:47 | 113,725,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,973 | java | package com.example.user.finalandroid;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MoneyAdepter extends ArrayAdapter<Money>{
private Context mContext;
private int mLayoutResId;
private ArrayList<Money> mMoneyList;
public MoneyAdepter(Context mContext, int mLayoutResId, ArrayList<Money> mMoneyList) {
super(mContext,mLayoutResId,mMoneyList);
this.mContext = mContext;
this.mLayoutResId = mLayoutResId;
this.mMoneyList = mMoneyList;
}
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemLayout = inflater.inflate(mLayoutResId, null);
Money item = mMoneyList.get(position);
ImageView image = (ImageView)itemLayout.findViewById(R.id.Type_imageView);
TextView TypeName = (TextView) itemLayout.findViewById(R.id.Type_EditText);
TextView Money = (TextView) itemLayout.findViewById(R.id.Money_EditText);
image.setImageDrawable(Drawable.createFromPath(item.picture));
TypeName.setText(item.type);
Money.setText(String.valueOf(item.money));
if(position == 0){
TypeName.setTextColor(Color.parseColor("#FFC125"));
Money.setTextColor(Color.parseColor("#FFC125"));
TypeName.setTypeface(Typeface.DEFAULT_BOLD);
Money.setTypeface(Typeface.DEFAULT_BOLD);
TypeName.setTextSize(20);
Money.setTextSize(20);
}
return itemLayout;
}
}
| [
"p_ota_007@hotmail.com"
] | p_ota_007@hotmail.com |
63f686011bb1093d31285888923e07a2e91dc1ce | 9579c009c6ebbd446db23572b6feb71569ec3faf | /src/main/java/com/team09/dao/impl/CommentDaoImpl.java | 289008e36e1e2c2504312351f5b2b247659356d7 | [] | no_license | 997Yi/team09_simpleBBS | 7308ec0005a264184f455cbec9ef45c1c64f9162 | 8b31717d6dae57654766443c525cabf85a088daa | refs/heads/master | 2023-02-14T21:10:52.002210 | 2021-01-18T00:39:41 | 2021-01-18T00:39:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,837 | java | package com.team09.dao.impl;
import com.team09.bean.Comment;
import com.team09.dao.BaseDao;
import com.team09.dao.CommentDao;
import com.team09.util.JdbcUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author team09
*/
public class CommentDaoImpl extends BaseDao implements CommentDao {
private static CommentDao commentDao = new CommentDaoImpl();
private CommentDaoImpl(){}
public static CommentDao getInstance(){
return commentDao;
}
@Override
public boolean addComment(Comment comment) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
try{
connection = dataSource.getConnection();
statement = connection.prepareStatement("insert into comment_tb value(uuid(), ?, ?, ?, ?, ?)");
statement.setString(1, comment.getContent());
statement.setString(2, comment.getStatus());
statement.setDate(3,new Date(comment.getTime().getTime()));
statement.setString(4, comment.getUserId());
statement.setString(5, comment.getBlogId());
return statement.executeUpdate() != 0;
}finally {
JdbcUtil.close(connection, statement);
}
}
@Override
public Comment getCommentById(String commentId) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
connection = dataSource.getConnection();
statement = connection.prepareStatement("select * from comment_tb where comment_id = ?");
statement.setString(1, commentId);
resultSet = statement.executeQuery();
Comment comment = null;
if(resultSet.next()){
comment = new Comment(resultSet.getString("comment_id"), resultSet.getString("comment_content"),
resultSet.getString("comment_status"), resultSet.getDate("comment_time"),
resultSet.getString("user_id"), resultSet.getString("blog_id"));
}
return comment;
}finally {
JdbcUtil.close(connection, statement, resultSet);
}
}
@Override
public List<Comment> getCommentsByUserId(String userId) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
connection = dataSource.getConnection();
statement = connection.prepareStatement("select * from comment_tb where user_id = ?");
statement.setString(1, userId);
resultSet = statement.executeQuery();
List<Comment> comments = new ArrayList<Comment>();
while(resultSet.next()){
comments.add(new Comment(resultSet.getString("comment_id"), resultSet.getString("comment_content"),
resultSet.getString("comment_status"), resultSet.getDate("comment_time"),
resultSet.getString("user_id"), resultSet.getString("blog_id")));
}
return comments;
}finally {
JdbcUtil.close(connection, statement, resultSet);
}
}
@Override
public List<Comment> getCommentsByBlogId(String blogId) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
connection = dataSource.getConnection();
statement = connection.prepareStatement("select * from comment_tb where blog_id = ?");
statement.setString(1, blogId);
resultSet = statement.executeQuery();
List<Comment> comments = new ArrayList<Comment>();
while(resultSet.next()){
comments.add(new Comment(resultSet.getString("comment_id"), resultSet.getString("comment_content"),
resultSet.getString("comment_status"), resultSet.getDate("comment_time"),
resultSet.getString("user_id"), resultSet.getString("blog_id")));
}
return comments;
}finally {
JdbcUtil.close(connection, statement, resultSet);
}
}
@Override
public boolean deleteComment(String commentId) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
try{
connection = dataSource.getConnection();
statement = connection.prepareStatement("delete from comment_tb where comment_id = ?");
statement.setString(1, commentId);
return statement.executeUpdate() != 0;
}finally {
JdbcUtil.close(connection, statement);
}
}
}
| [
"2012357983@qq.com"
] | 2012357983@qq.com |
ded4ef20bb9d31b19c0962e3b06570ca1fe71053 | d33d999cbc168010529e6355593e90a18d54e44c | /app/src/main/java/com/sojoline/charging/views/activities/PileListActivity.java | f73f2a0cc41a59c4ee0a7875768deaaacca31589 | [] | no_license | zhangliang520/trunk | f4ec430dd951d5bd0d3830dbd0ecd705548994b1 | 43751afa1132bbe864c3b74533ef4c89ffbff711 | refs/heads/master | 2023-03-18T09:24:22.023657 | 2018-12-20T05:40:39 | 2018-12-20T05:40:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,110 | java | package com.sojoline.charging.views.activities;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sojoline.charging.LvAppUtils;
import com.sojoline.charging.LvApplication;
import com.sojoline.charging.R;
import com.sojoline.charging.custom.toast.IToast;
import com.sojoline.charging.custom.toast.ToastUtils;
import com.sojoline.charging.utils.MyItemDecoration;
import com.sojoline.charging.views.base.LvBaseAppCompatActivity;
import com.sojoline.model.bean.StationDetailBean;
import com.sojoline.model.response.OrderResponse;
import com.sojoline.presenter.appointment.QueryOrderContract;
import com.sojoline.presenter.appointment.QueryOrderPresenter;
import com.sojoline.presenter.main.StationDetailContract;
import com.sojoline.presenter.main.StationDetailPresenter;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import java.lang.ref.WeakReference;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.leanvision.baseframe.log.DebugLog;
import cn.com.leanvision.baseframe.util.LvTextUtil;
/**
* <pre>
* author : 李小勇
* time : 2017/09/14
* desc :
* version: 1.0
* </pre>
*/
@Route(path = "/main/pile_list")
public class PileListActivity extends LvBaseAppCompatActivity implements StationDetailContract.View, QueryOrderContract.View {
@BindView(R.id.m_recycler_view)
RecyclerView mRecyclerView;
private String stationId;
private String cpId;
private int gunId;
private String state;
private String stationName;
private StationDetailPresenter presenter;
private QueryOrderPresenter queryOrderPresenter;
private UMShareListener mShareListener;
private ShareAction mShareAction;
private PopupWindow popWindow;
private StationDetailBean detailBean;
public static void navigation(String stationId, String stationName, double lat, double lng) {
ARouter.getInstance().build("/main/pile_list")
.withString("stationId", stationId)
.withString("stationName", stationName)
.withDouble("lat", lat)
.withDouble("lng", lng)
.navigation();
}
@Override
protected void setContentView(Bundle savedInstanceState) {
setContentView(R.layout.aty_station_detail);
}
@Override
protected void initPresenter() {
presenter = new StationDetailPresenter();
presenter.attachView(this);
queryOrderPresenter = new QueryOrderPresenter();
queryOrderPresenter.attachView(this);
}
@Override
protected void destroyPresenter() {
presenter.detachView();
queryOrderPresenter.detachView();
}
@Override
protected void initView() {
initToolbarNav("充电站详情");
initPopWindow();
stationId = getIntent().getStringExtra("stationId");
stationName = getIntent().getStringExtra("stationName");
presenter.getSubstationSummary(stationId);
initShare();
}
@Override
protected void onRestart() {
super.onRestart();
presenter.getSubstationSummary(stationId);
}
/**
* 初始化底部弹窗
*/
private void initPopWindow() {
View popView = LayoutInflater.from(this).inflate(R.layout.view_pop_select, null);
TextView tvOrder = (TextView) popView.findViewById(R.id.tv_one);
tvOrder.setText("我要预约");
TextView tvScan = (TextView) popView.findViewById(R.id.tv_two);
tvScan.setText("查看充电");
// TextView tvThree = (TextView) popView.findViewById(R.id.tv_three);
// tvThree.setVisibility(View.GONE);
TextView tvCancel = (TextView) popView.findViewById(R.id.tv_cancel);
tvCancel.setOnClickListener(popListener);
tvOrder.setOnClickListener(popListener);
tvScan.setOnClickListener(popListener);
popWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
popWindow.setFocusable(true);
popWindow.setTouchable(true);
popWindow.setOutsideTouchable(false);
popWindow.setAnimationStyle(R.style.AnimBottom);
popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
setBackgroundAlpha(1);
}
});
}
/**
* 弹窗点击监听
*/
View.OnClickListener popListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_one: //跳转预约界面
if (LvAppUtils.isLogin()) {
queryOrderPresenter.queryOrder();
} else {
LoginActivity.navigation(false);
}
break;
case R.id.tv_two://跳转查看充电界面
//判断是否充电
if ("工作".equals(state)){
TempChargingActivity.navigation(stationId, stationName, cpId, gunId);
}else {
showToast("充电枪没有充电");
}
break;
case R.id.tv_cancel:
break;
}
popWindow.dismiss();
}
};
/**
* 显示弹窗
*/
private void showPopWindow() {
if (!popWindow.isShowing()) {
popWindow.showAtLocation(popWindow.getContentView(), Gravity.BOTTOM, 0, 0);
setBackgroundAlpha(0.7f);
}
}
/**
* 初始化分享
*/
private void initShare() {
mShareListener = new PileListActivity.CustomShareListener(this);
mShareAction = new ShareAction(this).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
.setShareboardclickCallback(new ShareBoardlistener() {
@Override
public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
switch (snsPlatform.mShowWord) {
case "umeng_sharebutton_copy":
showToast("复制文本按钮");
break;
case "umeng_sharebutton_copyurl":
showToast("复制文本按钮");
break;
default:
// FIXME: 2017/7/26 需要修改分享的网址
// String url = "https://mobile.umeng.com/";
String url = "https://www.pgyer.com/Buca";
UMWeb web = new UMWeb(url);
web.setTitle("欢迎使用杰电APP");
web.setDescription("绿色,节能,低碳,畅享健康生活,北京双杰电动汽车充电桩欢迎您!");
web.setThumb(new UMImage(PileListActivity.this, R.mipmap.ic_launcher));
new ShareAction(PileListActivity.this).withMedia(web)
.setPlatform(share_media)
.setCallback(mShareListener)
.share();
break;
}
}
});
}
@OnClick(R.id.iv_share)
public void clickShare() {
mShareAction.open();
}
@OnClick(R.id.iv_error)
public void clickErrorCorrection() {
showErrorCorrectionDialog();
}
public static String[] items
= {"地理位置错误", "位置描述错误", "停车费信息错误", "终端无法充电", "其他"};
private void showErrorCorrectionDialog() {
new AlertDialog.Builder(this)
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DebugLog.log("which: %d", which);
if (which == 0) {
double lat = getIntent().getDoubleExtra("lat", 0.0f);
double lng = getIntent().getDoubleExtra("lng", 0.0f);
ErrorCorrectionLocationActivity.navigation(lat, lng, stationId);
} else {
ErrorCorrectionActivity.navigation(which, stationId);
}
}
})
.show();
}
@Override
public void showLoading(String msg) {
showLoadingDialog(msg);
}
@Override
public void showNormal() {
dismissLoadingDialog();
}
@Override
public void requestFailed(String msg) {
if (LvTextUtil.isEmpty(msg)) {
showToast(R.string.network_not_available);
} else {
showToast(msg);
}
}
@Override
public void getSummarySuccess(StationDetailBean stationDetailBean) {
detailBean = stationDetailBean;
initRecyclerView(stationDetailBean);
}
private void initRecyclerView(final StationDetailBean stationDetailBean) {
if (mRecyclerView.getAdapter() == null) {
RecyclerView.LayoutManager lm = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(lm);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addItemDecoration(new MyItemDecoration(this, MyItemDecoration.HORIZONTAL));
OnGunClickListener listener = new OnGunClickListener() {
@Override
public void onClick(String cpId, int gunId, String state) {
if ("离线".equals(state)){
showToast("充电桩离线了");
}else {
PileListActivity.this.cpId = cpId;
PileListActivity.this.gunId = gunId;
PileListActivity.this.state = state;
showPopWindow();
}
}
};
PileListActivity.Adapter adapter = new PileListActivity.Adapter(this,stationDetailBean.chargingPileList, listener);
mRecyclerView.setAdapter(adapter);
} else {
PileListActivity.Adapter adapter = (PileListActivity.Adapter) mRecyclerView.getAdapter();
adapter.setDataList(stationDetailBean.chargingPileList);
adapter.notifyDataSetChanged();
}
}
@Override
public void querySuccess(OrderResponse.Order order) {
showToast("您当前有一个预约");
}
@Override
public void noOrder(String msg) {
if (detailBean != null && detailBean.chargingPileList != null) {
OrderSettingActivity.navigation(stationId, cpId, gunId,
null, false, 0, null);
}
}
static class Adapter extends RecyclerView.Adapter<PileListActivity.Adapter.ViewHolder> {
private OnGunClickListener listener;
private Context context;
private int count;
private List<StationDetailBean.ChargingPileListEntity> dataList;
Adapter(Context context,List<StationDetailBean.ChargingPileListEntity> dataList,
OnGunClickListener listener) {
this.context = context;
this.dataList = dataList;
this.listener = listener;
}
public void setDataList(List<StationDetailBean.ChargingPileListEntity> chargingPileList) {
dataList = chargingPileList;
}
private Drawable getStateDrawable(StationDetailBean.ChargingPileListEntity cpe, int gunId){
String state = cpe.getGunState(gunId);
Drawable icon;
if (state.contains("工作")){
icon = context.getResources().getDrawable(R.drawable.state_working);
}else if (state.contains("告警")){
icon = context.getResources().getDrawable(R.drawable.state_warning);
}else if (state.contains("完成") || state.contains("待机")){
icon = context.getResources().getDrawable(R.drawable.state_idle);
}else { //离线
icon = context.getResources().getDrawable(R.drawable.state_offline);
}
icon.setBounds(0, 0, icon.getMinimumWidth(), icon.getMinimumHeight());
return icon;
}
@Override
public PileListActivity.Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pile, parent, false);
return new PileListActivity.Adapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(PileListActivity.Adapter.ViewHolder holder, int position) {
final StationDetailBean.ChargingPileListEntity cpe = dataList.get(position);
holder.shortCode.setText(cpe.getShortCode());
holder.longCode.setText(cpe.cpId);
holder.pileType.setText(cpe.getCpType());
//额定功率
if (!LvTextUtil.isEmpty(cpe.ratedPower)){
holder.pilePower.setText(cpe.ratedPower);
}else {
holder.pilePower.setText(cpe.getPower());
}
holder.pileState.setText(cpe.getState());
holder.itemView.setTag(cpe);
// 以下是显示枪的逻辑
int totalGuns = Integer.parseInt(cpe.cpinterfaceId);
// int totalGuns = 6;
if (totalGuns < 3 ) {
holder.tvGun1.setText(" 枪1 ");
holder.tvGun1.setCompoundDrawables(getStateDrawable(cpe, 1), null, null, null);
holder.llMin.setVisibility(View.VISIBLE);
holder.gridLayout.setVisibility(View.GONE);
holder.tvGun2.setVisibility(View.GONE);
holder.tvGun1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onClick(cpe.cpId, 0, cpe.getGunState(1));
}
}
});
if (totalGuns == 2){
holder.tvGun2.setVisibility(View.VISIBLE);
holder.tvGun2.setText(" 枪2 ");
holder.tvGun2.setCompoundDrawables(getStateDrawable(cpe, 2), null, null, null);
holder.tvGun2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onClick(cpe.cpId, 1, cpe.getGunState(2));
}
}
});
}
}else {
holder.gridLayout.removeAllViews();
holder.llMin.setVisibility(View.GONE);
holder.gridLayout.setVisibility(View.VISIBLE);
int row = totalGuns / 4 == 0 ? totalGuns / 4 : totalGuns / 4 + 1;
holder.gridLayout.setRowCount(row);
View v ;
TextView tvGun;
count = 0;
for (int i = 0; i < totalGuns; i++) {
count = i + 1;
v = LayoutInflater.from(context).inflate(R.layout.item_gun, null, false);
tvGun = (TextView) v.findViewById(R.id.tv_gun);
tvGun.setText(String.format(" 枪%d ", count));
tvGun.setCompoundDrawables(getStateDrawable(cpe, count), null, null, null);
holder.gridLayout.addView(v);
}
for (int i = 0; i < totalGuns; i++) {
count = i + 1;
v = holder.gridLayout.getChildAt(i);
v.setTag(count);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
count = (int) v.getTag();
listener.onClick(cpe.cpId, count, cpe.getGunState(count));
System.out.print(v);
DebugLog.log("------------------------" + cpe.cpId);
DebugLog.log("------------------------" + count);
}
}
});
}
}
}
@Override
public int getItemCount() {
return dataList == null ? 0 : dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.short_code)
TextView shortCode;
@BindView(R.id.long_code)
TextView longCode;
@BindView(R.id.pile_type)
TextView pileType;
@BindView(R.id.pile_power)
TextView pilePower;
@BindView(R.id.pile_state)
TextView pileState;
@BindView(R.id.tv_gun1)
TextView tvGun1;
@BindView(R.id.tv_gun2)
TextView tvGun2;
@BindView(R.id.ll_min)
LinearLayout llMin;
@BindView(R.id.pile_grid)
GridLayout gridLayout;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
public interface OnGunClickListener{
void onClick(String cpId, int gunId, String state);
}
//分享监听
private static class CustomShareListener implements UMShareListener {
private WeakReference<Activity> mActivity;
private CustomShareListener(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void onStart(SHARE_MEDIA share_media) {
}
@Override
public void onResult(SHARE_MEDIA platform) {
ToastUtils.getInstance(LvApplication.getContext()).makeTextShow(platform + " 分享成功啦", IToast.LENGTH_SHORT);
// ToastUtils.makeText(mActivity.get(), platform + " 分享成功啦", CustomToast.LENGTH_SHORT).show();
}
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
ToastUtils.getInstance(LvApplication.getContext()).makeTextShow(platform + " 分享失败啦", IToast.LENGTH_SHORT);
// ToastUtils.makeText(mActivity.get(), platform + " 分享失败啦", CustomToast.LENGTH_SHORT).show();
if (t != null) {
DebugLog.log("throw:" + t.getMessage());
}
}
@Override
public void onCancel(SHARE_MEDIA platform) {
ToastUtils.getInstance(LvApplication.getContext()).makeTextShow(platform + " 分享取消了", IToast.LENGTH_SHORT);
// ToastUtils.makeText(mActivity.get(), platform + " 分享取消了", CustomToast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
}
/**
* 设置背景透明度
* @param alpha
*/
private void setBackgroundAlpha(float alpha){
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = alpha;
getWindow().setAttributes(params);
}
}
| [
"kevin_cheng_hu@163.com"
] | kevin_cheng_hu@163.com |
70fc3b66f4789c9e5e5b6a2e510f4fb66f11d113 | 1ca299884b4effae1e0ffa8d6a26e81216a0deb4 | /src/com/lydia/servlet/BadgeCode.java | 7115fc160f068d781d83cbf80aedff0de99700ca | [] | no_license | edagarli/lydiaDeveloperCenter | ecf5c74c9ad5ea3a31028602ca380e5744a8b73f | ed05fea54f9eed233b5716457d74a40c07f4645f | refs/heads/master | 2020-04-11T19:00:54.380938 | 2015-12-23T04:30:32 | 2015-12-23T04:30:32 | 30,065,241 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,270 | java | package com.lydia.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lydia.bean.Badge;
import com.lydia.bean.ShortUrl;
import com.lydia.util.BufferedReaderFile;
import com.lydia.util.Constant;
import com.lydia.util.JsonUtil;
import com.lydia.util.JsonValidator;
import com.lydia.util.PageSpider;
import com.lydia.util.Parameter;
import com.lydia.util.SyncHttp;
import com.lydia.util.Token;
public class BadgeCode extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
public BadgeCode() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
// if (Token.isTokenStringValid(
// request.getParameter(Token.TOKEN_STRING_NAME),
// request.getSession()))
// {
String url=request.getParameter("url");
System.out.println("-------"+url);
if(url==null||url.equals("")||!url.endsWith("manifest.webapp"))
{
out.println("{\"status\":"+Constant.RESULT_PARAM_INVALID+"}");
}
else
{
JsonValidator js=new JsonValidator();
PageSpider ps=new PageSpider(url);
System.out.println("===2==");
if(js.validate(ps.data))
{
System.out.println("===3==");
Map<String,Object> rtn = JsonUtil.parseJSONMap(ps.data);
if(JsonUtil.parseJSONMap(JsonUtil.toJson(rtn.get("icons"))).get("128").toString().startsWith("http"))
{
try {
System.out.println("===4==");
List<Parameter> pList=new ArrayList<Parameter>();
Parameter p=new Parameter();
p.setName("url");
p.setValue(url);
pList.add(p);
System.out.println("===5==");
System.out.println("----sss=====");
String reponse=new SyncHttp().httpPost("http://0.0.0.0:8080/j/shorten",pList);
System.out.println("====reponse=="+reponse);
ShortUrl su=JsonUtil.fromJson(reponse,ShortUrl.class);
Badge badge=new Badge();
badge.setStatus(Constant.RESULT_SUCCESS);
badge.setInstallPage("http://lydiabox.com/apps/"+su.getShorten().substring(20));
String jsonStr = JsonUtil.toJson(badge);
out.println(jsonStr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
out.println("{\"status\":" + Constant.RESULT_INTERNAL_ERROR+"}");
}
}
else
{
out.println("{\"status\":"+Constant.RESULT_PARAM_INVALID+"}");
}
}
else
{
out.println("{\"status\":"+Constant.RESULT_PARAM_INVALID+"}");
}
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
| [
"www19940501@126.com"
] | www19940501@126.com |
ba6af0a31dee558b170a8cc4ba3f25b754400453 | a794349131efd02734a5ae22f35b809ac8be091a | /redisson/src/main/java/org/redisson/RedissonPermitExpirableSemaphore.java | 92434bc1ce94120208d7326b225f6128e231066f | [
"Apache-2.0"
] | permissive | WannerZoer/redisson | a23f9273d4670b939989a69889d484ef72102988 | c602555a122cb7b98f67d689f32936c155d4674c | refs/heads/master | 2021-01-11T20:15:16.284797 | 2017-01-12T14:12:35 | 2017-01-12T14:12:35 | 79,075,419 | 1 | 0 | null | 2017-01-16T02:28:31 | 2017-01-16T02:28:31 | null | UTF-8 | Java | false | false | 29,042 | java | /**
* Copyright 2016 Nikita Koksharov
*
* 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.redisson;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.redisson.api.RFuture;
import org.redisson.api.RPermitExpirableSemaphore;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.command.CommandExecutor;
import org.redisson.misc.RPromise;
import org.redisson.pubsub.SemaphorePubSub;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.internal.ThreadLocalRandom;
/**
*
* @author Nikita Koksharov
*
*/
public class RedissonPermitExpirableSemaphore extends RedissonExpirable implements RPermitExpirableSemaphore {
private final SemaphorePubSub semaphorePubSub;
final CommandExecutor commandExecutor;
private final String timeoutName;
private final long nonExpirableTimeout = 922337203685477L;
protected RedissonPermitExpirableSemaphore(CommandExecutor commandExecutor, String name, SemaphorePubSub semaphorePubSub) {
super(commandExecutor, name);
this.timeoutName = "{" + name + "}:timeout";
this.commandExecutor = commandExecutor;
this.semaphorePubSub = semaphorePubSub;
}
String getChannelName() {
return getChannelName(getName());
}
public static String getChannelName(String name) {
if (name.contains("{")) {
return "redisson_sc:" + name;
}
return "redisson_sc:{" + name + "}";
}
@Override
public String acquire() throws InterruptedException {
return acquire(1, -1, TimeUnit.MILLISECONDS);
}
@Override
public String acquire(long leaseTime, TimeUnit timeUnit) throws InterruptedException {
return acquire(1, leaseTime, timeUnit);
}
@Override
public RFuture<String> acquireAsync(long leaseTime, TimeUnit timeUnit) {
return acquireAsync(1, leaseTime, timeUnit);
}
private String acquire(int permits, long ttl, TimeUnit timeUnit) throws InterruptedException {
String permitId = tryAcquire(permits, ttl, timeUnit);
if (permitId != null && !permitId.startsWith(":")) {
return permitId;
}
RFuture<RedissonLockEntry> future = subscribe();
commandExecutor.syncSubscription(future);
try {
while (true) {
final Long nearestTimeout;
permitId = tryAcquire(permits, ttl, timeUnit);
if (permitId != null) {
if (!permitId.startsWith(":")) {
return permitId;
} else {
nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis();
}
} else {
nearestTimeout = null;
}
if (nearestTimeout != null) {
getEntry().getLatch().tryAcquire(permits, nearestTimeout, TimeUnit.MILLISECONDS);
} else {
getEntry().getLatch().acquire(permits);
}
}
} finally {
unsubscribe(future);
}
// return get(acquireAsync(permits, ttl, timeUnit));
}
public RFuture<String> acquireAsync() {
return acquireAsync(1, -1, TimeUnit.MILLISECONDS);
}
private RFuture<String> acquireAsync(final int permits, final long ttl, final TimeUnit timeUnit) {
final RPromise<String> result = newPromise();
long timeoutDate = calcTimeout(ttl, timeUnit);
RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
tryAcquireFuture.addListener(new FutureListener<String>() {
@Override
public void operationComplete(Future<String> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
String permitId = future.getNow();
if (permitId != null && !permitId.startsWith(":")) {
if (!result.trySuccess(permitId)) {
releaseAsync(permitId);
}
return;
}
final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
@Override
public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
}
});
}
});
return result;
}
private void tryAcquireAsync(final AtomicLong time, final int permits, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<String> result, final long ttl, final TimeUnit timeUnit) {
if (result.isDone()) {
unsubscribe(subscribeFuture);
return;
}
if (time.get() <= 0) {
unsubscribe(subscribeFuture);
result.trySuccess(null);
return;
}
long timeoutDate = calcTimeout(ttl, timeUnit);
final long current = System.currentTimeMillis();
RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
tryAcquireFuture.addListener(new FutureListener<String>() {
@Override
public void operationComplete(Future<String> future) throws Exception {
if (!future.isSuccess()) {
unsubscribe(subscribeFuture);
result.tryFailure(future.cause());
return;
}
final Long nearestTimeout;
String permitId = future.getNow();
if (permitId != null) {
if (!permitId.startsWith(":")) {
unsubscribe(subscribeFuture);
if (!result.trySuccess(permitId)) {
releaseAsync(permitId);
}
return;
} else {
nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis();
}
} else {
nearestTimeout = null;
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
if (time.get() <= 0) {
unsubscribe(subscribeFuture);
result.trySuccess(null);
return;
}
// waiting for message
final long current = System.currentTimeMillis();
final RedissonLockEntry entry = getEntry();
synchronized (entry) {
if (entry.getLatch().tryAcquire()) {
tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
} else {
final AtomicReference<Timeout> waitTimeoutFutureRef = new AtomicReference<Timeout>();
final Timeout scheduledFuture;
if (nearestTimeout != null) {
scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (waitTimeoutFutureRef.get() != null && !waitTimeoutFutureRef.get().cancel()) {
return;
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
}
}, nearestTimeout, TimeUnit.MILLISECONDS);
} else {
scheduledFuture = null;
}
final Runnable listener = new Runnable() {
@Override
public void run() {
if (waitTimeoutFutureRef.get() != null && !waitTimeoutFutureRef.get().cancel()) {
entry.getLatch().release();
return;
}
if (scheduledFuture != null && !scheduledFuture.cancel()) {
entry.getLatch().release();
return;
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
}
};
entry.addListener(listener);
long t = time.get();
Timeout waitTimeoutFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (scheduledFuture != null && !scheduledFuture.cancel()) {
return;
}
synchronized (entry) {
if (entry.removeListener(listener)) {
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
}
}
}
}, t, TimeUnit.MILLISECONDS);
waitTimeoutFutureRef.set(waitTimeoutFuture);
}
}
}
});
}
private void acquireAsync(final int permits, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<String> result, final long ttl, final TimeUnit timeUnit) {
if (result.isDone()) {
unsubscribe(subscribeFuture);
return;
}
long timeoutDate = calcTimeout(ttl, timeUnit);
RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
tryAcquireFuture.addListener(new FutureListener<String>() {
@Override
public void operationComplete(Future<String> future) throws Exception {
if (!future.isSuccess()) {
unsubscribe(subscribeFuture);
result.tryFailure(future.cause());
return;
}
final Long nearestTimeout;
String permitId = future.getNow();
if (permitId != null) {
if (!permitId.startsWith(":")) {
unsubscribe(subscribeFuture);
if (!result.trySuccess(permitId)) {
releaseAsync(permitId);
}
return;
} else {
nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis();
}
} else {
nearestTimeout = null;
}
final RedissonLockEntry entry = getEntry();
synchronized (entry) {
if (entry.getLatch().tryAcquire(permits)) {
acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
} else {
final Timeout scheduledFuture;
if (nearestTimeout != null) {
scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
}
}, nearestTimeout, TimeUnit.MILLISECONDS);
} else {
scheduledFuture = null;
}
Runnable listener = new Runnable() {
@Override
public void run() {
if (scheduledFuture != null && !scheduledFuture.cancel()) {
entry.getLatch().release();
return;
}
acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
}
};
entry.addListener(listener);
}
}
}
});
}
@Override
public String tryAcquire() {
String res = tryAcquire(1, -1, TimeUnit.MILLISECONDS);
if (res != null && res.startsWith(":")) {
return null;
}
return res;
}
private String tryAcquire(int permits, long ttl, TimeUnit timeUnit) {
long timeoutDate = calcTimeout(ttl, timeUnit);
return get(tryAcquireAsync(permits, timeoutDate));
}
private long calcTimeout(long ttl, TimeUnit timeUnit) {
if (ttl != -1) {
return System.currentTimeMillis() + timeUnit.toMillis(ttl);
}
return nonExpirableTimeout;
}
public RFuture<String> tryAcquireAsync() {
final RPromise<String> result = newPromise();
RFuture<String> res = tryAcquireAsync(1, nonExpirableTimeout);
res.addListener(new FutureListener<String>() {
@Override
public void operationComplete(Future<String> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
String permitId = future.getNow();
if (permitId != null && !permitId.startsWith(":")) {
if (!result.trySuccess(permitId)) {
releaseAsync(permitId);
}
} else {
result.trySuccess(null);
}
}
});
return result;
}
protected String generateId() {
byte[] id = new byte[16];
// TODO JDK UPGRADE replace to native ThreadLocalRandom
ThreadLocalRandom.current().nextBytes(id);
return ByteBufUtil.hexDump(id);
}
public RFuture<String> tryAcquireAsync(int permits, long timeoutDate) {
if (permits < 0) {
throw new IllegalArgumentException("Permits amount can't be negative");
}
String id = generateId();
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_STRING_DATA,
"local expiredIds = redis.call('zrangebyscore', KEYS[2], 0, ARGV[4], 'limit', 0, ARGV[1]); " +
"if #expiredIds > 0 then " +
"redis.call('zrem', KEYS[2], unpack(expiredIds)); " +
"local value = redis.call('incrby', KEYS[1], #expiredIds); " +
"if tonumber(value) > 0 then " +
"redis.call('publish', KEYS[3], value); " +
"end;" +
"end; " +
"local value = redis.call('get', KEYS[1]); " +
"if (value ~= false and tonumber(value) >= tonumber(ARGV[1])) then " +
"redis.call('decrby', KEYS[1], ARGV[1]); " +
"redis.call('zadd', KEYS[2], ARGV[2], ARGV[3]); " +
"return ARGV[3]; " +
"end; " +
"local v = redis.call('zrange', KEYS[2], 0, 0, 'WITHSCORES'); " +
"if v[1] ~= nil and v[2] ~= ARGV[5] then " +
"return ':' .. tostring(v[2]); " +
"end " +
"return nil;",
Arrays.<Object>asList(getName(), timeoutName, getChannelName()), permits, timeoutDate, id, System.currentTimeMillis(), nonExpirableTimeout);
}
public RFuture<String> tryAcquireAsync(long waitTime, TimeUnit unit) {
return tryAcquireAsync(1, waitTime, -1, unit);
}
@Override
public String tryAcquire(long waitTime, long ttl, TimeUnit unit) throws InterruptedException {
return tryAcquire(1, waitTime, ttl, unit);
}
@Override
public RFuture<String> tryAcquireAsync(long waitTime, long ttl, TimeUnit unit) {
return tryAcquireAsync(1, waitTime, ttl, unit);
}
private String tryAcquire(int permits, long waitTime, long ttl, TimeUnit unit) throws InterruptedException {
long time = unit.toMillis(waitTime);
long current = System.currentTimeMillis();
String permitId = tryAcquire(permits, ttl, unit);
if (permitId != null && !permitId.startsWith(":")) {
return permitId;
}
time -= (System.currentTimeMillis() - current);
if (time <= 0) {
return null;
}
current = System.currentTimeMillis();
RFuture<RedissonLockEntry> future = subscribe();
if (!await(future, time, TimeUnit.MILLISECONDS)) {
return null;
}
try {
time -= (System.currentTimeMillis() - current);
if (time <= 0) {
return null;
}
while (true) {
current = System.currentTimeMillis();
final Long nearestTimeout;
permitId = tryAcquire(permits, ttl, unit);
if (permitId != null) {
if (!permitId.startsWith(":")) {
return permitId;
} else {
nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis();
}
} else {
nearestTimeout = null;
}
time -= (System.currentTimeMillis() - current);
if (time <= 0) {
return null;
}
// waiting for message
current = System.currentTimeMillis();
if (nearestTimeout != null) {
getEntry().getLatch().tryAcquire(permits, Math.min(time, nearestTimeout), TimeUnit.MILLISECONDS);
} else {
getEntry().getLatch().tryAcquire(permits, time, TimeUnit.MILLISECONDS);
}
long elapsed = System.currentTimeMillis() - current;
time -= elapsed;
if (time <= 0) {
return null;
}
}
} finally {
unsubscribe(future);
}
// return get(tryAcquireAsync(permits, waitTime, ttl, unit));
}
private RFuture<String> tryAcquireAsync(final int permits, long waitTime, final long ttl, final TimeUnit timeUnit) {
final RPromise<String> result = newPromise();
final AtomicLong time = new AtomicLong(timeUnit.toMillis(waitTime));
final long current = System.currentTimeMillis();
long timeoutDate = calcTimeout(ttl, timeUnit);
RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
tryAcquireFuture.addListener(new FutureListener<String>() {
@Override
public void operationComplete(Future<String> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
String permitId = future.getNow();
if (permitId != null && !permitId.startsWith(":")) {
if (!result.trySuccess(permitId)) {
releaseAsync(permitId);
}
return;
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
if (time.get() <= 0) {
result.trySuccess(null);
return;
}
final long current = System.currentTimeMillis();
final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
@Override
public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
if (futureRef.get() != null) {
futureRef.get().cancel();
}
long elapsed = System.currentTimeMillis() - current;
time.addAndGet(-elapsed);
tryAcquireAsync(time, permits, subscribeFuture, result, ttl, timeUnit);
}
});
if (!subscribeFuture.isDone()) {
Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (!subscribeFuture.isDone()) {
result.trySuccess(null);
}
}
}, time.get(), TimeUnit.MILLISECONDS);
futureRef.set(scheduledFuture);
}
}
});
return result;
}
private RedissonLockEntry getEntry() {
return semaphorePubSub.getEntry(getName());
}
private RFuture<RedissonLockEntry> subscribe() {
return semaphorePubSub.subscribe(getName(), getChannelName(), commandExecutor.getConnectionManager());
}
private void unsubscribe(RFuture<RedissonLockEntry> future) {
semaphorePubSub.unsubscribe(future.getNow(), getName(), getChannelName(), commandExecutor.getConnectionManager());
}
@Override
public String tryAcquire(long waitTime, TimeUnit unit) throws InterruptedException {
String res = tryAcquire(1, waitTime, -1, unit);
if (res != null && res.startsWith(":")) {
return null;
}
return res;
}
@Override
public void release(String permitId) {
get(releaseAsync(permitId));
}
@Override
public boolean tryRelease(String permitId) {
return get(tryReleaseAsync(permitId));
}
@Override
public RFuture<Boolean> tryReleaseAsync(String permitId) {
if (permitId == null) {
throw new IllegalArgumentException("permitId can't be null");
}
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"local removed = redis.call('zrem', KEYS[3], ARGV[1]);" +
"if tonumber(removed) ~= 1 then " +
"return 0;" +
"end;" +
"local value = redis.call('incrby', KEYS[1], ARGV[2]); " +
"redis.call('publish', KEYS[2], value); " +
"return 1;",
Arrays.<Object>asList(getName(), getChannelName(), timeoutName), permitId, 1);
}
@Override
public RFuture<Boolean> deleteAsync() {
return commandExecutor.writeAsync(getName(), RedisCommands.DEL_OBJECTS, getName(), timeoutName);
}
@Override
public RFuture<Void> releaseAsync(final String permitId) {
final RPromise<Void> result = newPromise();
tryReleaseAsync(permitId).addListener(new FutureListener<Boolean>() {
@Override
public void operationComplete(Future<Boolean> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
if (future.getNow()) {
result.trySuccess(null);
} else {
result.tryFailure(new IllegalArgumentException("Permit with id " + permitId + " has already been released or doesn't exist"));
}
}
});
return result;
}
@Override
public int availablePermits() {
return get(availablePermitsAsync());
}
@Override
public RFuture<Integer> availablePermitsAsync() {
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_INTEGER,
"local expiredIds = redis.call('zrangebyscore', KEYS[2], 0, ARGV[1], 'limit', 0, -1); " +
"if #expiredIds > 0 then " +
"redis.call('zrem', KEYS[2], unpack(expiredIds)); " +
"local value = redis.call('incrby', KEYS[1], #expiredIds); " +
"if tonumber(value) > 0 then " +
"redis.call('publish', KEYS[3], value); " +
"end;" +
"return value; " +
"end; " +
"return redis.call('get', KEYS[1]); ",
Arrays.<Object>asList(getName(), timeoutName, getChannelName()), System.currentTimeMillis());
}
@Override
public boolean trySetPermits(int permits) {
return get(trySetPermitsAsync(permits));
}
@Override
public RFuture<Boolean> trySetPermitsAsync(int permits) {
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"local value = redis.call('get', KEYS[1]); " +
"if (value == false or value == 0) then "
+ "redis.call('set', KEYS[1], ARGV[1]); "
+ "redis.call('publish', KEYS[2], ARGV[1]); "
+ "return 1;"
+ "end;"
+ "return 0;",
Arrays.<Object>asList(getName(), getChannelName()), permits);
}
@Override
public void addPermits(int permits) {
get(addPermitsAsync(permits));
}
@Override
public RFuture<Void> addPermitsAsync(int permits) {
return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_VOID,
"local value = redis.call('get', KEYS[1]); " +
"if (value == false) then "
+ "value = 0;"
+ "end;"
+ "redis.call('set', KEYS[1], tonumber(value) + tonumber(ARGV[1])); "
+ "if tonumber(ARGV[1]) > 0 then "
+ "redis.call('publish', KEYS[2], ARGV[1]); "
+ "end;",
Arrays.<Object>asList(getName(), getChannelName()), permits);
}
}
| [
"abracham.mitchell@gmail.com"
] | abracham.mitchell@gmail.com |
7b4cbb1801f229c22d67e1a266c7d0952c38ee11 | ecbe2d1ebc529201e32c184c5a73ca7ef7e25d22 | /src/integeruser/jgltut/tut08/Interpolation.java | 28437ae9fecf232e48ca17dce6ccb132158be28f | [
"CC-BY-3.0",
"CC-BY-4.0"
] | permissive | Zellcore/jgltut | 264a5f1bb97e73379f718fd1568170bc1ba58f9e | 229bda51081945fb11cd42b42d0090e120a35993 | refs/heads/master | 2021-01-15T23:27:57.356636 | 2016-07-04T16:34:43 | 2016-07-04T16:34:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,540 | java | package integeruser.jgltut.tut08;
import integeruser.jglsdk.glm.Glm;
import integeruser.jgltut.Tutorial;
import integeruser.jgltut.framework.Framework;
import integeruser.jgltut.framework.Mesh;
import integeruser.jgltut.framework.Timer;
import org.joml.Matrix4f;
import org.joml.MatrixStackf;
import org.joml.Quaternionf;
import org.joml.Vector4f;
import org.lwjgl.glfw.GLFWKeyCallback;
import java.util.ArrayList;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
/**
* Visit https://github.com/integeruser/jgltut for info, updates and license terms.
* <p>
* Part II. Positioning
* Chapter 8. Getting Oriented
* <p>
* SPACE - toggles between regular linear interpolation and slerp.
* Q,W,E,R,T,Y,U - cause the ship to interpolate to a new orientation.
*/
public class Interpolation extends Tutorial {
public static void main(String[] args) {
Framework.CURRENT_TUTORIAL_DATAPATH = "/integeruser/jgltut/tut08/data/";
new Interpolation().start(500, 500);
}
@Override
protected void init() {
initializeProgram();
try {
ship = new Mesh("Ship.xml");
} catch (Exception exception) {
exception.printStackTrace();
System.exit(-1);
}
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0f, 1.0f);
glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS) {
for (int orientIndex = 0; orientIndex < orientKeys.length; orientIndex++) {
if (key == orientKeys[orientIndex]) {
applyOrientation(orientIndex);
break;
}
}
switch (key) {
case GLFW_KEY_SPACE:
boolean slerp = orient.toggleSlerp();
System.out.printf(slerp ? "Slerp\n" : "Lerp\n");
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
}
}
}
});
}
@Override
protected void display() {
orient.updateTime();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
MatrixStackf currMatrix = new MatrixStackf();
currMatrix.translate(0.0f, 0.0f, -200.0f);
currMatrix.mul(orient.getOrient().get(new Matrix4f()));
glUseProgram(theProgram);
currMatrix.scale(3.0f, 3.0f, 3.0f);
currMatrix.rotateX((float) Math.toRadians(-90.0f));
// Set the base color for this object.
glUniform4f(baseColorUnif, 1.0f, 1.0f, 1.0f, 1.0f);
glUniformMatrix4fv(modelToCameraMatrixUnif, false, currMatrix.get(mat4Buffer));
ship.render("tint");
glUseProgram(0);
}
@Override
protected void reshape(int w, int h) {
cameraToClipMatrix.m00(frustumScale * (h / (float) w));
cameraToClipMatrix.m11(frustumScale);
glUseProgram(theProgram);
glUniformMatrix4fv(cameraToClipMatrixUnif, false, cameraToClipMatrix.get(mat4Buffer));
glUseProgram(0);
glViewport(0, 0, w, h);
}
@Override
protected void update() {
}
////////////////////////////////
private int theProgram;
private int modelToCameraMatrixUnif;
private int cameraToClipMatrixUnif;
private int baseColorUnif;
private Matrix4f cameraToClipMatrix = new Matrix4f();
private final float frustumScale = calcFrustumScale(20.0f);
private void initializeProgram() {
ArrayList<Integer> shaderList = new ArrayList<>();
shaderList.add(Framework.loadShader(GL_VERTEX_SHADER, "PosColorLocalTransform.vert"));
shaderList.add(Framework.loadShader(GL_FRAGMENT_SHADER, "ColorMultUniform.frag"));
theProgram = Framework.createProgram(shaderList);
modelToCameraMatrixUnif = glGetUniformLocation(theProgram, "modelToCameraMatrix");
cameraToClipMatrixUnif = glGetUniformLocation(theProgram, "cameraToClipMatrix");
baseColorUnif = glGetUniformLocation(theProgram, "baseColor");
float zNear = 1.0f;
float zFar = 600.0f;
cameraToClipMatrix.m00(frustumScale);
cameraToClipMatrix.m11(frustumScale);
cameraToClipMatrix.m22((zFar + zNear) / (zNear - zFar));
cameraToClipMatrix.m23(-1.0f);
cameraToClipMatrix.m32((2 * zFar * zNear) / (zNear - zFar));
glUseProgram(theProgram);
glUniformMatrix4fv(cameraToClipMatrixUnif, false, cameraToClipMatrix.get(mat4Buffer));
glUseProgram(0);
}
private float calcFrustumScale(float fovDeg) {
float fovRad = (float) Math.toRadians(fovDeg);
return (float) (1.0f / Math.tan(fovRad / 2.0f));
}
////////////////////////////////
private Mesh ship;
private Quaternionf orients[] = {
new Quaternionf(0.7071f, 0.0f, 0.0f, 0.7071f),
new Quaternionf(0.5f, -0.5f, 0.5f, 0.5f),
new Quaternionf(-0.7892f, -0.3700f, -0.02514f, -0.4895f),
new Quaternionf(0.7892f, 0.3700f, 0.02514f, 0.4895f),
new Quaternionf(-0.1591f, -0.7991f, -0.4344f, 0.3840f),
new Quaternionf(0.5208f, 0.6483f, 0.0410f, 0.5537f),
new Quaternionf(0.0f, 1.0f, 0.0f, 0.0f)
};
private int orientKeys[] = {
GLFW_KEY_Q,
GLFW_KEY_W,
GLFW_KEY_E,
GLFW_KEY_R,
GLFW_KEY_T,
GLFW_KEY_Y,
GLFW_KEY_U
};
private Orientation orient = new Orientation();
private class Orientation {
boolean isAnimating;
boolean slerp;
int currOrientIndex;
Animation anim = new Animation();
class Animation {
int finalOrientIndex;
Timer currTimer;
boolean updateTime() {
return currTimer.update(elapsedTime);
}
void startAnimation(int destinationIndex, float duration) {
finalOrientIndex = destinationIndex;
currTimer = new Timer(Timer.Type.SINGLE, duration);
}
Quaternionf getOrient(Quaternionf initial, boolean slerp) {
if (slerp) {
return slerp(initial, orients[finalOrientIndex], currTimer.getAlpha());
} else {
return lerp(initial, orients[finalOrientIndex], currTimer.getAlpha());
}
}
int getFinalIndex() {
return finalOrientIndex;
}
}
void updateTime() {
if (isAnimating) {
boolean isFinished = anim.updateTime();
if (isFinished) {
isAnimating = false;
currOrientIndex = anim.getFinalIndex();
}
}
}
void animateToOrient(int destinationIndex) {
if (currOrientIndex == destinationIndex) return;
anim.startAnimation(destinationIndex, 1.0f);
isAnimating = true;
}
boolean toggleSlerp() {
slerp = !slerp;
return slerp;
}
Quaternionf getOrient() {
if (isAnimating) {
return anim.getOrient(orients[currOrientIndex], slerp);
} else {
return orients[currOrientIndex];
}
}
boolean isAnimating() {
return isAnimating;
}
}
private void applyOrientation(int orientationIndex) {
if (!orient.isAnimating()) {
orient.animateToOrient(orientationIndex);
}
}
private Quaternionf slerp(Quaternionf v0, Quaternionf v1, float alpha) {
final float DOT_THRESHOLD = 0.9995f;
float dot = v0.dot(v1);
if (dot > DOT_THRESHOLD) return lerp(v0, v1, alpha);
Glm.clamp(dot, -1.0f, 1.0f);
float theta_0 = (float) Math.acos(dot);
float theta = theta_0 * alpha;
Vector4f p = vectorize(v0).mul(dot).negate();
Vector4f v2 = vectorize(v1).add(p).normalize();
Vector4f a = vectorize(v0).mul((float) Math.cos(theta));
Vector4f b = new Vector4f(v2).mul((float) Math.sin(theta));
Vector4f res = a.add(b);
return new Quaternionf(res.x, res.y, res.z, res.w);
}
private Quaternionf lerp(Quaternionf v0, Quaternionf v1, float alpha) {
Vector4f start = vectorize(v0);
Vector4f end = vectorize(v1);
Vector4f interp = new Vector4f(start).lerp(end, alpha);
System.out.printf("alpha: %f, (%f, %f, %f, %f)\n", alpha, interp.w, interp.x, interp.y, interp.z);
interp.normalize();
return new Quaternionf(interp.x, interp.y, interp.z, interp.w);
}
private Vector4f vectorize(Quaternionf theQuat) {
Vector4f vec = new Vector4f();
vec.x = theQuat.x;
vec.y = theQuat.y;
vec.z = theQuat.z;
vec.w = theQuat.w;
return vec;
}
}
| [
"francesco.cagnin@gmail.com"
] | francesco.cagnin@gmail.com |
6d6cc09201b4e50db03f381b732a9a828c8b9769 | eef0422a68c9878491877185b357e54f2af13c1f | /design_pattern/src/main/java/com/example/pattern/abstractFactory(抽象工厂)/Plant_Tomato.java | dba3c529ba398d57d679e64d398445ad91c3f6f2 | [] | no_license | ainusers/java-design-pattern | 1b2bdb459f5bf93a633e8caaaa635dc9a9cd2a84 | b551a7ce0fe93e04de0e8894dea2e72679e83558 | refs/heads/master | 2020-09-09T04:16:03.915742 | 2019-11-15T06:06:49 | 2019-11-15T06:06:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 370 | java | import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author: tianyong
* @date: 2019/11/15 11:00
* @desciption:西红柿 子类
*/
@Setter
@Getter
@ToString
public class Plant_Tomato implements Plant {
// 输出名字
private String name;
// 有参构造
public Plant_Tomato(String name) {
this.name = name;
}
}
| [
"979111986@qq.com"
] | 979111986@qq.com |
95cd80f2f9aa92c1ff65fa7b8cfface51271fcd7 | 13662f35a6b65bbec5d5cd2ffc76dbd4639c7cac | /src/main/java/com/ngochuy/apiphoneshop/payload/ProductInCart.java | ecfee5290bbfea61b485f5167bb9188613216474 | [] | no_license | ngochuy1999/API_Phone_Shop | bf8452bdf9ca0f85df534f2f9e9e05440eac364a | 6e00d912243753786b6d47dc1b17c8efc8e6f847 | refs/heads/master | 2023-07-03T16:35:58.369108 | 2021-09-01T17:28:40 | 2021-09-01T17:28:40 | 399,744,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 622 | java | package com.ngochuy.apiphoneshop.payload;
public class ProductInCart {
int productId;
int quantityCart;
public ProductInCart() {
}
public ProductInCart(int productId, int quantityCart) {
this.productId = productId;
this.quantityCart = quantityCart;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantityCart() {
return quantityCart;
}
public void setQuantityCart(int quantityCart) {
this.quantityCart = quantityCart;
}
}
| [
"ngochuy199x@gmail.com"
] | ngochuy199x@gmail.com |
1aacda7d7616067e5643ec86a526bc13b402869b | 1a666c416ecf45861c6f6bf2542e86a7a71ba25a | /src/FinalExamsJavaFundamentals/WorldTour_01.java | 94c13a444bad57c9e2286bf52bd6c73c6298e165 | [] | no_license | Kmet90/JavaProgrammingFundamentals2 | 7a0a0f42bad3c30d8ea085129a2e5fa24346a991 | 79ec4508613d9d56af71a582bcf24fd3b69e681f | refs/heads/master | 2023-05-10T16:00:15.087087 | 2021-06-07T04:49:09 | 2021-06-07T04:49:09 | 343,919,339 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,176 | java | package FinalExamsJavaFundamentals;
import java.util.Scanner;
public class WorldTour_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder initialDestination = new StringBuilder(scanner.nextLine());
String input = scanner.nextLine();
while (!input.equals("Travel")) {
String[] commandParts = input.split(":");
String commandName = commandParts[0];
switch (commandName) {
case "Add Stop":
int addStopIndex = Integer.parseInt(commandParts[1]);
String stopToInsert = commandParts[2];
if (addStopIndex >= 0 && addStopIndex < initialDestination.length()) {
initialDestination.insert(addStopIndex, stopToInsert);
}
System.out.println(initialDestination);
break;
case "Remove Stop":
int removeBeginIndex = Integer.parseInt(commandParts[1]);
int removeEndIndex = Integer.parseInt(commandParts[2]);
if (removeBeginIndex >= 0 && removeBeginIndex < initialDestination.length() &&
removeEndIndex >= 0 && removeEndIndex < initialDestination.length()) {
initialDestination.delete(removeBeginIndex, removeEndIndex + 1);
}
System.out.println(initialDestination);
break;
case "Switch":
String oldString = commandParts[1];
String newString = commandParts[2];
String destinationAsString = initialDestination.toString();
destinationAsString = destinationAsString.replace(oldString, newString);
initialDestination = new StringBuilder(destinationAsString);
System.out.println(initialDestination);
break;
}
input = scanner.nextLine();
}
System.out.printf("Ready for world tour! Planned stops: %s", initialDestination);
}
} | [
"kmet90@gmail.com"
] | kmet90@gmail.com |
04f7ee1bd2570540f79dfc90f23e2f8be8cb4d9c | 0fd8b8702647a62f44126b109afcc5b1c9d477c8 | /src/main/java/com/abc/database/po/TriggerEvent.java | 671a30317d1d9198c03b581c6a20fc7f00aa959b | [] | no_license | liujinwene/spring-util | 0765b1f301a1431547b1a36f15130374ba12495f | 8784dcb115d574ac3bf440a6ef5ad7c587dd3c5a | refs/heads/master | 2020-03-25T20:06:14.468537 | 2018-08-09T12:06:29 | 2018-08-09T12:06:29 | 144,115,097 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 329 | java | package com.abc.database.po;
import lombok.Builder;
import lombok.Data;
import java.util.Date;
/**
* Created by liujinwen on 2018-07-24
*/
@Builder
@Data
public class TriggerEvent {
private String id;
private Integer status;
private String event_id;
private Date create_time;
private Date update_time;
}
| [
"278810263@qq.com"
] | 278810263@qq.com |
7d197ac819e613dbdc3662beee55b4fa5f0fb01c | 201caac2bcb64c5f0d143800ea55fe735928c4f3 | /src/sample/view/UpdateLogViewController.java | eca19df2b8da6973d68045c9c6f17f4b106a1f52 | [] | no_license | YFCodeDream/Binary-Tree-Visualizer | ef7441eb234e6156ec108c45418f1419b1009b6d | 3c8f20b100ab366ce885767c9964aee0aacc1f8d | refs/heads/main | 2023-03-18T10:51:11.819262 | 2021-03-01T01:45:07 | 2021-03-01T01:45:07 | 309,238,326 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 543 | java | package sample.view;
import javafx.fxml.FXML;
import javafx.scene.image.Image;
import javafx.stage.Stage;
/**
* @author YFCodeDream
* @version 1.0
* @date 2020/11/2 10:17
*/
public class UpdateLogViewController {
private Stage dialogStage;
@FXML
private void handleGotIt() {
dialogStage.close();
}
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
this.dialogStage.getIcons().add(new Image("file:resources/images/tree-icon.png"));
}
}
| [
"noreply@github.com"
] | noreply@github.com |
3328c653e99c539927ce1d6d2038d5f89549e58f | 3d6fb5535b4c457bbf9a8a1b580dd248677aed4c | /pcg/src/com/pcgtcg/game/Player.java | 8110d53f858a6e08ac833559b27d14d37fefea7a | [] | no_license | mholtkamp/pcgtcg | 8fcfca8d3fc7abb58b1f7f62ee64728b6732a1f8 | 56a118f05841545b27261dc20a8b0a448df284f7 | refs/heads/master | 2021-04-26T16:46:42.935972 | 2015-05-24T01:01:59 | 2015-05-24T01:01:59 | 19,433,693 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 234 | java | package com.pcgtcg.game;
public class Player {
public String name;
public Deck deck;
public int life;
public Player()
{
life = 40;
deck = new Deck();
}
public Player(String name)
{
this();
this.name = name;
}
}
| [
"mholt012@gmail.com"
] | mholt012@gmail.com |
b10adc7581fa450a805a6702b3f85c66037f6ec6 | cbb2378cdcd2c103e53b4c545145e36aa349c255 | /WebDriver/Sample-5/src/sample/pkg5/sample51.java | 3ea3f32e5e16f246f7deb649c0b18dff2483eb00 | [
"MIT"
] | permissive | chintamanand/Selenium-Testing | 3dd8420c6eabdcec3a63e134886f205a31851655 | 1d733fc29fcc6d9c7d41c45f46eb56958aab913e | refs/heads/master | 2021-06-26T00:51:59.138664 | 2020-10-18T17:56:50 | 2020-10-18T17:56:50 | 157,729,064 | 2 | 0 | MIT | 2020-10-18T17:56:52 | 2018-11-15T15:02:21 | Java | UTF-8 | Java | false | false | 1,331 | java | package sample.pkg5;
import java.util.Scanner;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class sample51 {
public static WebDriver driver;
public static String browser="chrome";
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "F:\\Selenium\\chromedriver.exe");
System.setProperty("webdriver.gecko.driver", "F:\\Selenium\\geckodriver.exe");
Scanner scan=new Scanner(System.in);
String browser=scan.nextLine();
if(browser.equals("chrome")){
driver=new ChromeDriver();
} else if(browser.equals("firefox")){
driver=new FirefoxDriver();
}else if(browser.equals("ie")){
driver=new InternetExplorerDriver();
}else{
System.out.println("InCorrect Input");
}
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.navigate().to("https://mail.google.com/mail/");
System.out.println("This will be Title of the Page: "+driver.getTitle());
System.out.println("This is the Current URl: "+driver.getCurrentUrl());
System.out.println("Length of the Title is: "+driver.getTitle().length());
driver.close();
}
}
| [
"chintamanand56@gmail.com"
] | chintamanand56@gmail.com |
4dac61bfe350194dad7505b0c9807155c24a37d6 | f7364d80f406f701f475188e6399fd37ae3c356a | /app/src/main/java/com/example/puza/mvpapiimplementation/application/network/postReviewDao/ReviewErrorAndMessageResponse.java | f5b0db141d726f63fb68be8c08f6f3db6fc4f33f | [] | no_license | puja110/Ghumgham | bd7e77947667e824aab0e70e449bf725c6e4e24a | df4691529e677aebd64c8b9eded6c4668c56c2f5 | refs/heads/master | 2020-05-04T21:40:12.288745 | 2019-04-04T12:49:47 | 2019-04-04T12:49:47 | 179,484,485 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 782 | java |
package com.example.puza.mvpapiimplementation.application.network.postReviewDao;
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ReviewErrorAndMessageResponse implements Serializable
{
@SerializedName("message")
@Expose
private String message;
@SerializedName("errors")
@Expose
private Errors errors;
private final static long serialVersionUID = -1742413997687895922L;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
}
| [
"csta.puja@gmail.com"
] | csta.puja@gmail.com |
b0c38d4d75346e438da1d19ab9b109e150ee30a4 | cbdd8a8e5d1c0d664ca3f8c7b31c4f1c1644e839 | /wikipedia/visualize-app/src/edu/mit/cci/wikipedia/util/MapSorter.java | 20c3cbf730e608c58843e73b39cf3f95e27acd72 | [] | no_license | jintrone/CCI-Shared-Code | 2d8ee44b6afea69fd8ae401ff77a285d3fd45346 | a3dffbf2ddc4d49825e8ef02427197f4c2b2e6b1 | refs/heads/master | 2021-01-10T19:44:14.116522 | 2012-10-24T21:43:33 | 2012-10-24T21:43:33 | 1,411,506 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,066 | java | package edu.mit.cci.wikipedia.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class MapSorter {
public List<String> sortMap(String data, int rank) {
//log.info(data);
List<String> output = new LinkedList<String>();
Hashtable<String,Integer> table = new Hashtable<String,Integer>();
Hashtable<String,Integer> editSizeTable = new Hashtable<String,Integer>();
int prevSize = 0;
String[] lines = data.split("\n");
for (int i = 0; i < lines.length; i++) {
//log.info(i + "\t" + lines[i].split("\t").length + "\t" + lines[i]);
String[] arr = lines[i].split("\t");
if (arr.length < 1)
continue;
String user = arr[1];
int size = Integer.parseInt(arr[4]);
int diff = size - prevSize;
if (editSizeTable.containsKey(user)) {
int v = editSizeTable.get(user);
v += diff;
editSizeTable.put(user,v);
} else {
editSizeTable.put(user,diff);
}
prevSize = size;
if (table.containsKey(user)) {
int v = table.get(user);
v++;
table.put(user, v);
} else {
table.put(user, 1);
}
}
// Sort by edit count
ArrayList al = new ArrayList(table.entrySet());
Collections.sort(al, new Comparator(){
public int compare(Object obj1, Object obj2){
Map.Entry ent1 =(Map.Entry)obj1;
Map.Entry ent2 =(Map.Entry)obj2;
return -(((int)Integer.parseInt(ent1.getValue().toString())) - ((int)Integer.parseInt(ent2.getValue().toString())));
}
});
int alsize = al.size();
if (alsize < rank)
rank = alsize;
else if (rank == 0)
rank = alsize;
for (int j = 0; j < rank; j++) {
String str = al.get(j).toString();
String user = str.substring(0,str.lastIndexOf("="));
String edits = str.substring(str.lastIndexOf("=")+1);
String editSize = String.valueOf(editSizeTable.get(user));
output.add(edits + "\t" + user + "\t" + editSize);
//log.info(edits + "\t" + user + "\t" + editSize);
}
return output;
}
}
| [
"nemoto@mit.edu"
] | nemoto@mit.edu |
0d8057aead9094789abd8e2718ef86f6ebc6b7df | 84f818927d7379ed049047aadb4faf3828c82cbf | /Application_programming_in_java/Class_stuff/class_5/src/main/java/serialization/ValidationDemo.java | b8130284c3a0e25136cd3f2b35347fe88480bbab | [] | no_license | joettcrow/University_of_Washington | 00c667c3bff1ebb871f5becf06d0325bea02a76b | 59fcd9c0fb3ab61d432d023963c010bdb3e50238 | refs/heads/master | 2020-03-10T20:10:27.490849 | 2018-09-10T23:08:44 | 2018-09-10T23:08:44 | 129,564,659 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,660 | java | package serialization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.swing.JOptionPane;
public class ValidationDemo
implements Serializable, ObjectInputValidation
{
private static final long serialVersionUID = -7517072649567918665L;
private int counter;
private double degrees;
public static void main(String[] args)
{
ValidationDemo demo = new ValidationDemo( 5, 260 );
System.out.println( demo );
byte[] bArr = persist( demo );
String msg = "VALID demo object has been persisted.\n"
+ "press OK to restore";
JOptionPane.showMessageDialog( null, msg );
demo = restore( bArr );
demo.counter = -1;
bArr = persist( demo );
System.out.println( demo );
msg = "INVALID demo object has been persisted.\n"
+ "press OK to restore";
JOptionPane.showMessageDialog( null, msg );
demo = restore( bArr );
System.out.println( demo );
}
public ValidationDemo( int counter, double degrees )
{
// In real life: validate counter >= 0, |degrees| <= 360
// For purposes of demonstration: allow invalid data
this.counter = counter;
this.degrees = degrees;
}
private void readObject( ObjectInputStream inStr )
throws IOException, ClassNotFoundException
{
inStr.registerValidation( this, 0 );
inStr.defaultReadObject();
}
@Override
public void validateObject() throws InvalidObjectException
{
if ( counter < 0 )
throw new InvalidObjectException( "counter < 0" );
if ( Math.abs( degrees ) > 360 )
throw new InvalidObjectException( "invalid degrees" );
}
@Override
public String toString()
{
StringBuilder bldr = new StringBuilder();
bldr.append( "counter=" ).append( counter )
.append( ",degrees=" ).append( degrees );
return bldr.toString();
}
private static byte[] persist( ValidationDemo demo )
{
byte[] rval = null;
try(
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream( bStream );
)
{
oStream.writeObject( demo );
rval = bStream.toByteArray();
}
catch ( IOException exc )
{
exc.printStackTrace();
System.exit( 1 );
}
return rval;
}
private static ValidationDemo restore( byte[] bArr )
{
ValidationDemo demo = null;
try (
ByteArrayInputStream bStream = new ByteArrayInputStream( bArr );
ObjectInputStream oStream = new ObjectInputStream( bStream );
)
{
Object obj = oStream.readObject();
if ( !(obj instanceof ValidationDemo) )
throw new IOException( "Not a GeoPlane object" );
demo = (ValidationDemo)obj;
}
catch ( IOException | ClassNotFoundException exc )
{
exc.printStackTrace();
System.exit( 1 );
}
return demo;
}
}
| [
"jcrowley@indeed.com"
] | jcrowley@indeed.com |
64b6dedc05172521d7fcba32e0e50b445d8c9e3b | 92eaade013d9d048231650045b28bdaf6ab152a8 | /ch15_classDemo/src/business/Product.java | fb2ae9027820d4157f42d5769010e53d5f2636dc | [] | no_license | akidwell/Java | 185a0991a0508003057cb054261375bf707e2d48 | 42332b98c1b96835a88540d46fabdd150ed4a618 | refs/heads/master | 2020-05-16T19:19:57.773239 | 2019-05-28T12:46:24 | 2019-05-28T12:46:24 | 183,255,159 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,503 | java | package business;
public class Product {
private String code;
private String description;
private Double price;
//declare constructors
public Product() {
code = "";
description = "";
price = 0.0;
}
// generated by eclipse:
// public Product(String code, String description, Double price) {
// this.code = code;
// this.description = description;
// this.price = price; OR
//Wrote this one in class
public Product(String inCode, String inDescription, Double inPrice) {
code = inCode;
description = inDescription;
price = inPrice;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Product: code=" + code + ", description=" + description + ", price=" + price;
}
public static void aStaticMethod() {
System.out.println("an arbitrary static method");
}
// @Override
// public Product get(String Code) {
// // TODO Auto-generated method stub
// return null;
// }
// @Override
// public String getAll() {
// // TODO Auto-generated method stub
// return null;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String "C") {
//
// code = c;
}
| [
"hemmerlea2@gmail.com"
] | hemmerlea2@gmail.com |
5ccf666312b12f37ea88da817b96285b727f91e2 | 8957d10aed574a84848207fb96a7efcfdbf97ffc | /알고리즘스터디/src/D3/Solution_9317_석찬이의받아쓰기.java | c623220b5e9c52a208b9789a29c3cbfc85521061 | [] | no_license | ghs12222/HoonSung | 95ef12d8664bcc9c17eded7a87e6456ac6fa589e | 8f63d502d967d27d6ceb77083660bc7d9a6cd61b | refs/heads/master | 2021-01-01T13:28:53.026443 | 2020-05-20T06:59:32 | 2020-05-20T06:59:32 | 239,299,332 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 867 | java | package D3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.InputMap;
public class Solution_9317_석찬이의받아쓰기 {
static int T, N;
static int res;
static String target, sukchan;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
N = Integer.parseInt(br.readLine());
target = br.readLine();
sukchan = br.readLine();
res = 0;
for (int i = 0; i < sukchan.length(); i++) {
if(sukchan.charAt(i) == target.charAt(i))
res++;
}
sb.append("#"+t+" "+res+"\n");
}
System.out.println(sb);
}
}
| [
"ghs12222@naver.com"
] | ghs12222@naver.com |
01e4146e16b5b9bfe9c2aa2e83bdd4d9c3bd0e69 | 9d0650df0c1216ad9e50a7b8dad85e0231c0ab6a | /PIII-master/FlyBook/src/com/group_0471/flybook/flightListActivity.java | 093634ae53e8f6fcb9032188b9b29f891324745b | [] | no_license | persa188/flybook | 41c93e5078e83f5a92898f5d0057b16339815287 | 32ec15e1226b897497c62f27db7a2865e660255b | refs/heads/master | 2020-06-02T07:54:18.323245 | 2016-09-15T00:07:14 | 2016-09-15T00:07:14 | 37,269,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,275 | java | package com.group_0471.flybook;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
/**
* An activity representing a list of flights. This activity has different
* presentations for handset and tablet-size devices. On handsets, the activity
* presents a list of items, which when touched, lead to a
* {@link flightDetailActivity} representing item details. On tablets, the
* activity presents the list of items and item details side-by-side using two
* vertical panes.
* <p>
* The activity makes heavy use of fragments. The list of items is a
* {@link flightListFragment} and the item details (if present) is a
* {@link flightDetailFragment}.
* <p>
* This activity also implements the required
* {@link flightListFragment.Callbacks} interface to listen for item selections.
*/
public class flightListActivity extends ActionBarActivity implements
flightListFragment.Callbacks {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flight_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (findViewById(R.id.flight_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((flightListFragment) getSupportFragmentManager().findFragmentById(
R.id.flight_list)).setActivateOnItemClick(true);
}
// TODO: If exposing deep links into your app, handle intents here.
}
/**
* {@inheritDoc}
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.client_menu, menu);
return true;
}
/**
* Callback method from {@link flightListFragment.Callbacks} indicating that
* the item with the given ID was selected.
*/
@Override
public void onItemSelected(String id) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(flightDetailFragment.ARG_ITEM_ID, id);
flightDetailFragment fragment = new flightDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.flight_detail_container, fragment).commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, flightDetailActivity.class);
detailIntent.putExtra(flightDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
Intent intent = new Intent(this, ClientMenu.class);
finish();
startActivity(intent);
return true;
}else if( id == R.id.logout){ // logout
NavUtils.navigateUpTo(this, new Intent(this,
MainActivity.class));
}else if(id == R.id.shopping_cart){ //view cart
Intent i = new Intent(this, ShoppingCartActivity.class);
startActivity(i);
}else if(id == R.id.account_settings){ //account settings
Intent i = new Intent(this, ClientInfoListActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
| [
"dev.persaud@mail.utoronto.ca"
] | dev.persaud@mail.utoronto.ca |
8580a3510e105b440c1dc9aa5eb0336e863fadf0 | 1a32ee8a44091ef9057d9faf199a6b09a312610a | /Mx_compiler/node/VarDeclNode.java | 9dbbd92b0e8ca9346dbdbfbe23030e6677083063 | [] | no_license | ZihuaZhao/Compiler | 84dceb816f801f8c2615d24a4d85593bb1f7b90d | c45a313652eaea16153f7f06fa014f179cfbb264 | refs/heads/master | 2020-05-03T08:32:56.737431 | 2019-05-16T03:11:04 | 2019-05-16T03:11:04 | 178,528,825 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 728 | java | package Mx_compiler.node;
import Mx_compiler.visitor.AstVisitor;
public class VarDeclNode extends DeclNode {
private TypeNode type;
private ExprNode expr;
public VarDeclNode(TypeNode type , String name , ExprNode expr){
this.type = type;
this.name = name;
this.expr = expr;
}
public VarDeclNode(TypeNode type , String name){
this.type = type;
this.name = name;
this.expr = null;
}
public TypeNode getType(){
return type;
}
public String getName(){
return name;
}
public ExprNode getExpr(){
return expr;
}
@Override
public void accept(AstVisitor visitor){
visitor.visit(this);
}
}
| [
"sjtuszzh@sjtu.edu.cn"
] | sjtuszzh@sjtu.edu.cn |
3928f9becef1346553ba36b35c48dcec96359edd | e86fdec875bb02967fd492eaf2aed1745e5ed5dd | /SelectionSor.java | 9dad571d3050507ae740777a44658746c0170f3e | [] | no_license | VeNOM4171/JavaProblems | 0d72618e533c47028acec79e857dbb5bf6362ab2 | 4b9a619f955875469d8cbc255e68851de273a78f | refs/heads/master | 2021-05-25T22:30:53.738110 | 2020-04-16T11:37:10 | 2020-04-16T11:37:10 | 253,948,199 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,027 | java | public class SelectionSort {
static int loop = 1;
public static void selectionSort(int[] arr){
int temp;
for(int i=0;i<arr.length;i++){
loop++;
for(int j=i+1;j<arr.length;j++){
loop++;
if(arr[i]>arr[j]){
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
public static void main(final String args[]) {
int[] arr = { 5, 9, 3, 1, 2, 8, 4, 7, 6 };
System.out.print("Before Sorting Array: ");
for(int i=0; i<arr.length;i++){
System.out.print( arr[i] + " ");
}
System.out.println();
selectionSort(arr);
System.out.print("After Sorting Is Done. Array: ");
for(int i=0; i<arr.length;i++){
System.out.print( arr[i] + " ");
}
System.out.println();
System.out.print("Iteration: "+loop);
}
} | [
"49753535+VeNOM4171@users.noreply.github.com"
] | 49753535+VeNOM4171@users.noreply.github.com |
8409da5310b269c0d964b1bf2f99dce2a640e603 | 5a9989a352ecee46ac86acd808caa8b4cd116932 | /src/main/java/io/zipcoder/tc_spring_poll_application/QuickPollApplication.java | 0c8fb004d0487c1cde5eb65bef02b744cbd88f29 | [] | no_license | Xcuello/Spring-QuickPoll | 92ea55c1bcabdaccd9c796342f41156b06ed40aa | 4d2f2b57c2498407ca345e2d4b262881ed188855 | refs/heads/master | 2020-04-18T01:58:42.846343 | 2019-01-23T07:59:43 | 2019-01-23T07:59:43 | 167,142,035 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package io.zipcoder.tc_spring_poll_application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QuickPollApplication {
public static void main(String[] args) {
SpringApplication.run(QuickPollApplication.class, args);
}
} | [
"Xzaviacuello@gmail.com"
] | Xzaviacuello@gmail.com |
93d4ef1c42eb1c6dc9292dcdccafd408041b06d8 | 82f581a93c6e619c1417fcf7e67e6af180701999 | /cagrid/Software/portal/cagrid-portal/aggr/test/src/java/gov/nih/nci/cagrid/portal/aggr/status/AbstractServiceSatusTest.java | 90ba3286ff23e68493f6514cbfd166842311c2c7 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | NCIP/cagrid | e9ad9121d41d03185df7b1f08381ad19745a0ce6 | b1b99fdeaa4d4f15117c01c5f1e5eeb2cb8180bb | refs/heads/master | 2023-03-13T15:50:00.120900 | 2014-04-02T19:15:14 | 2014-04-02T19:15:14 | 9,086,195 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,359 | java | package gov.nih.nci.cagrid.portal.aggr.status;
import gov.nih.nci.cagrid.portal.aggr.ServiceUrlProvider;
import junit.framework.TestCase;
import java.util.HashSet;
import java.util.Set;
/**
* User: kherm
*
* @author kherm manav.kher@semanticbits.com
*/
public class AbstractServiceSatusTest extends TestCase {
final String svcInIndex1 = "http://service1";
final String svcInIndex2 = "http://service2";
final String svcInIndex3 = "http://service3";
final String validSvcNotInIndex = "http://cagrid-service.nci.nih.gov:8080/wsrf/services/cagrid/CaDSRService";
IdxServiceStatusProvider idxProvider;
public AbstractServiceSatusTest() {
String indexSvcUrl = "http://some.index.svc";
idxProvider = new IdxServiceStatusProvider();
idxProvider.setIndexServiceUrls(new String[]{
indexSvcUrl
}
);
idxProvider.setStrictIndexVerification(true);
ServiceUrlProvider dynProv = new ServiceUrlProvider() {
public Set<String> getUrls(String indexServiceUrl) {
Set<String> urls = new HashSet<String>();
urls.add(svcInIndex1);
urls.add(svcInIndex2);
urls.add(svcInIndex3);
return urls;
}
};
idxProvider.setDynamicServiceUrlProvider(dynProv);
}
}
| [
"kherm"
] | kherm |
6eaf2192e7786002fa15c0b6d5244c53e287fe78 | 02c9a49f169da2cbac731c87679eb05499d1a697 | /spring-mvc-demo/src/main/java/com/luv2code/springdemo/mvc/Customer.java | 39451e5ca4bab3390fafc25bdcc0ace736fc8ed6 | [] | no_license | Evgenij-Pavlenko/Spring | 6ad920867b95172bdae4929486a2cb0178929108 | b9a0ff566c5754f4725b3118efc6abdbb9e31b65 | refs/heads/master | 2023-02-13T05:03:53.938554 | 2021-01-18T17:38:30 | 2021-01-18T17:38:30 | 299,124,033 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,565 | java | package com.luv2code.springdemo.mvc;
import com.luv2code.springdemo.mvc.validation.CourseCode;
import javax.validation.constraints.*;
public class Customer {
private String firstName;
@NotNull(message = "is required")
@Size(min = 1, message = "is required")
private String lastName;
@NotNull(message = "is required")
@Min(value = 0, message = "must be greater than or equal to zero")
@Max(value = 10, message = "must be less than or equal to 10")
private Integer freePasses;
@Pattern(regexp = "^[a-zA-Z0-9]{5}", message = "only 5 chars/digits")
private String postalCode;
@CourseCode(value = "TODO", message = "must start with TODO")
private String courseCode;
public Customer() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getFreePasses() {
return freePasses;
}
public void setFreePasses(Integer freePasses) {
this.freePasses = freePasses;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
}
| [
"evgenij.pavlenko@gmail.com"
] | evgenij.pavlenko@gmail.com |
25b29bd46fee568f9564888d544f97b5a6a2f301 | 4b60f40691aed433e1ca832e79bfc834380ddfed | /app/src/main/java/net/maker/commonframework/base/rx/binding/support/v7/widget/ToolbarNavigationClickOnSubscribe.java | b7fa43183149779e4294ddde1dd3aa4b7940b6b9 | [] | no_license | HuangPugang/commonFrame | 3a9ba656cbc8efbbc18c216bbf47e5950fd0790a | cbec29fcb327dabfc020407b9afc08bd71cddc80 | refs/heads/master | 2016-09-14T01:36:23.211102 | 2016-04-29T08:49:46 | 2016-04-29T08:49:46 | 57,370,537 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,041 | java | package net.maker.commonframework.base.rx.binding.support.v7.widget;
import android.support.v7.widget.Toolbar;
import android.view.View;
import rx.Observable;
import rx.Subscriber;
import rx.android.MainThreadSubscription;
import static net.maker.commonframework.base.rx.binding.internal.Preconditions.checkUiThread;
final class ToolbarNavigationClickOnSubscribe implements Observable.OnSubscribe<Void> {
final Toolbar view;
ToolbarNavigationClickOnSubscribe(Toolbar view) {
this.view = view;
}
@Override public void call(final Subscriber<? super Void> subscriber) {
checkUiThread();
View.OnClickListener listener = new View.OnClickListener() {
@Override public void onClick(View v) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(null);
}
}
};
view.setNavigationOnClickListener(listener);
subscriber.add(new MainThreadSubscription() {
@Override protected void onUnsubscribe() {
view.setNavigationOnClickListener(null);
}
});
}
}
| [
"huangpg@59store.com"
] | huangpg@59store.com |
3c730eeccd73e8720b430284c25c7ebdcc6b2c29 | 670a51d60eb1fe822bbd08a67d1877c2cb63c36d | /televisa_commons_master/commons-services/src/main/java/com/televisa/commons/services/utilities/Base64Encoding.java | 3d63d8394b8bfbe2b511af63b8cbc84dab5501f9 | [] | no_license | edgarhdz/TIM_Code_Deportes | c8bfb2031d230b013053464c4776f8dfaab267f2 | f25efebd9578241519f17f0462c1c78c5bc80bb2 | refs/heads/master | 2016-09-09T19:19:11.595527 | 2014-02-17T22:52:31 | 2014-02-17T22:52:31 | 16,928,699 | 0 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,009 | java | package com.televisa.commons.services.utilities;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
public class Base64Encoding {
public static String encoding(String key){
if(key != null && key.length() > 0){
byte[] encoded = Base64.encodeBase64(key.getBytes());
return new String(encoded);
}else{
return null;
}
}
public static String decoding(String key){
if(key != null && key.length() > 0){
byte[] decoded = Base64.decodeBase64(key.getBytes());
return new String(decoded);
}else{
return null;
}
}
public static void main(String args[]) throws IOException {
String original = "original String before base64 encoding in Java";
System.out.println("Original String: " + original );
String encoded = encoding(original);
System.out.println("Base64 Encoded String : " + encoded);
String decoded = decoding(encoded);
System.out.println("Base 64 Decoded String : " + decoded);
}
}
| [
"edgar.hernandez@esmas.net"
] | edgar.hernandez@esmas.net |
1d5640c4599da80ef0cc57ed59648d7ef304a6bf | 8bbee634f9dac7dc2e754c027a2de63b24c50681 | /IntroduccionPOO/src/paquete1/A.java | 191ca11aee154e7003f144ff13d06050e1f94b0d | [] | no_license | begghg/programacionDAW18 | 82de281483d6eaff71dcfe4d44b52243717e2cd9 | afef8bf3cd564d89dd9b78eade1139b8f1f586f2 | refs/heads/master | 2020-04-01T18:46:14.979116 | 2019-01-22T17:52:04 | 2019-01-22T17:52:04 | 153,513,444 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 148 | java | package paquete1;
public class A {
public int datoA;
public A(int numero){
System.out.println("imprimimos datoA-->"+numero);
}
}
| [
"begona.herraez@laarboleda.es"
] | begona.herraez@laarboleda.es |
f91ed4bea7b5a3620c68e0bf6871b25a5905fa66 | 4bc0ee1bba898a09c7c6bcd2f36c7440b1a9b4b9 | /src/main/java/org/imobprime/model/PropertyState.java | 2e103066c6b7be469944fe16ffbb65e8ec67d74e | [] | no_license | JanessaTech/imobprime-spring-boot | dac849fea2b1ddc50f6fe1fcef61c9f013f5ac67 | c83007836d9d0552bcba173c1831322a67c425d7 | refs/heads/master | 2023-07-09T06:15:35.163552 | 2019-02-05T18:01:38 | 2019-02-05T18:01:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,232 | java | package org.imobprime.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "situacao_imovel")
public class PropertyState implements Serializable {
private static final long serialVersionUID = -8493462134493280643L;
@Id
@Column(name = "id_situacao_imovel")
private Integer id;
@Column(name = "nome_situacao_imovel", nullable = false, length = 55)
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PropertyState other = (PropertyState) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| [
"jorgealmeidajunior@gmail.com"
] | jorgealmeidajunior@gmail.com |
d40cb9f93cf0ab10622834a5c683c0191379e3cf | 776f7a8bbd6aac23678aa99b72c14e8dd332e146 | /src/rx/internal/operators/OperatorToMultimap$1.java | 6e24583fa568d37ab61b15d2e6bafc8cafea384f | [] | no_license | arvinthrak/com.nianticlabs.pokemongo | aea656acdc6aa419904f02b7331f431e9a8bba39 | bcf8617bafd27e64f165e107fdc820d85bedbc3a | refs/heads/master | 2020-05-17T15:14:22.431395 | 2016-07-21T03:36:14 | 2016-07-21T03:36:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,439 | java | package rx.internal.operators;
import java.util.Collection;
import java.util.Map;
import rx.Subscriber;
import rx.functions.Func0;
import rx.functions.Func1;
class OperatorToMultimap$1
extends Subscriber<T>
{
private Map<K, Collection<V>> map = (Map)OperatorToMultimap.access$000(this$0).call();
OperatorToMultimap$1(OperatorToMultimap paramOperatorToMultimap, Subscriber paramSubscriber1, Subscriber paramSubscriber2)
{
super(paramSubscriber1);
}
public void onCompleted()
{
Map localMap = map;
map = null;
val$subscriber.onNext(localMap);
val$subscriber.onCompleted();
}
public void onError(Throwable paramThrowable)
{
map = null;
val$subscriber.onError(paramThrowable);
}
public void onNext(T paramT)
{
Object localObject1 = OperatorToMultimap.access$100(this$0).call(paramT);
Object localObject2 = OperatorToMultimap.access$200(this$0).call(paramT);
Collection localCollection = (Collection)map.get(localObject1);
paramT = localCollection;
if (localCollection == null)
{
paramT = (Collection)OperatorToMultimap.access$300(this$0).call(localObject1);
map.put(localObject1, paramT);
}
paramT.add(localObject2);
}
public void onStart()
{
request(Long.MAX_VALUE);
}
}
/* Location:
* Qualified Name: rx.internal.operators.OperatorToMultimap.1
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"reverseengineeringer@hackeradmin.com"
] | reverseengineeringer@hackeradmin.com |
dd52f733ab571b3975c90a082e6bf31d5213d1c7 | e73c60f124e7020fddc15c6193d50dfea7c93662 | /SRS/src/main/java/servlet/searchProfessorServlet.java | 4a6b232a9ff22f0c4c08e99f53a5768add2cbb3e | [] | no_license | sahunter/SRS | 4d43e7ea0a5a7fd55e7975f1d28194e5d698b592 | e0337f8edfcd8686eeb491de8c9a1452b0655e6c | refs/heads/master | 2021-01-09T20:15:14.886331 | 2016-07-11T10:57:47 | 2016-07-27T00:45:06 | 62,644,962 | 2 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,730 | java | package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DaoFactory;
import dao.PersonDao;
import dao.SectionDao;
import model.Professor;
/**
* Servlet implementation class searchProfessorServlet
*/
@WebServlet("/searchProfessorServlet")
public class searchProfessorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public searchProfessorServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
PersonDao personDao = DaoFactory.createPersonDao();
List<Professor> professors = new ArrayList<Professor>();
professors= personDao.searchProfessor(null);
request.setAttribute("professors", professors);
request.getRequestDispatcher("pages/showprofessor.jsp").forward(request,response);
}
}
| [
"1849892563@qq.com"
] | 1849892563@qq.com |
b5b40bd25f9c99e762ce8f6319cd3f24a185f170 | 9d32980f5989cd4c55cea498af5d6a413e08b7a2 | /A72n_10_0_0/src/main/java/android/hardware/face/OppoMirrorFaceManager.java | 25ed2ac8465e8e8687d4f917564694c1e7808c74 | [] | no_license | liuhaosource/OppoFramework | e7cc3bcd16958f809eec624b9921043cde30c831 | ebe39acabf5eae49f5f991c5ce677d62b683f1b6 | refs/heads/master | 2023-06-03T23:06:17.572407 | 2020-11-30T08:40:07 | 2020-11-30T08:40:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 355 | java | package android.hardware.face;
import com.oppo.reflect.RefClass;
import com.oppo.reflect.RefMethod;
public class OppoMirrorFaceManager {
public static Class<?> TYPE = RefClass.load(OppoMirrorFaceManager.class, FaceManager.class);
public static RefMethod<Integer> getFailedAttempts;
public static RefMethod<Long> getLockoutAttemptDeadline;
}
| [
"dstmath@163.com"
] | dstmath@163.com |
767cbb6d9f5c7efc0c6440a5bebf6c1106a3aad3 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/org/robobinding/viewattribute/property/PropertyViewAttributeBinderTest.java | e68a8d96ac116caa1c82f4d4d8773462245fbc5c | [] | no_license | STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919811 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | null | UTF-8 | Java | false | false | 1,655 | java | package org.robobinding.viewattribute.property;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.robobinding.BindingContext;
import org.robobinding.viewattribute.ViewAttributeContractTest;
/**
*
*
* @since 1.0
* @version $Revision: 1.0 $
* @author Robert Taylor
*/
@RunWith(MockitoJUnitRunner.class)
public final class PropertyViewAttributeBinderTest extends ViewAttributeContractTest<PropertyViewAttributeBinder> {
@Mock
BindingContext bindingContext;
@Mock
AbstractBindingProperty bindingProperty;
private PropertyViewAttributeBinder viewAttributeBinder;
@Test
public void givenAlwaysPreInitializingView_whenBindTo_thenPreInitializeTheViewToReflectTheValueModel() {
Mockito.when(bindingProperty.isAlwaysPreInitializingView()).thenReturn(true);
viewAttributeBinder = new PropertyViewAttributeBinder(bindingProperty, null);
viewAttributeBinder.bindTo(bindingContext);
Mockito.verify(bindingProperty).preInitializeView(bindingContext);
}
@Test
public void givenAlwaysPreInitializingView_whenPreInitializeViewAfterBindTo_thenPreInitializingViewHappensOnceOnly() {
Mockito.when(bindingProperty.isAlwaysPreInitializingView()).thenReturn(true);
viewAttributeBinder = new PropertyViewAttributeBinder(bindingProperty, null);
viewAttributeBinder.bindTo(bindingContext);
viewAttributeBinder.preInitializeView(bindingContext);
Mockito.verify(bindingProperty, Mockito.times(1)).preInitializeView(bindingContext);
}
}
| [
"benjamin.danglot@inria.fr"
] | benjamin.danglot@inria.fr |
7ae2ffa8ed3e6efc84f5a320478799eec532657b | 906f94960abfeea5d73155c4d39867d3bcfeaa80 | /app/src/test/java/com/example/myapplication/codecraftrestaurant/ExampleUnitTest.java | 53fc245683f549a4e235878afa24d865aa15d015 | [] | no_license | rajkiran025/DemoRestuarants | a7e17be2ad7ed47b826a6ac352ed188cae1fc63a | fed6476388694c362321f9d86c7eb6cdf956c195 | refs/heads/master | 2023-01-09T23:27:22.634585 | 2020-11-10T16:13:16 | 2020-11-10T16:13:16 | 309,871,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 406 | java | package com.example.myapplication.codecraftrestaurant;
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);
}
} | [
"rajkrish@teksystems.com"
] | rajkrish@teksystems.com |
6fca7e149e3a98470ffe4aeae2fcdd921225a595 | 5b88a1fa67ea55a15d0d02fe5ea9ad92ab1f76ae | /src/main/java/com/bikefriends/web/rest/SocialController.java | 1dda07c4150905430280df25c64b3017a2f7be93 | [] | no_license | lukaszziaja/bikefriends | 70c8fb0964985ea39b7f49aaa8f447e1bc7be18c | 277b4b795049980bd6670836709114e7bbd833f9 | refs/heads/master | 2021-05-08T19:35:11.566501 | 2018-01-31T10:16:29 | 2018-01-31T10:16:29 | 119,573,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,895 | java | package com.bikefriends.web.rest;
import com.bikefriends.config.Constants;
import com.bikefriends.service.SocialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.support.URIBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.view.RedirectView;
@RestController
@RequestMapping("/social")
public class SocialController {
private final Logger log = LoggerFactory.getLogger(SocialController.class);
private final SocialService socialService;
private final ProviderSignInUtils providerSignInUtils;
public SocialController(SocialService socialService, ProviderSignInUtils providerSignInUtils) {
this.socialService = socialService;
this.providerSignInUtils = providerSignInUtils;
}
@GetMapping("/signup")
public RedirectView signUp(WebRequest webRequest, @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = Constants.DEFAULT_LANGUAGE) String langKey) {
try {
Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest);
socialService.createSocialUser(connection, langKey.replace("\"", ""));
return new RedirectView(URIBuilder.fromUri("/#/social-register/" + connection.getKey().getProviderId())
.queryParam("success", "true")
.build().toString(), true);
} catch (Exception e) {
log.error("Exception creating social user: ", e);
return new RedirectView(URIBuilder.fromUri("/#/social-register/no-provider")
.queryParam("success", "false")
.build().toString(), true);
}
}
}
| [
"lukasz.ziaja@atos.net"
] | lukasz.ziaja@atos.net |
b10d4d9d742948cf65fb36510e34e38ce5576370 | e1e040fa3784ddfbd61fe505d1aed88099f837aa | /src/test/java/com/xry/studygit/StudygitApplicationTests.java | b4bbff6cb4fe569c8f81d4b66d92f8e271ccc0fd | [] | no_license | xiaorenyi/springboot | 81d49614d98a4d911bfd79814c32c256f5f96ea6 | 1d438bedf66866057ccac3fab53e881cc158c7b7 | refs/heads/master | 2021-04-09T10:52:06.938345 | 2018-08-19T14:24:05 | 2018-08-19T14:24:05 | 125,447,045 | 0 | 1 | null | 2018-07-18T06:17:45 | 2018-03-16T01:28:48 | Shell | UTF-8 | Java | false | false | 335 | java | package com.xry.studygit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudygitApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"2847779149@qq.com"
] | 2847779149@qq.com |
71aac891937beab34b7bd4017bac739f2e2f8bd2 | 3134e1df254662eb64648254787b8e696fe51cb9 | /src/test/java/dao/Sql2oReviewDaoTest.java | 21f339bf2dbd98fa3ba59b62084e7dea1774fbf3 | [] | no_license | thebyronc/Java-Week4-Jadle-Restaurant-API | 485d7d643fa1c9fc76fb0377c3584874ba37d319 | 59588068e2d62e29197b0770b0e441cf7a6566d1 | refs/heads/master | 2021-09-05T09:15:50.569233 | 2018-01-26T00:24:06 | 2018-01-26T00:24:06 | 118,481,299 | 1 | 0 | null | 2018-01-22T16:11:52 | 2018-01-22T16:11:51 | null | UTF-8 | Java | false | false | 2,325 | java | package dao;
import models.Review;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sql2o.Connection;
import org.sql2o.Sql2o;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.*;
/**
* Created by Guest on 1/22/18.
*/
public class Sql2oReviewDaoTest {
private Sql2oReviewDao reviewDao;
private Connection conn;
@Before
public void setUp() throws Exception {
String connectionString = "jdbc:h2:mem:testing;INIT=RUNSCRIPT from 'classpath:db/create.sql'";
Sql2o sql2o = new Sql2o(connectionString, "", "");
reviewDao = new Sql2oReviewDao(sql2o);
conn = sql2o.open();
}
@After
public void tearDown() throws Exception {
conn.close();
}
@Test
public void addReviewSetsId() throws Exception {
Review review = setupNewReview();
int originalReviewId = review.getId();
reviewDao.add(review);
assertNotEquals(originalReviewId, review.getId());
}
@Test
public void getAllReviews() throws Exception {
Review review1 = setupNewReview();
Review review2 = new Review("Mocha", 3, "Smells Good", 1);
reviewDao.add(review1);
reviewDao.add(review2);
assertEquals(2, reviewDao.getAll().size());
}
@Test
public void findReviewById() throws Exception {
Review review = setupNewReview();
reviewDao.add(review);
Review foundReview = reviewDao.findById(review.getId());
assertEquals(review, foundReview);
}
@Test
public void deleteAllReviews() throws Exception {
Review review = setupNewReview();
reviewDao.add(review);
reviewDao.deleteAll();
assertEquals(0, reviewDao.getAll().size());
}
@Test
public void findByRestaurantId() throws Exception {
Review review1 = setupNewReview();
Review review2 = new Review("Mocha", 3, "Smells Good", 1);
reviewDao.add(review1);
reviewDao.add(review2);
int restaurantId = review1.getRestaurantId();
assertEquals(2, reviewDao.getAllReviewsByRestaurant(restaurantId).size());
}
public Review setupNewReview() {
return new Review("Byron Chang", 4, "The one glorious pizza", 1);
}
} | [
"Guest@Epicodus-5C.local"
] | Guest@Epicodus-5C.local |
deb92258a1d1446816eceacb256b0c25975389f3 | 93002f1abea87e3955073bc9eaad85d0fb85879c | /api/src/main/java/net/signalr/client/json/DefaultJsonMapper.java | dd8507bc9923d60c4c92358bc6f7ebbb73ecbef9 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mtamme/signalr-client | ae534bab4a2fdc8219783daa9f0119d00207b86a | 5501cb1f08f3d26d165f7197e814e1f02b7da933 | refs/heads/master | 2020-04-05T23:33:30.347038 | 2017-10-23T08:51:07 | 2017-10-23T08:51:07 | 16,641,539 | 7 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,878 | java | /*
* Copyright © Martin Tamme
*
* 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 net.signalr.client.json;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
/**
* Represents the default JSON mapper.
*/
public final class DefaultJsonMapper implements JsonMapper {
/**
* The factory.
*/
private final JsonFactory _factory;
/**
* Initializes a new instance of the {@link DefaultJsonMapper}.
*
* @param factory The factory.
*/
public DefaultJsonMapper(final JsonFactory factory) {
if (factory == null) {
throw new IllegalArgumentException("Factory must not be null");
}
_factory = factory;
}
@Override
public final JsonElement toElement(final String text) {
if (text == null) {
throw new IllegalArgumentException("Text must not be null");
}
final StringReader input = new StringReader(text);
try (final JsonReader reader = _factory.newReader(input)) {
return reader.readElement();
}
}
@Override
public final <T extends JsonReadable> T toObject(final String text, final Class<T> type) {
if (text == null) {
throw new IllegalArgumentException("Text must not be null");
}
if (type == null) {
throw new IllegalArgumentException("Type must not be null");
}
final T object;
try {
final Constructor<T> constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
object = constructor.newInstance();
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
final StringReader input = new StringReader(text);
try (final JsonReader reader = _factory.newReader(input)) {
object.readJson(reader);
}
return object;
}
@Override
public final String toJson(final JsonWriteable object) {
if (object == null) {
throw new IllegalArgumentException("Object must not be null");
}
final StringWriter output = new StringWriter();
try (final JsonWriter writer = _factory.newWriter(output)) {
object.writeJson(writer);
}
return output.toString();
}
}
| [
"mtamme@gmx.at"
] | mtamme@gmx.at |
d8ccc259048497d9a0e3eae87d1c25ff7e923fa6 | 0e0b3dc99034b715bb349ddd39e194a0119f9171 | /PainDiary/app/src/main/java/luyangye/paindiary/Main_app.java | a668379f72ea148b1e05720204314d3568f86e0b | [] | no_license | Yeeees/AS-5046 | b2f005b2859d3853345c3f9a04c2ca4a787fb112 | ca24669877bf8d44c25afbc67f5b491b326ac053 | refs/heads/master | 2021-01-01T19:59:03.609989 | 2017-11-01T00:35:54 | 2017-11-01T00:35:54 | 98,738,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,937 | java | package luyangye.paindiary;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by YLY on 22/04/2016.
*/
public class Main_app extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportActionBar().setTitle("PainDiary");
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
//tvShow.setOnClickListener(showResult);
// tvPressure.setText(openWeather.getPressure());
// tvTemp.setText(openWeather.getTemperature());
// tvSpeed.setText(openWeather.getWindspeed());
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment nextFragment = null;
switch (id) {
case R.id.nav_daily_record:
nextFragment = new DailyRecFragment();
break;
case R.id.nav_report:
nextFragment = new ReportFragment();
break;
case R.id.nav_map:
nextFragment = new MapFragment();
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,
nextFragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| [
"yeluyang530@163.com"
] | yeluyang530@163.com |
85c93d9492289c9035930c7ed6cf59bc182632f7 | 8ba377ffc3a75de2b798b2f67d73e5f06a245a13 | /fhir-server-test/src/test/java/com/ibm/fhir/server/test/FHIRHealthcheckOperationTest.java | 877a38772aacf28878f2daab8f35bce4d18af2ec | [
"Apache-2.0"
] | permissive | festewart/FHIR | 2349df8f3b1c6ca774019d1fd6fabc33bae79def | 7e74cf7e73c558c39d71691eec050980c65b13aa | refs/heads/master | 2020-12-23T17:31:41.989236 | 2020-01-29T21:43:03 | 2020-01-29T21:43:03 | 237,215,259 | 0 | 0 | Apache-2.0 | 2020-01-30T13:08:10 | 2020-01-30T13:08:09 | null | UTF-8 | Java | false | false | 979 | java | /*
* (C) Copyright IBM Corp. 2019
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.server.test;
import static org.testng.AssertJUnit.assertEquals;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.testng.annotations.Test;
import com.ibm.fhir.model.resource.OperationOutcome;
import com.ibm.fhir.model.type.code.IssueSeverity;
public class FHIRHealthcheckOperationTest extends FHIRServerTestBase {
@Test
public void testHealthcheck() {
WebTarget target = getWebTarget();
Response response = target.path("$healthcheck").request().get(Response.class);
assertResponse(response, Response.Status.OK.getStatusCode());
OperationOutcome operationOutcome = response.readEntity(OperationOutcome.class);
assertEquals(operationOutcome.getIssue().size(), 1);
assertEquals(operationOutcome.getIssue().get(0).getSeverity(), IssueSeverity.INFORMATION);
}
}
| [
"lmsurpre@us.ibm.com"
] | lmsurpre@us.ibm.com |
153988bace9e837e63738cdf6fda01e55779f5b8 | 36395784109069d285b4340506c69a753b5651f0 | /src/main/java/mosing/service/CalonMahasiswaService.java | 9056e97932c0a0e0ba155442074ce88f762f497a | [] | no_license | martallin/propensi-a6 | 504e884294c22db78e1d51378804266656361ccf | cf2b6e22eb56e437fd32874e8088c62d5a946cfc | refs/heads/master | 2020-04-16T02:43:02.462321 | 2017-05-22T04:05:34 | 2017-05-22T04:05:34 | 165,205,570 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 271 | java | package mosing.service;
import java.util.List;
import mosing.model.CalonMahasiswaModel;
public interface CalonMahasiswaService {
CalonMahasiswaModel selectCalon(int no_daftar);
void addCalon(CalonMahasiswaModel calon);
List<CalonMahasiswaModel> selectAllCalon();
}
| [
"emmasharahh@gmail.com"
] | emmasharahh@gmail.com |
45b9ad6bab2a56c8d71e0bf2dceb7730baf5b43f | 40d844c1c780cf3618979626282cf59be833907f | /src/testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_getParameter_Servlet_sub_61a.java | 51c328d433af47ca90c6407e240fe76c2e4557ba | [] | 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 | 3,029 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int_getParameter_Servlet_sub_61a.java
Label Definition File: CWE191_Integer_Underflow__int.label.xml
Template File: sources-sinks-61a.tmpl.java
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: getParameter_Servlet Read data from a querystring using getParameter()
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: sub
* GoodSink: Ensure there will not be an underflow before subtracting 1 from data
* BadSink : Subtract 1 from data, which can cause an Underflow
* Flow Variant: 61 Data flow: data returned from one method to another in different classes in the same package
*
* */
package testcases.CWE191_Integer_Underflow.s02;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE191_Integer_Underflow__int_getParameter_Servlet_sub_61a extends AbstractTestCaseServlet
{
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int data = (new CWE191_Integer_Underflow__int_getParameter_Servlet_sub_61b()).badSource(request, response);
/* POTENTIAL FLAW: if data == Integer.MIN_VALUE, this will overflow */
int result = (int)(data - 1);
IO.writeLine("result: " + result);
}
public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
goodG2B(request, response);
goodB2G(request, response);
}
/* goodG2B() - use goodsource and badsink */
private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int data = (new CWE191_Integer_Underflow__int_getParameter_Servlet_sub_61b()).goodG2BSource(request, response);
/* POTENTIAL FLAW: if data == Integer.MIN_VALUE, this will overflow */
int result = (int)(data - 1);
IO.writeLine("result: " + result);
}
/* goodB2G() - use badsource and goodsink */
private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int data = (new CWE191_Integer_Underflow__int_getParameter_Servlet_sub_61b()).goodB2GSource(request, response);
/* FIX: Add a check to prevent an overflow from occurring */
if (data > Integer.MIN_VALUE)
{
int result = (int)(data - 1);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too small to perform subtraction.");
}
}
/* 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 |
a729f5abd6eaf91e6d48464ed1263a1ae5baa699 | 95ce8d12aa5880280afe5ee62d0f7417c48a0815 | /app/models/Position.java | 28dbdf868af46edd7e1bf5551fb663d0247999c7 | [] | no_license | nzvonilov/aplana-personal | e122729f2900ee0ed608c0a62304286de4330632 | 94d86ec3a2d4d918d14a4022245df07997cb819f | refs/heads/master | 2021-01-18T00:42:45.652919 | 2015-07-26T18:06:18 | 2015-07-26T18:06:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 284 | java | package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by User on 25.07.2015.
*/
@Entity
@Table(name = "position")
public class Position extends AppModel{
@Id
public Long id;
public String name;
}
| [
"nstreltsov2@yandex.ru"
] | nstreltsov2@yandex.ru |
dca19565f8df8f091b1ee6d591767a5a67a0ccd1 | f2c8b25b6a63cd26a211f60fcf598c84d1f743c9 | /Android21/android-5.0.2_r1/src/android/net/IEthernetManager.java | 70cf72360df734c600478735763fa0ad9e23287d | [] | no_license | EnSoftCorp/AnalyzableAndroid | 1ba0d5db531025e517e5e4fbb7e455bbb2bb2191 | d9b29a11308eb8e6511335b24a44d0388eb7b068 | refs/heads/master | 2022-10-17T22:52:32.933849 | 2015-05-01T18:17:48 | 2015-05-01T18:17:48 | 21,949,091 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,912 | java | /*
* This file is auto-generated. DO NOT MODIFY.
* Original file: frameworks/base/core/java/android/net/IEthernetManager.aidl
*/
package android.net;
/**
* Interface that answers queries about, and allows changing
* ethernet configuration.
*//** {@hide} */
public interface IEthernetManager extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements android.net.IEthernetManager
{
private static final java.lang.String DESCRIPTOR = "android.net.IEthernetManager";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.net.IEthernetManager interface,
* generating a proxy if needed.
*/
public static android.net.IEthernetManager asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof android.net.IEthernetManager))) {
return ((android.net.IEthernetManager)iin);
}
return new android.net.IEthernetManager.Stub.Proxy(obj);
}
@Override public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_getConfiguration:
{
data.enforceInterface(DESCRIPTOR);
android.net.IpConfiguration _result = this.getConfiguration();
reply.writeNoException();
if ((_result!=null)) {
reply.writeInt(1);
_result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
}
else {
reply.writeInt(0);
}
return true;
}
case TRANSACTION_setConfiguration:
{
data.enforceInterface(DESCRIPTOR);
android.net.IpConfiguration _arg0;
if ((0!=data.readInt())) {
_arg0 = android.net.IpConfiguration.CREATOR.createFromParcel(data);
}
else {
_arg0 = null;
}
this.setConfiguration(_arg0);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.net.IEthernetManager
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
@Override public android.net.IpConfiguration getConfiguration() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
android.net.IpConfiguration _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getConfiguration, _data, _reply, 0);
_reply.readException();
if ((0!=_reply.readInt())) {
_result = android.net.IpConfiguration.CREATOR.createFromParcel(_reply);
}
else {
_result = null;
}
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public void setConfiguration(android.net.IpConfiguration config) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((config!=null)) {
_data.writeInt(1);
config.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_setConfiguration, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
}
static final int TRANSACTION_getConfiguration = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_setConfiguration = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public android.net.IpConfiguration getConfiguration() throws android.os.RemoteException;
public void setConfiguration(android.net.IpConfiguration config) throws android.os.RemoteException;
}
| [
"benjholla@gmail.com"
] | benjholla@gmail.com |
8942c1e45c84107e658fec59288ecb8ec6ce2359 | b3bdf2ecedbaa0d5f4452c32f7e0680914ba09c5 | /thread1.java | b361bdfbe4658689e81a4ddfbd70a14c32a3a47a | [] | no_license | tanyamishra2710/1BM18CS117_JAVA | ea99721b5d3e15265e579a32ac416d62971ee4db | 76a04b8a1cfd9a863b7abcf28bc5b058d2ea3fcd | refs/heads/master | 2020-07-19T23:33:18.392165 | 2019-11-21T10:07:03 | 2019-11-21T10:07:03 | 206,532,029 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 744 | java | class thread1 extends Thread
{
int num;
thread1(int a)
{
num = a;
this.start();
}
public void run()
{
try
{
if(num<=5)
{
thread1 t = new thread1(num+1);
this.sleep(3000/num);
System.out.println("Thread"+num);
}
}
catch(InterruptedException ie)
{
System.out.println("Interrupted");
}
}
}
class threadseq
{
public static void main(String args[])
{
try
{
thread1 t = new thread1(1);
}
catch(Exception ie)
{
System.out.println("Interrupted");
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.