text
stringlengths
10
2.72M
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.server.adapter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import io.micrometer.observation.ObservationRegistry; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.HttpHandlerDecoratorFactory; import org.springframework.http.server.reactive.observation.DefaultServerRequestObservationConvention; import org.springframework.http.server.reactive.observation.ServerRequestObservationConvention; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebExceptionHandler; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebHandler; import org.springframework.web.server.handler.ExceptionHandlingWebHandler; import org.springframework.web.server.handler.FilteringWebHandler; import org.springframework.web.server.i18n.LocaleContextResolver; import org.springframework.web.server.session.DefaultWebSessionManager; import org.springframework.web.server.session.WebSessionManager; /** * This builder has two purposes: * * <p>One is to assemble a processing chain that consists of a target {@link WebHandler}, * then decorated with a set of {@link WebFilter WebFilters}, then further decorated with * a set of {@link WebExceptionHandler WebExceptionHandlers}. * * <p>The second purpose is to adapt the resulting processing chain to an {@link HttpHandler}: * the lowest-level reactive HTTP handling abstraction which can then be used with any of the * supported runtimes. The adaptation is done with the help of {@link HttpWebHandlerAdapter}. * * <p>The processing chain can be assembled manually via builder methods, or detected from * a Spring {@link ApplicationContext} via {@link #applicationContext}, or a mix of both. * * @author Rossen Stoyanchev * @author Sebastien Deleuze * @since 5.0 * @see HttpWebHandlerAdapter */ public final class WebHttpHandlerBuilder { /** Well-known name for the target WebHandler in the bean factory. */ public static final String WEB_HANDLER_BEAN_NAME = "webHandler"; /** Well-known name for the WebSessionManager in the bean factory. */ public static final String WEB_SESSION_MANAGER_BEAN_NAME = "webSessionManager"; /** Well-known name for the ServerCodecConfigurer in the bean factory. */ public static final String SERVER_CODEC_CONFIGURER_BEAN_NAME = "serverCodecConfigurer"; /** Well-known name for the LocaleContextResolver in the bean factory. */ public static final String LOCALE_CONTEXT_RESOLVER_BEAN_NAME = "localeContextResolver"; /** Well-known name for the ForwardedHeaderTransformer in the bean factory. */ public static final String FORWARDED_HEADER_TRANSFORMER_BEAN_NAME = "forwardedHeaderTransformer"; private final WebHandler webHandler; @Nullable private final ApplicationContext applicationContext; private final List<WebFilter> filters = new ArrayList<>(); private final List<WebExceptionHandler> exceptionHandlers = new ArrayList<>(); @Nullable private Function<HttpHandler, HttpHandler> httpHandlerDecorator; @Nullable private WebSessionManager sessionManager; @Nullable private ServerCodecConfigurer codecConfigurer; @Nullable private LocaleContextResolver localeContextResolver; @Nullable private ForwardedHeaderTransformer forwardedHeaderTransformer; @Nullable private ObservationRegistry observationRegistry; @Nullable private ServerRequestObservationConvention observationConvention; /** * Private constructor to use when initialized from an ApplicationContext. */ private WebHttpHandlerBuilder(WebHandler webHandler, @Nullable ApplicationContext applicationContext) { Assert.notNull(webHandler, "WebHandler must not be null"); this.webHandler = webHandler; this.applicationContext = applicationContext; } /** * Copy constructor. */ private WebHttpHandlerBuilder(WebHttpHandlerBuilder other) { this.webHandler = other.webHandler; this.applicationContext = other.applicationContext; this.filters.addAll(other.filters); this.exceptionHandlers.addAll(other.exceptionHandlers); this.sessionManager = other.sessionManager; this.codecConfigurer = other.codecConfigurer; this.localeContextResolver = other.localeContextResolver; this.forwardedHeaderTransformer = other.forwardedHeaderTransformer; this.observationRegistry = other.observationRegistry; this.observationConvention = other.observationConvention; this.httpHandlerDecorator = other.httpHandlerDecorator; } /** * Static factory method to create a new builder instance. * @param webHandler the target handler for the request * @return the prepared builder */ public static WebHttpHandlerBuilder webHandler(WebHandler webHandler) { return new WebHttpHandlerBuilder(webHandler, null); } /** * Static factory method to create a new builder instance by detecting beans * in an {@link ApplicationContext}. The following are detected: * <ul> * <li>{@link WebHandler} [1] -- looked up by the name * {@link #WEB_HANDLER_BEAN_NAME}. * <li>{@link WebFilter} [0..N] -- detected by type and ordered, * see {@link AnnotationAwareOrderComparator}. * <li>{@link WebExceptionHandler} [0..N] -- detected by type and * ordered. * <li>{@link HttpHandlerDecoratorFactory} [0..N] -- detected by type and * ordered. * <li>{@link WebSessionManager} [0..1] -- looked up by the name * {@link #WEB_SESSION_MANAGER_BEAN_NAME}. * <li>{@link ServerCodecConfigurer} [0..1] -- looked up by the name * {@link #SERVER_CODEC_CONFIGURER_BEAN_NAME}. * <li>{@link LocaleContextResolver} [0..1] -- looked up by the name * {@link #LOCALE_CONTEXT_RESOLVER_BEAN_NAME}. * </ul> * @param context the application context to use for the lookup * @return the prepared builder */ public static WebHttpHandlerBuilder applicationContext(ApplicationContext context) { WebHttpHandlerBuilder builder = new WebHttpHandlerBuilder( context.getBean(WEB_HANDLER_BEAN_NAME, WebHandler.class), context); List<WebFilter> webFilters = context .getBeanProvider(WebFilter.class) .orderedStream() .toList(); builder.filters(filters -> filters.addAll(webFilters)); List<WebExceptionHandler> exceptionHandlers = context .getBeanProvider(WebExceptionHandler.class) .orderedStream() .toList(); builder.exceptionHandlers(handlers -> handlers.addAll(exceptionHandlers)); context.getBeanProvider(HttpHandlerDecoratorFactory.class) .orderedStream() .forEach(builder::httpHandlerDecorator); try { builder.sessionManager( context.getBean(WEB_SESSION_MANAGER_BEAN_NAME, WebSessionManager.class)); } catch (NoSuchBeanDefinitionException ex) { // Fall back on default } try { builder.codecConfigurer( context.getBean(SERVER_CODEC_CONFIGURER_BEAN_NAME, ServerCodecConfigurer.class)); } catch (NoSuchBeanDefinitionException ex) { // Fall back on default } try { builder.localeContextResolver( context.getBean(LOCALE_CONTEXT_RESOLVER_BEAN_NAME, LocaleContextResolver.class)); } catch (NoSuchBeanDefinitionException ex) { // Fall back on default } try { builder.forwardedHeaderTransformer( context.getBean(FORWARDED_HEADER_TRANSFORMER_BEAN_NAME, ForwardedHeaderTransformer.class)); } catch (NoSuchBeanDefinitionException ex) { // Fall back on default } return builder; } /** * Add the given filter(s). * @param filters the filter(s) to add that's */ public WebHttpHandlerBuilder filter(WebFilter... filters) { if (!ObjectUtils.isEmpty(filters)) { this.filters.addAll(Arrays.asList(filters)); updateFilters(); } return this; } /** * Manipulate the "live" list of currently configured filters. * @param consumer the consumer to use */ public WebHttpHandlerBuilder filters(Consumer<List<WebFilter>> consumer) { consumer.accept(this.filters); updateFilters(); return this; } private void updateFilters() { if (this.filters.isEmpty()) { return; } List<WebFilter> filtersToUse = this.filters.stream() .peek(filter -> { if (filter instanceof ForwardedHeaderTransformer forwardedHeaderTransformerFilter && this.forwardedHeaderTransformer == null) { this.forwardedHeaderTransformer = forwardedHeaderTransformerFilter; } }) .filter(filter -> !(filter instanceof ForwardedHeaderTransformer)) .toList(); this.filters.clear(); this.filters.addAll(filtersToUse); } /** * Add the given exception handler(s). * @param handlers the exception handler(s) */ public WebHttpHandlerBuilder exceptionHandler(WebExceptionHandler... handlers) { if (!ObjectUtils.isEmpty(handlers)) { this.exceptionHandlers.addAll(Arrays.asList(handlers)); } return this; } /** * Manipulate the "live" list of currently configured exception handlers. * @param consumer the consumer to use */ public WebHttpHandlerBuilder exceptionHandlers(Consumer<List<WebExceptionHandler>> consumer) { consumer.accept(this.exceptionHandlers); return this; } /** * Configure the {@link WebSessionManager} to set on the * {@link ServerWebExchange WebServerExchange}. * <p>By default {@link DefaultWebSessionManager} is used. * @param manager the session manager * @see HttpWebHandlerAdapter#setSessionManager(WebSessionManager) */ public WebHttpHandlerBuilder sessionManager(WebSessionManager manager) { this.sessionManager = manager; return this; } /** * Whether a {@code WebSessionManager} is configured or not, either detected from an * {@code ApplicationContext} or explicitly configured via {@link #sessionManager}. * @since 5.0.9 */ public boolean hasSessionManager() { return (this.sessionManager != null); } /** * Configure the {@link ServerCodecConfigurer} to set on the {@code WebServerExchange}. * @param codecConfigurer the codec configurer */ public WebHttpHandlerBuilder codecConfigurer(ServerCodecConfigurer codecConfigurer) { this.codecConfigurer = codecConfigurer; return this; } /** * Whether a {@code ServerCodecConfigurer} is configured or not, either detected from an * {@code ApplicationContext} or explicitly configured via {@link #codecConfigurer}. * @since 5.0.9 */ public boolean hasCodecConfigurer() { return (this.codecConfigurer != null); } /** * Configure the {@link LocaleContextResolver} to set on the * {@link ServerWebExchange WebServerExchange}. * @param localeContextResolver the locale context resolver */ public WebHttpHandlerBuilder localeContextResolver(LocaleContextResolver localeContextResolver) { this.localeContextResolver = localeContextResolver; return this; } /** * Whether a {@code LocaleContextResolver} is configured or not, either detected from an * {@code ApplicationContext} or explicitly configured via {@link #localeContextResolver}. * @since 5.0.9 */ public boolean hasLocaleContextResolver() { return (this.localeContextResolver != null); } /** * Configure the {@link ForwardedHeaderTransformer} for extracting and/or * removing forwarded headers. * @param transformer the transformer * @since 5.1 */ public WebHttpHandlerBuilder forwardedHeaderTransformer(ForwardedHeaderTransformer transformer) { this.forwardedHeaderTransformer = transformer; return this; } /** * Whether a {@code ForwardedHeaderTransformer} is configured or not, either * detected from an {@code ApplicationContext} or explicitly configured via * {@link #forwardedHeaderTransformer(ForwardedHeaderTransformer)}. * @since 5.1 */ public boolean hasForwardedHeaderTransformer() { return (this.forwardedHeaderTransformer != null); } /** * Configure an {@link ObservationRegistry} for recording server exchange observations. * By default, a {@link ObservationRegistry#NOOP no-op} registry will be configured. * @param observationRegistry the observation registry * @since 6.1 */ public WebHttpHandlerBuilder observationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; return this; } /** * Configure a {@link ServerRequestObservationConvention} to use for server observations. * By default, a {@link DefaultServerRequestObservationConvention} will be used. * @param observationConvention the convention to use for all recorded observations * @since 6.1 */ public WebHttpHandlerBuilder observationConvention(ServerRequestObservationConvention observationConvention) { this.observationConvention = observationConvention; return this; } /** * Configure a {@link Function} to decorate the {@link HttpHandler} returned * by this builder which effectively wraps the entire * {@link WebExceptionHandler} - {@link WebFilter} - {@link WebHandler} * processing chain. This provides access to the request and response before * the entire chain and likewise the ability to observe the result of * the entire chain. * @param handlerDecorator the decorator to apply * @since 5.3 */ public WebHttpHandlerBuilder httpHandlerDecorator(Function<HttpHandler, HttpHandler> handlerDecorator) { this.httpHandlerDecorator = (this.httpHandlerDecorator != null ? handlerDecorator.andThen(this.httpHandlerDecorator) : handlerDecorator); return this; } /** * Whether a decorator for {@link HttpHandler} is configured or not via * {@link #httpHandlerDecorator(Function)}. * @since 5.3 */ public boolean hasHttpHandlerDecorator() { return (this.httpHandlerDecorator != null); } /** * Build the {@link HttpHandler}. */ public HttpHandler build() { WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters); decorated = new ExceptionHandlingWebHandler(decorated, this.exceptionHandlers); HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated); if (this.sessionManager != null) { adapted.setSessionManager(this.sessionManager); } if (this.codecConfigurer != null) { adapted.setCodecConfigurer(this.codecConfigurer); } if (this.localeContextResolver != null) { adapted.setLocaleContextResolver(this.localeContextResolver); } if (this.forwardedHeaderTransformer != null) { adapted.setForwardedHeaderTransformer(this.forwardedHeaderTransformer); } if (this.observationRegistry != null) { adapted.setObservationRegistry(this.observationRegistry); } if (this.observationConvention != null) { adapted.setObservationConvention(this.observationConvention); } if (this.applicationContext != null) { adapted.setApplicationContext(this.applicationContext); } adapted.afterPropertiesSet(); return (this.httpHandlerDecorator != null ? this.httpHandlerDecorator.apply(adapted) : adapted); } /** * Clone this {@link WebHttpHandlerBuilder}. * @return the cloned builder instance */ @Override public WebHttpHandlerBuilder clone() { return new WebHttpHandlerBuilder(this); } /** * {@code BlockHoundIntegration} for spring-web classes. * @since 5.3.6 */ public static class SpringWebBlockHoundIntegration implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { // Avoid hard references potentially anywhere in spring-web (no need for structural dependency) builder.allowBlockingCallsInside("org.springframework.http.MediaTypeFactory", "<clinit>"); builder.allowBlockingCallsInside("org.springframework.web.util.HtmlUtils", "<clinit>"); } } }
package com.flipkart.DAO; import java.util.List; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.flipkart.model.Course; import com.flipkart.model.Student; import org.apache.log4j.Logger; import com.flipkart.constants.SQLConstantsQuery; import com.flipkart.utils.DBUtil; public class CatalogDaoImpl implements CatalogDao { private static Logger logger= Logger.getLogger(CatalogDaoImpl.class); //View Catalog @Override public List<Course> viewCatalog() { // TODO Auto-generated method stub List <Course> courseList=new ArrayList<>(); Connection connect=DBUtil.getConnection(); try { String sql=SQLConstantsQuery.VIEW_CATALOG; PreparedStatement stmt = connect.prepareStatement(sql); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ int courseId= rs.getInt("courseId"); String courseName = rs.getString("courseName"); //logger.info("ID: " + courseId + ", Name: " + courseName); Course course=new Course(); course.courseId=courseId; course.courseName=courseName; courseList.add(course); } return courseList; } catch (SQLException e) { logger.error(e.getMessage()); } return null; } }
package loecraftpack.common.entity.render; import loecraftpack.common.entity.EntityPedestal; import net.minecraft.client.model.ModelSkeletonHead; import net.minecraft.client.renderer.ImageBufferDownload; import net.minecraft.client.renderer.RenderEngine; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemSkull; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.StringUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class RenderPedestal extends Render { private ModelSkeletonHead field_82396_c = new ModelSkeletonHead(0, 0, 64, 32); private ModelSkeletonHead field_82395_d = new ModelSkeletonHead(0, 0, 64, 64);//zombie public void doRenderPedestal(EntityPedestal entity, double d0, double d1, double d2, float f, float f1) { GL11.glPushMatrix(); renderItem(entity, entity.boundingBox, d0, d1, d2); this.loadTexture(entity.getTexture()); renderStand(entity.boundingBox, d0 - entity.lastTickPosX, d1 - entity.lastTickPosY, d2 - entity.lastTickPosZ); GL11.glPopMatrix(); } public void renderItem(EntityPedestal entity, AxisAlignedBB par0AxisAlignedBB, double xPos, double yPos, double zPos) { ItemStack itemstack = entity.getDisplayedItem(); if (itemstack != null) { if (itemstack.getItem() instanceof ItemSkull) { ItemSkull item = (ItemSkull)itemstack.getItem(); this.renderSkull(entity, (float)xPos, (float)yPos, (float)zPos, itemstack.getItemDamage(), entity.name); return; } EntityItem entityitem = new EntityItem(entity.worldObj, xPos, yPos, zPos, itemstack); entityitem.getEntityItem().stackSize = 1; entityitem.hoverStart = 0.0F; GL11.glPushMatrix(); { //apply coords GL11.glTranslatef((float)xPos, (float)yPos+0.5625f/*9 pixels*/, (float)zPos); GL11.glPushMatrix(); { applyDisplayMode(entity); //apply centering of item GL11.glTranslatef(0.0F, -0.125F/*2 pixels*/, 0.0F); RenderItem.renderInFrame = true; RenderManager.instance.renderEntityWithPosYaw(entityitem, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F); RenderItem.renderInFrame = false; } GL11.glPopMatrix(); } GL11.glPopMatrix(); } } public void renderSkull(EntityPedestal entity, float xPos, float yPos, float zPos, int type, String playerName) { ModelSkeletonHead modelskeletonhead = this.field_82396_c; switch (type) { case 0: default: this.loadTexture("/mob/skeleton.png"); break; case 1: this.loadTexture("/mob/skeleton_wither.png"); break; case 2: this.loadTexture("/mob/zombie.png"); modelskeletonhead = this.field_82395_d; break; case 3: if (playerName != null && playerName.length() > 0) { String s1 = "http://skins.minecraft.net/MinecraftSkins/" + StringUtils.stripControlCodes(playerName) + ".png"; if (!this.renderManager.renderEngine.hasImageData(s1)) { this.renderManager.renderEngine.obtainImageData(s1, new ImageBufferDownload()); } this.bindTextureByURL(s1, "/mob/char.png"); } else { this.loadTexture("/mob/char.png"); } break; case 4: this.loadTexture("/mob/creeper.png"); } GL11.glPushMatrix(); { GL11.glDisable(GL11.GL_CULL_FACE); GL11.glTranslatef(xPos, yPos + 0.5F/*8 pixels*/, zPos); GL11.glPushMatrix(); { applyDisplayMode(entity); float f4 = 0.0625F; GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glScalef(0.8F, -0.8F, -0.8F); modelskeletonhead.render((Entity)null, 0.0F, 0.0F, 0.0F, 0, 0.0F, f4); } GL11.glPopMatrix(); GL11.glEnable(GL11.GL_CULL_FACE); } GL11.glPopMatrix(); } public void applyDisplayMode(EntityPedestal entity) { //apply rotations switch(entity.getDisplayMode()) { case 0://static GL11.glRotatef((float)entity.getDisplayAngle(), 0.0F, 1.0F, 0.0F); break; case 1://slow rotate GL11.glRotatef((float)entity.getDisplayAngle(), 0.0F, 1.0F, 0.0F); GL11.glRotatef(-10, 1.0F, 0.0F, 0.0F); GL11.glRotatef(-5, 0.0F, 0.0F, 1.0F); break; case 2://follow closest player GL11.glRotatef((float)entity.getDisplayAngle(), 0.0F, 1.0F, 0.0F); GL11.glRotatef((float)entity.getDisplayAngleSub(), 1.0F, 0.0F, 0.0F); break; } } /** * Binds a texture that Minecraft will attempt to load from the given URL. (arguments: url, localFallback) */ protected void bindTextureByURL(String par1Str, String par2Str) { RenderEngine renderengine = this.renderManager.renderEngine; if (renderengine != null) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, renderengine.getTextureForDownloadableImage(par1Str, par2Str)); } renderengine.resetBoundTexture(); } public void renderStand(AxisAlignedBB par0AxisAlignedBB, double xPos, double yPos, double zPos) { Tessellator tessellator = Tessellator.instance; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); double minX = par0AxisAlignedBB.minX; double maxX = par0AxisAlignedBB.maxX; double minY = par0AxisAlignedBB.minY; double maxY = par0AxisAlignedBB.minY + 0.1875d; double minZ = par0AxisAlignedBB.minZ; double maxZ = par0AxisAlignedBB.maxZ; /** * side top */ float minU = 0.0625f; float maxU = 0.4375F; float minV = 0.5625f; float maxV = 0.9375f; tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 1.0F, 0.0F); tessellator.addVertexWithUV(maxX, maxY, maxZ, maxU, minV); tessellator.addVertexWithUV(maxX, maxY, minZ, minU, minV); tessellator.addVertexWithUV(minX, maxY, minZ, minU, maxV); tessellator.addVertexWithUV(minX, maxY, maxZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * side bottom */ minU = 0.5625f; maxU = 0.9375f; minV = 0.5625f; maxV = 0.9375f; tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, -1.0F, 0.0F); tessellator.addVertexWithUV(minX, minY, maxZ, maxU, minV); tessellator.addVertexWithUV(minX, minY, minZ, minU, minV); tessellator.addVertexWithUV(maxX, minY, minZ, minU, maxV); tessellator.addVertexWithUV(maxX, minY, maxZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * side west */ minU = 0.5625f; maxU = 0.9375f; minV = 0.40625f; maxV = 0.5f; tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(-1.0F, 0.0F, 0.0F); tessellator.addVertexWithUV(minX, maxY, maxZ, maxU, minV); tessellator.addVertexWithUV(minX, maxY, minZ, minU, minV); tessellator.addVertexWithUV(minX, minY, minZ, minU, maxV); tessellator.addVertexWithUV(minX, minY, maxZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * side north */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 0.0F, -1.0F); tessellator.addVertexWithUV(minX, maxY, minZ, maxU, minV); tessellator.addVertexWithUV(maxX, maxY, minZ, minU, minV); tessellator.addVertexWithUV(maxX, minY, minZ, minU, maxV); tessellator.addVertexWithUV(minX, minY, minZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * side east */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(1.0F, 0.0F, 0.0F); tessellator.addVertexWithUV(maxX, maxY, minZ, maxU, minV); tessellator.addVertexWithUV(maxX, maxY, maxZ, minU, minV); tessellator.addVertexWithUV(maxX, minY, maxZ, minU, maxV); tessellator.addVertexWithUV(maxX, minY, minZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * side south */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 0.0F, 1.0F); tessellator.addVertexWithUV(maxX, maxY, maxZ, maxU, minV); tessellator.addVertexWithUV(minX, maxY, maxZ, minU, minV); tessellator.addVertexWithUV(minX, minY, maxZ, minU, maxV); tessellator.addVertexWithUV(maxX, minY, maxZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * * GLOW * */ GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_SRC_ALPHA); minX = par0AxisAlignedBB.minX + 0.125d; maxX = par0AxisAlignedBB.maxX - 0.125d; minY = par0AxisAlignedBB.minY + 0.1875d; maxY = par0AxisAlignedBB.minY + 0.5d; minZ = par0AxisAlignedBB.minZ + 0.125d; maxZ = par0AxisAlignedBB.maxZ - 0.125d; minU = 0.125f; maxU = 0.375F; minV = 0.34375f; maxV = 0.5f; /** * * INNER GLOW * */ /** * glow west */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(-1.0F, 0.0F, 0.0F); tessellator.addVertexWithUV(minX, minY, maxZ, maxU, minV); tessellator.addVertexWithUV(minX, minY, minZ, minU, minV); tessellator.addVertexWithUV(minX, maxY, minZ, minU, maxV); tessellator.addVertexWithUV(minX, maxY, maxZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * glow north */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 0.0F, -1.0F); tessellator.addVertexWithUV(minX, minY, minZ, maxU, minV); tessellator.addVertexWithUV(maxX, minY, minZ, minU, minV); tessellator.addVertexWithUV(maxX, maxY, minZ, minU, maxV); tessellator.addVertexWithUV(minX, maxY, minZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * glow east */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(1.0F, 0.0F, 0.0F); tessellator.addVertexWithUV(maxX, minY, minZ, maxU, minV); tessellator.addVertexWithUV(maxX, minY, maxZ, minU, minV); tessellator.addVertexWithUV(maxX, maxY, maxZ, minU, maxV); tessellator.addVertexWithUV(maxX, maxY, minZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * glow south */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 0.0F, 1.0F); tessellator.addVertexWithUV(maxX, minY, maxZ, maxU, minV); tessellator.addVertexWithUV(minX, minY, maxZ, minU, minV); tessellator.addVertexWithUV(minX, maxY, maxZ, minU, maxV); tessellator.addVertexWithUV(maxX, maxY, maxZ, maxU, maxV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * * OUTTER GLOW * */ /** * glow west */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(-1.0F, 0.0F, 0.0F); tessellator.addVertexWithUV(minX, maxY, maxZ, maxU, maxV); tessellator.addVertexWithUV(minX, maxY, minZ, minU, maxV); tessellator.addVertexWithUV(minX, minY, minZ, minU, minV); tessellator.addVertexWithUV(minX, minY, maxZ, maxU, minV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * glow north */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 0.0F, -1.0F); tessellator.addVertexWithUV(minX, maxY, minZ, maxU, maxV); tessellator.addVertexWithUV(maxX, maxY, minZ, minU, maxV); tessellator.addVertexWithUV(maxX, minY, minZ, minU, minV); tessellator.addVertexWithUV(minX, minY, minZ, maxU, minV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * glow east */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(1.0F, 0.0F, 0.0F); tessellator.addVertexWithUV(maxX, maxY, minZ, maxU, maxV); tessellator.addVertexWithUV(maxX, maxY, maxZ, minU, maxV); tessellator.addVertexWithUV(maxX, minY, maxZ, minU, minV); tessellator.addVertexWithUV(maxX, minY, minZ, maxU, minV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); /** * glow south */ tessellator.startDrawingQuads(); tessellator.setTranslation(xPos, yPos, zPos); tessellator.setNormal(0.0F, 0.0F, 1.0F); tessellator.addVertexWithUV(maxX, maxY, maxZ, maxU, maxV); tessellator.addVertexWithUV(minX, maxY, maxZ, minU, maxV); tessellator.addVertexWithUV(minX, minY, maxZ, minU, minV); tessellator.addVertexWithUV(maxX, minY, maxZ, maxU, minV); tessellator.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); GL11.glDisable(GL11.GL_BLEND); } @Override public void doRender(Entity entity, double d0, double d1, double d2, float f, float f1) { doRenderPedestal((EntityPedestal)entity, d0, d1, d2, f, f1); } }
package pt.utl.ist.bw.exceptions; @SuppressWarnings("serial") public class WrongConditionException extends Exception { }
package com.stokkur.exam.demoAccounts.model; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.Entity; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.sql.Timestamp; @Entity public class LogsHistory { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(nullable=false) private String ip; @Column(nullable=false) private String data; @CreationTimestamp private java.sql.Timestamp create_time; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getData() { return data; } public void setData(String data) { this.data = data; } public Timestamp getCreate_time() { return create_time; } public void setCreate_time(Timestamp create_time) { this.create_time = create_time; } }
package main.java; import Jama.Matrix; /** * TODO */ public class LinearRegression extends Model { /** * TODO * * @param x predictor training data * @param y target training data */ @Override public void fit( Matrix x, Matrix y ) { System.out.println( "Not yet implemented." ); } /** * TODO * * @param x predictor data * @return */ @Override public Matrix predict( Matrix x ) { System.out.println( "Not yet implemented." ); return new Matrix( 1, 1 ); } /** * TODO * * @param x predictor test data * @param y target test data * @return */ @Override public double score( Matrix x, Matrix y ) { System.out.println( "Not yet implemented." ); return 0; } }
/** * Bitonic Array Maximum (easy) Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1]. Input: [1, 3, 8, 12, 4, 2] Output: 12 Explanation: The maximum number in the input bitonic array is '12'. Input: [3, 8, 3, 1] Output: 8 Input: [1, 3, 8, 12] Output: 12 Input: [10, 9, 8] Output: 10 */ class MaxInBitonicArray { public static int findMax(int[] arr) { int start = 0, end = arr.length - 1; // 左闭右开区间 while (start < end) { int mid = start + (end - start) / 2; if (arr[mid] > arr[mid + 1]) { end = mid; } else if (arr[mid] <= arr[mid + 1]){ start = mid + 1; } } //结束条件 left = right return arr[start]; } public static void main(String[] args) { System.out.println(MaxInBitonicArray.findMax(new int[] { 1, 3, 8, 12, 4, 2 })); System.out.println(MaxInBitonicArray.findMax(new int[] { 3, 8, 3, 1 })); System.out.println(MaxInBitonicArray.findMax(new int[] { 1, 3, 8, 12 })); System.out.println(MaxInBitonicArray.findMax(new int[] { 10, 9, 8 })); } }
/** * Copyright (C) 2014-2017 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.commons.charset; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.util.SortedMap; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.CodingStyleguideUnaware; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.PresentForCodeCoverage; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.collection.ext.CommonsLinkedHashMap; import com.helger.commons.collection.ext.ICommonsOrderedMap; import com.helger.commons.string.StringHelper; /** * Whole lotta charset management routines. * * @author Philip Helger */ @Immutable public final class CharsetManager { @CodingStyleguideUnaware private static final SortedMap <String, Charset> s_aAllCharsets; static { // Returns an immutable object s_aAllCharsets = Charset.availableCharsets (); } @PresentForCodeCoverage private static final CharsetManager s_aInstance = new CharsetManager (); private CharsetManager () {} /** * Resolve the charset by the specified name. The difference to * {@link Charset#forName(String)} is, that this method has no checked * exceptions but only unchecked exceptions. * * @param sCharsetName * The charset to be resolved. May neither be <code>null</code> nor * empty. * @return The Charset object * @throws IllegalArgumentException * If the charset could not be resolved. */ @Nonnull public static Charset getCharsetFromName (@Nonnull @Nonempty final String sCharsetName) { try { return Charset.forName (sCharsetName); } catch (final IllegalCharsetNameException ex) { // Not supported in any version throw new IllegalArgumentException ("Charset '" + sCharsetName + "' unsupported in Java", ex); } catch (final UnsupportedCharsetException ex) { // Unsupported on this platform throw new IllegalArgumentException ("Charset '" + sCharsetName + "' unsupported on this platform", ex); } } /** * Resolve the charset by the specified name. The difference to * {@link Charset#forName(String)} is, that this method throws no exceptions. * * @param sCharsetName * The charset to be resolved. May be <code>null</code> or empty. * @return The Charset object or <code>null</code> if no such charset was * found. */ @Nullable public static Charset getCharsetFromNameOrNull (@Nullable final String sCharsetName) { if (StringHelper.hasText (sCharsetName)) try { return getCharsetFromName (sCharsetName); } catch (final IllegalArgumentException ex) { // Fall through } return null; } /** * @return An immutable collection of all available charsets from the standard * charset provider. */ @Nonnull @ReturnsMutableCopy public static ICommonsOrderedMap <String, Charset> getAllCharsets () { return new CommonsLinkedHashMap<> (s_aAllCharsets); } @Nonnull @ReturnsMutableCopy public static byte [] getAsBytes (@Nonnull final String sText, @Nonnull final Charset aCharset) { ValueEnforcer.notNull (sText, "Text"); ValueEnforcer.notNull (aCharset, "Charset"); ValueEnforcer.isTrue (aCharset.canEncode (), () -> "Cannot encode to " + aCharset); return sText.getBytes (aCharset); } @Nullable public static String getAsStringInOtherCharset (@Nullable final String sText, @Nonnull final Charset aCurrentCharset, @Nonnull final Charset aNewCharset) { ValueEnforcer.notNull (aCurrentCharset, "CurrentCharset"); ValueEnforcer.notNull (aNewCharset, "NewCharset"); if (sText == null || aCurrentCharset.equals (aNewCharset)) return sText; return getAsString (getAsBytes (sText, aCurrentCharset), aNewCharset); } @Nonnull public static String getAsString (@Nonnull final byte [] aBuffer, @Nonnull final Charset aCharset) { ValueEnforcer.notNull (aBuffer, "Buffer"); return getAsString (aBuffer, 0, aBuffer.length, aCharset); } @Nonnull public static String getAsString (@Nonnull final byte [] aBuffer, @Nonnegative final int nOfs, @Nonnegative final int nLength, @Nonnull final Charset aCharset) { ValueEnforcer.isArrayOfsLen (aBuffer, nOfs, nLength); ValueEnforcer.notNull (aCharset, "Charset"); return new String (aBuffer, nOfs, nLength, aCharset); } /** * Get the number of bytes necessary to represent the passed string as an * UTF-8 string. * * @param s * The string to count the length. May be <code>null</code> or empty. * @return A non-negative value. */ @Nonnegative public static int getUTF8ByteCount (@Nullable final String s) { return s == null ? 0 : getUTF8ByteCount (s.toCharArray ()); } /** * Get the number of bytes necessary to represent the passed char array as an * UTF-8 string. * * @param aChars * The characters to count the length. May be <code>null</code> or * empty. * @return A non-negative value. */ @Nonnegative public static int getUTF8ByteCount (@Nullable final char [] aChars) { int nCount = 0; if (aChars != null) for (final char c : aChars) nCount += getUTF8ByteCount (c); return nCount; } @Nonnegative public static int getUTF8ByteCount (final char c) { return getUTF8ByteCount ((int) c); } /** * Get the number of bytes necessary to represent the passed character. * * @param c * The character to be evaluated. * @return A non-negative value. */ @Nonnegative public static int getUTF8ByteCount (@Nonnegative final int c) { ValueEnforcer.isBetweenInclusive (c, "c", Character.MIN_VALUE, Character.MAX_VALUE); // see JVM spec 4.4.7, p 111 // http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html // #1297 if (c == 0) return 2; // Source: http://icu-project.org/apiref/icu4c/utf8_8h_source.html if (c <= 0x7f) return 1; if (c <= 0x7ff) return 2; if (c <= 0xd7ff) return 3; // It's a surrogate... return 0; } }
package com.tensquare.user; import java.math.BigDecimal; public class test { public static void main(String[] args) { BigDecimal decimal=new BigDecimal("4.00000"); //decimal=decimal.add(new BigDecimal("3").multiply(new BigDecimal(4))).subtract(new BigDecimal("1")).setScale(3,BigDecimal.ROUND_UP); decimal=decimal.add(new BigDecimal("0.002")); System.out.println(new BigDecimal("12").compareTo(new BigDecimal("11"))); } }
package controlador; import Juego.DragonAlgoBall; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Label; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import modelo.Personaje; import modelo.excepciones.TransformacionInvalida; import modelo.turnos.Turno; import vista.ContenedorPrincipal; public class BotonTransformarHandler implements EventHandler<ActionEvent> { private Turno turno; private ContenedorPrincipal contenedor; public BotonTransformarHandler(DragonAlgoBall juego,ContenedorPrincipal contenedor) { this.contenedor = contenedor; this.turno = juego.getTurnoActual(); } @Override public void handle(ActionEvent actionEvent) { try{ turno.elegirPersonajeEvolucionar(); Personaje personajeEvolucionar = turno.getPersonajeAEvolucionar(); personajeEvolucionar.transformar(); contenedor.actualizarBotones(turno); Label etiqueta = new Label(); etiqueta.setText(personajeEvolucionar.getNombre() +" se transformo a su nueva fase checkear stats"); etiqueta.setFont(Font.font("courier new", FontWeight.SEMI_BOLD, 14)); etiqueta.setTextFill(Color.WHITE); this.contenedor.actualizarConsola(etiqueta); } catch (TransformacionInvalida p){ contenedor.actualizarBotones(turno); Label etiqueta = new Label(); etiqueta.setText("Transformacion invalida"); etiqueta.setFont(Font.font("courier new", FontWeight.SEMI_BOLD, 14)); etiqueta.setTextFill(Color.WHITE); this.contenedor.actualizarConsola(etiqueta); } } }
package riseapps.com.firstlesson; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import java.util.ArrayList; import java.util.List; public class SecondTask extends AppCompatActivity { private static final String TAG = "MyTag"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_task); final List<String> strings = new ArrayList<>(); final EditText editText = findViewById(R.id.editText); final View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.clear_two: Log.d(TAG, "Clear button is pressed"); if (strings.size() < 5) { strings.add(editText.getText().toString()); } else { strings.remove(0); strings.add(editText.getText().toString()); } editText.setText(""); break; case R.id.restore: Log.d(TAG, "Restore button is pressed"); if (strings.size() > 0) { editText.setText(strings.get(strings.size() - 1)); strings.remove(strings.size() - 1); } break; } } }; editText.setOnClickListener(listener); findViewById(R.id.clear_two).setOnClickListener(listener); findViewById(R.id.restore).setOnClickListener(listener); } }
package View; import java.util.HashMap; import javafx.scene.layout.Pane; public interface MainViewInterface extends ViewInterface { void changeView(WindowType type); void setUser(UserType userRole); }
package com.zemoso.training.exception; import org.springframework.http.HttpStatus; public class ApiErrorResponse { private HttpStatus httpStatus; private String errorMessage; private String details; public ApiErrorResponse(){ super(); } public ApiErrorResponse(HttpStatus httpStatus, String message, String details) { super(); this.httpStatus = httpStatus; this.errorMessage = message; this.details = details; } public HttpStatus getHttpStatus() { return httpStatus; } public void setHttpStatus(HttpStatus httpStatus) { this.httpStatus = httpStatus; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } }
package com.madrapps.dagger.models; import javax.inject.Inject; public class Highways implements Road { @Inject Highways(Car car1, Car car2) { } }
package com.uit.huydaoduc.hieu.chi.hhapp.Main; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.afollestad.materialdialogs.MaterialDialog; import com.uit.huydaoduc.hieu.chi.hhapp.Define; import com.uit.huydaoduc.hieu.chi.hhapp.Framework.ImageUtils; import com.uit.huydaoduc.hieu.chi.hhapp.Model.User.UserInfo; import com.uit.huydaoduc.hieu.chi.hhapp.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.io.IOException; import java.util.Objects; import cn.bingoogolapple.titlebar.BGATitleBar; import de.hdodenhof.circleimageview.CircleImageView; public class AboutUser extends AppCompatActivity { private static final int GET_IMG_FROM_STORAGE_REQUEST_CODE = 0; private static final int GET_IMG_FROM_CAMERA_REQUEST_CODE = 1; CircleImageView circleEditView; RelativeLayout group_profile_image; public TextView txtPhoneNumber, tv_error; EditText et_NameUser; EditText et_Yob; public static String phone = ""; public static String name = ""; private DatabaseReference dbRefe; BGATitleBar titleBar; CircleImageView circleImageView; UserInfo userInfo; private String getCurUid() { return FirebaseAuth.getInstance().getCurrentUser().getUid(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_user); userInfo = CurUserInfo.getInstance().getUserInfo(); Init(); titleBar.setDelegate(new BGATitleBar.Delegate() { @Override public void onClickLeftCtv() { finish(); } @Override public void onClickTitleCtv() { } @Override public void onClickRightCtv() { showLoadingDialog(getString(R.string.loading_saving)); if (TextUtils.isEmpty(et_NameUser.getText().toString()) || TextUtils.isEmpty(et_Yob.getText().toString())) { tv_error.setVisibility(View.VISIBLE); tv_error.setText(R.string.input_info_request); return; } userInfo.setName(et_NameUser.getText().toString()); userInfo.setYearOfBirth(et_Yob.getText().toString()); dbRefe.child(Define.DB_USERS_INFO) .child(getCurUid()) .setValue(userInfo) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { hideLoadingDialog(); CurUserInfo.getInstance().setUserInfo(userInfo); AboutUser.this.setResult(Activity.RESULT_OK); AboutUser.this.finish(); } else { onClickRightCtv(); } } }); } @Override public void onClickRightSecondaryCtv() { } }); et_NameUser.setText(userInfo.getName()); et_Yob.setText(userInfo.getYearOfBirth()); // avatar if (userInfo.getPhoto() != null) { Bitmap bitmap = ImageUtils.base64ToBitmap(userInfo.getPhoto()); circleImageView.setImageBitmap(bitmap); } // Import avatar from Camera or Storage final String[] items = new String[]{"From SD Card", "From Camera"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Image"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { dialog.dismiss(); Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); AboutUser.this.startActivityForResult(pickPhoto, GET_IMG_FROM_STORAGE_REQUEST_CODE); } else { dialog.dismiss(); Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePicture, GET_IMG_FROM_CAMERA_REQUEST_CODE); // checkPermission(); } } }); final AlertDialog dialog = builder.create(); group_profile_image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.show(); } }); } public void Init() { titleBar = (BGATitleBar) findViewById(R.id.titlebar); txtPhoneNumber = findViewById(R.id.txtPhoneEditAcc); tv_error = findViewById(R.id.tv_error); et_NameUser = findViewById(R.id.et_NameUser); et_Yob = findViewById(R.id.et_Yob); circleImageView = findViewById(R.id.profile_image); circleEditView = findViewById(R.id.profile_edit); group_profile_image = findViewById(R.id.group_profile_image); dbRefe = FirebaseDatabase.getInstance().getReference(); phone = userInfo.getPhoneNumber(); name = userInfo.getName(); txtPhoneNumber.setText(phone); et_NameUser.setText(name); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case GET_IMG_FROM_STORAGE_REQUEST_CODE: if (resultCode == RESULT_OK) { Uri uri = data.getData(); circleImageView.setImageURI(uri); String base64Photo = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { base64Photo = ImageUtils.bitmapToBase64(ImageUtils.uriToBitmap(AboutUser.this.getContentResolver(), uri)); // base64Photo = ImageUtils.bitmapToBase64(ImageUtils.compressImage(AboutUser.this.getContentResolver(), uri.toString())); } else { base64Photo = ImageUtils.bitmapToBase64(ImageUtils.compressImage(AboutUser.this.getContentResolver(), uri.toString())); } userInfo.setPhoto(base64Photo); } break; case GET_IMG_FROM_CAMERA_REQUEST_CODE: { if (resultCode == RESULT_OK) { Bitmap bitmap = (Bitmap) data.getExtras().get("data"); circleImageView.setImageBitmap(bitmap); String base64Photo = ImageUtils.bitmapToBase64(bitmap); userInfo.setPhoto(base64Photo); } break; } } } //region Loading Dialog MaterialDialog loadingPassengerInfo; private void showLoadingDialog(String title) { loadingPassengerInfo = new MaterialDialog.Builder(this) .title(title) .content("Please wait...") .progress(true, 0) .titleColor(getResources().getColor(R.color.title_bar_background_color_blue)) .widgetColorRes(R.color.title_bar_background_color_blue) .buttonRippleColorRes(R.color.title_bar_background_color_blue).show(); } private void hideLoadingDialog() { if (loadingPassengerInfo != null) loadingPassengerInfo.dismiss(); } //endregion }
package king_tokyo_power_up.game.state; import king_tokyo_power_up.game.Game; import king_tokyo_power_up.game.event.EventType; import king_tokyo_power_up.game.card.Target; import king_tokyo_power_up.game.monster.Monster; import king_tokyo_power_up.game.util.Terminal; import java.io.IOException; /** * The end of the current players turn [Requirement 15], this gives an overview of the stats * resets the loop so that StartTurnState changes the current monster to the next. * This state is also responsible for checking the following victory conditions: * - [Requirement 16] First monster to get 20 stars win the king_tokyo_power_up.game * - [Requirement 17] The sole surviving monster wins the king_tokyo_power_up.game (other monsters at 0 or less health) * - [Requirement 18] A monster that reaches 0 or less health is out of the king_tokyo_power_up.game * If any of the victory conditions have been met than the winner is announced and king_tokyo_power_up.game exits. */ public class EndTurnState implements GameState { /** * * @param game the state of the king_tokyo_power_up.game */ @Override public void update(Game game) { Monster monster = game.getCurrent(); monster.notify(game, EventType.END_TURN); Terminal terminal = monster.getTerminal(); terminal.writeString(toString(game)); terminal.writeString("QUERY:ENTER\n"); try { terminal.readString(); } catch(IOException e) { e.printStackTrace(); game.exit(); } checkVictoryConditions(game); game.setState(new StartTurnState()); } /** * Checks the victory conditions based on requirement 16 - 18. * If there is a winner monster then this is announced and the king_tokyo_power_up.game is exited. * @param game the state of the king_tokyo_power_up.game */ public void checkVictoryConditions(Game game) { Monster winner = getWinningMonster(game); if (winner != null) { for (Monster mon : game.getAllMonsters()) { if (winner == mon) { mon.getTerminal().writeString("\n\n\n-- You win! -- \n"); } else { mon.getTerminal().writeString("\n\n\n-- You lose! --\n"); } } game.messageTo("Congratulations to " + winner.getName() + " the " + winner.getType() + "!\nHere is the final result:\n" + game.toString() +"\n", Target.ALL); game.exit(); } } /** * Get the monster who is victorious, if none is null is returned. * @param game the state of the king_tokyo_power_up.game * @return the monster who is winning, null if none */ public Monster getWinningMonster(Game game) { Monster winner = getMonster20Stars(game); if (winner != null) return winner; winner = getLastStandingMonster(game); if (winner != null) return winner; return null; } /** * Get the winning monster with 20 or more stars [Requirement 16]. * If no monster has at least 20 stars then null is returned. * @param game the state of the king_tokyo_power_up.game * @return the monster with 20 or more stars, if none then null is returned */ public Monster getMonster20Stars(Game game) { for (Monster mon : game.getAllMonsters()) { if (mon.getStars() >= 20) { return mon; } } return null; } /** * Get the last standing monster if there are multiple * alive monsters then null is returned [Requirement 17]. * @param game the state of the king_tokyo_power_up.game * @return the last standing monster */ public Monster getLastStandingMonster(Game game) { Monster winner = null; int alive = 0; for (Monster mon : game.getAllMonsters()) { if (isMonsterPlaying(mon)) { alive++; winner = mon; } } if (alive == 1) { return winner; } else { return null; } } /** * Check if a monster is playing i.e. is alive [Requirement 17]. * @param monster the monster to check * @return true if monster is still playing, false otherwise. */ public boolean isMonsterPlaying(Monster monster) { return monster.isAlive(); } @Override public String toString(Game game) { String name = game.getCurrent().getName(); StringBuilder buffer = new StringBuilder(); buffer.append("\n\nIt is the end of your turn. Here are the stats:\n"); buffer.append(game.toString()); buffer.append("Press [ENTER]\n"); return buffer.toString(); } }
package com.sola.webdemo.entity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; @Table(name = "song_r_artist") public class SongArtist { @Id private Long id; @Column(name = "song_id") private Long songId; @Column(name = "artist_id") private Long artistId; @Column(name = "artist_identity_id") private Long artistIdentityId; public SongArtist(Long id, Long songId, Long artistId, Long artistIdentityId) { this.id = id; this.songId = songId; this.artistId = artistId; this.artistIdentityId = artistIdentityId; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getSongId() { return songId; } public void setSongId(Long songId) { this.songId = songId; } public Long getArtistId() { return artistId; } public void setArtistId(Long artistId) { this.artistId = artistId; } public Long getArtistIdentityId() { return artistIdentityId; } public void setArtistIdentityId(Long artistIdentityId) { this.artistIdentityId = artistIdentityId; } }
package com.sunrj.application.ToolClass.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义注解权限校验 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AuthPassport { boolean validate() default true; }
package zw.co.pcz.domain; /** * Created by tdhlakama on 10/17/2015. * Used for Report Purposes */ public class Item { public String name; public int count; }
package com.shahinnazarov.gradle.utils; import com.shahinnazarov.gradle.extensions.DockerFile; import com.shahinnazarov.gradle.extensions.DockerFileConfig; import com.shahinnazarov.gradle.models.DockerStage; import com.shahinnazarov.gradle.models.DockerStageStep; import java.util.*; public class DockerFileContainer { public static DockerFile getForJavaDockerFileForGradle(String appFileName) { DockerFile dockerFile = new DockerFile(); DockerStage stage = new DockerStage(); stage.setFromImage(DockerStage.DockerImages.OPENJDK.getImageWithDefaultVersion()); stage.setBuildLabel("main"); String copyExecutableFileCommand = String.format("COPY /libs/%s /app/application.jar", appFileName); String setWorkDir = "WORKDIR /app"; String executeJar = "ENTRYPOINT exec java $JAVA_OPTS -jar application.jar"; DockerStageStep step = new DockerStageStep(); step.setSubSteps(Arrays.asList(setWorkDir, copyExecutableFileCommand, executeJar)); stage.setSteps(Arrays.asList(step)); dockerFile.setStages(Arrays.asList(stage)); dockerFile.setDefaultFileName("Dockerfile"); return dockerFile; } public static DockerFile getConfiguredDockerFile(DockerFileConfig dockerFileConfig, String appFileName) { DockerFile dockerFile = new DockerFile(); String image = DockerStage.DockerImages.OPENJDK.getImageWithDefaultVersion(); if(dockerFileConfig.getImage() != null) { image = dockerFileConfig.getImage(); } String buildLabel = "main"; if(dockerFileConfig.getBuildLabel() != null) { buildLabel = dockerFileConfig.getBuildLabel(); } String workDir = "/app"; if(dockerFileConfig.getWorkDir() != null) { workDir = dockerFileConfig.getWorkDir(); } String args = "$JAVA_OPTS"; if(dockerFileConfig.getArgs() != null) { args = dockerFileConfig.getArgs(); } String dockerFileName = "Dockerfile"; if(dockerFileConfig.getOutputFileName() != null) { dockerFileName = dockerFileConfig.getOutputFileName(); } DockerStage stage = new DockerStage(); stage.setFromImage(image); stage.setBuildLabel(buildLabel); List<String> subSteps = new ArrayList<>(); subSteps.add(String.format("COPY /libs/%s %s/application.jar", appFileName, workDir)); subSteps.add(String.format("WORKDIR %s", workDir)); if(dockerFileConfig.getRunAsUser() != null) { String runAsUser = dockerFileConfig.getRunAsUser(); String runInGroup = runAsUser; if(dockerFileConfig.getRunInGroup() != null) { runInGroup = dockerFileConfig.getRunInGroup(); } int runAsUserId = 1000; if(dockerFileConfig.getRunAsUserId() != null) { runAsUserId = dockerFileConfig.getRunAsUserId(); } int runInGroupId = runAsUserId; if(dockerFileConfig.getRunInGroupId() != null) { runInGroupId = dockerFileConfig.getRunInGroupId(); } subSteps.add(String.format( "RUN addgroup -g %d %s && \\\n" + " adduser -D -u %d -G %s %s", runInGroupId, runInGroup, runAsUserId, runInGroup, runAsUser )); subSteps.add(String.format( "RUN chown -R %s:%s %s", runAsUser, runInGroup, workDir )); subSteps.add(String.format( "USER %s", runAsUser )); } subSteps.add(String.format("ENTRYPOINT exec java %s -jar application.jar", args)); DockerStageStep step = new DockerStageStep(); step.setSubSteps(subSteps); stage.setSteps(Arrays.asList(step)); dockerFile.setStages(Arrays.asList(stage)); dockerFile.setDefaultFileName(dockerFileName); return dockerFile; } }
package realtime.vo; import java.math.BigDecimal; public class JuHeStockVO { private String gid; /* 股票编号 */ private String name; /* 股票名称 */ private Double increPer; /* 涨跌百分比 */ private BigDecimal increase; /* 涨跌额 */ private Double todayStartPri; /* 今日开盘价 */ private Double yestodEndPri; /* 昨日收盘价 */ private Double nowPri; /* 当前价格 */ private Double todayMax; /* 今日最高价 */ private Double todayMin; /* 今日最低价 */ private Double competitivePri; /* 竞买价 */ private Double reservePri; /* 竞卖价 */ private Double traNumber; /* 成交量 */ private Double traAmount; /* 成交金额 */ private Double buyOne; /* 买一 */ private Double buyOnePri; /* 买一报价 */ private Double buyTwo; /* 买二 */ private Double buyTwoPri; /* 买二报价 */ private Double buyThree; /* 买三 */ private Double buyThreePri; /* 买三报价 */ private Double buyFour; /* 买四 */ private Double buyFourPri; /* 买四报价 */ private Double buyFive; /* 买五 */ private Double buyFivePri; /* 买五报价 */ private Double sellOne; /* 卖一 */ private Double sellOnePri; /* 卖一报价 */ private Double sellTwo; /* 卖二 */ private Double sellTwoPri; /* 卖二报价 */ private Double sellThree; /* 卖三 */ private Double sellThreePri; /* 卖三报价 */ private Double sellFour; /* 卖四 */ private Double sellFourPri; /* 卖四报价 */ private Double sellFive; /* 卖五 */ private Double sellFivePri; /* 卖五报价 */ private String date; /* 日期 */ private String time; public String getGid() { return gid; } public void setGid(String gid) { this.gid = gid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getIncrePer() { return increPer; } public void setIncrePer(Double increPer) { this.increPer = increPer; } public Double getTodayStartPri() { return todayStartPri; } public BigDecimal getIncrease() { return increase; } public void setIncrease(BigDecimal increase) { this.increase = increase; } public void setTodayStartPri(Double todayStartPri) { this.todayStartPri = todayStartPri; } public Double getYestodEndPri() { return yestodEndPri; } public void setYestodEndPri(Double yestodEndPri) { this.yestodEndPri = yestodEndPri; } public Double getNowPri() { return nowPri; } public void setNowPri(Double nowPri) { this.nowPri = nowPri; } public Double getTodayMax() { return todayMax; } public void setTodayMax(Double todayMax) { this.todayMax = todayMax; } public Double getTodayMin() { return todayMin; } public void setTodayMin(Double todayMin) { this.todayMin = todayMin; } public Double getCompetitivePri() { return competitivePri; } public void setCompetitivePri(Double competitivePri) { this.competitivePri = competitivePri; } public Double getReservePri() { return reservePri; } public void setReservePri(Double reservePri) { this.reservePri = reservePri; } public Double getTraNumber() { return traNumber; } public void setTraNumber(Double traNumber) { this.traNumber = traNumber; } public Double getTraAmount() { return traAmount; } public void setTraAmount(Double traAmount) { this.traAmount = traAmount; } public Double getBuyOne() { return buyOne; } public void setBuyOne(Double buyOne) { this.buyOne = buyOne; } public Double getBuyOnePri() { return buyOnePri; } public void setBuyOnePri(Double buyOnePri) { this.buyOnePri = buyOnePri; } public Double getBuyTwo() { return buyTwo; } public void setBuyTwo(Double buyTwo) { this.buyTwo = buyTwo; } public Double getBuyTwoPri() { return buyTwoPri; } public void setBuyTwoPri(Double buyTwoPri) { this.buyTwoPri = buyTwoPri; } public Double getBuyThree() { return buyThree; } public void setBuyThree(Double buyThree) { this.buyThree = buyThree; } public Double getBuyThreePri() { return buyThreePri; } public void setBuyThreePri(Double buyThreePri) { this.buyThreePri = buyThreePri; } public Double getBuyFour() { return buyFour; } public void setBuyFour(Double buyFour) { this.buyFour = buyFour; } public Double getBuyFourPri() { return buyFourPri; } public void setBuyFourPri(Double buyFourPri) { this.buyFourPri = buyFourPri; } public Double getBuyFive() { return buyFive; } public void setBuyFive(Double buyFive) { this.buyFive = buyFive; } public Double getBuyFivePri() { return buyFivePri; } public void setBuyFivePri(Double buyFivePri) { this.buyFivePri = buyFivePri; } public Double getSellOne() { return sellOne; } public void setSellOne(Double sellOne) { this.sellOne = sellOne; } public Double getSellOnePri() { return sellOnePri; } public void setSellOnePri(Double sellOnePri) { this.sellOnePri = sellOnePri; } public Double getSellTwo() { return sellTwo; } public void setSellTwo(Double sellTwo) { this.sellTwo = sellTwo; } public Double getSellTwoPri() { return sellTwoPri; } public void setSellTwoPri(Double sellTwoPri) { this.sellTwoPri = sellTwoPri; } public Double getSellThree() { return sellThree; } public void setSellThree(Double sellThree) { this.sellThree = sellThree; } public Double getSellThreePri() { return sellThreePri; } public void setSellThreePri(Double sellThreePri) { this.sellThreePri = sellThreePri; } public Double getSellFour() { return sellFour; } public void setSellFour(Double sellFour) { this.sellFour = sellFour; } public Double getSellFourPri() { return sellFourPri; } public void setSellFourPri(Double sellFourPri) { this.sellFourPri = sellFourPri; } public Double getSellFive() { return sellFive; } public void setSellFive(Double sellFive) { this.sellFive = sellFive; } public Double getSellFivePri() { return sellFivePri; } public void setSellFivePri(Double sellFivePri) { this.sellFivePri = sellFivePri; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
import java.util.Arrays; /** * 二叉堆 */ public class MyBinaryHeap { public static void main(String[] args) throws Exception { MyBinaryHeap maxHeap = new MyBinaryHeap(10); maxHeap.insert(10); maxHeap.insert(4); maxHeap.insert(9); maxHeap.insert(1); maxHeap.insert(7); maxHeap.insert(5); maxHeap.insert(3); System.out.println(Arrays.toString(maxHeap.heap)); maxHeap.delete(5); System.out.println(Arrays.toString(maxHeap.heap)); maxHeap.delete(2); System.out.println(Arrays.toString(maxHeap.heap)); } int[] heap; int heapSize; int childNodeNum=2; public MyBinaryHeap(int capacity) { heap=new int[capacity+1]; heapSize=0; Arrays.fill(heap,-1); } public void insert(int num) throws Exception { if(isFull()){ throw new Exception("Full"); } heap[heapSize]=num; heapSize++; heapifyUp(heapSize-1); } public int delete(int i) throws Exception { if(isEmpty()){ throw new Exception("Empty"); } int ele=heap[i]; heap[i]=heap[heapSize-1]; heapSize--; heapifyDown(i); return ele; } public int findMax() throws Exception { if(isEmpty()){ throw new Exception("Empty"); } return heap[0]; } private void heapifyDown(int i) { int value=heap[i]; while (kthChild(i,1)<heapSize){ int child=maxChild(i); if(heap[i]>=heap[child]){ break; } heap[i]=heap[child]; i=child; } heap[i]=value; } private int maxChild(int i) { int l=kthChild(i,1); int r=kthChild(i,2); return heap[l]>heap[r]?l:r; } private int kthChild(int i,int k) { return childNodeNum*i+k; } private void heapifyUp(int i) { int value=heap[i]; while (i>0&&heap[i]>heap[parent(i)]){ heap[i]=heap[parent(i)]; i=parent(i); } heap[i]=value; } private int parent(int i) { return (i-1)/2; } private boolean isFull(){ return heapSize==heap.length; } private boolean isEmpty(){ return heapSize==0; } }
package be.mxs.common.util.export; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.HTMLEntities; public class ExportMessage { private static final SimpleDateFormat DATEFORMAT = new SimpleDateFormat("yyyyMMddHHmmssSSS"); private Document document; private Date start; public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Document getDocument() { return document; } public void setDocument(Document document) { this.document = document; } public ExportMessage(int days){ long day = 24*3600*1000; this.start=new Date(new Date().getTime()-days*day); } public ExportMessage(Date start) { this.start=start; } public void createExportMessage(){ document = DocumentHelper.createDocument(); Element message = DocumentHelper.createElement("message"); message.addAttribute("serveid", MedwanQuery.getInstance().getConfigString("serverId")); message.addAttribute("servename", MedwanQuery.getInstance().getConfigString("servername")); message.addAttribute("date", DATEFORMAT.format(new Date())); message.addAttribute("start", DATEFORMAT.format(start)); document.setRootElement(message); document.getRootElement().add(addPatients()); } private void addTextElement(Element parent, String name, String text){ if(text!=null && text.trim().length()>0){ Element element = DocumentHelper.createElement(name); element.setText(HTMLEntities.xmlencode(text)); parent.add(element); } } private void addDateElement(Element parent, String name, Date date){ if(date!=null){ Element element = DocumentHelper.createElement(name); element.setText(DATEFORMAT.format(date)); parent.add(element); } } private void addIdElement(Element parent, String type, String text){ if(text!=null && text.trim().length()>0){ Element element = DocumentHelper.createElement("id"); element.addAttribute("type",type); element.setText(text); parent.add(element); } } private Element getPersonElement(ResultSet rs){ Element element = DocumentHelper.createElement("person"); try{ element.addAttribute("updatetime", DATEFORMAT.format(rs.getTimestamp("updatetime"))); addTextElement(element,"lastname", rs.getString("lastname")); addTextElement(element,"firstname", rs.getString("firstname")); addTextElement(element,"middlename", rs.getString("middlename")); addTextElement(element,"gender", rs.getString("gender")); addDateElement(element,"dateofbirth", rs.getDate("dateofbirth")); addTextElement(element,"language", rs.getString("language")); addDateElement(element,"engagement", rs.getDate("engagement")); addDateElement(element,"pension", rs.getDate("pension")); addTextElement(element,"nativecountry", rs.getString("native_country")); addTextElement(element,"nativetown", rs.getString("native_town")); addDateElement(element,"startdate_inactivity", rs.getDate("startdate_inactivity")); addDateElement(element,"enddate_inactivity", rs.getDate("enddate_inactivity")); addTextElement(element,"comment1", rs.getString("comment1")); addTextElement(element,"comment2", rs.getString("comment2")); addTextElement(element,"comment3", rs.getString("comment3")); addTextElement(element,"comment4", rs.getString("comment4")); addTextElement(element,"comment5", rs.getString("comment5")); } catch(Exception e){ e.printStackTrace(); } return element; } private Element getPrivateElement(ResultSet rs){ Element element = DocumentHelper.createElement("private"); try{ element.addAttribute("updatetime", DATEFORMAT.format(rs.getTimestamp("updatetime"))); addDateElement(element,"start", rs.getDate("start")); addDateElement(element,"stop", rs.getDate("stop")); addTextElement(element,"address", rs.getString("address")); addTextElement(element,"city", rs.getString("city")); addTextElement(element,"zipcode", rs.getString("zipcode")); addTextElement(element,"country", rs.getString("country")); addTextElement(element,"telephone", rs.getString("telephone")); addTextElement(element,"fax", rs.getString("fax")); addTextElement(element,"mobile", rs.getString("mobile")); addTextElement(element,"email", rs.getString("email")); addTextElement(element,"comment", rs.getString("comment")); addTextElement(element,"type", rs.getString("type")); addTextElement(element,"district", rs.getString("district")); addTextElement(element,"sanitarydistrict", rs.getString("sanitarydistrict")); addTextElement(element,"province", rs.getString("province")); addTextElement(element,"sector", rs.getString("sector")); addTextElement(element,"cell", rs.getString("cell")); addTextElement(element,"quarter", rs.getString("quarter")); addTextElement(element,"business", rs.getString("business")); addTextElement(element,"businessfunction", rs.getString("businessfunction")); } catch(Exception e){ e.printStackTrace(); } return element; } private Element getAdminIdElement(ResultSet rs){ Element element = DocumentHelper.createElement("ids"); try{ addIdElement(element,"national", rs.getString("natreg")); addIdElement(element,"employer", rs.getString("immatnew")); addIdElement(element,"healthrecord", rs.getString("immatold")); addIdElement(element,"archive", rs.getString("archiveFileCode")); } catch(Exception e){ e.printStackTrace(); } return element; } private Element addPatients(){ int personid; Hashtable patientids = new Hashtable(); Hashtable person = new Hashtable(); Hashtable privatedata = new Hashtable(); Element patients = DocumentHelper.createElement("patients"); //Hier maken we een lijst van alle patiŽnten waarvan gegevens geŽxporteerd moeten kunnen worden Connection conn = MedwanQuery.getInstance().getAdminConnection(); PreparedStatement ps=null; ResultSet rs=null; try{ //We beginnen met de admin tabel ps=conn.prepareStatement("select * from admin where updatetime>=?"); ps.setTimestamp(1, new java.sql.Timestamp(start.getTime())); rs=ps.executeQuery(); while(rs.next()){ personid=rs.getInt("personid"); patientids.put(personid,getAdminIdElement(rs)); person.put(personid, getPersonElement(rs)); } rs.close(); ps.close(); //Dan voegen we de gegevens van de AdminPrivate tabel toe ps=conn.prepareStatement("select * from adminprivate where updatetime>=?"); ps.setTimestamp(1, new java.sql.Timestamp(start.getTime())); rs=ps.executeQuery(); while(rs.next()){ personid=rs.getInt("personid"); if(patientids.get(personid)==null){ patientids.put(personid,DocumentHelper.createElement("ids")); } privatedata.put(personid, getPrivateElement(rs)); } rs.close(); ps.close(); //Nu hebben we alle patiŽnten waarvoor wijzigingen werden aangebracht in de database, we gaan deze exporteren Enumeration ids = patientids.keys(); while (ids.hasMoreElements()){ personid=(Integer)ids.nextElement(); Element patient = DocumentHelper.createElement("patient"); patient.addAttribute("iid", personid+""); //Add ID elements patient.add((Element)patientids.get(personid)); //Add admin element Element admin=DocumentHelper.createElement("admin"); if(person.get(personid)!=null){ admin.add((Element)person.get(personid)); } if(privatedata.get(personid)!=null){ admin.add((Element)privatedata.get(personid)); } patient.add(admin); //Add financial element //Add healthrecord element patients.add(patient); } } catch(Exception e){ e.printStackTrace(); } finally { try{ if(rs!=null && !rs.isClosed()) rs.close(); if(ps!=null && !ps.isClosed()) ps.close(); } catch(Exception e2){ e2.printStackTrace(); } try{ conn.close(); } catch(Exception e2){ e2.printStackTrace(); } } return patients; } }
package com.designpattern.dp6proxypattern.staticproxyPlus; /** * 持久层操作类 */ public class OrderDao { public int insert(Order order){ System.out.println("OrderDao 插入order成功!"); return 1; } }
package com.xiaole.mvc.model.checker.simpleChecker; /** * Created by llc on 17/3/24. */ public class SimpleCheckerFactory { public static CheckSimpleInterface genSimpleChecker(String src) { if (src.equals("xiaole")) { return new XiaoleSimpleChecker(); } else { return new BevaSimpleChecker(); } } }
package com.example.conroller.set; import com.example.model.set.FifthSet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FifthSetHandler extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); int fifthSet = FifthSet.setData(request.getParameter("nationality_id"), request.getParameter("language_id")); request.setAttribute("fifthSet", fifthSet); RequestDispatcher view = request.getRequestDispatcher("result.jsp"); view.forward(request, response); } }
public class WinState implements State { public void doAction(Context context) { System.out.println("Winner winner, chicken dinner!"); context.setState(this); } @Override public String toString(){ return "(Win State)"; } }
package com.maxwell.hrworker.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.maxwell.hrworker.entities.Worker; public interface WorkerRepository extends JpaRepository<Worker, Long> { }
package cal; public class Main { public static void main(String[] args) { JFrameCal jFrameCal = new JFrameCal(); } }
package com.zhicai.byteera.activity.myhome.interfaceview; import android.app.Activity; import android.graphics.Bitmap; import com.zhicai.byteera.activity.bean.ZCUser; /** Created by bing on 2015/7/1. */ public interface ModifyUserInfoActivityIV { Activity getContext(); void setUserInfo(ZCUser userInfo); void setTextNickName(String dialogNickName); void setTextSex(String dialogSex); String getDialogBirtyday(); void setTextBirthday(String dialogBirtyday); void setTextCard(String content); void setTextCity(String content); void setIcon(Bitmap photo); }
package com.turios.activities.fragments; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.Context; import android.database.Cursor; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.ImageButton; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.model.LatLng; import com.turios.R; import com.turios.activities.TuriosActionBarController; import com.turios.activities.fragments.dialog.DialogFragments; import com.turios.activities.fragments.dialog.GenericYesNoDialogFragment.GenericYesNoDialogInterface; import com.turios.activities.util.WakeScreen; import com.turios.dagger.DaggerFragment; import com.turios.dagger.quialifiers.ForActivity; import com.turios.modules.core.DatabaseCoreModule; import com.turios.modules.core.DisplayCoreModule; import com.turios.modules.core.ExpirationCoreModule; import com.turios.modules.core.LocationsCoreModule; import com.turios.modules.core.ParseCoreModule; import com.turios.modules.core.PathsCoreModule; import com.turios.modules.data.AddressHolder; import com.turios.modules.data.HydrantHolder; import com.turios.modules.extend.AccessplansModule; import com.turios.modules.extend.BasisModule; import com.turios.modules.extend.BrowserModule; import com.turios.modules.extend.DirectionsModule; import com.turios.modules.extend.DropboxModule; import com.turios.modules.extend.GoogleMapsModule; import com.turios.modules.extend.GoogleMapsModule.FetchAddressCallback; import com.turios.modules.extend.HydrantsModule; import com.turios.modules.extend.PicklistModule; import com.turios.modules.utils.MapUtils; import com.turios.persistence.MessagesContentProvider; import com.turios.util.Constants; import com.turios.util.Device; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import butterknife.ButterKnife; public class DisplayFragment extends DaggerFragment { protected static final String TAG = DisplayFragment.class.getSimpleName(); public static int NAVIGATION_INDEX = 0; private ScrollView mScrollView; private ViewGroup mContainerView; private View mRootView; private View statusBar; private View visibleStatus; private View hiddenStatus; private View optionsBar; // visible private TextView tvReceived; private TextView tvAutomaticDeleteText; private TextView tvAutomaticDelete; private ImageButton hydrantsButton; private ImageButton routeButton; private ImageButton pdfButton; private ImageButton expandButton; private ProgressDialog progress; @Inject @ForActivity Context context; @Inject FragmentManager fm; @Inject TuriosActionBarController mTuriosActionBar; @Inject ActionBar mActionBar; @Inject MenuInflater mMenuInflater; @Inject LayoutInflater inflater; @Inject WakeScreen wakeScreen; @Inject Device device; @Inject Handler handler; @Inject ParseCoreModule parse; @Inject ExpirationCoreModule expiration; @Inject DatabaseCoreModule database; @Inject PathsCoreModule paths; @Inject DisplayCoreModule display; @Inject LocationsCoreModule locationService; @Inject AccessplansModule accessplansModule; @Inject BasisModule basisModule; @Inject BrowserModule browserModule; @Inject DropboxModule dropboxModule; @Inject GoogleMapsModule googleMapsModule; @Inject DirectionsModule directionsModule; @Inject HydrantsModule hydrantsModule; @Inject PicklistModule picklistModule; // invisible private ViewGroup mContainerhydrantsNearAddress; private long mPageid = -1; private List<String> mEntries; private AddressHolder mAddressHolder; public static DisplayFragment newInstance(int position) { DisplayFragment frag = new DisplayFragment(); Bundle bundle = new Bundle(); bundle.putInt(Constants.EXTRA_MESSAGE, position); frag.setArguments(bundle); return frag; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); } private ScheduledExecutorService exec; private void startDeleteCountdownExec() { shutDownExec(); exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleWithFixedDelay(new Runnable() { @Override public void run() { updateAutomaticDeleteTime(true); } }, 0, 1, TimeUnit.MINUTES); } private void shutDownExec() { if (exec != null && !exec.isTerminated()) { exec.shutdown(); } } @Override public void onCreate(Bundle savedInstanceState) { mEntries = new ArrayList<String>(); super.onCreate(savedInstanceState); } private int hiddenStatusHeight; private int currentStatusBarHeight; private void getStatusBarHeight() { final ViewTreeObserver observer = hiddenStatus.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { hiddenStatus.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); hiddenStatusHeight = hiddenStatus.getMeasuredHeight(); currentStatusBarHeight = statusBar.getHeight(); ViewTreeObserver obs = hiddenStatus.getViewTreeObserver(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { obs.removeOnGlobalLayoutListener(this); } else { obs.removeGlobalOnLayoutListener(this); } } }); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mPageid != -1 && mTuriosActionBar.getSelectedNavigationIndex() == DisplayFragment.NAVIGATION_INDEX || mActionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_STANDARD) { mMenuInflater.inflate(R.menu.menu_display, menu); MenuItem menu_add_time = menu.findItem(R.id.button_add_time); if (!basisModule.getPreferences().isAutomaticDeleteEnabled() || display.isPageDeletionDelayed(mPageid)) { menu_add_time.setVisible(false); } } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.button_remove: DialogFragment dialog = (DialogFragment) fm .findFragmentByTag("fragment_confirm_delete"); final int page = display.getCurrentPageSelected(); if (dialog == null || !dialog.isVisible()) { DialogFragments.deletePage(new GenericYesNoDialogInterface() { @Override public void yesClicked() { display.deletePage(page); } @Override public void noClicked() { } }).show(fm, "fragment_confirm_delete"); } return true; case R.id.button_add_time: display.addPageToDelayList(mPageid); updateAutomaticDeleteTime(false); Toast.makeText(context, context.getString(R.string.page_delete_delayed), Toast.LENGTH_SHORT).show(); getActivity().invalidateOptionsMenu(); return true; } return false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Log.d(TAG, "onCreateView"); this.mRootView = inflater.inflate(R.layout.fragment_display, container, false); ButterKnife.bind(this, mRootView); this.mContainerView = (ViewGroup) mRootView.findViewById(R.id.display); this.mScrollView = (ScrollView) mRootView.findViewById(R.id.scrollview); return mRootView; } @Override public void onViewStateRestored(Bundle savedInstanceState) { Log.d(TAG, "onViewStateRestored"); createStatusBar(); createOptionsBar(); // extract data from database Bundle bundle = getArguments(); int position = bundle.getInt(Constants.EXTRA_MESSAGE); mPageid = display.getPageId(position); Log.d(TAG, "position " + position); Log.d(TAG, "pageId " + mPageid); Cursor messageCursor = database.getPageById(mPageid); if (messageCursor.getCount() == 0) { Log.d(TAG, "page not found in database"); mRootView.findViewById(android.R.id.empty).setVisibility( View.VISIBLE); statusBar.setVisibility(View.GONE); optionsBar.setVisibility(View.GONE); statusBar.setVisibility(View.GONE); mEntries.clear(); } else { // read database Log.d(TAG, "reading database"); messageCursor.moveToNext(); long received = messageCursor.getLong(messageCursor .getColumnIndexOrThrow(MessagesContentProvider.TIMESTAMP)); setTimeReceived(received); String message = messageCursor.getString(messageCursor .getColumnIndexOrThrow(MessagesContentProvider.MESSAGE)); mEntries = display.processEntriesToArray(message); for (String entry : mEntries) { addTextEntry(entry); } } messageCursor.close(); super.onViewStateRestored(savedInstanceState); } @Override public void onDestroyView() { super.onDestroyView(); } private OnClickListener ExpandClickListener = new OnClickListener() { @Override public void onClick(View v) { boolean isExpanded = (Boolean) expandButton .getTag(R.id.TAG_EXPANDED); int originalHeight = (Integer) expandButton .getTag(R.id.TAG_ORIGINAL_HEIGHT); if (isExpanded) { expandButton.setTag(R.id.TAG_EXPANDED, false); expandButton.setImageResource(R.drawable.ic_action_down); // statusBar.setLayoutParams(new FrameLayout.LayoutParams( // LayoutParams.MATCH_PARENT, originalHeight)); Log.d(TAG, "Collapsing to " + originalHeight); ValueAnimator va = ValueAnimator.ofInt(currentStatusBarHeight, originalHeight); va.setDuration(500); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { Integer value = (Integer) animation.getAnimatedValue(); statusBar.getLayoutParams().height = value.intValue(); statusBar.requestLayout(); } }); va.start(); } else { expandButton.setTag(R.id.TAG_EXPANDED, true); expandButton.setImageResource(R.drawable.ic_action_collapse); currentStatusBarHeight = originalHeight + hiddenStatusHeight; // statusBar.setLayoutParams(new FrameLayout.LayoutParams( // LayoutParams.MATCH_PARENT, currentStatusBarHeight + 15)); Log.d(TAG, "Expanding to " + originalHeight + "+" + hiddenStatusHeight + "=" + currentStatusBarHeight); ValueAnimator va = ValueAnimator.ofInt(originalHeight, currentStatusBarHeight); va.setDuration(500); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { Integer value = (Integer) animation.getAnimatedValue(); statusBar.getLayoutParams().height = value.intValue(); statusBar.requestLayout(); } }); va.start(); } } }; private void createStatusBar() { this.tvReceived = (TextView) mRootView .findViewById(R.id.status_time_received); this.tvAutomaticDeleteText = (TextView) mRootView .findViewById(R.id.status_time_delete_relative_text); this.tvAutomaticDelete = (TextView) mRootView .findViewById(R.id.status_time_delete_relative); this.statusBar = mRootView.findViewById(R.id.displayStatusBar); this.visibleStatus = mRootView.findViewById(R.id.status_always_visible); this.mContainerhydrantsNearAddress = (ViewGroup) mRootView .findViewById(R.id.status_hydrants_near_address_container); this.hiddenStatus = mRootView.findViewById(R.id.status_hidden); getStatusBarHeight(); } private void createOptionsBar() { this.optionsBar = mRootView.findViewById(R.id.optionsBar); optionsBar.setVisibility(View.INVISIBLE); createOptionsExpandButton(); createHydrantsButton(); createRouteButton(); createPDFButton(); } private void createOptionsExpandButton() { this.expandButton = (ImageButton) mRootView .findViewById(R.id.button_more); expandButton.setImageResource(R.drawable.ic_action_down); expandButton.setTag(R.id.TAG_EXPANDED, false); expandButton.setTag(R.id.TAG_ORIGINAL_HEIGHT, statusBar.getLayoutParams().height); expandButton.setOnClickListener(ExpandClickListener); setExpandOptionsReady(false); } private void createHydrantsButton() { this.hydrantsButton = (ImageButton) mRootView .findViewById(R.id.button_hydrants); hydrantsButton.setTag(false); setHydrantsReady((mAddressHolder != null && mAddressHolder.isHydrantsNearby())); hydrantsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Log.d(TAG, "hydrantsButton onClick " + device.isMultiPane()); googleMapsModule.clearMap(); if (!device.isMultiPane()) { // select the googlemaps tab mActionBar .setSelectedNavigationItem(GoogleMapFragment.NAVIGATION_INDEX); } hydrantsModule.addHydrantsNearAddress(mAddressHolder, true); } }); } private void createRouteButton() { this.routeButton = (ImageButton) mRootView .findViewById(R.id.button_route); routeButton.setTag(false); setRouteReady(mAddressHolder != null); routeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Log.d(TAG, "routeButton onClick"); googleMapsModule.clearMap(); if (!device.isMultiPane()) { // select the googlemaps tab mActionBar .setSelectedNavigationItem(GoogleMapFragment.NAVIGATION_INDEX); } directionsModule.addDirectionsToMap(mAddressHolder); } }); } private void createPDFButton() { this.pdfButton = (ImageButton) mRootView.findViewById(R.id.button_pdf); pdfButton.setTag(""); setPdfReady(false, ""); pdfButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { progress = new ProgressDialog(getActivity()); progress.setMessage(getString(R.string.working_please_wait)); progress.show(); accessplansModule.viewAccessplan((String) pdfButton.getTag()); } }); } @Override public void onResume() { Log.d(TAG, "onResume"); if (basisModule.getPreferences().isAutomaticDeleteEnabled()) { startDeleteCountdownExec(); } else { tvAutomaticDelete.setVisibility(View.INVISIBLE); tvAutomaticDeleteText.setVisibility(View.INVISIBLE); } refreshScreen(); super.onResume(); } public void refreshScreen() { if (mEntries == null || mEntries.isEmpty()) { // do nothing } else { showStatusBar(); showOptionsBar(); runEntryCheck(); if (mAddressHolder == null) { aquireAdress(); } updateNearbyHydrantInformation(); } } private void showOptionsBar() { expandButton.setVisibility(View.GONE); hydrantsButton.setVisibility(View.GONE); routeButton.setVisibility(View.GONE); pdfButton.setVisibility(View.GONE); boolean showOptionsBar = false; if (googleMapsModule.isActivated()) { if (hydrantsModule.isActivated()) { showOptionsBar = true; expandButton.setVisibility(View.VISIBLE); hydrantsButton.setVisibility(View.VISIBLE); } if (directionsModule.isActivated()) { showOptionsBar = true; routeButton.setVisibility(View.VISIBLE); } } if (accessplansModule.isActivated()) { showOptionsBar = true; pdfButton.setVisibility(View.VISIBLE); } if (showOptionsBar) { optionsBar.setVisibility(View.VISIBLE); hiddenStatus.setVisibility(View.VISIBLE); } else { optionsBar.setVisibility(View.GONE); hiddenStatus.setVisibility(View.GONE); } } private void showStatusBar() { if (statusBar != null) { if (googleMapsModule.isActivated() || accessplansModule.isActivated()) { statusBar.setVisibility(View.VISIBLE); } } } @Override public void onPause() { Log.d(TAG, "onPause"); shutDownExec(); if (progress != null && progress.isShowing()) { progress.dismiss(); } super.onPause(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); shutDownExec(); super.onDestroy(); } public long getPageId() { return mPageid; } private void setExpandOptionsReady(boolean value) { if (value) { expandButton.setSelected(true); setImageButtonReady(expandButton, true, -1); } else { expandButton.setSelected(false); setImageButtonReady(expandButton, false, -1); } } private void setHydrantsReady(boolean value) { if ((Boolean) hydrantsButton.getTag() == false) { if (value) { setExpandOptionsReady(true); hydrantsButton.setTag(true); setImageButtonReady(hydrantsButton, true, R.color.Red); } else { setImageButtonReady(hydrantsButton, false, R.color.DarkGrey); } } } private void setRouteReady(boolean value) { if ((Boolean) routeButton.getTag() == false) { if (value) { routeButton.setTag(true); setImageButtonReady(routeButton, true, R.color.Orange); } else { setImageButtonReady(routeButton, false, R.color.DarkGrey); } } } private void setPdfReady(boolean value, final String filename) { if (((String) pdfButton.getTag()).isEmpty()) { if (value && accessplansModule.isAccessplan(filename)) { pdfButton.setTag(filename); setImageButtonReady(pdfButton, true, R.color.Green); } else { setImageButtonReady(pdfButton, false, R.color.DarkGrey); } } } /** * @param button * @param value * @param color * set to -1 to prevent color change */ private void setImageButtonReady(ImageButton button, boolean value, int color) { if (!isAdded()) return; if (value) { button.setAlpha(1.0f); button.setClickable(true); button.setEnabled(true); } else { button.setAlpha(0.35f); button.setClickable(false); button.setEnabled(false); } if (color != -1) { button.setColorFilter(getResources().getColor(color)); } } private void setTimeReceived(long time) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH); tvReceived.setText(sdf.format(new Date(time))); tvReceived.setTag(R.id.TAG_TIMERECEIVED, time); } public void updateAutomaticDeleteTime(final boolean performDeletion) { handler.post(new Runnable() { @Override public void run() { tvAutomaticDelete.setVisibility(View.VISIBLE); tvAutomaticDeleteText.setVisibility(View.VISIBLE); long deleteTime = basisModule.getPreferences() .getAutomaticDeleteTime(); long delay = display.getPageDeletionDelay(mPageid); deleteTime = deleteTime + delay; Long timeReceived = (Long) tvReceived .getTag(R.id.TAG_TIMERECEIVED); long now = System.currentTimeMillis(); if (timeReceived == null) { tvAutomaticDelete.setText("N/A"); } else { long timeToDelete = (timeReceived + deleteTime); CharSequence relativeTimeString = DateUtils .getRelativeTimeSpanString(timeToDelete, now, DateUtils.SECOND_IN_MILLIS); tvAutomaticDelete.setText(relativeTimeString); if (timeToDelete - now <= 0 && performDeletion) { display.deletePage(mPageid); } } } }); } public void runEntryCheck() { int picklistEntry = picklistModule.getPreferences().getPicklistEntry(); int accessPlanEntry = accessplansModule.getPreferences() .getAccessPlanEntry(); for (int i = 0; i < mContainerView.getChildCount() && mEntries.size() >= i; i++) { int entry = i + 1; String entryText = mEntries.get(i); View entryView = mContainerView.getChildAt(i); if (entryView instanceof TextView) { TextView entryTextView = (TextView) entryView; String currentText = entryTextView.getText().toString(); // BASIS - PREFIX,SUFFIX,STANDARDVALUE String processedText = basisModule .addPrefixSuffixfixStandardToString(entryText, entry); if (!processedText.equals(currentText)) { Log.d(TAG, "BASIS " + currentText + "!=" + processedText); replaceTextEntry(i, processedText); } // PICKLIST if (picklistEntry == entry) { String pickListEntry = convertIfPicklist(entry, entryText); if (!currentText.equals(pickListEntry)) { Log.d(TAG, "PICKLIST " + currentText + "!=" + pickListEntry); replaceTextEntry(i, pickListEntry); } } // ACCESSPLAN if (accessPlanEntry == entry && accessplansModule.isAccessplan(entryText)) { setPdfReady(true, entryText); } } } } private void replaceTextEntry(int index, String text) { mContainerView.removeViewAt(index); addTextEntryAt(text, index); } public void cancelScrollToBottom() { mScrollView.removeCallbacks(scrollToBottom); } public void scrollToBottomDelayed(int delay) { handler.postDelayed(scrollToBottom, delay); } private Runnable scrollToBottom = new Runnable() { @Override public void run() { mScrollView.fullScroll(View.FOCUS_DOWN); } }; public boolean haveAddressPosition() { return mAddressHolder != null && mAddressHolder.position != null; } public AddressHolder getAddressHolder() { return mAddressHolder; } public void addTextEntry(String text) { int nextIndex = mContainerView.getChildCount(); addTextEntryAt(text, nextIndex); } public void addEntry(TextView entry) { addEntryAt(entry, mContainerView.getChildCount()); } public void addEntry(View entry) { mRootView.findViewById(android.R.id.empty).setVisibility(View.GONE); statusBar.setVisibility(View.VISIBLE); mContainerView.addView(entry); } public void addTextEntryAt(String text, int index) { // Log.d(TAG, "addTextEntryAt " + text + " " + index); TextView entry_tv = (TextView) inflater.inflate(R.layout.view_entry, null); text = convertIfPicklist(index + 1, text); entry_tv.setText(text); Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans-Bold.ttf"); entry_tv.setTypeface(face); addEntryAt(entry_tv, index); } public void addEntryAt(TextView entry, int index) { mRootView.findViewById(android.R.id.empty).setVisibility(View.GONE); statusBar.setVisibility(View.VISIBLE); mContainerView.addView(entry, index); } public void appendEntries(List<String> append_entries) { // int delay = 200; for (final String entry : append_entries) { // append to existing entries mEntries.add(entry); // new Handler().postDelayed(new Runnable() { // // @Override // public void run() { addTextEntry(entry); // } // }, delay); // // delay += 200; } scrollToBottomDelayed(2000); } private String convertIfPicklist(int entry, String text) { int picklistEntry = picklistModule.getPreferences().getPicklistEntry(); if (entry == picklistEntry) { return picklistModule.convertKey(text); } return text; } private void aquireAdress() { // Log.d(TAG, "aquireAdress"); GoogleMapsModule mapsModule = googleMapsModule; // only if we do not already have a valid address if (!mapsModule.isActivated()) return; int addressEntry = mapsModule.getPreferences().getAddressEntry(); int cityEntry = mapsModule.getPreferences().getCityEntry(); if (mEntries.size() < addressEntry) return; if (mEntries.size() < cityEntry) return; if (addressEntry != 0 && cityEntry != 0) { final String addressString = mEntries.get(addressEntry - 1); final String cityString = mEntries.get(cityEntry - 1); mapsModule.lookupAddress(new FetchAddressCallback() { @Override public void addressLookupFailed() { } @Override public void addressFound(AddressHolder addressHolder) { LatLng deviceLocation = locationService .getLastLocationLatLng(); // if (deviceLocation != null) { // MapUtils.distBetween(pos1, pos2) mAddressHolder = addressHolder; setRouteReady(true); updateNearbyHydrantInformation(); // } } }, addressString, cityString); } } private void updateNearbyHydrantInformation() { if (haveAddressPosition() && (!mAddressHolder.isHydrantsNearby() || mContainerhydrantsNearAddress.getChildCount() < 3)) { final LatLng addressPosition = mAddressHolder.position; final List<HydrantHolder> hydrants = hydrantsModule .getNearbyHydrants(mAddressHolder); if (hydrants.size() > 0) { mAddressHolder.setHydrantsNearby(true); handler.post(new Runnable() { @Override public void run() { SortedMap<Integer, HydrantHolder> distanceSortedHydrants = new TreeMap<Integer, HydrantHolder>(); for (HydrantHolder hydrant : hydrants) { LatLng hydrantPosition = new LatLng(hydrant .getLatitude(), hydrant.getLongitude()); float distanceToAddress = MapUtils.distBetween( addressPosition, hydrantPosition); distanceSortedHydrants.put((int) distanceToAddress, hydrant); } mContainerhydrantsNearAddress.removeAllViews(); int counter = 0; for (Integer distance : distanceSortedHydrants.keySet()) { HydrantHolder hydrant = distanceSortedHydrants .get(distance); createHydrantView(hydrant, distance); counter++; if (counter == 3) break; } setHydrantsReady(true); // update height after views has been added getStatusBarHeight(); } }); } } } private void createHydrantView(HydrantHolder hydrant, float distanceToAddress) { Log.d(TAG, "createHydrantView return : " + !isAdded()); if (!isAdded()) return; View hydrantView = (View) inflater.inflate(R.layout.view_hydrant, null); TextView hydrantType = (TextView) hydrantView .findViewById(R.id.tv_hydrantType); TextView hydrantAddress = (TextView) hydrantView .findViewById(R.id.tv_hydrantAddress); TextView hydrantDistance = (TextView) hydrantView .findViewById(R.id.tv_hydrantDistance); hydrantType.setText(hydrant.getHydrantType()); hydrantAddress.setText(hydrant.getAddress() + " " + hydrant.getAddressNumber()); hydrantDistance.setText(distanceToAddress + " " + getString(R.string.meter)); mContainerhydrantsNearAddress.addView(hydrantView); hydrantView.setSelected(true); } }
package com.zhaolong.lesson11.controller; import com.zhaolong.lesson11.annotation.LoginRequired; import com.zhaolong.lesson11.entity.User; import com.zhaolong.lesson11.util.JwtUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.UUID; @RestController @RequestMapping("/api") @Api(value = "token") public class ApiController { @Autowired private HttpServletRequest request; @Autowired private JwtUtil jwtUtil; @LoginRequired @GetMapping("/userid") public Object getUserId(){ String auth = request.getHeader(jwtUtil.HEADER_STRING); return jwtUtil.getIdByJWT(auth); } @GetMapping("/test1") public Object testLogin1() { return "success"; } @PostMapping("/token") @ApiOperation(value = "登陆获取token", notes = "") public Object login(@RequestBody Account account) { if (isValidPassword(account)) { User user=getUser(); String jwt = jwtUtil.generateToken(user.getUuid()); return new HashMap<String, String>() {{ put(jwtUtil.HEADER_STRING, jwt); }}; } else { return new ResponseEntity(HttpStatus.UNAUTHORIZED); } } private static class Account { @ApiModelProperty(value = "用户名", required = true) public String username; @ApiModelProperty(value = "密码", required = true) public String password; } private boolean isValidPassword(Account ac) { User user=getUser(); return user.getName().equals(ac.username)&& user.getPassword().equals(ac.password); } private User getUser(){ User user=new User(); user.setUuid(UUID.randomUUID().toString().replace("-", "")); user.setName("admin"); user.setPassword("admin"); return user; } }
package threadpractice; public class Customer implements Runnable { private final String name; private final int eatingTime; private final Thread thread; public Customer(String name, int eatingTime) { this.name = name; this.eatingTime = eatingTime; this.thread = new Thread(this); } public String getName() { return name; } public int getEatingTime() { return eatingTime; } public boolean isFullOfEat() { return this.thread.isAlive(); } @Override public String toString() { return "Customer{" + "name='" + name + '\'' + ", eatingTime=" + eatingTime + '}'; } public void eating() { System.out.println(name + " is eating"); this.thread.start(); } @Override public void run() { eating(); try { wait(eatingTime); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + " finish eating"); } }
package com.ex.musicdb.model.binding; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.time.LocalDateTime; public class CommentAddBindingModel { @NotEmpty @Size(min = 5) private String textContent; @DateTimeFormat(pattern = "dd-MM-yyyy HH:mm") private LocalDateTime addedOn; public CommentAddBindingModel() { } public String getTextContent() { return textContent; } public CommentAddBindingModel setTextContent(String textContent) { this.textContent = textContent; return this; } public LocalDateTime getAddedOn() { return addedOn; } public CommentAddBindingModel setAddedOn(LocalDateTime addedOn) { this.addedOn = addedOn; return this; } }
package com.novakivska.runners.lesson15; import com.novakivska.app.classwork.lesson15.AbstractHouse; import com.novakivska.app.classwork.lesson15.NewYork; /** * Created by Tas_ka on 5/5/2017. */ public class HouseRunner { public static void main(String[] args){ AbstractHouse newYork = new NewYork(34); newYork.build(); } }
package com.mptr.spacetime.SpacetimeLocalizer.SpacetimeWatcher; import java.util.Calendar; /** * Created by Michal Poteralski on 16.11.14. * <p/> * Simple class which represents time i.e. Hours, minutes and seconds. */ public class SpacetimeTime24 extends SpacetimeTime { public SpacetimeTime24(int hours, int minutes, int seconds) { super(hours, minutes, seconds); } public SpacetimeTime24() { this(0, 0, 0); } public SpacetimeTime24(int hours) { this(hours, 0, 0); } public SpacetimeTime24(int hours, int minutes) { this(hours, minutes, 0); } @Override int getTimeInSeconds() { return (getSeconds() + getMinutes() * 60 + getHours() * 60 * 60); } @Override boolean timeIn24HoursFormat() { return true; } @Override boolean checkHoursValRange(int hours) { return (hours >= 0 && hours < 24); } @Override boolean checkMinutesValRange(int minutes) { return (minutes >= 0 && minutes < 60); } @Override boolean checkSecondsValRange(int seconds) { return (seconds >= 0 && seconds < 60); } @Override public boolean before(SpacetimeTime time) { return (getTimeInSeconds() < time.getTimeInSeconds()); } @Override public boolean before(Calendar calendar) { int timeInSec = calendar.get(Calendar.SECOND) + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.HOUR_OF_DAY) * 60 * 60; return (getTimeInSeconds() < timeInSec); } @Override public boolean after(SpacetimeTime time) { return (getTimeInSeconds() > time.getTimeInSeconds()); } @Override public boolean after(Calendar calendar) { int timeInSec = calendar.get(Calendar.SECOND) + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.HOUR_OF_DAY) * 60 * 60; return (getTimeInSeconds() > timeInSec); } @Override public boolean equal(SpacetimeTime time) { return getTimeInSeconds() == time.getTimeInSeconds(); } @Override public boolean equal(Calendar calendar) { int timeInSec = calendar.get(Calendar.SECOND) + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.HOUR_OF_DAY) * 60 * 60; return (getTimeInSeconds() == timeInSec); } }
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; public class Sprite { public ImageIcon characterimage; public Rectangle hitbox; public int x; public int y; public Sprite(String pathfile, int x, int y){ try{ URL url=this.getClass().getResource(pathfile); characterimage= new ImageIcon(url); } catch (Exception e) { e.printStackTrace(); } this.x=x; this.y=y; hitbox=new Rectangle(this.x,this.y,characterimage.getIconWidth(),characterimage.getIconHeight()); } public void updateHitBox(){ hitbox=hitbox=new Rectangle(x+(characterimage.getIconWidth()/4),y,characterimage.getIconWidth()/2,characterimage.getIconHeight()); } public static boolean collision(Rectangle r1, Rectangle r2){ if(r1.getBounds().intersects(r2.getBounds())){ return true; } return false; } }
package com.arthur.leetcode; import java.util.ArrayList; import java.util.List; /** * @title: No438 * @Author ArthurJi * @Date: 2021/3/3 16:34 * @Version 1.0 */ public class No438 { public static void main(String[] args) { List<Integer> ans = new No438().findAnagrams("cbaebabacd", "abc"); ans.forEach(System.out::println); } public List<Integer> findAnagrams(String s, String p) { int len = s.length(); int plen = p.length(); int[] pFreq = new int[26]; int[] Freq = new int[26]; ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < plen; i++) { pFreq[p.charAt(i) - 'a']++; } int right = 0; for (int i = 0; i < len; i++) { Freq[s.charAt(i) - 'a']++; while (Freq[s.charAt(i) - 'a'] > pFreq[s.charAt(i) - 'a']) { Freq[s.charAt(right) - 'a']--; right++; } if(i - right + 1 == plen) { ans.add(right); } } return ans; } } //438. 找到字符串中所有字母异位词 /*找到字符串中所有字母异位词 给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。 字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。 说明: 字母异位词指字母相同,但排列不同的字符串。 不考虑答案输出的顺序。 示例 1: 输入: s: "cbaebabacd" p: "abc" 输出: [0, 6] 解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。 起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。*/ /* 解题思路 本题是典型的窗口滑动+左右索引指针的算法 一开始还是先将字符串转换为字符数组,定义一个ans来接收结果 这里使用了两个数组needs和window来分别记录需要得到的元素和滑动窗口遍历到的元素 首先把目标数组arrP中有的元素都放入needs中,然后通过不断移动滑动窗口将目标元素的个数保存到window中 如果window数组中记录的元素个数超过了needs数组的元素个数,则开始移动左窗口慢慢减少多余的个数 最后把整个遍历过程中所有符合要求的左窗口索引放到ans中并返回即可。 代码 java class Solution { public List<Integer> findAnagrams(String s, String p) { char[] arrS = s.toCharArray(); char[] arrP = p.toCharArray(); // 接收最后返回的结果 List<Integer> ans = new ArrayList<>(); // 定义一个 needs 数组来看 arrP 中包含元素的个数 int[] needs = new int[26]; // 定义一个 window 数组来看滑动窗口中是否有 arrP 中的元素,并记录出现的个数 int[] window = new int[26]; // 先将 arrP 中的元素保存到 needs 数组中 for (int i = 0; i < arrP.length; i++) { needs[arrP[i] - 'a'] += 1; } // 定义滑动窗口的两端 int left = 0; int right = 0; // 右窗口开始不断向右移动 while (right < arrS.length) { int curR = arrS[right] - 'a'; right++; // 将右窗口当前访问到的元素 curR 个数加 1 window[curR] += 1; // 当 window 数组中 curR 比 needs 数组中对应元素的个数要多的时候就该移动左窗口指针 while (window[curR] > needs[curR]) { int curL = arrS[left] - 'a'; 作者:Jason_H 链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/solution/20200321438median-by-jasion_han-r/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
package de.uulm.in.vs.grn.chat.client; import javax.swing.*; import java.awt.*; import java.io.*; import java.net.Socket; import java.util.ArrayList; public class Client extends JFrame { /*Socket command = null; BufferedReader commandIN = null; PrintWriter commandOUT = null;*/ Socket pubSub = null; BufferedReader pubSubIN = null; PrintWriter pubSubOUT = null; public Client() { setSize(500, 500); setResizable(false); setLayout(null); JPanel container = new JPanel(); container.setBackground(Color.CYAN); container.setSize(getWidth(), getHeight()); container.setLayout(null); add(container); JTextArea messages = new JTextArea(); messages.setEditable(false); JScrollPane scroll = new JScrollPane (messages); scroll.setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ); scroll.setBounds(25, 50, 450, 325); container.add(scroll); JTextField input = new JTextField(); input.setBounds(25, 400, 325, 50); container.add(input); JButton send = new JButton("SEND"); send.setBounds(375, 400, 100, 50); container.add(send); setTitle("GRNCP Client"); setVisible(true); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); connect(); String line; ArrayList<String> currentMsg = new ArrayList<String>(); try { while ((line = pubSubIN.readLine()) != null) { currentMsg.add(line); if(line.trim().equals("")) { messages.append(formateMessage(currentMsg)); messages.setCaretPosition(messages.getDocument().getLength()); currentMsg.clear(); } } } catch (IOException e) { e.printStackTrace(); } } private String formateMessage(ArrayList<String> msg) { // Formats Server Response to display it in the GUI String type = msg.get(0).split(" ")[1]; if(type.equals("MESSAGE")) { String date =msg.get(1).split(" ")[2].substring(0,5); String username = msg.get(2).substring(10); String text = msg.get(3).substring(6); String[] words = text.split(" "); String txt = ""; int maxCharsPerLine = 60; for (int i = 0; i <words.length ; i++) { if(txt.length() + words[i].length()+1<maxCharsPerLine) { txt+=words[i] + " "; } else { txt += "\n" + words[i] + " "; maxCharsPerLine+=60; } } text = txt; return username +"\n\n"+text+"\n\t\t\t\t " + date +"\n" +"_____________________________________________________________\n"; } else if (type.equals("EVENT")) { String date =msg.get(1).split(" ")[2].substring(0,5); String description = msg.get(2).substring(13); return description+"\n\t\t\t\t " + date +"\n" +"_____________________________________________________________\n"; } return "ERROR\n"; } private void connect() { // connects to server (pub/sub only atm) try { /*command = new Socket("grn-services.lxd-vs.uni-ulm.de",8122); commandIN = new BufferedReader(new InputStreamReader(command.getInputStream(),"UTF-8")); commandOUT = new PrintWriter(command.getOutputStream(),true);*/ pubSub = new Socket("grn-services.lxd-vs.uni-ulm.de",8123); pubSubIN = new BufferedReader(new InputStreamReader(pubSub.getInputStream(),"UTF-8")); pubSubOUT = new PrintWriter(pubSub.getOutputStream(),true); } catch (IOException e) { e.printStackTrace(); } } }
package OOP.Constructors.this_usage; public class Main { public static void main(String[] args) { Cat myCat = new Cat("Barsik", 5); System.out.println("Name: " + myCat.name + ", Age; " + myCat.age); } }
/* * 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 tiendasellosUI; /** * * @author Antonio */ public class ListarSellos extends javax.swing.JFrame { /** * Creates new form ListarSellos */ public ListarSellos() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setText("Sellos (Código - Descripción - Valor facial - País)"); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED)); jTextArea1.setColumns(20); jTextArea1.setRows(5); jTextArea1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jScrollPane1.setViewportView(jTextArea1); jLabel2.setText("Ordenar por:"); jRadioButton1.setText(" Descripción(A-Z)"); jRadioButton2.setText(" Descripción(Z-A)"); jRadioButton3.setText(" Valor facial"); jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); jButton1.setText("Ver Información"); jButton2.setText("Cerrar Listado"); jLabel3.setText("Totales"); jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED)); jLabel4.setText("Total de sellos:"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel4) .addGap(93, 93, 93) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(80, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(31, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton2) .addGap(18, 18, 18) .addComponent(jRadioButton3)) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(10, 10, 10)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(0, 0, Short.MAX_VALUE))))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton1) .addComponent(jRadioButton2) .addComponent(jRadioButton3) .addComponent(jButton1)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jButton2) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jRadioButton3ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
package course.chapter12lab; public class Text implements Drawable { String value; public Text(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public void draw() { System.out.println(value); } }
package com.maliang.core.exception; public class TianmaException extends RuntimeException{ private static final long serialVersionUID = 1L; public TianmaException(String msg){ super(msg); } }
package cn.ztuo.bitrade.model.screen; import cn.ztuo.bitrade.ability.ScreenAbility; import cn.ztuo.bitrade.constant.AuditStatus; import com.querydsl.core.types.dsl.BooleanExpression; import lombok.Data; import java.util.ArrayList; @Data public class FeedbackScreen implements ScreenAbility { private String memberName; private AuditStatus status; @Override public ArrayList<BooleanExpression> getBooleanExpressions() { return booleanExpressions; } }
package casino; public class Carta { //atributos private int numero; private String simbolo; //constructora public Carta (int pNumero, String pSimbolo) { numero=pNumero; simbolo=pSimbolo; } // otros métodos public int getNumero(){ return numero; } public String getSimbolo(){ return simbolo; } public boolean tieneMismoSimbolo(Carta pCarta) { if (pCarta.simbolo==simbolo) { return true; } else { return false; } } public boolean tieneMismoNumero(Carta pCarta) { if (pCarta.numero==numero) { return true; } else { return false; } } public boolean estanEnEscalera(Carta pCarta) { if ((pCarta.numero-1==numero)&&(pCarta.numero==numero-1)) { return true; } else { return false; } } public int distanciaEntreCartas(Carta pCarta){ int distancia = 0; if (numero>pCarta.getNumero()){ distancia = numero - pCarta.getNumero(); } else{ distancia = pCarta.getNumero() - numero; } return distancia; } public void imprimir(){ if (this.numero==13){ System.out.println("K de " +(this.simbolo)); } else if (this.numero==12){ System.out.println("Q de " +(this.simbolo)); } else if (this.numero==11){ System.out.println("J de " +(this.simbolo)); } else if (this.numero==1){ System.out.println("A de " +(this.simbolo)); } else{ System.out.println((this.numero)+" de "+(this.simbolo)); } } }
package github.dwstanle.tickets.repository; import github.dwstanle.tickets.model.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import static github.dwstanle.tickets.model.Data.generateId; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @DataJpaTest public class ReservationRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private ReservationRepository reservationRepository; private Account account; private Venue venue; private Section section; private Event event; @Before public void setUp() { this.section = entityManager.persist(new Section("S S S \n S S S")); this.account = entityManager.persist(new Account("foo@email.com")); this.venue = entityManager.persist(Venue.builder().section(section).build()); this.event = entityManager.persist(new Event("Event Test", venue)); entityManager.persist(Reservation.builder() .account(account.getEmail()) .event(event) .seat(new Seat(0, 0)) .seat(new Seat(0, 1)) .build()); } @Test public void findByAccountEmail() { Reservation reservation = reservationRepository.findByAccount("foo@email.com").iterator().next(); assertEquals("foo@email.com", reservation.getAccount()); assertEquals(event, reservation.getEvent()); assertEquals(2, reservation.getSeats().size()); } @Test public void whenSearchByEventId_thenReturnReservation() { Reservation reservation = reservationRepository.findByEventId(event.getId()).iterator().next(); assertEquals(event, reservation.getEvent()); } @Test public void whenEventIdIsNull_thenNoReservationsFound() { assertEquals(0, reservationRepository.findByEventId(null).stream().count()); } @Test public void whenEventIdIsUnknown_thenNoReservationsFound() { assertEquals(0, reservationRepository.findByEventId(700L).stream().count()); } @Test public void whenSave_thenReservationCreated() { Reservation reservation = reservationRepository.save(Reservation.builder() .account(account.getEmail()) .event(event) .seat(new Seat(0, 0)) .seat(new Seat(0, 1)) .build()); assertNotNull(reservation); assertNotNull(reservation.getId()); } @Test public void whenAlreadySaved_thenReservationCreated() { Reservation reservation = reservationRepository.save(Reservation.builder() .id(generateId()) .account(account.getEmail()) .event(event) .seat(new Seat(0, 0)) .seat(new Seat(0, 1)) .build()); assertNotNull(reservation); assertNotNull(reservation.getId()); } @Test public void whenDelete_thenReservationIsRemoved() { Reservation reservation = reservationRepository.save(Reservation.builder() .id(generateId()) .account(account.getEmail()) .event(event) .seat(new Seat(0, 0)) .seat(new Seat(0, 1)) .build()); reservationRepository.deleteById(reservation.getId()); assertFalse(reservationRepository.findById(reservation.getId()).isPresent()); } @Test(expected = Exception.class) public void whenDeleteUnknown_thenExceptionIsThrown() { reservationRepository.deleteById(0L); } @Test(expected = Exception.class) public void whenDeleteWithNull_thenExceptionIsThrown() { reservationRepository.deleteById(null); } }
/** * Annotations and supporting classes for declarative cache management. * Hooked into Spring's cache interception infrastructure via * {@link org.springframework.cache.interceptor.CacheOperationSource}. */ @NonNullApi @NonNullFields package org.springframework.cache.annotation; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.splwg.cm.domain.batch; public final class CmConstant { //Message Number public static final String EMPLOYER_EMAIL_INVALID = "301"; public static final String EMPLOYER_EMAIL_EXIST = "302"; public static final String TRN_EXIST = "303"; public static final String TRN_INVALID = "304"; public static final String NINET_INVALID = "305"; public static final String TIN_INVALID = "306"; public static final String DATE_LESSEQUAL_TODAY_VALID= "307"; public static final String DATE_SAT_SUN_VALID= "308"; public static final String DATE_EST_GREAT_IMM= "309"; public static final String DATE_EMP_GREAT_EST= "310"; public static final String DATE_EMP_GREAT_IMM= "311"; public static final String INVALID_DATE= "312"; public static final String NINEA_EXIST= "313"; public static final String NINEA_INVALID = "314"; public static final String TELEPHONE_INVALID = "315"; public static final String NAME_INVALID = "324"; public static final String NAME_LETTER_CHECK = "325"; public static final String NIN_INVALID = "326"; public static final String EMAIL_INVALID = "327"; public static final String EMPTY = "328"; public static final String DATE_DEL_GREAT_EXP= "329"; //String public static final String NINEA_PREFIX ="00"; public static final String UTF ="UTF-8"; public static final String INVALID_DATE_STRING = "invalidate"; public static final String IMMATRICULATION_DATE = "Date d’immatriculation au registre de commerce"; public static final String ESTABLISHMENT_DATE = "Date Ouverture Établissement"; public static final String PHONE = "Téléphone fixe"; public static final String TAX_IDENTIFY_NUM = "Code d'identification fiscale"; public static final String EMAIL_EMPLOYER = "Email de l'employeur"; public static final String TRADE_REG_NUM = "Numéro de registre du commerce"; public static final String PREMIER_EMP_DATE = "Date d’embauche du premier salarié"; //String empty check public static final String TYPE_D_EMPLOYEUR = "Type d'employeur"; public static final String RAISON_SOCIALE = "Raison Sociale"; public static final String NINEA = "NINEA"; public static final String NINET = "NINET"; public static final String FORME_JURIDIQUE = "Forme Juridique"; public static final String DATE_DE_CREATION = "Date de création"; public static final String DATE_IDENTIFICATION_FISCALE = "Date d'identification fiscale"; public static final String NUMERO_REGISTER_DE_COMMERCE = "Numéro du registre de commerce"; public static final String DATE_IMM_REGISTER_DE_COMMERCE = "Date d’immatriculation au registre de commerce"; public static final String DATE_OUVERTURE_EST = "Date Ouverture Etablissement"; public static final String DATE_EMBAUCHE_PREMIER_SALARY = "Date d’embauche du premier salarié"; public static final String SECTEUR_ACTIVITIES = "Secteur d’Activités"; public static final String ACTIVATE_PRINCIPAL = "Activité principale"; public static final String TAUX_AT = "Taux AT"; public static final String NOMBRE_TRAVAIL_REGIME_GENERAL = "Nombre de travailleurs en régime général"; public static final String NOMBRE_TRAVAIL_REGIME_CADRE = "Nombre de travailleurs en régime cadre"; public static final String REGION = "Region"; public static final String DEPARTMENT = "Département"; public static final String ARONDISSEMENT = "Arondissement"; public static final String COMMUNE = "Commune"; public static final String QUARTIER = "Quartier"; public static final String ADDRESS = "Adresse"; public static final String TELEPHONE = "Téléphone"; public static final String EMAIL = "Email"; public static final String ZONE_GEOGRAPHIQUE_CSS = "Zones géographiques CSS"; public static final String ZONE_GEOGRAPHIQUE_IPRES = "Zones géographiques IPRES"; public static final String SECTOR_GEOGRAPHIC_CSS = "Secteurs géographiques CSS"; public static final String SECTOR_GEOGRAPHIC_IPRES = "Secteurs géographiques IPRES"; public static final String AGENCE_CSS = "Agence CSS"; public static final String AGENCE_IPRES = "Agence IPRES"; public static final String LEGAL_REPRESENTANT = "Représentant légal"; public static final String LAST_NAME = "Nom de famille"; public static final String FIRST_NAME = "Prénom"; public static final String DATE_DE_NAISSANCE = "Date de naissance"; public static final String NATIONALITE = "Nationalité"; public static final String LEGAL_REP_NIN = "NIN représentant légal"; public static final String EMPLOYEE_NIN = "NIN de l'employé"; public static final String PAYS_DE_NAISSANCE = "Pays de naissance"; public static final String TYPE_PIECE_IDENTITE = "Type de pièce d’identité"; public static final String NUMERO_PIECE_IDENTITE = "Numéro pièce d'identité"; public static final String DATE_DE_DELIVRANCE = "Date de délivrance"; public static final String DATE_DE_EXPIRATION = "Date d’expiration"; public static final String MOBILE_NUM = "Numéro mobile"; /* public static final String SECTEUR_ACTIVITE_PRINCIPAL = "Secteur d’activité principal"; public static final String CONVENTION_DE_BRANCHES = "Conventions de Branches"; public static final String VILLE = "Ville"; public static final String ZONE_GEOGRAPHIC = "Zone géographique"; public static final String STATUT_LEGAL = "Statut légal"; public static final String SEXE = "Sexe"; public static final String NUMERO_IDENTIFICATION_CSS = "Numéro d'identification CSS"; public static final String NUMERO_IDENTIFICATION_IPRES = "Numéro d'identification IPRES"; public static final String DELIVER_LE = "Délivré le"; public static final String DELIVER_PAR = "Délivré par"; public static final String PAYS = "Pays"; public static final String DATE_DEBUT_CONTRAT = "Date de début du contrat"; public static final String PROFESSION = "Profession"; public static final String EMPLOYEE_CADRE = "Employé cadre"; public static final String CONVENTION_APPLICABLE = "Convention applicable"; public static final String NATUR_DU_CONTRAT = "Nature du contrat"; public static final String SALAIRE_CONTRACTUEL = "Salaire contractuel"; public static final String EMPLOYE_SECTEUR_AFFAIRES = "Employe AT/MP Secteur des affaires"; public static final String CATEGORIE = "Catégorie"; public static final String DATE_DEBUT = "Date de début";*/ //Regular Expression public static final String VALIDATE_PHONE_NUMBER = "^(?:33|70|76|77){0,2}\\d{7}$"; public static final String VALIDATE_NINEA_NUMBER = "\\d{9}$"; public static final String VALIDATE_NIN_NUMBER = "^[1-2]{1}[0-9]{3}[0-9]{4}[0-9]{5,6}$"; public static final String VALIDATE_ALPHABETS_ONLY = "[A-Za-z]+"; public static final String VALIDATE_NINET_NUMBER = "\\d{13}$"; public static final String VALIDATE_TAX_IDENFICATION_NUMBER = "^[0-9]{1}[A-Z]{1}[0-9]{1}$"; public static final String VALIDATE_COMMERCIAL_REGISTER = "^(?:SN)\\.[A-Za-z0-9]{3}\\.[0-9]{4}\\.(?:A|B|C|E|M){1}\\.[0-9]{1,5}$"; }
/* * This file is part of BlueMap, licensed under the MIT License (MIT). * * Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.bluecolored.bluemap.api; import com.flowpowered.math.vector.Vector2i; import de.bluecolored.bluemap.api.debug.DebugDump; import java.io.IOException; import java.util.Collection; /** * The {@link RenderManager} is used to schedule tile-renders and process them on a number of different threads. */ public interface RenderManager { /** * Schedules a task to update the given map. * @param map the map to be updated * @return true if a new task has been scheduled, false if not (usually because there is already an update-task for this map scheduled) */ default boolean scheduleMapUpdateTask(BlueMapMap map) { return scheduleMapUpdateTask(map, false); } /** * Schedules a task to update the given map. * @param map the map to be updated * @param force it this is true, the task will forcefully re-render all tiles, even if there are no changes since the last map-update. * @return true if a new task has been scheduled, false if not (usually because there is already an update-task for this map scheduled) */ boolean scheduleMapUpdateTask(BlueMapMap map, boolean force); /** * Schedules a task to update the given map. * @param map the map to be updated * @param regions The regions that should be updated ("region" refers to the coordinates of a minecraft region-file (32x32 chunks, 512x512 blocks))<br> * BlueMaps updating-system works based on region-files. For this reason you can always only update a whole region-file at once. * @param force it this is true, the task will forcefully re-render all tiles, even if there are no changes since the last map-update. * @return true if a new task has been scheduled, false if not (usually because there is already an update-task for this map scheduled) */ boolean scheduleMapUpdateTask(BlueMapMap map, Collection<Vector2i> regions, boolean force); /** * Schedules a task to purge the given map. * An update-task will be scheduled right after the purge, to get the map up-to-date again. * @param map the map to be purged * @return true if a new task has been scheduled, false if not (usually because there is already an update-task for this map scheduled) * @throws IOException if an IOException occurs while trying to create the task. */ boolean scheduleMapPurgeTask(BlueMapMap map) throws IOException; /** * Getter for the current size of the render-queue. * @return the current size of the render-queue */ @DebugDump int renderQueueSize(); /** * Getter for the current count of render threads. * @return the count of render threads */ @DebugDump int renderThreadCount(); /** * Whether this {@link RenderManager} is currently running or stopped. * @return <code>true</code> if this renderer is running */ @DebugDump boolean isRunning(); /** * Starts the renderer if it is not already running. * The renderer will be started with the configured number of render threads. */ void start(); /** * Starts the renderer if it is not already running. * The renderer will be started with the given number of render threads. * @param threadCount the number of render threads to use, * must be greater than 0 and should be less than or equal to the number of available cpu-cores. */ void start(int threadCount); /** * Stops the renderer if it currently is running. */ void stop(); }
package be.kuleuven.mume.servlets; import java.io.IOException; import java.util.HashMap; import javax.jdo.PersistenceManager; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import be.kuleuven.mume.PMF; import be.kuleuven.mume.shared.Antwoord; import be.kuleuven.mume.shared.FieldVerifier; import be.kuleuven.mume.shared.FormatException; import be.kuleuven.mume.shared.Persoon; import be.kuleuven.mume.shared.Vak; import be.kuleuven.mume.shared.Vraag; public class VraagServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 5522536807910452864L; private static final HashMap<String, String> regex = new HashMap<String, String>(); public VraagServlet(){ VraagServlet.regex.put("q", "add|reply|get"); VraagServlet.regex.put("text","[^\\n]+"); VraagServlet.regex.put("vakid","\\p{Graph}+"); VraagServlet.regex.put("replytoid", "\\p{Graph}+"); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PersistenceManager pm = PMF.get().getPersistenceManager(); Persoon p = Persoon.getCurrentPersoon(pm, req, resp, true); if(p==null) return; try{ String q = FieldVerifier.getParam(VraagServlet.regex, req, resp, "q"); if(q.equals("add")) addVraag(p, pm, req, resp); else if(q.equals("reply")) addReply(p, pm, req, resp); else if(q.equals("get")) getVragen(pm, req, resp); } catch (FormatException e) { resp.getWriter().write(e.getMessage()); resp.setStatus(400); } } private void addReply(Persoon p, PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp) throws FormatException, IOException { String text = FieldVerifier.getParam(VraagServlet.regex, req, resp, "text"); String replyToId = FieldVerifier.getParam(VraagServlet.regex, req, resp, "replytoid"); Key key = KeyFactory.stringToKey(replyToId); Vraag vraag = pm.getObjectById(Vraag.class, key); Antwoord a = new Antwoord(p,text,vraag); pm.close(); resp.getWriter().write("Reply added" + a.toString()); } private void getVragen(PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp) throws IOException, FormatException { String vakId = FieldVerifier.getParam(VraagServlet.regex, req, resp, "vakid"); Key key = KeyFactory.stringToKey(vakId); Vak vak = pm.getObjectById(Vak.class, key); StringBuilder str = new StringBuilder(); for (Vraag v : vak.getVragen()) { str.append(v.toString()); str.append("\n"); } pm.close(); resp.getWriter().write(str.toString()); } private void addVraag(Persoon p, PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp) throws FormatException, IOException { String text = FieldVerifier.getParam(VraagServlet.regex, req, resp, "text"); String vakId = FieldVerifier.getParam(VraagServlet.regex, req, resp, "vakid"); Key vakkey = KeyFactory.stringToKey(vakId); Vak vak = pm.getObjectById(Vak.class, vakkey); Vraag vraag = new Vraag(p, vak, text); pm.makePersistent(vraag); pm.close(); resp.getWriter().write("Vraag stored successfully, id:" + KeyFactory.keyToString(vraag.getId())); } }
package com.ivoronline.springboot_mockito_mock_injectinto_property.controllers; import com.ivoronline.springboot_mockito_mock_injectinto_property.entities.Person; import com.ivoronline.springboot_mockito_mock_injectinto_property.repositories.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MyController { //PROPERTIES @Autowired PersonRepository personRepository; //ENDPOINT @ResponseBody @RequestMapping("/GetPerson") public String getPerson(@RequestParam Integer id) { //GET PERSON Person person = personRepository.getPersonById(1); //GREET PERSON return "Hello " + person.name; } }
package uz.pdp.lesson5task1.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import uz.pdp.lesson5task1.entity.User; import uz.pdp.lesson5task1.repository.UsersRepository; import java.util.Optional; @Service public class AuthService implements UserDetailsService { @Autowired JavaMailSender javaMailSender; @Autowired UsersRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> optionalUser = userRepository.findByEmail(username); if(optionalUser.isPresent()) return optionalUser.get(); throw new UsernameNotFoundException(username+" Topilmadi"); } }
package cts.miron.cristina.g1093.pattern.factory; public class BookingFactory { public static OnlineBooking getBooking(EventType type, String eventName, int price) { OnlineBooking booking = null; switch(type) { case CONCERTS: booking = new ConcertBooking(eventName, price, "TheBeattles"); break; case EVENTS: booking = new EventBooking(eventName, price, 100); break; case MUSEUMS: booking = new MuseumBooking(eventName, price); break; default: throw new UnsupportedOperationException(); } return booking; } }
/* * 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 Adapter; /** * * @author ifpb */ public class Adaptador extends ClasseExistente implements Alvo{ public Adaptador() { } @Override public String operacao(String pinoFase, String pinoNeutro) { String pinoInexistente = "Terra"; return metodoUtil(pinoFase, pinoNeutro, pinoInexistente); } }
/* * Copyright 2014 LinkedIn Corp. * * 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 azkaban.executor; import com.webank.wedatasphere.schedulis.common.executor.ExecutionCycle; import com.webank.wedatasphere.schedulis.common.log.LogFilterEntity; import java.io.IOException; import java.lang.Thread.State; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import azkaban.project.Project; import azkaban.user.User; import azkaban.utils.FileIOUtils.JobMetaData; import azkaban.utils.FileIOUtils.LogData; import azkaban.utils.Pair; import azkaban.utils.Props; public interface ExecutorManagerAdapter { public Props getAzkabanProps(); public boolean isFlowRunning(int projectId, String flowId) throws ExecutorManagerException; public ExecutableFlow getExecutableFlow(int execId) throws ExecutorManagerException; public List<Integer> getRunningFlows(int projectId, String flowId); public List<ExecutableFlow> getRunningFlows(); public long getQueuedFlowSize(); /** * <pre> * Returns All running with executors and queued flows * Note, returns empty list if there isn't any running or queued flows * </pre> */ public List<Pair<ExecutableFlow, Optional<Executor>>> getActiveFlowsWithExecutor() throws IOException; public List<ExecutableFlow> getRecentlyFinishedFlows(); public List<ExecutableFlow> getExecutableFlows(Project project, String flowId, int skip, int size) throws ExecutorManagerException; public List<ExecutableFlow> getExecutableFlows(int skip, int size) throws ExecutorManagerException; List<ExecutableFlow> getMaintainedExecutableFlows(String username, List<Integer> projectIds, int skip, int size) throws ExecutorManagerException; public List<ExecutableFlow> getExecutableFlowsQuickSearch(String flowIdContains, int skip, int size) throws ExecutorManagerException; public List<ExecutableFlow> getMaintainedFlowsQuickSearch(String flowIdContains, int skip, int size, String username, List<Integer> projectIds) throws ExecutorManagerException; public List<ExecutableFlow> getExecutableFlows(String projContain, String flowContain, String execIdContain, String userContain, String status, long begin, long end, int skip, int size, int flowType) throws ExecutorManagerException; List<ExecutableFlow> getMaintainedExecutableFlows(String projContain, String flowContain, String execIdContain, String userContain, String status, long begin, long end, int skip, int size, int flowType, String username, List<Integer> projectIds) throws ExecutorManagerException; public int getExecutableFlows(int projectId, String flowId, int from, int length, List<ExecutableFlow> outputList) throws ExecutorManagerException; public List<ExecutableFlow> getExecutableFlows(int projectId, String flowId, int from, int length, Status status) throws ExecutorManagerException; public List<ExecutableJobInfo> getExecutableJobs(Project project, String jobId, int skip, int size) throws ExecutorManagerException; public long getExecutableJobsMoyenneRunTime(Project project, String jobId) throws ExecutorManagerException; public int getNumberOfJobExecutions(Project project, String jobId) throws ExecutorManagerException; public int getNumberOfExecutions(Project project, String flowId) throws ExecutorManagerException; public LogData getExecutableFlowLog(ExecutableFlow exFlow, int offset, int length) throws ExecutorManagerException; public LogData getExecutionJobLog(ExecutableFlow exFlow, String jobId, int offset, int length, int attempt) throws ExecutorManagerException; public Long getLatestLogOffset(ExecutableFlow exFlow, String jobId, Long length, int attempt, User user) throws ExecutorManagerException; public List<Object> getExecutionJobStats(ExecutableFlow exflow, String jobId, int attempt) throws ExecutorManagerException; public String getJobLinkUrl(ExecutableFlow exFlow, String jobId, int attempt); public JobMetaData getExecutionJobMetaData(ExecutableFlow exFlow, String jobId, int offset, int length, int attempt) throws ExecutorManagerException; public void cancelFlow(ExecutableFlow exFlow, String userId) throws ExecutorManagerException; public void resumeFlow(ExecutableFlow exFlow, String userId) throws ExecutorManagerException; /** * 设置flow失败 * @param exFlow * @param userId * @param params * @throws Exception */ public void setFlowFailed(ExecutableFlow exFlow, String userId, List<Pair<String, String>> params) throws Exception; /** * flow失败暂停设置 重试指定的失败job * @param exFlow * @param userId * @param request * @throws Exception */ public String retryFailedJobs(ExecutableFlow exFlow, String userId, String request) throws Exception; /** * 设置job状态为disabled * @param exFlow * @param userId * @param request * @throws Exception */ public String setJobDisabled(ExecutableFlow exFlow, String userId, String request) throws Exception; /** * 设置跳过执行失败的jobs * @param exFlow * @param userId * @param request * @throws Exception */ public String skipFailedJobs(ExecutableFlow exFlow, String userId, String request) throws Exception; public void pauseFlow(ExecutableFlow exFlow, String userId) throws ExecutorManagerException; public void pauseExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds) throws ExecutorManagerException; public void resumeExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds) throws ExecutorManagerException; public void retryFailures(ExecutableFlow exFlow, String userId) throws ExecutorManagerException; //跳过所有FAILED_WAITING 状态job public void skipAllFailures(ExecutableFlow exFlow, String userId) throws ExecutorManagerException; public void retryExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds) throws ExecutorManagerException; public void disableExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds) throws ExecutorManagerException; public void enableExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds) throws ExecutorManagerException; public void cancelExecutingJobs(ExecutableFlow exFlow, String userId, String... jobIds) throws ExecutorManagerException; public String submitExecutableFlow(ExecutableFlow exflow, String userId) throws ExecutorManagerException; /** * Manage servlet call for stats servlet in Azkaban execution server Action can take any of the * following values <ul> <li>{@link azkaban.executor.ConnectorParams#STATS_SET_REPORTINGINTERVAL}<li> * <li>{@link azkaban.executor.ConnectorParams#STATS_SET_CLEANINGINTERVAL}<li> <li>{@link * azkaban.executor.ConnectorParams#STATS_SET_MAXREPORTERPOINTS}<li> <li>{@link * azkaban.executor.ConnectorParams#STATS_GET_ALLMETRICSNAME}<li> <li>{@link * azkaban.executor.ConnectorParams#STATS_GET_METRICHISTORY}<li> <li>{@link * azkaban.executor.ConnectorParams#STATS_SET_ENABLEMETRICS}<li> <li>{@link * azkaban.executor.ConnectorParams#STATS_SET_DISABLEMETRICS}<li> </ul> */ public Map<String, Object> callExecutorStats(int executorId, String action, Pair<String, String>... param) throws IOException, ExecutorManagerException; public Map<String, Object> callExecutorJMX(String hostPort, String action, String mBean) throws IOException; public void start() throws ExecutorManagerException; public void shutdown(); public Set<String> getAllActiveExecutorServerHosts(); public State getExecutorManagerThreadState(); public boolean isExecutorManagerThreadActive(); public long getLastExecutorManagerThreadCheckTime(); public Set<? extends String> getPrimaryServerHosts(); /** * Returns a collection of all the active executors maintained by active executors */ public Collection<Executor> getAllActiveExecutors(); /** * <pre> * Fetch executor from executors with a given executorId * Note: * 1. throws an Exception in case of a SQL issue * 2. return null when no executor is found with the given executorId * </pre> */ public Executor fetchExecutor(int executorId) throws ExecutorManagerException; /** * <pre> * Setup activeExecutors using azkaban.properties and database executors * Note: * 1. If azkaban.use.multiple.executors is set true, this method will * load all active executors * 2. In local mode, If a local executor is specified and it is missing from db, * this method add local executor as active in DB * 3. In local mode, If a local executor is specified and it is marked inactive in db, * this method will convert local executor as active in DB * </pre> */ public void setupExecutors() throws ExecutorManagerException; /** * Enable flow dispatching in QueueProcessor */ public void enableQueueProcessorThread() throws ExecutorManagerException; /** * Disable flow dispatching in QueueProcessor */ public void disableQueueProcessorThread() throws ExecutorManagerException; public String getAllExecutionJobLog(ExecutableFlow exFlow, String jobId, int attempt) throws ExecutorManagerException; public List<ExecutableFlow> getUserExecutableFlows(int skip, int size, String user) throws ExecutorManagerException; public List<ExecutableFlow> getUserExecutableFlowsByAdvanceFilter(String projContain, String flowContain,String execIdContain, String userContain, String status, long begin, long end, int skip, int size, int flowType) throws ExecutorManagerException; public List<ExecutableFlow> getUserExecutableFlowsQuickSearch(String flowIdContains, String user, int skip, int size) throws ExecutorManagerException; /** * * @param projectId * @param flowId * @return * @throws ExecutorManagerException */ ExecutableFlow getProjectLastExecutableFlow(int projectId, String flowId) throws ExecutorManagerException; /** * 根据执行ID获取所有执行日志压缩包地址 * @return * @throws ExecutorManagerException */ String getDownLoadAllExecutionLog(ExecutableFlow executableFlow) throws ExecutorManagerException; /** * 根据 Job ID 获取 Job日志 压缩包地址 * @return * @throws ExecutorManagerException */ String getJobLogByJobId(int execId, String jobName) throws ExecutorManagerException; /** * 获取所有的日志过滤条件 * @return * @throws ExecutorManagerException */ List<LogFilterEntity> listAllLogFilter() throws ExecutorManagerException; /** * 根据条件获取历史记录总条数 * @param filterMap * @return * @throws ExecutorManagerException */ public int getExecHistoryTotal(final Map<String, String> filterMap) throws ExecutorManagerException; int getExecHistoryTotal(String username, final Map<String, String> filterMap, List<Integer> projectIds) throws ExecutorManagerException; /** * 根据工程ID查询历史记录总条数 * @param projectIds * @return * @throws ExecutorManagerException */ int getMaintainedExecHistoryTotal(String username, List<Integer> projectIds) throws ExecutorManagerException; /** * 根据条件获取历史记录总条数 * @param filterMap * @return * @throws ExecutorManagerException */ public int getExecHistoryQuickSerachTotal(final Map<String, String> filterMap) throws ExecutorManagerException; public int getMaintainedFlowsQuickSearchTotal(String username, final Map<String, String> filterMap, List<Integer> projectIds) throws ExecutorManagerException; /** * * @param projectId * @param flowId * @param from * @param length * @param outputList * @return * @throws ExecutorManagerException */ public int getUserExecutableFlowsTotalByProjectIdAndFlowId(int projectId, String flowId, int from, int length, List<ExecutableFlow> outputList, final String userName) throws ExecutorManagerException; public long getExecutableFlowsMoyenneRunTime(int projectId, String flowId, String user) throws ExecutorManagerException; /** * 根据条件获取用户历史记录总条数 * @param filterMap * @return * @throws ExecutorManagerException */ public int getUserExecHistoryTotal(final Map<String, String> filterMap) throws ExecutorManagerException; /** * 根据条件获取历史记录总条数 * @param filterMap * @return * @throws ExecutorManagerException */ public int getUserExecHistoryQuickSerachTotal(final Map<String, String> filterMap) throws ExecutorManagerException; /** * 根据登录用户条件获取历史记录总条数 * @return * @throws ExecutorManagerException */ public List<ExecutableFlow> getUserExecutableFlows(String loginUser, String projContain, String flowContain, String execIdContain, String userContain, String status, long begin, long end, int skip, int size, int flowType) throws ExecutorManagerException; /** * * @param userName * @return * @throws ExecutorManagerException */ public List<ExecutableFlow> getTodayExecutableFlowData(final String userName) throws ExecutorManagerException; /** * * @param userName * @return * @throws ExecutorManagerException */ public List<ExecutableFlow> getTodayExecutableFlowDataNew(final String userName) throws ExecutorManagerException; /** * 获取定时调度任务今天运行次数 * @param flowId * @return * @throws ExecutorManagerException */ public Integer getTodayFlowRunTimesByFlowId(final String projectId, final String flowId, final String usename) throws ExecutorManagerException; /** * * @param userName * @return * @throws ExecutorManagerException */ public List<ExecutableFlow> getRealTimeExecFlowData(final String userName) throws ExecutorManagerException; /** * * @return * @throws ExecutorManagerException */ public ExecutableFlow getRecentExecutableFlow(final int projectId, final String flowId) throws ExecutorManagerException; /** * 获取正在执行的工作流数据集合 */ List<Map<String,String>> getExectingFlowsData() throws IOException; int getExecutionCycleTotal(Optional<String> usernameOp) throws ExecutorManagerException; int getExecutionCycleTotal(String username, List<Integer> projectIds) throws ExecutorManagerException; List<ExecutionCycle> listExecutionCycleFlows(Optional<String> usernameOP, int offset, int length) throws ExecutorManagerException; List<ExecutionCycle> listExecutionCycleFlows(String username, List<Integer> projectIds, int offset, int length) throws ExecutorManagerException; int saveExecutionCycleFlow(ExecutionCycle cycleFlow) throws ExecutorManagerException; ExecutionCycle getExecutionCycleFlow(String projectId, String flowId) throws ExecutorManagerException; ExecutionCycle getExecutionCycleFlow(int id) throws ExecutorManagerException; int updateExecutionFlow(ExecutionCycle executionCycle) throws ExecutorManagerException; int stopAllCycleFlows() throws ExecutorManagerException; List<ExecutionCycle> getAllRunningCycleFlows() throws ExecutorManagerException; }
/** * Contains {@link textstatistics.client.view.TextStatisticsView} class who * describes view of TextStatistics client application. */ package textstatistics.client.view;
package com.aipiao.bkpkold; import android.app.Application; import com.mastersdk.android.NewMasterSDK; import java.util.ArrayList; import cn.bmob.v3.Bmob; import cn.jpush.android.api.JPushInterface; /** * Created by caihui on 2018/3/20. */ public class FbApplication extends Application { @Override public void onCreate() { super.onCreate(); try { Bmob.initialize(this, "1ed31a5067fb491eeb33cb3e2298263f"); JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志 JPushInterface.init(this); // 初始化 JPush Class<?> arg0 = WelcomeActivity.class; ArrayList<String> arg1 = new ArrayList<>(); arg1.add("http://dmeushk2981.com:9991"); arg1.add("http://apsiujk2819.com:9991"); arg1.add("http://dmeushk2981.com:9991"); arg1.add("http://dkieual123.com:9991"); arg1.add("http://smdi301oa.com:9991"); Application arg2 = this; NewMasterSDK.init(arg0, arg1, arg2); } catch (Exception e) { e.printStackTrace(); } } }
package br.com.senior.furb.basico; import java.util.ArrayList; import java.util.List; import java.util.Map; import br.com.senior.furb.basico.BasicoValidator; import br.com.senior.furb.basico.*; public class TrocaDiretorFilmeInput { /** * Nome do filme */ public String filme; /** * Nome do genero */ public String diretor; public TrocaDiretorFilmeInput() { } /** * This constructor allows initialization of all fields, required and optional. */ public TrocaDiretorFilmeInput(String filme, String diretor) { this.filme = filme; this.diretor = diretor; } public void validate() { validate(true); } public void validate(boolean required) { validate(null, required); } public void validate(Map<String, Object> headers, boolean required) { validate(headers, required, new ArrayList<>()); } void validate(Map<String, Object> headers, boolean required, List<Object> validated) { BasicoValidator.validate(this, headers, required, validated); } @Override public int hashCode() { int ret = 1; if (filme != null) { ret = 31 * ret + filme.hashCode(); } if (diretor != null) { ret = 31 * ret + diretor.hashCode(); } return ret; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TrocaDiretorFilmeInput)) { return false; } TrocaDiretorFilmeInput other = (TrocaDiretorFilmeInput) obj; if ((filme == null) != (other.filme == null)) { return false; } if ((filme != null) && !filme.equals(other.filme)) { return false; } if ((diretor == null) != (other.diretor == null)) { return false; } if ((diretor != null) && !diretor.equals(other.diretor)) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); toString(sb, new ArrayList<>()); return sb.toString(); } void toString(StringBuilder sb, List<Object> appended) { sb.append(getClass().getSimpleName()).append(" ["); if (appended.contains(this)) { sb.append("<Previously appended object>").append(']'); return; } appended.add(this); sb.append("filme=").append(filme == null ? "null" : filme).append(", "); sb.append("diretor=").append(diretor == null ? "null" : diretor); sb.append(']'); } }
/* * In java Integer, Float , Double.. are classes that extends the abstract class Number * here we can create object for Interger, Float classes * so we can use Number class that has all Integer , Float classes instead of creating the objects and mehthods * refer below program to understand why we need the abstract class */ class Printer { public void show(Number i) { // Number is a abstract super class that has all the // the properties of Integer, Float , int, .... System.out.println("the number is " + i) ; } } public class WhyAbstract { public static void main(String[] args) { Printer p = new Printer(); p.show(55); p.show(55.6789); p.show(89.4f); } }
package com.codetop.dp; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; public class CoinChange { /** * dp[i]的含义 凑出总金额为amount的最少硬币个数 * * 状态转移方程 * dp[i] = min(dp[i-coin[0]],dp[i-coin[1]],...,dp[i-coin[j]])+1 * * 如果min(dp[i-coin[0]],dp[i-coin[1]],...,dp[i-coin[j]])等于0,就不加1 * * 初始值 * dp[0] = 0 * * return dp[amount] * * * public int coinChange(int[] coins, int amount) { * if(coins.length == 0){ * return -1; * } * int[] dp=new int[amount+1]; * dp[0]=0; * for(int i = 1;i<=amount;i++){ * int min = Integer.MAX_VALUE; * for (int j = 0;j<coins.length;j++){ * if(i-coins[j]>=0 && dp[i-coins[j]] < min){ * min = dp[i-coins[j]]; * } * } * dp[i]=(min==Integer.MAX_VALUE?Integer.MAX_VALUE:min+1); * } * return dp[amount]==Integer.MAX_VALUE ? -1:dp[amount]; * } * * * @param coins * @param amount * @return */ public int coinChange(int[] coins, int amount) { int[] dp = new int[amount+1]; Arrays.fill(dp,amount+1); dp[0] = 0; for (int i = 1; i < amount+1; i++) { for (int j = 0; j < coins.length; j++) { if(i>=coins[j]){ dp[i] = Math.min(dp[i],dp[i-coins[j]]+1); } } System.out.println(dp[i]); } return dp[amount] == amount+1 ? -1 : dp[amount]; } public int coinChange2(int[] coins, int amount) { int[] dp = new int[amount+1]; Arrays.fill(dp,Integer.MAX_VALUE); dp[0] = 0; for (int i = 1; i < amount+1; i++) { for (int j = 0; j < coins.length; j++) { if(i>=coins[j]){ dp[i] = Math.min(dp[i],dp[i-coins[j]]); } } if (dp[i] != Integer.MAX_VALUE) { dp[i] = dp[i] +1; } System.out.println(dp[i]); } return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount]; } @Test public void test(){ /** * coins = [1, 5, 11], amount = 15 * * [186,419,83,408] * 6249 * 输出: * 15 * 预期结果: * 20 */ int[] nums = new int[]{2}; Assert.assertEquals(0,coinChange2(nums,3)); } }
package org.View; import java.io.IOException; import java.util.ResourceBundle; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; public class MyLogger { private static FileHandler fileTxt; private static ConsoleHandler consoleTxt; private static SimpleFormatter formatterTxt; public static void setup(final ResourceBundle languageBundle) throws FileException { Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); Logger rootLogger = Logger.getLogger(""); Handler[] handlers = rootLogger.getHandlers(); if (handlers[0] instanceof ConsoleHandler) { rootLogger.removeHandler(handlers[0]); } logger.setLevel(Level.INFO); try { fileTxt = new FileHandler("Logging.txt"); consoleTxt = new ConsoleHandler(); } catch (IOException e) { throw new FileException(languageBundle.getString("file"), e); } formatterTxt = new SimpleFormatter(); fileTxt.setFormatter(formatterTxt); consoleTxt.setFormatter(formatterTxt); logger.addHandler(fileTxt); logger.addHandler(consoleTxt); } }
package br.com.android.fjanser.hotspotz; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewCompat; import android.support.v7.widget.ShareActionProvider; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; //import com.bumptech.glide.Glide; import java.util.Arrays; import br.com.android.fjanser.hotspotz.database.HotSpotContract; import br.com.android.fjanser.hotspotz.database.HotSpotDBHelper; import br.com.android.fjanser.hotspotz.database.HotSpotProvider; //import br.com.android.fjanser.hotspotz.http.MovieByIdTask; import br.com.android.fjanser.hotspotz.model.HotSpot; import br.com.android.fjanser.hotspotz.R; import static android.R.attr.onClick; public class DetailHotSpotFragment extends Fragment { private static final String EXTRA_HOTSPOT = "hotspot"; private static final int LOADER_DB = 0; private static final int LOADER_WEB = 1; ImageView imgPoster; TextView txtTitle; TextView txtYear; TextView txtGenre; TextView txtDirector; TextView txtPlot; TextView txtRuntime; TextView txtActors; RatingBar rating; TextView txtEtapa1; EditText editTxtEtapa1; TextView txtEtapa2; EditText editTxtEtapa2; TextView txtEtapa3; EditText editTxtEtapa3; TextView txtEtapa4; EditText editTxtEtapa4; TextView txtEtapa5; EditText editTxtEtapa5; TextView txtEtapa6; EditText editTxtEtapa6; TextView txtEtapa7; EditText editTxtEtapa7; Button btnAttPontuacoes; HotSpot mHotSpot; LocalBroadcastManager mLocalBroadcastManager; HotSpotEventReceiver mReceiver; ShareActionProvider mShareActionProvider; Intent mShareIntent; // Para criarmos um DetailMovieFragment precisamos passar um objeto Movie public static DetailHotSpotFragment newInstance(HotSpot hotSpot) { Bundle args = new Bundle(); args.putSerializable(EXTRA_HOTSPOT, hotSpot); DetailHotSpotFragment detailHotSpotFragment = new DetailHotSpotFragment(); detailHotSpotFragment.setArguments(args); return detailHotSpotFragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inicializando o layout do fragment... View view = inflater.inflate(R.layout.fragment_detail_hotspot, container, false); //View view = inflater.inflate(R.layout.fragment_detail_hotspot, container, false); //imgPoster = (ImageView)view.findViewById(R.id.detail_image_poster); //txtTitle = (TextView)view.findViewById(R.id.detail_text_title); // txtYear = (TextView)view.findViewById(R.id.detail_text_year); // txtGenre = (TextView)view.findViewById(R.id.detail_text_genre); // txtDirector = (TextView)view.findViewById(R.id.detail_text_director); // txtPlot = (TextView)view.findViewById(R.id.detail_text_plot); // txtRuntime = (TextView)view.findViewById(R.id.detail_text_runtime); // txtActors = (TextView)view.findViewById(R.id.detail_text_actors); // rating = (RatingBar)view.findViewById(R.id.detail_rating); //editTxtEtapa1 = (EditText) view.findViewById(R.id.detail_text_etapa1); //editTxtEtapa2 = (EditText) view.findViewById(R.id.detail_text_etapa2); //editTxtEtapa3 = (EditText) view.findViewById(R.id.detail_text_etapa3); //editTxtEtapa4 = (EditText) view.findViewById(R.id.detail_text_etapa4); //editTxtEtapa5 = (EditText) view.findViewById(R.id.detail_text_etapa5); //editTxtEtapa6 = (EditText) view.findViewById(R.id.detail_text_etapa6); //editTxtEtapa7 = (EditText) view.findViewById(R.id.detail_text_etapa7); //btnAttPontuacoes = (Button) view.findViewById(R.id.btnAttPontuacoes); //btnAttPontuacoes.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // atualizarPontuacaoEquipe(); // } //}); // Animação de transição de tela //ViewCompat.setTransitionName(imgPoster, "capa"); //ViewCompat.setTransitionName(txtTitle, "titulo"); //ViewCompat.setTransitionName(txtYear, "ano"); // Inicializamos mMovie (ver onSaveInsatnceState) if (savedInstanceState == null){ // Se não tem um estado anterior, use o que foi passado no método newInstance. mHotSpot = (HotSpot)getArguments().getSerializable(EXTRA_HOTSPOT); } else { // Se há um estado anterior, use-o mHotSpot = (HotSpot)savedInstanceState.getSerializable(EXTRA_HOTSPOT); } // Se o objeto mMovie possui um ID (no banco local), carregue do banco local, // senão carregue do servidor. // boolean isFavorite = MovieDetailUtils.isFavorite(getActivity(), mMovie.getImdbId()); // if (isFavorite){ // // Faz a requisição em background ao banco de dados (ver mCursorCallback) // getLoaderManager().initLoader(LOADER_DB, null, mCursorCallback); // } else { // // Faz a requisição em background ao servidor (ver mMovieCallback) // getLoaderManager().initLoader(LOADER_WEB, null, mMovieCallback); // } //txtTitle.setText("Equipe " + String.valueOf(mHotSpot.getEquipe())); //recuperaPontuacoesEquipe(); //editTxtEtapa1.setText(String.valueOf(mHotSpot.getEtapa1())); //editTxtEtapa2.setText(String.valueOf(mHotSpot.getEtapa2())); //editTxtEtapa3.setText(String.valueOf(mHotSpot.getEtapa3())); //editTxtEtapa4.setText(String.valueOf(mHotSpot.getEtapa4())); //editTxtEtapa5.setText(String.valueOf(mHotSpot.getEtapa5())); //editTxtEtapa6.setText(String.valueOf(mHotSpot.getEtapa6())); //editTxtEtapa7.setText(String.valueOf(mHotSpot.getEtapa7())); //// Registramos o receiver para tratar sabermos quando o botão de favoritos da //// activity de detalhes foi chamado. //mReceiver = new MovieEventReceiver(); //mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity()); //mLocalBroadcastManager.registerReceiver(mReceiver, new IntentFilter(HotSpotEvent.UPDATE_FAVORITE)); return view; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Precisamos manter o objeto mMovie atualizado pois ele pode ter sido // incluído e excluído dos favoritos. outState.putSerializable(EXTRA_HOTSPOT, mHotSpot); } @Override public void onDestroyView() { super.onDestroyView(); // Desregistramos o receiver ao destruir a View do fragment //mLocalBroadcastManager.unregisterReceiver(mReceiver); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_detail, menu); MenuItem item = menu.findItem(R.id.menu_item_share); mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item); if (mShareIntent != null){ mShareActionProvider.setShareIntent(mShareIntent); } } // --------------- LoaderManager.LoaderCallbacks<Movie> // Esse callback trata o retorno da requisição feita ao servidor LoaderManager.LoaderCallbacks mHotSpotCallback = new LoaderManager.LoaderCallbacks<HotSpot>() { @Override public Loader<HotSpot> onCreateLoader(int id, Bundle args) { // inicializa a requisição em background para o servidor usando AsyncTaskLoader // (veja a classe MovieByIdTask) return null;//new MovieByIdTask(getActivity(), mMovie.getImdbId()); } @Override public void onLoadFinished(Loader<HotSpot> loader, HotSpot hotSpot) { updateUI(hotSpot); } @Override public void onLoaderReset(Loader<HotSpot> loader) { } }; // --------------- LoaderManager.LoaderCallbacks<Cursor> // Esse callback trata o retorno da requisição feita ao servidor LoaderManager.LoaderCallbacks<Cursor> mCursorCallback = new LoaderManager.LoaderCallbacks<Cursor>(){ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // inicializa a requisição em background para o ContentProvider usando CursorLoader // perceba que estamos utilizando a Uri específica // (veja o método query do MovieProvider) return new CursorLoader(getActivity(), HotSpotProvider.HOTSPOT_URI, null, HotSpotContract.COL_ENDERECO +" = ?", new String[]{ String.valueOf(mHotSpot.getEndereco()) }, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Ao receber o retorno do cursor, criamos um objeto Movie e preenchemos a tela // (ver updateUI) if (cursor != null && cursor.moveToFirst()) { HotSpot hotSpot = new HotSpot(); hotSpot.setId(cursor.getLong(cursor.getColumnIndex(HotSpotContract._ID))); hotSpot.setEndereco(cursor.getString(cursor.getColumnIndex(HotSpotContract.COL_ENDERECO))); hotSpot.setPais(cursor.getString(cursor.getColumnIndex(HotSpotContract.COL_PAIS))); hotSpot.setLatitude(cursor.getFloat(cursor.getColumnIndex(HotSpotContract.COL_LATITUDE))); hotSpot.setLongitude(cursor.getFloat(cursor.getColumnIndex(HotSpotContract.COL_LONGITUDE))); updateUI(hotSpot); createShareIntent(hotSpot); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }; private void createShareIntent(HotSpot hotSpot) { mShareIntent = new Intent(Intent.ACTION_SEND); mShareIntent.setType("text/plain"); mShareIntent.putExtra(Intent.EXTRA_TEXT,getString(R.string.share_text, hotSpot.getEndereco(), hotSpot.getPais())); } // --------------- INNER // Esse receiver é chamado pelo FAB da DetailActivity para iniciar o processo // de inserir/excluir o movie nos favoritos class HotSpotEventReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(HotSpotEvent.UPDATE_FAVORITE)) { toggleFavorite(); } } } // --------------- PRIVATE private void updateUI(HotSpot hotSpot){ // Atualiza o objeto mMovie com os dados vindos dos callbacks // (ver mCursorCallback e mMovieCallback) mHotSpot = hotSpot; //txtTitle.setText(hotSpot.getTitle()); //txtYear.setText(hotSpot.getYear()); //txtGenre.setText(hotSpot.getGenre()); //txtDirector.setText(hotSpot.getDirector()); //txtPlot.setText(hotSpot.getPlot()); //txtRuntime.setText(hotSpot.getRuntime()); //rating.setRating(hotSpot.getRating() / 2); // Tanto no JSON quanto no Banco, estamos salvando a lista // de atores separado por vírgula //TODO Criar uma nova tabela e fazer chave estrangeira // StringBuffer sb = new StringBuffer(); // for (String actor : hotSpot.getActors()) { // sb.append(actor).append('\n'); // } // txtActors.setText(sb.toString()); // // // Enviando mensagem para todos que querem saber que o filme carregou // // (ver DetailActivity.MovieReceiver) // notifyUpdate(HotSpotEvent.HOTSPOT_LOADED); // // // Quando estiver em tablet, exiba o poster no próprio fragment // if (getResources().getBoolean(R.bool.tablet)){ // imgPoster.setVisibility(View.VISIBLE); // //Glide.with(imgPoster.getContext()).load(movie.getPoster()).into(imgPoster); // } } // Método auxiliar que insere/remove o movie no banco de dados private void toggleFavorite() { if (mHotSpot == null) return; // isso não deve acontecer... // Primeiro verificamos se o livro está no banco de dados boolean isFavorite = HotSpotDetailUtils.isFavorite(getActivity(), mHotSpot.getEndereco()); boolean success = false; if (isFavorite) { // Se já é favorito, exclua if (deleteFavorite(mHotSpot.getId())){ success = true; mHotSpot.setId(0); getLoaderManager().destroyLoader(LOADER_DB); } //TODO Mensagem de erro ao excluir } else { // Se não é favorito, inclua... long id = insertFavorite(mHotSpot); success = id > 0; mHotSpot.setId(id); } // Se deu tudo certo... if (success) { // Envia a mensagem para as activities (para atualizar o FAB) notifyUpdate(HotSpotEvent.HOTSPOT_FAVORITE_UPDATED); // Exibe o snackbar que permite o "desfazer" //TODO Internailizar a aplicação // Snackbar.make(getView(), // isFavorite ? R.string.msg_removed_favorites : R.string.msg_added_favorites, // Snackbar.LENGTH_LONG) // .setAction(R.string.text_undo, new View.OnClickListener() { // @Override // public void onClick(View v) { // toggleFavorite(); // } // }).show(); } } private void notifyUpdate(String action){ // Cria a intent e dispara o broadcast Intent it = new Intent(action); it.putExtra(HotSpotEvent.EXTRA_HOTSPOT, mHotSpot); mLocalBroadcastManager.sendBroadcast(it); } // Método auxiliar para excluir nos favoritos //TODO fazer delete em background private boolean deleteFavorite(long hotspotId){ return getActivity().getContentResolver().delete( ContentUris.withAppendedId(HotSpotProvider.HOTSPOT_URI, hotspotId), null, null) > 0; } // Método auxiliar para inserir nos favoritos //TODO fazer insert em background private long insertFavorite(HotSpot hotSpot){ ContentValues contentValues = new ContentValues(); contentValues.put(HotSpotContract.COL_ENDERECO, hotSpot.getEndereco()); contentValues.put(HotSpotContract.COL_PAIS, hotSpot.getPais()); contentValues.put(HotSpotContract.COL_LATITUDE, hotSpot.getLatitude()); contentValues.put(HotSpotContract.COL_LONGITUDE, hotSpot.getLongitude()); Uri uri = getActivity().getContentResolver().insert(HotSpotProvider.HOTSPOT_URI, contentValues); //TODO mensagem de erro ao falhar return ContentUris.parseId(uri); } public void recuperaCoordenadas(){ HotSpotDBHelper mHelper; SQLiteDatabase db; Cursor cursor; mHelper = new HotSpotDBHelper(getContext()); db = mHelper.getReadableDatabase(); cursor = db.rawQuery("SELECT " + HotSpotContract.COL_ENDERECO + ", " + HotSpotContract.COL_PAIS + ", " + HotSpotContract.COL_LATITUDE + ", " + HotSpotContract.COL_LONGITUDE + " FROM " + HotSpotContract.TABLE_NAME + " " + "WHERE " + HotSpotContract.COL_ENDERECO + " Like '%?%' ", new String[]{mHotSpot.getEndereco()}); if(cursor.getCount() > 0){ cursor.moveToFirst(); mHotSpot.setPais(cursor.getString(cursor.getColumnIndex(HotSpotContract.COL_PAIS))); mHotSpot.setLatitude(cursor.getFloat(cursor.getColumnIndex(HotSpotContract.COL_LATITUDE))); mHotSpot.setLongitude(cursor.getFloat(cursor.getColumnIndex(HotSpotContract.COL_LONGITUDE))); } cursor.close(); } }
import java.util.*; class ShowEvenIndexElements { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter The Size Of An Array "); int size=sc.nextInt(); int i=0,j=0; int sum=0; int arr[]=new int[size]; for(i=0;i<arr.length;i++) { System.out.print("Enter "+i+" index: "); arr[i]=sc.nextInt(); } System.out.println(); for(i=0;i<arr.length;i++) { // System.out.print(" "+arr[i]); if(i%2==0) { // System.out.println(); System.out.println("even index of Array is "+arr[i]+"at index "+i); } } } }
package com.gestion.service.impression; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.ArrayList; import javax.servlet.http.HttpServletResponse; import com.gestion.entity.Bonlivraison; import com.gestion.entity.Intervention; import com.gestion.entity.Livraison; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfPageEventHelper; import com.itextpdf.text.pdf.PdfWriter; public class HeaderFooterIntervention extends PdfPageEventHelper { Phrase[] header = new Phrase[2]; int pagenumber; public HeaderFooterIntervention(Intervention inter , HttpServletResponse response , String logo , Font.FontFamily font) { try { Document document = new Document(PageSize.A4); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); PdfWriter g = PdfWriter.getInstance(document, baos);; g.setBoxSize("art", new Rectangle(36, 54, 559, 788)); g.setBoxSize("art1", new Rectangle(36, 300, 200, 788)); g.setPageEvent(this); document.open(); document.add(ServiceImpression.addImage(logo)); ServiceImpression.addLine(g , document); BonIntervention.addTitlePage(document , inter , "INTERVENTION INFORMATIQUE : " , font); BonIntervention.getTable(document , inter , g ); document.close(); response.addHeader("Expires", "0"); response.addHeader("Content-Disposition", "attachment"); response.setContentType("application/pdf"); response.setContentLength(baos.size()); OutputStream os = response.getOutputStream(); baos.writeTo(os); os.flush(); os.close(); g.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); } } }
package cn.yq.web.controller; import cn.yq.service.BusinessService; import cn.yq.service.impl.BusinessServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; /** * @author 钦 * @create 2019-08-29 16:51 */ public class ListBookServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BusinessService businessService=new BusinessServiceImpl(); Map map=businessService.getAll(); request.setAttribute("map",map); request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response){ doPost(request, response); } }
package us.gibb.dev.gwt.server.appengine.inject; import javax.servlet.http.HttpServletRequest; import net.sf.gilead.adapter4appengine.EngineRemoteService; import us.gibb.dev.gwt.server.appengine.remote.AppengineProcessCallHandler; import us.gibb.dev.gwt.server.remote.RemoteServiceAdapter; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPCRequest; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; @Singleton public class AppengineRemoteServiceServlet extends EngineRemoteService implements RemoteServiceAdapter { private static final long serialVersionUID = 68052617558196206L; @Inject private Injector injector; @Inject private AppengineProcessCallHandler processCallHandler; @Override public String processCall(String payload) throws SerializationException { return processCallHandler.processCall(payload, this); } @Override public void onAfterRequestDeserialized(RPCRequest rpcRequest) { super.onAfterRequestDeserialized(rpcRequest); } @Override public RemoteService getRemoteService(Class<?> serviceClass) { return (RemoteService) injector.getInstance(serviceClass); } @Override public HttpServletRequest getRequest() { return getThreadLocalRequest(); } }
package mb.tianxundai.com.toptoken.aty.login; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.sahooz.library.Country; import com.sahooz.library.LetterHolder; import com.sahooz.library.PickActivity; import com.sahooz.library.PyAdapter; import com.sahooz.library.PyEntity; import com.sahooz.library.SideBar; import com.sahooz.library.VH; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.base.BaseAty; import mb.tianxundai.com.toptoken.interfaces.DarkNavigationBarTheme; import mb.tianxundai.com.toptoken.interfaces.DarkStatusBarTheme; import mb.tianxundai.com.toptoken.interfaces.Layout; import mb.tianxundai.com.toptoken.uitl.JumpParameter; /** * @author txd_dbb * @emil 15810277571@163.com * create at 2018/10/1611:48 * description: */ @Layout(R.layout.aty_pick) @DarkStatusBarTheme(true) //开启顶部状态栏图标、文字暗色模式 //@NavigationBarBackgroundColor(a = 0, r = 0, g = 0, b = 0) //透明颜色 设置底部导航栏背景颜色(a = 255,r = 255,g = 255,b = 255 黑色的) @DarkNavigationBarTheme(true) //开启底部导航栏按钮暗色 public class PickAty extends BaseAty { @BindView(R.id.et_search) EditText etSearch; @BindView(R.id.rv_pick) RecyclerView rvPick; @BindView(R.id.side) SideBar side; @BindView(R.id.tv_letter) TextView tvLetter; private ArrayList<Country> selectedCountries = new ArrayList<>(); private ArrayList<Country> allCountries = new ArrayList<>(); @Override public void initViews() { ButterKnife.bind(this); } @Override public void initDatas(JumpParameter jumpParameter) { allCountries.clear(); allCountries.addAll(Country.getAll(this, null)); selectedCountries.clear(); selectedCountries.addAll(allCountries); final CAdapter adapter = new CAdapter(selectedCountries); rvPick.setAdapter(adapter); final LinearLayoutManager manager = new LinearLayoutManager(this); rvPick.setLayoutManager(manager); rvPick.setAdapter(adapter); // adapter.setOnItemClickListener(new PyAdapter.OnItemClickListener() { // @Override // public void onItemClick(PyEntity entity, int position) { // Log.i("city",selectedCountries.get(position).toJson()); // setResponse(new JumpParameter().put("country", selectedCountries.get(position).toJson())); // finish(); // } // }); rvPick.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String string = s.toString(); selectedCountries.clear(); for (Country country : allCountries) { if (country.name.toLowerCase().contains(string.toLowerCase())) selectedCountries.add(country); } adapter.update(selectedCountries); } }); side.addIndex("#", side.indexes.size()); side.setOnLetterChangeListener(new SideBar.OnLetterChangeListener() { @Override public void onLetterChange(String letter) { tvLetter.setVisibility(View.VISIBLE); tvLetter.setText(letter); int position = adapter.getLetterPosition(letter); if (position != -1) { manager.scrollToPositionWithOffset(position, 0); } } @Override public void onReset() { tvLetter.setVisibility(View.GONE); } }); } @Override public void setEvents() { } class CAdapter extends PyAdapter<RecyclerView.ViewHolder> { public CAdapter(List<? extends PyEntity> entities) { super(entities); } @Override public RecyclerView.ViewHolder onCreateLetterHolder(ViewGroup parent, int viewType) { return new LetterHolder(getLayoutInflater().inflate(com.sahooz.library.R.layout.item_letter, parent, false)); } @Override public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) { return new VH(getLayoutInflater().inflate(com.sahooz.library.R.layout.item_country_large_padding, parent, false)); } @Override public void onBindHolder(RecyclerView.ViewHolder holder, PyEntity entity, int position) { VH vh = (VH) holder; final Country country = (Country) entity; vh.ivFlag.setImageResource(country.flag); vh.tvCode.setText("+" + country.code); vh.tvName.setText(country.name); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("city",country.toJson()); setResponse(new JumpParameter().put("country", country.toJson())); finish(); } }); } @Override public void onBindLetterHolder(RecyclerView.ViewHolder holder, LetterEntity entity, int position) { ((LetterHolder) holder).textView.setText(entity.letter.toUpperCase()); } } }
package com.vuforia.samples.VuforiaSamples.ui.Common; import android.app.Activity; import android.app.ProgressDialog; import android.net.Uri; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; /** * Created by K.Oda on 2017/12/16. */ public class HttpRequest extends AsyncTask<Uri.Builder, Integer, String> implements HttpInterFace{ private String url; private String json; private CallBackTask callBackTask; private Activity activity; public ProgressType progressType = ProgressType.DIALOG; private ProgressDialog progressDialog; public HttpRequest(String url,String json, Activity activity){ this.url = url; this.json = json; this.activity = activity; } public String excutePost(String url, String json) { HttpURLConnection connection = null; OutputStream outputStream = null; PrintStream ps = null; String res = ""; try { //URL設定 URL ur = new URL(url); connection = (HttpURLConnection) ur.openConnection(); connection.setRequestMethod("POST"); //no Redirects connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); connection.setReadTimeout(10000); connection.setConnectTimeout(20000); //ヘッダーの設定 connection.addRequestProperty("Content-Type", "application/json; charset=UTF-8"); //接続 connection.connect(); //リクエストボディに書き出しを行う outputStream = connection.getOutputStream(); ps = new PrintStream(outputStream); ps.print(json); ps.close(); outputStream.close(); //レスポンスボディの読み出しを行う //String responseCode = connection.getResponseCode(); res = convertToString(connection.getInputStream()); return res;// = "1"; } catch (NullPointerException e) { return res; } catch (ProtocolException e) { e.printStackTrace(); return res; } catch (MalformedURLException e) { e.printStackTrace(); return res; } catch (IOException e) { e.printStackTrace(); return res; } catch (RuntimeException e) { e.printStackTrace(); return res = ""; } finally { ps.close(); } } public static String convertToString(InputStream stream) throws IOException { StringBuffer sb = new StringBuffer(); String line = ""; BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); while (null != (line = br.readLine())) { sb.append(line); } try { stream.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } @Override protected String doInBackground(Uri.Builder... builders) { /* Thread thread = new Thread(); try { thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } */ String res = ""; try { res = (excutePost(this.url,this.json)); }catch (Exception e){ } return res; } @Override protected void onPreExecute(){ try { if(progressType == ProgressType.DIALOG) { //ダイアログを表示する progressDialog = new ProgressDialog(this.activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("接続中"); progressDialog.setCancelable(true); progressDialog.show(); } }catch (Exception e){ e.printStackTrace(); } } @Override protected void onPostExecute(String result){ super.onPostExecute(result); //プログレスダイアログを閉じる try{ if(progressType == ProgressType.DIALOG){ progressDialog.dismiss(); } callBackTask.CallBack(result); }catch (Exception e){ } } public void setOnCallBack(CallBackTask _cbj){ callBackTask = _cbj; } public static abstract class CallBackTask{ abstract public void CallBack(String result); } }
package com.bomoda; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.io.FileWriter; import java.util.ArrayList; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.dao.BizDao; import com.dao.PageDao; import com.dao.impl.BizDaoImpl; import com.dao.impl.PageDaoImpl; import com.pay.domain.Biz; import com.pay.domain.Page; public class TranslatePage { public static void main(String[] args) throws ParseException, IOException { // TODO Auto-generated method stub readHtmlToNewpages("wechat_test/pages"); translatePages("wechat_test/newpages"); } public static void readHtmlToNewpages(String fileName) throws IOException { File inFile = new File(fileName); File outFile = new File("wechat_test//newpages"); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); Document doc = (Document) Jsoup.parse(inFile, "UTF-8"); int num = 0; Elements url = doc.getElementsByTag("URL"); Elements title = doc.getElementsByTag("TITLE"); //Elements content = doc.getElementsByTag("BODY"); Elements time = doc.getElementsByTag("TIME"); Elements date = doc.getElementsByTag("DATE"); Elements id = doc.getElementsByTag("ID"); Elements elements = doc.getAllElements(); ArrayList alid = new ArrayList(); ArrayList alurl = new ArrayList(); ArrayList altitle = new ArrayList(); //ArrayList alcontent = new ArrayList(); ArrayList altime = new ArrayList(); ArrayList aldate = new ArrayList(); ArrayList al = new ArrayList(); for (Element i : url) { alurl.add(i.text()); } for (Element i : title) { num++; if (num % 2 == 0) { altitle.add(i.text()); } } //for (Element i : content) { // alcontent.add(i.text()); //} for (Element i : id) { alid.add(i.text()); } for (Element i : date) { aldate.add(i.text()); } for (Element i : time) { altime.add(i.text()); } for (int i = 0; i < alurl.size(); i++) { bw.write(String.valueOf(alid.get(i))); bw.write("\t"); bw.write(String.valueOf(alurl.get(i))); bw.write("\t"); bw.write(String.valueOf(altitle.get(i))); bw.write("\t"); bw.write(String.valueOf(altitle.get(i))); bw.write("\t"); bw.write(String.valueOf(altime.get(i))); bw.write("\t"); bw.write(String.valueOf(aldate.get(i))); bw.write("\t"); bw.write("\r\n"); } bw.close(); } public static void translatePages(String fileName) throws ParseException { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { System.out.println("line " + line + ": " + tempString); String[] recordStr = tempString.split("\t"); for (int i = 0; i < recordStr.length; i++) { System.out.println(i + " " + recordStr[i]); } Page page = new Page(); page.setId(Integer.parseInt(recordStr[0])); page.setUrl(recordStr[1]); page.setTitle(recordStr[2]); page.setContent(recordStr[3]); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Long time = new Long(Long.parseLong(recordStr[4])); String d = format.format(time); String[] mytime = d.split(" "); Date date = format.parse(recordStr[5]+ " " + mytime[1]); page.setTimestamp(date); PageDao pagedb = new PageDaoImpl(); pagedb.insert(page); pagedb.commit(); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } }
package TheFifth; import java.io.InputStream; import java.net.URL; import java.util.Scanner; public class URLfir { String temp = null; public URLfir() { try { URL url = new URL("http://jwzx.cqupt.edu.cn/data/json_StudentSearch.php?searchKey=16111804"); InputStream input = url.openStream(); Scanner scan = new Scanner(input); scan.useDelimiter("\n"); while (scan.hasNext()) { temp = temp + scan.next(); } } catch (Exception e) { e.printStackTrace(); } } }
package org.carlook.services.util; public class Konstanten { private Konstanten(){ } public static final String START = "Startseite"; public static final String REGISTER = "Registrierung"; public static final String SUCHE = "Autosuche"; public static final String RSV_AUTOS = "MeineReserviertenAutos"; public static final String VER_MAIN = "MeineInseriertenAutos"; }
package Controllers; import Models.Cliente; import DataBase.DatosAbonosReparacion; import DataBase.DatosReparacion; import Models.Abono; import Models.Reparacion; import java.net.URL; import java.sql.Date; import java.util.Calendar; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Cursor; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javax.swing.JOptionPane; public class AbonoReparacionController implements Initializable { private final DatosAbonosReparacion datosAbonosReparacion = new DatosAbonosReparacion(); private final DatosReparacion datosReparacion = new DatosReparacion(); private Reparacion reparacion = null; @FXML private TextField txtBusqueda; @FXML private TableView<Reparacion> tblReparaciones; @FXML private Label lblArticulo; @FXML private TextField txtArticulo; @FXML private Label lblDescripcion; @FXML private TextArea txtDescripcion; @FXML private Label lblTotalFactura; @FXML private Label lblTotal; @FXML private Label lblPagadoFactura; @FXML private Label lblPagado; @FXML private Label lblFaltanteFactura; @FXML private Label lblFaltante; @FXML private TextField txtMontoAbono; @FXML private RadioButton rbtnEfectivo; @FXML private ToggleGroup rbtngTipoPago; @FXML private RadioButton rbtnTarjeta; @FXML private Button btnRealizarAbono; @FXML private Label lblIdClienteFactura; @FXML private Label lblIdCliente; @FXML private Label lblNombreClienteFactura; @FXML private Label lblNumeroClienteFactura; @FXML private Label lblNombreCliente; @FXML private Label lblNumeroCliente; @FXML private Label lblNoMonto; @FXML private Label lblMontoAbono; @FXML private Label lblTipoDePago; @FXML private Button btnImprimir; @FXML private Button btnNuevoAbono; @Override public void initialize(URL url, ResourceBundle rb) { btnRealizarAbono.setCursor(Cursor.HAND); rbtnEfectivo.setCursor(Cursor.HAND); rbtnTarjeta.setCursor(Cursor.HAND); tblReparaciones.setCursor(Cursor.CROSSHAIR); btnImprimir.setCursor(Cursor.HAND); btnNuevoAbono.setCursor(Cursor.HAND); btnImprimir.setVisible(false); btnNuevoAbono.setVisible(false); ParteReparacion(false); CargarColumnas(); CargarReparaciones("Ninguna"); lblNoMonto.setVisible(false); } @FXML private void BuscarReparacion(KeyEvent event) { if(txtBusqueda.getText().equals("")){ CargarReparaciones("Ninguna"); }else{ CargarReparaciones(txtBusqueda.getText()); } } @FXML private void MostrarReparacion(MouseEvent event) { if(tblReparaciones.getSelectionModel().getSelectedItem() != null){ CargarReparacion(tblReparaciones.getSelectionModel().getSelectedItem()); ParteReparacion(true); } } @FXML private void RealizarAbono(ActionEvent event) { btnRealizarAbono.setDisable(true); if(ValidarMonto()){ int tipoPago = 1; if(rbtnTarjeta.isSelected()){ tipoPago = 2; } double monto = Double.parseDouble(txtMontoAbono.getText()); reparacion = tblReparaciones.getSelectionModel().getSelectedItem(); Calendar c = Calendar.getInstance(); Date fecha = new Date(c.get(Calendar.YEAR)-1900,c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH)); if(datosAbonosReparacion.RealizarAbono(new Abono(0, reparacion.getCodigoReparacion(), monto, fecha, tipoPago))){ reparacion.setMontoPagado(reparacion.getMontoTotal()); btnImprimir.setVisible(true); btnNuevoAbono.setVisible(true); }else{ JOptionPane.showMessageDialog(null, "Error al realizar el Abono"); btnRealizarAbono.setDisable(false); } }else{ btnRealizarAbono.setDisable(false); } } private void ParteReparacion(boolean bandera){ lblArticulo.setVisible(bandera); txtArticulo.setVisible(bandera); lblDescripcion.setVisible(bandera); txtDescripcion.setVisible(bandera); lblIdCliente.setVisible(bandera); lblIdClienteFactura.setVisible(bandera); lblNombreCliente.setVisible(bandera); lblNombreClienteFactura.setVisible(bandera); lblNumeroCliente.setVisible(bandera); lblNumeroClienteFactura.setVisible(bandera); lblTotal.setVisible(bandera); lblTotalFactura.setVisible(bandera); lblPagado.setVisible(bandera); lblPagadoFactura.setVisible(bandera); lblFaltante.setVisible(bandera); lblFaltanteFactura.setVisible(bandera); lblMontoAbono.setVisible(bandera); txtMontoAbono.setVisible(bandera); lblTipoDePago.setVisible(bandera); rbtnEfectivo.setVisible(bandera); rbtnTarjeta.setVisible(bandera); btnRealizarAbono.setVisible(bandera); } private void CargarColumnas() { TableColumn tblCCodigoReparacion = new TableColumn("Codigo"); tblCCodigoReparacion.setCellValueFactory(new PropertyValueFactory<>("codigoReparacion")); tblCCodigoReparacion.setPrefWidth(51); TableColumn tblCArticulo = new TableColumn("Articulo"); tblCArticulo.setCellValueFactory(new PropertyValueFactory<>("articulo")); tblCArticulo.setPrefWidth(171); TableColumn tblCFecha = new TableColumn("Fecha"); tblCFecha.setCellValueFactory(new PropertyValueFactory<>("fecha")); tblCFecha.setPrefWidth(90); TableColumn tblCMontoTotal = new TableColumn("Monto Total"); tblCMontoTotal.setCellValueFactory(new PropertyValueFactory<>("montoTotal")); tblCMontoTotal.setPrefWidth(90); TableColumn tblCMontoPagado = new TableColumn("Monto Pagado"); tblCMontoPagado.setCellValueFactory(new PropertyValueFactory<>("montoPagado")); tblCMontoPagado.setPrefWidth(90); tblReparaciones.getColumns().addAll(tblCCodigoReparacion, tblCArticulo, tblCFecha, tblCMontoTotal, tblCMontoPagado); } private void CargarReparaciones(String busqueda){ tblReparaciones.getItems().clear(); tblReparaciones.getItems().addAll(datosReparacion.CargarReparacionesPendientes(1, busqueda)); } private void CargarReparacion(Reparacion reparacion){ txtArticulo.setText(reparacion.getArticulo()); txtDescripcion.setText(reparacion.getDescripcion()); lblIdCliente.setText(Integer.toString(reparacion.getIdCliente())); Cliente cliente = datosReparacion.Cliente(reparacion.getIdCliente()); lblNombreCliente.setText(cliente.getNombre()); lblNumeroCliente.setText(cliente.getNumero()); lblTotal.setText(String.valueOf(reparacion.getMontoTotal())); lblPagado.setText(String.valueOf(reparacion.getMontoPagado())); lblFaltante.setText(String.valueOf(reparacion.getMontoTotal() - reparacion.getMontoPagado())); } private boolean ValidarMonto(){ if(txtMontoAbono.getText().equals("")){ lblNoMonto.setVisible(true); return false; } try { double monto = Double.parseDouble(txtMontoAbono.getText()); if(monto > Double.parseDouble(lblFaltante.getText())){ JOptionPane.showMessageDialog(null, "Monto Invalido\nEl Monto del Abono no puede ser mayor al monto" + "faltante"); return false; } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Monto Invalido\nNo digite letras en el espacio del Monto del Abono"); return false; } return true; } @FXML private void Imprimir(ActionEvent event) { btnImprimir.setDisable(true); datosReparacion.ImprimirReparacion(reparacion); btnImprimir.setDisable(false); } @FXML private void NuevoAbono(ActionEvent event) { btnNuevoAbono.setDisable(true); txtMontoAbono.setText(""); rbtnEfectivo.setSelected(true); ParteReparacion(false); tblReparaciones.getSelectionModel().select(null); if(txtBusqueda.getText().equals("")){ CargarReparaciones("Ninguna"); }else{ CargarReparaciones(txtBusqueda.getText()); } lblNoMonto.setVisible(false); btnImprimir.setVisible(false); btnNuevoAbono.setVisible(false); btnRealizarAbono.setDisable(false); reparacion = null; btnNuevoAbono.setDisable(false); } }
package Servlets; import Utils.*; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; 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; /** * Servlet implementation class OverviewServlet */ @WebServlet("/OverviewServlet") public class OverviewServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); if(username != null) { float foodEmissions = selectFoodEmissionsbyUser(username); float transportEmissions = selectTransportEmissionsbyUser(username); float avgTransportEmissions = selectTransportEmissionsAvg(); float avgFoodEmissions = selectFoodEmissionsAvg(); if(foodEmissions != -1 && transportEmissions != -1 ) { float totalUserBudget = getUserBudget(username); float totalUserEmissions = foodEmissions + transportEmissions; float remainingBudget = totalUserBudget - totalUserEmissions; float avgEmissions = avgTransportEmissions + avgFoodEmissions; float offset = 0; float meanRemainingBudget = totalUserBudget / 2; String warning = "false"; if(remainingBudget < 0) { warning = "overLimit"; offset = - remainingBudget; remainingBudget = 0; } else if(totalUserEmissions >= meanRemainingBudget) { warning = "aboveMean"; } else { warning = "belowMean"; } RequestDispatcher rd = request.getRequestDispatcher("overview.jsp"); request.setAttribute("FoodEmissions", foodEmissions); request.setAttribute("TransportEmissions", transportEmissions); request.setAttribute("TotalUserEmmissions", totalUserEmissions); request.setAttribute("RemainingBudget", remainingBudget); request.setAttribute("AvgEmissions", avgEmissions); request.setAttribute("TotalUserBudget", totalUserBudget); request.setAttribute("warning", warning); request.setAttribute("offset", offset); request.setAttribute("username", username); rd.forward(request, response); } else { out.print("Oops.. Something went wrong!"); request.setAttribute("username", username); RequestDispatcher rd = request.getRequestDispatcher("overview.jsp"); rd.include(request, response); } } } /** * Calculates & returns the total carbon quantity spent by the user's food consumption * @param username * @return totalCarbonQuantity */ public float selectFoodEmissionsbyUser(String username) { float totalCarbonQuantity = -1; ConnectionDetails connDetails = new ConnectionDetails(); Connection conn = connDetails.getConnection(); String sql = "SELECT SUM(carbonQuantity) AS CarbonSum FROM FoodEmissions WHERE username = ? AND MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())"; try { PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, username); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()) { totalCarbonQuantity = rs.getFloat("CarbonSum"); } } catch(SQLException ex) { ex.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return totalCarbonQuantity; } /** * Calculates & returns the total carbon quantity spent by the user's transport * @param username * @return totalCarbonQuantity */ public float selectTransportEmissionsbyUser(String username) { float totalCarbonQuantity = -1; ConnectionDetails connDetails = new ConnectionDetails(); Connection conn = connDetails.getConnection(); String sql = "SELECT SUM(carbonQuantity) AS CarbonSum FROM TransportEmissions WHERE username = ? AND MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())"; try { PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, username); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()) { totalCarbonQuantity = rs.getFloat("CarbonSum"); } } catch(SQLException ex) { ex.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return totalCarbonQuantity; } /** * Calculates the average carbon emissions by transport from all users * @return avgCarbonQuantity */ public float selectTransportEmissionsAvg() { float avgCarbonQuantity = -1; ConnectionDetails connDetails = new ConnectionDetails(); Connection conn = connDetails.getConnection(); String sql = "SELECT AVG(carbonQuantity) AS CarbonAvg FROM TransportEmissions WHERE MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())"; try { PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { avgCarbonQuantity = rs.getFloat("CarbonAvg"); } } catch(SQLException ex) { ex.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return avgCarbonQuantity; } /** * Returns the average carbon emissions by food from all users * @return avgCarbonQuantity */ public float selectFoodEmissionsAvg() { float avgCarbonQuantity = -1; ConnectionDetails connDetails = new ConnectionDetails(); Connection conn = connDetails.getConnection(); String sql = "SELECT AVG(carbonQuantity) AS CarbonAvg FROM FoodEmissions WHERE MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())"; try { PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { avgCarbonQuantity = rs.getFloat("CarbonAvg"); } } catch(SQLException ex) { ex.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return avgCarbonQuantity; } /** * Returns the specific user's carbon budget * @param username * @return budget */ public float getUserBudget(String username) { float budget = 0; ConnectionDetails connDetails = new ConnectionDetails(); Connection conn = connDetails.getConnection(); String sql = "SELECT budget FROM Users WHERE username = ?"; try { PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, username); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { budget = rs.getFloat("budget"); } } catch(SQLException ex) { ex.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return budget; } }
package com.letscrawl.processor.extract.extractor.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.letscrawl.base.bean.AbstractObject; import com.letscrawl.base.bean.Url; import com.letscrawl.processor.extract.extractor.IExtractor; public class JsoupExtractor extends AbstractObject implements IExtractor { private static final JsoupExtractor instance; private static final String A_ELEMENT = "a[href]"; private static final String A_ATTRIBUTE = "href"; private static final String SRC_ELEMENT = "[src]"; private static final String SRC_ATTRIBUTE = "src"; static { instance = new JsoupExtractor(); } private JsoupExtractor() { } public static JsoupExtractor getInstance() { return instance; } public List<Url> extract(String content) { List<Url> urlList = new ArrayList<Url>(); Set<Url> extractedUrlSet = new HashSet<Url>(); Document document = Jsoup.parse(content); handle(document, A_ELEMENT, A_ATTRIBUTE, urlList, extractedUrlSet); handle(document, SRC_ELEMENT, SRC_ATTRIBUTE, urlList, extractedUrlSet); return urlList; } private void handle(Document document, String elementName, String attributeName, List<Url> urlList, Set<Url> extractedUrlSet) { Elements elements = document.select(elementName); for (Element element : elements) { Url url = new Url(element.attr(attributeName)); if (extractedUrlSet.contains(url)) { continue; } urlList.add(url); extractedUrlSet.add(url); } } }
package slimeknights.tconstruct.library.utils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraftforge.oredict.OreDictionary; import slimeknights.mantle.client.CreativeTab; public final class RecipeUtil { // list of orePreferences, to be filled by the config private static String[] orePreferences = new String[0]; // cache to avoid grabing the same name twice private static Map<String,ItemStack> preferenceCache = new HashMap<>(); private RecipeUtil() {} /** * Called by the config to add the preferences. Do not call outside of Tinkers Construct * @param preferences */ public static void setOrePreferences(String[] preferences) { orePreferences = preferences; } /** * Gets the preferred ore for the given oredict name * @param oreName Oredictionary key * @return The preferred ItemStack, or ItemStack.EMPTY if the name is empty. * This is the same ItemStack from the cache, so be sure to copy it if you plan to place it in an inventory or otherwise change it. */ public static ItemStack getPreference(String oreName) { return preferenceCache.computeIfAbsent(oreName, RecipeUtil::cachePreference); } /** * Function called to actually do the caching * @param oreName String to check * @param items Items to search */ private static ItemStack cachePreference(String oreName) { List<ItemStack> items = OreDictionary.getOres(oreName, false); if(items.isEmpty()) { return ItemStack.EMPTY; } // search through each preference name, finding the first item for the name ItemStack preference = null; for(String mod : orePreferences) { Optional<ItemStack> optional = items .stream() .filter(stack -> stack.getItem().getRegistryName().getResourceDomain().equals(mod)) .findFirst(); // if we found something, use that stack and stop searching if(optional.isPresent()) { preference = optional.get(); break; } } // if we found no preference, just use the first available stack if(preference == null) { preference = items.get(0); } // ensure we do not return a wildcard value if(preference.getMetadata() == OreDictionary.WILDCARD_VALUE) { NonNullList<ItemStack> subItems = NonNullList.create(); preference.getItem().getSubItems(CreativeTab.SEARCH, subItems); // just in case if(subItems.isEmpty()) { // so you have an oredicted item with no sub items? I guess all we can do is give damage 0 preference = preference.copy(); preference.setItemDamage(0); } else { // just grab the first sub item preference = subItems.get(0); } } // finally cache the preference return preference; } }
package models; import java.util.Set; public class GetOne extends BaseRequest { private IModel result; // constructor needed for serialization public GetOne() {} public GetOne(Set<IModel> models) { super(); if(models.isEmpty()) { throw new IllegalArgumentException(); } this.result = (IModel) models.toArray()[0]; } public IModel getResult() { return result; } }
package net.bdsc.entity; import javax.persistence.Entity; import java.math.BigDecimal; @Entity public class Income extends BaseEntity<Long>{ private Long userId; private int productId; private String productName; private int invest; private int frozenInvest; private int frozenInvestTemp; private BigDecimal allBtc; private BigDecimal allHpt; private int allEth; private int lastEth; private BigDecimal lastBtc; private BigDecimal lastHpt; private String lastTime; private String frozenTime; private String investTime; private BigDecimal returnMoney; private int returnDays; private String userName; private String phone; private boolean isExpire; private String validity; private BigDecimal allBtcPrice; private BigDecimal allHptPrice; private BigDecimal lastBtcPrice; private BigDecimal lastHptPrice; private BigDecimal allEthPrice; private BigDecimal lastEthPrice; private int type; private String profit; private String profitYear; private String electric; private String electricDiscount; private String manage; private String manageDiscount; private String btcDiscount; private String hbtDiscount; private String expireDate; private String comeDate; private String expirationDate; private int coinType; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public int getInvest() { return invest; } public void setInvest(int invest) { this.invest = invest; } public int getFrozenInvest() { return frozenInvest; } public void setFrozenInvest(int frozenInvest) { this.frozenInvest = frozenInvest; } public int getFrozenInvestTemp() { return frozenInvestTemp; } public void setFrozenInvestTemp(int frozenInvestTemp) { this.frozenInvestTemp = frozenInvestTemp; } public BigDecimal getAllBtc() { return allBtc; } public void setAllBtc(BigDecimal allBtc) { this.allBtc = allBtc; } public BigDecimal getAllHpt() { return allHpt; } public void setAllHpt(BigDecimal allHpt) { this.allHpt = allHpt; } public int getAllEth() { return allEth; } public void setAllEth(int allEth) { this.allEth = allEth; } public int getLastEth() { return lastEth; } public void setLastEth(int lastEth) { this.lastEth = lastEth; } public BigDecimal getLastBtc() { return lastBtc; } public void setLastBtc(BigDecimal lastBtc) { this.lastBtc = lastBtc; } public BigDecimal getLastHpt() { return lastHpt; } public void setLastHpt(BigDecimal lastHpt) { this.lastHpt = lastHpt; } public String getLastTime() { return lastTime; } public void setLastTime(String lastTime) { this.lastTime = lastTime; } public String getFrozenTime() { return frozenTime; } public void setFrozenTime(String frozenTime) { this.frozenTime = frozenTime; } public String getInvestTime() { return investTime; } public void setInvestTime(String investTime) { this.investTime = investTime; } public BigDecimal getReturnMoney() { return returnMoney; } public void setReturnMoney(BigDecimal returnMoney) { this.returnMoney = returnMoney; } public int getReturnDays() { return returnDays; } public void setReturnDays(int returnDays) { this.returnDays = returnDays; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public boolean isExpire() { return isExpire; } public void setExpire(boolean expire) { isExpire = expire; } public String getValidity() { return validity; } public void setValidity(String validity) { this.validity = validity; } public BigDecimal getAllBtcPrice() { return allBtcPrice; } public void setAllBtcPrice(BigDecimal allBtcPrice) { this.allBtcPrice = allBtcPrice; } public BigDecimal getAllHptPrice() { return allHptPrice; } public void setAllHptPrice(BigDecimal allHptPrice) { this.allHptPrice = allHptPrice; } public BigDecimal getLastBtcPrice() { return lastBtcPrice; } public void setLastBtcPrice(BigDecimal lastBtcPrice) { this.lastBtcPrice = lastBtcPrice; } public BigDecimal getLastHptPrice() { return lastHptPrice; } public void setLastHptPrice(BigDecimal lastHptPrice) { this.lastHptPrice = lastHptPrice; } public BigDecimal getAllEthPrice() { return allEthPrice; } public void setAllEthPrice(BigDecimal allEthPrice) { this.allEthPrice = allEthPrice; } public BigDecimal getLastEthPrice() { return lastEthPrice; } public void setLastEthPrice(BigDecimal lastEthPrice) { this.lastEthPrice = lastEthPrice; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getProfit() { return profit; } public void setProfit(String profit) { this.profit = profit; } public String getProfitYear() { return profitYear; } public void setProfitYear(String profitYear) { this.profitYear = profitYear; } public String getElectric() { return electric; } public void setElectric(String electric) { this.electric = electric; } public String getElectricDiscount() { return electricDiscount; } public void setElectricDiscount(String electricDiscount) { this.electricDiscount = electricDiscount; } public String getManage() { return manage; } public void setManage(String manage) { this.manage = manage; } public String getManageDiscount() { return manageDiscount; } public void setManageDiscount(String manageDiscount) { this.manageDiscount = manageDiscount; } public String getBtcDiscount() { return btcDiscount; } public void setBtcDiscount(String btcDiscount) { this.btcDiscount = btcDiscount; } public String getHbtDiscount() { return hbtDiscount; } public void setHbtDiscount(String hbtDiscount) { this.hbtDiscount = hbtDiscount; } public String getExpireDate() { return expireDate; } public void setExpireDate(String expireDate) { this.expireDate = expireDate; } public String getComeDate() { return comeDate; } public void setComeDate(String comeDate) { this.comeDate = comeDate; } public String getExpirationDate() { return expirationDate; } public void setExpirationDate(String expirationDate) { this.expirationDate = expirationDate; } public int getCoinType() { return coinType; } public void setCoinType(int coinType) { this.coinType = coinType; } }
package cn.jiucaituan.vo; import java.util.ArrayList; import java.util.List; public class Stock { String id; String name; String area; String vol; String amo; String zf; String bf; String stockMsg; public String getStockMsg() { return stockMsg; } public void setStockMsg(String stockMsg) { this.stockMsg = stockMsg; } public List getStockList() { return stockList; } public void setStockList(List stockList) { this.stockList = stockList; } List stockList = new ArrayList(); public String getVol() { return vol; } public void setVol(String vol) { this.vol = vol; } public String getAmo() { return amo; } public void setAmo(String amo) { this.amo = amo; } public String getZf() { return zf; } public void setZf(String zf) { this.zf = zf; } public String getBf() { return bf; } public void setBf(String bf) { this.bf = bf; } String op; public String getOp() { return op; } public void setOp(String op) { this.op = op; } public String getCp() { return cp; } public void setCp(String cp) { this.cp = cp; } public String getHp() { return hp; } public void setHp(String hp) { this.hp = hp; } public String getLp() { return lp; } public void setLp(String lp) { this.lp = lp; } String cp; String hp; String lp; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public Stock() { // TODO Auto-generated constructor stub } public String toString() { return "StockID[" + this.id + "]" + "op[" + op + "]hp[" + hp + "]lp[" + lp + "]cp[" + cp + "]"; } }
package com.vietstore.service; import java.io.File; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import com.vietstore.bean.MailInfo; @Service public class MailService { @Autowired JavaMailSender mailer; public void send(MailInfo mail) throws MessagingException { MimeMessage message=mailer.createMimeMessage(); MimeMessageHelper helper=new MimeMessageHelper(message,true,"utf-8"); helper.setFrom(mail.getFrom()); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); helper.setText(mail.getBody(),true); helper.setReplyTo(mail.getFrom()); if(mail.getCc() != null) { helper.setCc(mail.getCc()); } if(mail.getBcc() != null) { helper.setBcc(mail.getBcc()); } if(mail.getFiles() != null) { String[] paths = mail.getFiles().split(";"); for(String path: paths) { File file=new File(path); helper.addAttachment(file.getName(), file); } } mailer.send(message); } }
import java.util.*; class TwoDArray { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int i=0,j=0; int choice; System.out.println("Enter Row Size :"); int row=sc.nextInt(); System.out.println("Enter Column Size :"); int column=sc.nextInt(); int Arr[][]=new int[row][column]; System.out.println("Enter Array Elements :"); for(i=0;i<row;i++) { for(j=0;j<column;j++) { System.out.print("Enter Arr["+i+"]["+j+"] Element :"); Arr[i][j]=sc.nextInt(); } } System.out.println(); System.out.println(" Array Elements :"); System.out.println(); for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { System.out.print(" "+Arr[i][j]); } System.out.println(); } System.out.println(); while(true) { System.out.println("1: Find Sum Of All Element in Array :"); System.out.println("2: Find Sum Of ALL * Position :"); System.out.println("3: Find sum of All Non * Position :"); System.out.println("4: Find Biggest Number in Array :"); System.out.println("5: Find Biggest & Smallest Number in Array :"); System.out.println("6: Copy Elements A[][]=B[][] :"); System.out.println("7: Display Array Using For :"); System.out.println("8: Exit:"); System.out.println(); System.out.println("Enter Your Choice :"); choice=sc.nextInt(); switch(choice) { case 1: int sum=0; for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { sum=sum+Arr[i][j]; } System.out.println(); } System.out.println("Sum Of 2D Array is :"+sum); System.out.println(); break; case 2: int summ=0; for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { if(i+j>4) { summ=summ+Arr[i][j]; System.out.print(" "+Arr[i][j]+" "); } else System.out.print(" * "); } System.out.println(); } System.out.println("Sum Of 2D Array is :"+summ); System.out.println(); break; case 3: int summm=0; for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { if(i+j<5) { summm=summm+Arr[i][j]; System.out.print(" "+Arr[i][j]+" "); } else System.out.print(" * "); } System.out.println(); } System.out.println("Sum Of 2D Array is :"+summm); System.out.println(); break; case 4: System.out.println("Biggest & Smallest Number in 2D Array :"); int min=Arr[0][0]; int max=Arr[0][0]; for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { if(max<Arr[i][j]) max=Arr[i][j]; if(min>Arr[i][j]) min=Arr[i][j]; } System.out.println(); } System.out.println("Minimum from 2D ARray :"+min); System.out.println("Maximum from 2D Array :"+max); System.out.println(); break; case 5: System.out.println("Biggest Number in 2D Array :"); int maxx=Arr[0][0]; for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { if(maxx<Arr[i][j]) maxx=Arr[i][j]; } System.out.println(); } System.out.println("Maximum from 2D Array :"+maxx); System.out.println(); break; case 6: System.out.println("Copyied Array is :"); int Brr[][]=new int[5][5]; for(i=0;i<Arr.length;i++) { for(j=0;j<Arr[i].length;j++) { Brr[i][j]=Arr[i][j]; System.out.print(" "+Brr[i][j]); } System.out.println(); } System.out.println(); break; case 7: System.out.println("Display Array Arr & Brr using for each loop :"); for(int[] u: Arr) { for(int v:u) { System.out.print(v+" "); } System.out.println(); } break; case 8: System.exit(0); break; default: System.out.println("Enter Correct Choice :"); } } } }
package com.mindstatus.component.logon; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.beanutils.PropertyUtils; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import com.mindstatus.bean.vo.MsUser; import com.mindstatus.bo.IMsUserBo; import com.mindstatus.common.ApplicationConst; public class ProcessLogonAction extends Action { IMsUserBo msUserBo; public void setMsUserBo(IMsUserBo msUserBo) { this.msUserBo = msUserBo; } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm dynaForm = (DynaActionForm) form; MsUser msUser=new MsUser(); PropertyUtils.copyProperties(msUser, dynaForm.getMap()); int errcode=msUserBo.logon(msUser); if(errcode==IMsUserBo.LOGON_CODE_SUCCESS){ msUser.setPassword(dynaForm.get("password").toString()); HttpSession session=request.getSession(); session.setAttribute(ApplicationConst.CURRENT_USER, msUser); return mapping.findForward(ApplicationConst.ACTION_FORWARD_SUCCESS); }else{ dynaForm.set("errorCode", ""+errcode); return mapping.getInputForward(); } } }
package aplicacionjavaformateovariables; import java.util.ArrayList; import java.util.List; public class AplicacionJavaFormateoVariables { public static void main(String[] args) { List<DatosBean> lista = new ArrayList(); for(int cont=1;cont<5;cont++) { DatosBean datosBean=new DatosBean(); lista.add(datosBean); } System.out.println(lista); } }
package gateway.persist; import domain.GroupEntity; public interface GroupDbGateway { void persist(GroupEntity group); }
package cc.ipotato.HeimaExercises; import java.io.File; import java.util.Arrays; import java.util.Scanner; /** * 从键盘接收一个文件夹路径,统计该文件夹大小 * Created by haohao on 2018/5/4. */ public class DirectorySizeCount { public static void main(String[] args) { File d = getDirectory(); System.out.println(getFileLength(d)); } public static File getDirectory() { Scanner scanner = new Scanner(System.in); System.out.println("请输入合理的目录路径:"); while (true) { String line = scanner.nextLine(); File f = new File(line); if (f.isDirectory()) { return f; } else { System.out.println("输入错误,请输入正确的目录路径:"); } } } public static long getFileLength(File dir) { long len = 0; File[] subFiles = dir.listFiles(); for (File subFile : subFiles) { if (subFile.isFile()) { len += subFile.length(); } else { len += getFileLength(subFile); } } return len; } }
package com.jerry.pattern; /** * Date: 2019/1/20 16:58 * * @author jerry.R */ public class Protoptype implements Cloneable { private String attribute = "initialization value "; public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } @Override protected Protoptype clone() throws CloneNotSupportedException { Protoptype cloneObject = new Protoptype(); cloneObject.setAttribute(this.attribute); return cloneObject; } public static void main(String[] args) throws CloneNotSupportedException { System.out.println(new Protoptype().clone().getAttribute()); } }
module modcommon { exports pkgcommon; }
package old.DefaultPackage; import java.util.ArrayList; public class Code06 { TreeNode root = new TreeNode(10); private ArrayList<ArrayList<Integer>> result = new ArrayList<>(); Code06(){ root.left = new TreeNode(5); root.right = new TreeNode(12); root.right.left = new TreeNode(11); root.right.right = new TreeNode(13); root.left.left = new TreeNode(4); root.left.right = new TreeNode(7); } public static void main(String[] args) { Code06 c = new Code06(); TreeNode node = c.Convert(c.root); } public TreeNode Convert(TreeNode pRootOfTree) { if(pRootOfTree == null) return null; ArrayList<TreeNode> list = new ArrayList<>(); list.add(pRootOfTree); convert(list, 0); for(int i=0; i<list.size() - 1; ++i){ list.get(i).right = list.get(i+1); list.get(i+1).left = list.get(i); } list.get(0).left = list.get(list.size()-1); return list.get(0); } public int convert(ArrayList<TreeNode> list, int i){ TreeNode node = list.get(i); if(node.left != null){ list.add(i, node.left); i = convert(list, i); i++; } if(node.right != null){ list.add(i+1, node.right); i = convert(list, i+1); } return i; } public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { if(root == null) return result; findPath(new ArrayList<Integer>(), root, target); return result; } public void findPath(ArrayList<Integer> list, TreeNode root, int target){ if(target == 0) result.add(list); if(root.val > target) return; list.add(root.val); if(root.left != null) findPath(new ArrayList<Integer>(list), root.left, target - root.val); if(root.right != null) findPath(new ArrayList<Integer>(list), root.right, target - root.val); } private class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } }
package com.ethan.df.factory_pattern.v_simplify; /** * 工厂抽象类 */ public abstract class Factory { public abstract <T extends Fruit> T createProduct(Class<T> clazz); }
package com.metoo.core.service; import java.util.List; import java.util.Map; /** * * <p> * Title: IQueryService.java * </p> * * <p> * Description: 基础查询service接口 * </p> * * <p> * Copyright: Copyright (c) 2014 * </p> * * <p> * Company: 湖南创发科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-4-24 * * @version koala_b2b2c v2.0 2015版 */ public interface IQueryService { List query(String scope, Map params, int page, int pageSize); List nativeQuery(String scope, Map params, int page, int pageSize); int executeNativeSQL (String nnq); int executeNativeSQL (String nnq, Map params); void flush(); }
package br.edu.fadam.estruturadedados.aula2; public class Funcionario implements Pagavel { private String nome; private String numeroDocumento; private double salarioBase; public double calculaSalario(){ return 0.0; } public double getSalarioBase() { return salarioBase; } public void setSalarioBase (double salarioBase) { this.salarioBase = salarioBase; } }
class DoubleLinkList { private int nElems = 0; ListItem head, tail; class ListItem{ int data; ListItem next; ListItem prev; ListItem(int data){ this.data = data; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); try { sb.append("{ PrevItem: "); if(!(this.prev == null)) sb.append(this.prev.data); else{ sb.append("null"); } sb.append(", ListItem: "); sb.append(this.data); // sb.append("\t"); sb.append(", NextListItem : "); if(!(this.next == null)) sb.append(this.next.data); else sb.append("null"); sb.append("}"); } catch (Exception e) { sb.append(e.getMessage()); } return sb.toString(); } } public void insert(int index, int data){ System.out.println("------------"); ListItem newListItem = new ListItem(data); if(head == null){ head = tail = newListItem; System.out.println("head: " + head); } else{ ListItem current = head; tail.next = newListItem; newListItem.prev = tail; tail = newListItem; while(current!=null){ System.out.println(current); current = current.next; } System.out.println(current); } nElems++; // System.out.println("current is :" + current); } public void insertAtIndex(int index, int data){ //4 element, index = 3 --------- 3 > 4 // System.out.println(nElems); if(index < 0 || index > (nElems)){ System.err.println("[ERROR]: Wrong Index provided"); } else{ System.out.println("[INFO]: Inserting "+ data + " at index " + index); ListItem newListItem = new ListItem(data); int indexCopy = 0; ListItem current = head; while(current != null){ if(indexCopy++ == index){ break; } current = current.next; } // System.out.println("@"+current); // System.out.println("Index : " + (indexCopy) ); // current = head; // System.out.println(current); if(head == null && tail == null){ System.out.println("i=" + indexCopy); head = tail = newListItem; nElems++; System.out.println("[INFO]: New ListItem added as head :" + head); // System.out.println(this); } else{ // current = current.next; System.out.println("i=" + indexCopy); current = getListItemHavingIndex(indexCopy-1); /* System.out.println("------" + this); System.out.println("currentis : " + current); System.out.println("to add : " + newListItem); // System.out.println(); ListItem prevNode = current.prev; //p11n p22n if(current == head){ current.next = newListItem; newListItem.prev = head; // head.prev = newListItem; head = newListItem; tail = tail.next; } else{ prevNode.next = newListItem; newListItem.prev = prevNode; newListItem.next = current; current.prev = newListItem; } /* if(current.next == null){ tail = newListItem; } else{ newListItem.next = current.next; current.next.prev = newListItem; } current.next = newListItem; newListItem.prev = current; */ current = getListItemHavingIndex(indexCopy-1); System.out.println("current is:" + current); if(current == head){ System.out.println("HEAD NOW"); current.next = newListItem; newListItem.prev = head; head = newListItem; } /*tail.next = newListItem; newListItem.prev = tail; tail = newListItem; /* if(current == head){ current.next = newListItem; newListItem.prev = head; // head.prev = newListItem; head = newListItem; tail = tail.next; } else{ prevNode.next = newListItem; newListItem.prev = prevNode; newListItem.next = current; current.prev = newListItem; } */ /* if(current == tail){ current.next = newListItem; newListItem.prev = current; tail = newListItem; } else{ current.next.prev = newListItem; newListItem.next = current.next; current.next = newListItem; newListItem.prev = current; }*/ nElems++; // System.out.println("[INFO]: Inserted " + data + " at index " + index); } System.out.println(this); } } public int getIndexHavingData(int data){ ListItem current = head; int i = 0; System.out.println(this); while(current != null && current.data != data){ i++; System.out.println(current); current = current.next; if(current.data == data) return i; } System.err.println("[ERROR]: No Index found, returning garbage value"); return Integer.MIN_VALUE; } public ListItem getListItemHavingIndex(int index){ int data = 0; int i = 0; int mid = nElems / 2; if(index > mid){ //end to mid System.out.println("Lol"); ListItem current = tail; int end = nElems - 1; while(current != null && end != index){ System.out.println(current); if(end == index) return current; end--; current = current.prev; } return current; } else{ //start to mid ListItem current = head; while(current != null && i != index){ i++; current = current.next; if(i == index) return current; } return current; } } public int getDataHavingIndex(int index){ return getListItemHavingIndex(index).data; } public void printList(){ ListItem current = head; while(current != null){ System.out.println(current); current = current.next; } } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("[INFO]: LIST("+ nElems +") NOW - ["); ListItem current = head; while(current != null){ sb.append(current.data); current = current.next; if(current != null) sb.append("->"); } sb.append("]"); return sb.toString(); } } public class DoubleLinkListApp{ public static void main(String[] args) { DoubleLinkList dll = new DoubleLinkList(); dll.insertAtIndex(0,11); dll.insertAtIndex(1,22); dll.insertAtIndex(2,33); dll.insertAtIndex(3,44); System.out.println(dll); System.out.println("--------"); // dll.insertAtIndex(2, 78); // dll.insertAtIndex(0, 99); // System.out.println(dll); // System.out.println(dll.getIndexHavingData(33)); // System.out.println(dll.getDataHavingIndex(1)); System.out.println(dll.getListItemHavingIndex(0)); // System.out.println(dll); // dll.printList(); } }
package com.jpeng.demo; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.PixelFormat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.Toast; import com.jpeng.demo.face.DetecterActivity; import com.jpeng.demo.face.FaceRecognition; public class StartFace extends AppCompatActivity implements View.OnClickListener { LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setWindow(); setContentView(R.layout.activity_start_face); ActivityCollector.addActivity(this); linearLayout=(LinearLayout)findViewById(R.id.start_face); linearLayout.setOnClickListener(this); } private void setWindow() { requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏 // 设置竖屏显示 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 选择支持半透明模式,在有surfaceview的activity中使用。 getWindow().setFormat(PixelFormat.TRANSLUCENT); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.start_face: new AlertDialog.Builder(this) .setTitle("请选择相机") .setIcon(android.R.drawable.ic_dialog_info) .setItems(new String[]{"后置相机", "前置相机"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startDetector(which); } }) .show(); break; default:break; } } private void startDetector(int camera) { finish(); ActivityCollector.removeActivity(this); Intent it = new Intent(StartFace.this, DetecterActivity.class); it.putExtra("Camera", camera); startActivity(it); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } return super.onKeyDown(keyCode, event); } }
package com.needii.dashboard.validator; import com.needii.dashboard.model.FileBucket; import com.needii.dashboard.model.MultiMapFileBucket; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import java.util.Map; @Component public class MultipleMapFileValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return MultiMapFileBucket.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { MultiMapFileBucket multiMapFileBucket = (MultiMapFileBucket) target; for (Map.Entry<String, FileBucket> bucket : multiMapFileBucket.getFiles().entrySet()){ if (bucket.getValue().getFile() != null && bucket.getValue().getFile().isEmpty()){ errors.rejectValue(bucket.getKey(), "Validator.Required.image"); } } } }
package io.magicthegathering.javasdk.filter; /** * <p> * Filter for filtering {@link io.magicthegathering.javasdk.resource.Card cards} by * their converted mana cost. * </p> * <p> * This {@link ConvertedManaCostFilter filter} can only use a single * value as request value. * </p> * * @author Timon Link - timon.link@gmail.com */ public class ConvertedManaCostFilter extends AbstractBaseFilter { private static final String PARAMETER_NAME = "cmc"; /** * Creates a new instance of the {@link ConvertedManaCostFilter}. * * @param filter The {@link Filter filter} to assign to <code>this</code> {@link Filter filter}. * @param manaCost The converted mana cost to filter by. */ ConvertedManaCostFilter(Filter filter, String manaCost) { super(filter); addValue(manaCost); } @Override protected String parameterName() { return PARAMETER_NAME; } }
/* * Copyright 2017-2018, Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.operator.common.operator.resource; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.kubernetes.api.model.extensions.DeploymentList; import io.fabric8.kubernetes.api.model.extensions.DoneableDeployment; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.ScalableResource; import io.vertx.core.Future; import io.vertx.core.Vertx; /** * Operations for {@code Deployment}s. */ public class DeploymentOperator extends AbstractScalableResourceOperator<KubernetesClient, Deployment, DeploymentList, DoneableDeployment, ScalableResource<Deployment, DoneableDeployment>> { /** * Constructor * @param vertx The Vertx instance * @param client The Kubernetes client */ public DeploymentOperator(Vertx vertx, KubernetesClient client) { super(vertx, client, "Deployment"); } @Override protected MixedOperation<Deployment, DeploymentList, DoneableDeployment, ScalableResource<Deployment, DoneableDeployment>> operation() { return client.extensions().deployments(); } @Override protected Integer currentScale(String namespace, String name) { Deployment deployment = get(namespace, name); if (deployment != null) { return deployment.getSpec().getReplicas(); } else { return null; } } /** * Asynchronously roll the deployment returning a Future which will complete once all the pods have been rolled * and the Deployment is ready. */ public Future<Void> rollingUpdate(String namespace, String name, long operationTimeoutMs) { return getAsync(namespace, name) .compose(deployment -> reconcile(namespace, name, incrementGeneration(deployment))) .compose(ignored -> readiness(namespace, name, 1_000, operationTimeoutMs)); } private Deployment incrementGeneration(Deployment deployment) { String generationStr = deployment.getSpec().getTemplate().getMetadata().getAnnotations().get(ANNOTATION_GENERATION); int generation = 0; if (generationStr != null && !generationStr.isEmpty()) { generation = Integer.parseInt(generationStr); generation++; } return new DeploymentBuilder(deployment) .editSpec() .editTemplate() .editMetadata() .addToAnnotations(ANNOTATION_GENERATION, Integer.toString(generation)) .endMetadata() .endTemplate() .endSpec() .build(); } }
package com.huadin.utils; import com.huadin.database.NewStopType; import com.huadin.database.OtherStopType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.litepal.crud.DataSupport; import java.util.ArrayList; import java.util.List; public class NewPareJsonArrayUtil { private static List<NewStopType> list = new ArrayList<>(); private static ArrayList<OtherStopType> otherList = new ArrayList<>(); public static List<NewStopType> pareJson(List<JSONArray> jsonList) { int count = 0; try { list.clear(); for (JSONArray array : jsonList) { for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); String lineName = obj.getString("lineName"); String startTime = obj.getString("startTime"); String stopDate = obj.getString("stopDate"); String typeCode = obj.getString("typeCode"); String scope = obj.getString("scope"); //日期 String[] tempStartTime = startTime.trim().split(" "); String date = tempStartTime[0];//日期 String tStartTime = tempStartTime[1];//开始时间 //时间 String[] tempEndTime = stopDate.trim().split(" "); String endTime = tempEndTime[1];//结束时间 String time = tStartTime + " - " + endTime; //判断scope中个数 String[] scopeArr = scope.trim().split(","); if (scopeArr.length > 1) { splitScope(scopeArr, lineName, time, date, typeCode); } else { setNewStopType(scope, lineName, time, date, typeCode); } otherNewStopType(scope , lineName , time ,date , typeCode); } count ++; } if (count == jsonList.size()) { DataSupport.deleteAll(OtherStopType.class);//清除旧数据 DataSupport.saveAll(otherList);//搜索的时候使用,scope没有拆分,显示官网类型的数据 otherList.clear(); return list; } } catch (JSONException e) { e.printStackTrace(); } return list; } /** * 拆分地址 scope : xxx村,xxx村 */ private static void splitScope(String[] scopeArr, String lineName, String time, String date, String typeCode) { for (String scope : scopeArr) { setNewStopType(scope , lineName,time,date,typeCode); } } private static void setNewStopType(String scope , String lineName, String time, String date, String typeCode) { String type = null; if (typeCode.equals("01")) { type = Const.STOP_TYPE_PLAN; } else if (typeCode.equals("02")) { type = Const.STOP_TYPE_FAULT; } if (typeCode.equals("07")) { type = Const.STOP_TYPE_TEMP; } NewStopType st = new NewStopType(); st.setScope(scope); st.setLineName(lineName); st.setTime(time); st.setDate(date); st.setTypeCode(type); list.add(st); } /** scope 不拆分,在搜索的时候使用 */ public static void otherNewStopType(String scope , String lineName, String time, String date, String typeCode) { OtherStopType ost = new OtherStopType(); ost.setScope(scope); ost.setLineName(lineName); ost.setStartTime(time); ost.setStopDate(date); ost.setTypeCode(typeCode); otherList.add(ost); } }
package com.shensu.dao; import java.util.List; import com.shensu.pojo.AboutMe; public interface AboutMeMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ int deleteByPrimaryKey(); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ int insert(AboutMe record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ int insertSelective(AboutMe record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ AboutMe selectByPrimaryKey(Integer aboutmeid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ int updateByPrimaryKeySelective(AboutMe record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ int updateByPrimaryKeyWithBLOBs(AboutMe record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table AboutMe * * @mbggenerated */ int updateByPrimaryKey(AboutMe record); //查询关于我们的内容 List<AboutMe> findAboutMeDetails(); //增加关于我们的内容 int addAboutMe(AboutMe aboutMe); //修该关于我们的内容 int modifyAboutMe(AboutMe aboutMe); }
package testNGExamples; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; public class JsDemo { public static void main(String[] args) throws InterruptedException { String path=System.getProperty("user.dir"); System.setProperty("webdriver.gecko.driver", path+"\\src\\test\\resources\\Drivers\\geckodriver.exe"); WebDriver driver=new FirefoxDriver(); driver.get("http://google.com"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); JavascriptExecutor js=(JavascriptExecutor)driver; //js.executeScript("alert('Welcome to Java')"); js.executeScript("prompt('Welcome','Enter your name')"); Alert alert=driver.switchTo().alert(); alert.sendKeys("hello"); Thread.sleep(4000); alert.accept(); driver.get("https://login.yahoo.com/config/login?.src=fpctx&.intl=in&.lang=en-IN&.done=https://in.yahoo.com"); //driver.findElement(By.id("persistent")).click(); Thread.sleep(2000); WebElement email=driver.findElement(By.name("username")); String emailId="swamy.learn@gmail.com"; js.executeScript("arguments[0].value='swamy.learn@gmail.com'", email,emailId); //js.executeScript("arguments[0].value=arguments[1]", email,emailId); //js.executeScript("document.getElementById('persistent').click()"); WebElement elm=driver.findElement(By.id("persistent")); js.executeScript("arguments[0].click()", elm); } }
package com.company; import java.io.Serializable; public abstract class Calory implements Serializable { private int sex; private float bodyweight; private float height; private int age; private float physicalactivity; public float getPhysicalactivity() { return physicalactivity; } public void setPhysicalactivity(float physicalactivity) { this.physicalactivity = physicalactivity; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getBodyweight() { return bodyweight; } public void setBodyweight(float bodyweight) { this.bodyweight = bodyweight; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } }
package com.lenovohit.ssm.treat.manager.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import com.lenovohit.core.utils.BeanUtils; import com.lenovohit.ssm.treat.dao.LisWebserviceDao; import com.lenovohit.ssm.treat.manager.HisAssayManager; import com.lenovohit.ssm.treat.model.AssayRecord; /** * */ /*1.OpenCon -------查看数据库链接状态 openCon.html 2.GetTestForm----获取病人化验记录 GetTestForm.html patientId:0003463433 patientType:门诊 dtReg:2017-04-01 etEnd:2017-04-15 3.PrintForm_ByBarcode根据条码获取详情图片 PrintForm_ByBarcode.html barcode:1004042290 4.EditPrinted-------打印回传 5.GetReportLockDoubt-------待查原因的查询 Barcode:1004042290 */ public class HisAssayManagerImpl implements HisAssayManager{ @Autowired private LisWebserviceDao lisWebserviceDao; private String imagePath; public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } /** * 查询化验单列表 assay/page get * @param patient * @return */ public List<AssayRecord> getAssayRecords(AssayRecord assayRecord){ try { List<AssayRecord> records = new ArrayList<AssayRecord>(); List<String> resultList = lisWebserviceDao.postForList("GetTestForm", assayRecord); AssayRecord _assayRecord = null; for(String result : resultList){ _assayRecord = this.parseAssayRecord(result, assayRecord); if(_assayRecord != null) records.add(_assayRecord); } return records; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 查询化验单明细(化验结果) assay/{id} get * @param record * @return */ public String getAssayImage(AssayRecord AssayRecord){ try { String fileName = lisWebserviceDao.postForEntity("PrintForm_ByBarcode", AssayRecord); if(StringUtils.isEmpty(fileName))return null; return imagePath+"/"+fileName; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 化验单打印回传 assay/printed post * @param record * @return */ public AssayRecord print(AssayRecord record){ try { lisWebserviceDao.postForEntity("EditPrinted", record); return record; } catch (Exception e) { e.printStackTrace(); } return record; } @Override public AssayRecord getTipsMsg(AssayRecord record) { try { String result = lisWebserviceDao.postForEntity("GetReportLockDoubt", record); AssayRecord assayRecord = this.parseTipsMsg(result, record); return assayRecord; } catch (Exception e) { e.printStackTrace(); } return null; } private AssayRecord parseAssayRecord(String content, AssayRecord def){ if(StringUtils.isBlank(content)) return null; String[] array = content.split(","); if(array == null || array.length != 14) return null; AssayRecord assayRecord = new AssayRecord(); BeanUtils.copyProperties(def, assayRecord); //0-审核标识,1-日期_barcode,2-仪器编码,3-样本号,4-报告日期,5-审核人Id,6-核收人Id,7-患者性别,8-患者年龄,9-样本类型,10-(项目编码),11-(项目名称),12-'',13-'' //例子: 5,150131_6019280563,I16200_D,400215,20150130,083863,041542,男,27岁,血清,476+475+477,血糖(急诊)+钾钠氯(急诊)+血淀粉酶(急诊),,205001010100 //0 5, // 第一个审核标识,5:审核,2:核收,0:接收,9:待查 String status = array[0]; assayRecord.setStatus(status); //1 170411_1004042293, // 第二个检验日期+条码号, String testdate_barcode = array[1]; String[] strs = testdate_barcode.split("_"); String testdate = strs[0]; String barcode = strs[1]; assayRecord.setBarcode(barcode); assayRecord.setTestdate(testdate); //2 JZ_StagoCompact, // 第三个仪器ID, assayRecord.setMachineId(array[2]); //3 3101, // 第四个样本号 // assayRecord.setSampleId(array[3]); //4 20170410, // 第五个是检验日期,申请日期 assayRecord.setApplydate(array[4]); //5 300950, // 第六个是患者门诊号, //6 300492, //7 女, // 第七个性别, assayRecord.setPatientGender(array[7]); //8 29岁, // 9 第八个年龄 assayRecord.setPatientAge(array[8]); //9 血浆, // 第九个样本类型, assayRecord.setSampleType(array[9]); //10 F00000051012, // 第十个检验项目编码, assayRecord.setSubjectCode(array[10]); //11 急诊凝血-1, // 第十一个检验项目名称 assayRecord.setSubjectName(array[11]); //12 , //13 205100000000, 第3位与审核标识描述一致,第4位: 0:未打印, 1:已打印 assayRecord.setPrintStatus(array[13].substring(3, 4)); return assayRecord; } private AssayRecord parseTipsMsg(String content, AssayRecord def){ if(StringUtils.isBlank(content)) return null; String[] array = content.split("\\^"); if(array == null || array.length!= 3 ) return null; AssayRecord assayRecord = new AssayRecord(); BeanUtils.copyProperties(def, assayRecord); //0-是否打印提示^1-是否弹窗提示^2-提示内容 //例子: 1^0^请到2号门诊楼12楼生化免疫室取报告 //0 1, // 第一个是否打印提示 0:不打印,1:打印 assayRecord.setPrintFlag(array[0]); //1 0, // 第二个是否弹窗提示 0:不弹窗,1:弹窗 assayRecord.setWindowFlag(array[1]); //2 请到2号门诊楼12楼生化免疫室取报告, // 提示内容, assayRecord.setMsg(array[2]); return assayRecord; } }