text
stringlengths 10
2.72M
|
|---|
package com.kodilla.restaurantfrontend;
public enum ProductType {
SOUP, DESSERT, DRINKS, FIRST_DISH, MAIN_COURSE
}
|
/*
* Copyright 2014-2016 See AUTHORS file.
*
* 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.kotcrab.vis.plugin.spriter.module;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.kotcrab.vis.editor.module.project.ProjectModule;
import com.kotcrab.vis.editor.plugin.api.ContainerExtension;
import com.kotcrab.vis.plugin.spriter.util.SpriterAssetData;
import com.kotcrab.vis.runtime.plugin.VisPlugin;
/** @author Kotcrab */
@VisPlugin
public class SpriterDataIOModule extends ProjectModule implements ContainerExtension {
private Json json;
@Override
public void init () {
json = getNewJson();
}
public Json getJson () {
return json;
}
public static Json getNewJson () {
Json json = new Json();
json.addClassTag("SpriterAssetData", SpriterAssetData.class);
return json;
}
public SpriterAssetData loadData (FileHandle file) {
return json.fromJson(SpriterAssetData.class, file);
}
@Override
public ExtensionScope getScope () {
return ExtensionScope.PROJECT;
}
}
|
package LeetCodeUtils.Contest.C2021_04_19;
import LeetCodeUtils.MyMatrix;
import org.junit.Test;
import java.util.*;
import java.util.PriorityQueue;
public class Third {
@Test
public void test() {
getOrder(MyMatrix.IntMatrixAdapter("[[19,13],[16,9],[21,10],[32,25],[37,4],[49,24],[2,15],[38,41],[37,34],[33,6],[45,4],[18,18],[46,39],[12,24]]", 14, 2));
}
public int[] getOrder(int[][] tasks) {
Map<int[], List<Integer>> map = new HashMap<>();
PriorityQueue<int[]> pq = new PriorityQueue<>( (a, b) -> {
if (a[1] == b[1]) {
return map.get(a).get(0) - map.get(b).get(0);
} else return a[1] - b[1];
} );
int[] result = new int[tasks.length];
int n = tasks.length;
for (int i = 0; i < tasks.length; ++i) {
map.computeIfAbsent(tasks[i], x -> new ArrayList<>()).add(i);
}
int next_finish = 0, next_start = 1, time = 1, taskIdx = 0, resultIdx = 0;
Arrays.sort(tasks, (a, b) -> a[0] - b[0]);
while (true) {
while (taskIdx < n && time >= tasks[taskIdx][0]) {
pq.add(tasks[taskIdx]);
taskIdx++;
//next_start =
}
if (pq.size() > 0) {
int[] peek = pq.poll();
result[resultIdx++] = map.get(peek).get(0);
map.get(peek).remove(0);
next_finish = time + peek[1] - 1;
} else {
next_finish = tasks[taskIdx][0] - 1;
}
time = 1 + next_finish;
if (pq.size() == 0 && taskIdx >= tasks.length) break;
}
return result;
}
}
|
package io.github.apfelcreme.Pipes.Manager;
import com.destroystokyo.paper.MaterialTags;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalCause;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import io.github.apfelcreme.Pipes.Exception.ChunkNotLoadedException;
import io.github.apfelcreme.Pipes.Exception.PipeTooLongException;
import io.github.apfelcreme.Pipes.Exception.TooManyOutputsException;
import io.github.apfelcreme.Pipes.Pipe.AbstractPipePart;
import io.github.apfelcreme.Pipes.Pipe.ChunkLoader;
import io.github.apfelcreme.Pipes.Pipe.Pipe;
import io.github.apfelcreme.Pipes.Pipe.PipeInput;
import io.github.apfelcreme.Pipes.Pipe.PipeOutput;
import io.github.apfelcreme.Pipes.Pipe.SimpleLocation;
import io.github.apfelcreme.Pipes.PipesConfig;
import io.github.apfelcreme.Pipes.PipesItem;
import io.github.apfelcreme.Pipes.PipesUtil;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Container;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.persistence.PersistentDataType;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
/*
* Copyright (C) 2016 Lord36 aka Apfelcreme
* <p>
* This program is free software;
* you can redistribute it and/or modify it under the terms of the GNU General
* Public License as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <http://www.gnu.org/licenses/>.
*
* @author Lord36 aka Apfelcreme
*/
public class PipeManager {
/**
* the DetectionManager instance
*/
private static PipeManager instance = null;
/**
* a cache to stop endless pipe checks
*/
private final Cache<SimpleLocation, Pipe> pipeCache;
/**
* a cache to stop endless pipe checks, this is for parts that can be attached to only one pipe (glass pipe blocks)
*/
private final Map<SimpleLocation, Pipe> singleCache;
/**
* a cache to stop endless pipe checks, this is for parts that can be attached to multiple pipes (outputs and chunk loader)
*/
private final Map<SimpleLocation, Set<Pipe>> multiCache;
/**
* A cache for pipe parts
*/
private final Map<SimpleLocation, AbstractPipePart> pipePartCache;
/**
* constructor
*/
private PipeManager() {
pipeCache = CacheBuilder.newBuilder()
.maximumSize(PipesConfig.getPipeCacheSize())
.expireAfterWrite(PipesConfig.getPipeCacheDuration(), TimeUnit.SECONDS)
.removalListener(new PipeRemovalListener())
.build();
singleCache = new HashMap<>();
multiCache = new HashMap<>();
pipePartCache = new HashMap<>();
}
/**
* returns the pipe cache
*
* @return the pipe cache
*/
public Cache<SimpleLocation, Pipe> getPipeCache() {
return pipeCache;
}
/**
* returns the cache for blocks that can only belong to a single pipe (and aren't inputs)
*
* @return the single cache
*/
public Map<SimpleLocation, Pipe> getSingleCache() {
return singleCache;
}
/**
* returns the cache for blocks that can belong to multiple pipes (outputs and chunk loaders)
*
* @return the multi cache
*/
public Map<SimpleLocation, Set<Pipe>> getMultiCache() {
return multiCache;
}
/**
* returns the cache for pipe parts
*
* @return the pipe part cache
*/
public Map<SimpleLocation, AbstractPipePart> getPipePartCache() {
return pipePartCache;
}
/**
* returns the PipeManager instance
*
* @return the PipeManager instance
*/
public static PipeManager getInstance() {
if (instance == null) {
instance = new PipeManager();
}
return instance;
}
/**
* Get the pipe by an input at a location. This will only lookup in the input cache and no other one.
* If none is found it will try to calculate the pipe that starts at that position
*
* @param location the location the input is at
* @return a Pipe or <code>null</code>
* @throws ChunkNotLoadedException When the pipe reaches into a chunk that is not loaded
* @throws PipeTooLongException When the pipe is too long
* @throws TooManyOutputsException when the pipe has too many outputs
*/
public Pipe getPipeByInput(SimpleLocation location) throws ChunkNotLoadedException, TooManyOutputsException, PipeTooLongException {
Pipe pipe = pipeCache.getIfPresent(location);
if (pipe == null) {
Block block = location.getBlock();
if (PipesUtil.getPipesItem(block) != PipesItem.PIPE_INPUT) {
return null;
}
pipe = isPipe(block);
if (pipe != null) {
addPipe(pipe);
}
} else {
pipe.checkLoaded(location);
}
return pipe;
}
/**
* Get the pipe that is at that location, returns an empty set instead of throwing an exception
*
* @param location The location
* @return the pipes; an empty set if none were found or an error occurred
*/
public Set<Pipe> getPipesSafe(SimpleLocation location) {
return getPipesSafe(location, false);
}
/**
* Get the pipe that is at that location, returns an empty set instead of throwing an exception
*
* @param location The location
* @param cacheOnly Only look in the cache, don't search for new ones
* @return the pipes; an empty set if none were found or an error occurred
*/
public Set<Pipe> getPipesSafe(SimpleLocation location, boolean cacheOnly) {
if (cacheOnly) {
Pipe pipe = pipeCache.getIfPresent(location);
if (pipe == null) {
pipe = singleCache.get(location);
}
if (pipe != null) {
return Collections.singleton(pipe);
}
return multiCache.getOrDefault(location, Collections.emptySet());
}
try {
return getPipes(location.getBlock(), false);
} catch (ChunkNotLoadedException | PipeTooLongException | TooManyOutputsException e) {
return Collections.emptySet();
}
}
/**
* Get the pipe, returns an empty set instead of throwing an exception
*
* @param block the block to get the pipe for
* @return the pipes; an empty set if none were found or an error occurred
*/
public Set<Pipe> getPipesSafe(Block block) {
try {
return getPipes(block);
} catch (ChunkNotLoadedException | PipeTooLongException | TooManyOutputsException e) {
return Collections.emptySet();
}
}
/**
* Get the pipe, returns an empty set instead of throwing an exception
*
* @param block the block to get the pipe for
* @param cacheOnly Only look in the cache, don't search for new ones
* @return the pipes; an empty set if none were found or an error occurred
*/
public Set<Pipe> getPipesSafe(Block block, boolean cacheOnly) {
try {
return getPipes(block, cacheOnly);
} catch (ChunkNotLoadedException | PipeTooLongException | TooManyOutputsException e) {
return Collections.emptySet();
}
}
/**
* Get the pipe for a block
*
* @param block The block
* @return the pipes; an empty set if none were found
* @throws ChunkNotLoadedException When the pipe reaches into a chunk that is not loaded
* @throws PipeTooLongException When the pipe is too long
* @throws TooManyOutputsException when the pipe has too many outputs
*/
public Set<Pipe> getPipes(Block block) throws ChunkNotLoadedException, PipeTooLongException, TooManyOutputsException {
return getPipes(block, false);
}
/**
* Get the pipe for a block
*
* @param block The block
* @param cacheOnly Only look in the cache, don't search for new ones
* @return the pipes; an empty set if none were found
* @throws ChunkNotLoadedException When the pipe reaches into a chunk that is not loaded
* @throws PipeTooLongException When the pipe is too long
* @throws TooManyOutputsException when the pipe has too many outputs
*/
public Set<Pipe> getPipes(Block block, boolean cacheOnly) throws ChunkNotLoadedException, PipeTooLongException, TooManyOutputsException {
if (block == null) {
return Collections.emptySet();
}
Set<Pipe> pipes = getPipesSafe(new SimpleLocation(block.getLocation()), true);
if (pipes.isEmpty() && !cacheOnly) {
Pipe pipe = isPipe(block);
if (pipe != null) {
addPipe(pipe);
return Collections.singleton(pipe);
}
}
return pipes;
}
public void removePipe(Pipe pipe) {
if (pipe == null) {
return;
}
for (Iterator<PipeInput> i = pipe.getInputs().values().iterator(); i.hasNext();) {
PipeInput input = i.next();
i.remove();
pipeCache.invalidate(input.getLocation());
}
}
/**
* Add all the pipes locations to the cache
* @param pipe The pipe
*/
private void addPipe(Pipe pipe) {
if (pipe == null) {
return;
}
for (PipeInput input : pipe.getInputs().values()) {
pipeCache.put(input.getLocation(), pipe);
pipePartCache.put(input.getLocation(), input);
if (!input.getHolder().getInventory().isEmpty()) {
ItemMoveScheduler.getInstance().add(input.getLocation());
}
}
for (SimpleLocation location : pipe.getPipeBlocks()) {
singleCache.put(location, pipe);
}
for (PipeOutput output : pipe.getOutputs().values()) {
addToMultiCache(output.getLocation(), pipe);
pipePartCache.put(output.getLocation(), output);
}
for (ChunkLoader chunkLoader : pipe.getChunkLoaders().values()) {
addToMultiCache(chunkLoader.getLocation(), pipe);
pipePartCache.put(chunkLoader.getLocation(), chunkLoader);
}
}
/**
* Add a part to a pipe while checking settings and caching the location
*
* @param pipe the pipe to add to
* @param pipePart the part to add
* @throws TooManyOutputsException when the pipe has too many outputs
*/
public void addPart(Pipe pipe, AbstractPipePart pipePart) throws TooManyOutputsException {
if (pipePart instanceof PipeInput) {
pipe.getInputs().put(pipePart.getLocation(), (PipeInput) pipePart);
for (PipeInput input : pipe.getInputs().values()) {
pipeCache.put(input.getLocation(), pipe);
}
} else if (pipePart instanceof PipeOutput) {
if (PipesConfig.getMaxPipeOutputs() > 0 && pipe.getOutputs().size() + 1 >= PipesConfig.getMaxPipeOutputs()) {
removePipe(pipe);
throw new TooManyOutputsException(pipePart.getLocation());
}
pipe.getOutputs().put(pipePart.getLocation(), (PipeOutput) pipePart);
addToMultiCache(pipePart.getLocation(), pipe);
} else if (pipePart instanceof ChunkLoader) {
pipe.getChunkLoaders().put(pipePart.getLocation(), (ChunkLoader) pipePart);
addToMultiCache(pipePart.getLocation(), pipe);
}
pipePartCache.put(pipePart.getLocation(), pipePart);
}
/**
* Remove a part from a pipe
*
* @param pipe the pipe to remove from
* @param pipePart the part to remove
*/
public void removePart(Pipe pipe, AbstractPipePart pipePart) {
if (pipePart instanceof PipeInput) {
pipe.getInputs().remove(pipePart.getLocation());
pipeCache.invalidate(pipePart.getLocation());
} else if (pipePart instanceof PipeOutput) {
pipe.getOutputs().remove(pipePart.getLocation());
if (pipe.getOutputs().isEmpty()) {
removePipe(pipe);
} else {
removeFromMultiCache(pipePart.getLocation(), pipe);
}
} else if (pipePart instanceof ChunkLoader) {
pipe.getChunkLoaders().remove(pipePart.getLocation());
removeFromMultiCache(pipePart.getLocation(), pipe);
}
pipePartCache.remove(pipePart.getLocation(), pipePart);
}
private void addToMultiCache(SimpleLocation location, Pipe pipe) {
multiCache.putIfAbsent(location, Collections.newSetFromMap(new WeakHashMap<>()));
multiCache.get(location).add(pipe);
}
private void removeFromMultiCache(SimpleLocation location, Pipe pipe) {
Collection<Pipe> pipes = multiCache.get(location);
if (pipes != null) {
if (pipes.size() == 1) {
multiCache.remove(location);
} else {
pipes.remove(pipe);
}
}
}
/**
* Add a block to a pipe while checking settings and caching the location
*
* @param pipe the pipe to add to
* @param block the block to add
* @throws PipeTooLongException When the pipe is too long
*/
public void addBlock(Pipe pipe, Block block) throws PipeTooLongException {
SimpleLocation location = new SimpleLocation(block.getLocation());
if (PipesConfig.getMaxPipeLength() > 0 && pipe.getPipeBlocks().size() >= PipesConfig.getMaxPipeLength()) {
removePipe(pipe);
throw new PipeTooLongException(location);
}
pipe.getPipeBlocks().add(location);
singleCache.put(location, pipe);
}
/**
* Merge multiple pipes into one
* @param pipes The pipes to merge
* @return the merged Pipe or <code>null</code> if they couldn't be merged
* @throws PipeTooLongException When the pipe is too long
* @throws TooManyOutputsException when the pipe has too many outputs
*/
public Pipe mergePipes(Set<Pipe> pipes) throws TooManyOutputsException, PipeTooLongException {
Material type = null;
for (Pipe pipe : pipes) {
if (type == null) {
type = pipe.getType();
}
if (pipe.getType() != type) {
return null;
}
}
LinkedHashMap<SimpleLocation, PipeInput> inputs = new LinkedHashMap<>();
LinkedHashMap<SimpleLocation, PipeOutput> outputs = new LinkedHashMap<>();
LinkedHashMap<SimpleLocation, ChunkLoader> chunkLoaders = new LinkedHashMap<>();
LinkedHashSet<SimpleLocation> blocks = new LinkedHashSet<>();
pipes.forEach(pipe -> {
removePipe(pipe);
inputs.putAll(pipe.getInputs());
outputs.putAll(pipe.getOutputs());
chunkLoaders.putAll(pipe.getChunkLoaders());
blocks.addAll(pipe.getPipeBlocks());
});
if (PipesConfig.getMaxPipeLength() > 0 &&blocks.size() >= PipesConfig.getMaxPipeLength()) {
throw new PipeTooLongException(blocks.iterator().next());
}
if (PipesConfig.getMaxPipeOutputs() > 0 && outputs.size() + 1 >= PipesConfig.getMaxPipeOutputs()) {
throw new TooManyOutputsException(outputs.keySet().iterator().next());
}
Pipe pipe = new Pipe(inputs, outputs, chunkLoaders, blocks, type);
addPipe(pipe);
return pipe;
}
/**
* checks if the block is part of a pipe.
*
* @param startingPoint a block
* @return a pipe, if there is one
* @throws ChunkNotLoadedException When the pipe reaches into a chunk that is not loaded
* @throws PipeTooLongException When the pipe is too long
* @throws TooManyOutputsException when the pipe has too many outputs
*/
public Pipe isPipe(Block startingPoint) throws ChunkNotLoadedException, TooManyOutputsException, PipeTooLongException {
Queue<SimpleLocation> queue = new LinkedList<>();
Set<SimpleLocation> found = new LinkedHashSet<>();
LinkedHashMap<SimpleLocation, PipeInput> inputs = new LinkedHashMap<>();
LinkedHashMap<SimpleLocation, PipeOutput> outputs = new LinkedHashMap<>();
LinkedHashMap<SimpleLocation, ChunkLoader> chunkLoaders = new LinkedHashMap<>();
LinkedHashSet<SimpleLocation> pipeBlocks = new LinkedHashSet<>();
Material type = null;
World world = startingPoint.getWorld();
queue.add(new SimpleLocation(
startingPoint.getWorld().getName(),
startingPoint.getX(),
startingPoint.getY(),
startingPoint.getZ()));
while (!queue.isEmpty()) {
SimpleLocation location = queue.remove();
if (!found.contains(location)) {
if (!world.isChunkLoaded(location.getX() >> 4, location.getZ() >> 4)
&& (chunkLoaders.size() == 0)) {
throw new ChunkNotLoadedException(location);
}
Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
if (MaterialTags.STAINED_GLASS.isTagged(block)) {
if (type == null) {
type = block.getType();
}
if (block.getType() == type) {
if (PipesConfig.getMaxPipeLength() > 0 && pipeBlocks.size() >= PipesConfig.getMaxPipeLength()) {
throw new PipeTooLongException(location);
}
pipeBlocks.add(location);
found.add(location);
for (BlockFace face : PipesUtil.BLOCK_FACES) {
queue.add(location.getRelative(face));
}
}
} else {
AbstractPipePart pipesPart = getPipePart(block);
if (pipesPart != null) {
switch (pipesPart.getType()) {
case PIPE_INPUT:
PipeInput pipeInput = (PipeInput) pipesPart;
Block relativeBlock = block.getRelative(pipeInput.getFacing());
if (type == null && MaterialTags.STAINED_GLASS.isTagged(relativeBlock)) {
type = relativeBlock.getType();
}
if (relativeBlock.getType() == type) {
inputs.put(pipeInput.getLocation(), pipeInput);
found.add(location);
queue.add(pipeInput.getTargetLocation());
}
break;
case PIPE_OUTPUT:
PipeOutput pipeOutput = (PipeOutput) pipesPart;
if (PipesConfig.getMaxPipeOutputs() > 0 && outputs.size() >= PipesConfig.getMaxPipeOutputs()) {
throw new TooManyOutputsException(location);
}
outputs.put(pipeOutput.getLocation(), pipeOutput);
if (found.isEmpty()) {
for (BlockFace face : PipesUtil.BLOCK_FACES) {
if (face != pipeOutput.getFacing()) {
Material relative = block.getRelative(face).getType();
if (relative == type || (type == null & MaterialTags.STAINED_GLASS.isTagged(relative))) {
queue.add(location.getRelative(face));
break;
}
}
}
}
found.add(location);
Block relativeToOutput = pipeOutput.getTargetLocation().getBlock();
if (relativeToOutput.getState(false) instanceof InventoryHolder) {
found.add(new SimpleLocation(relativeToOutput.getLocation()));
} else if (relativeToOutput.getType() == Material.COMPOSTER) {
found.add(new SimpleLocation(relativeToOutput.getLocation()));
}
break;
case CHUNK_LOADER:
chunkLoaders.put(pipesPart.getLocation(), (ChunkLoader) pipesPart);
found.add(location);
break;
}
}
}
}
}
// Remove outputs that point in our own inputs
for (Iterator<PipeOutput> it = outputs.values().iterator(); it.hasNext();) {
PipeOutput pipeOutput = it.next();
SimpleLocation targetLocation = pipeOutput.getTargetLocation();
if (inputs.containsKey(targetLocation)) {
it.remove();
}
}
if ((outputs.size() > 0) && (inputs.size() > 0) && pipeBlocks.size() > 0) {
return new Pipe(inputs, outputs, chunkLoaders, pipeBlocks, type);
}
return null;
}
/**
* Create a new pipe part
* @param item The PipesItem to create the part from
* @param block The block to create the part at
* @return The pipepart
*/
public AbstractPipePart createPipePart(PipesItem item, Block block) {
BlockState state = block.getState(false);
if (state instanceof Container) {
// Paper's non-snapshot BlockState's are broken in some cases
if (((Container) state).getPersistentDataContainer() == null) {
state = block.getState(true);
}
((Container) state).getPersistentDataContainer().set(AbstractPipePart.TYPE_KEY, PersistentDataType.STRING, item.name());
state.update();
}
AbstractPipePart part = PipesUtil.convertToPipePart(state, item);
pipePartCache.put(new SimpleLocation(block.getLocation()), part);
return part;
}
/**
* Get the pipes part. Will try to lookup the part in the cache first, if not found it will create a new one.
* @param block the block to get the part for
* @return the pipespart or null if the block isn't one
*/
public AbstractPipePart getPipePart(Block block) {
PipesItem type = PipesUtil.getPipesItem(block);
if (type == null) {
return null;
}
return pipePartCache.getOrDefault(
new SimpleLocation(block.getLocation()),
PipesUtil.convertToPipePart(block.getState(false), type)
);
}
/**
* Get the pipes part. Will try to lookup the part in the cache first, if not found it will create a new one.
* @param state the block's state to get the part for
* @return the pipespart or null if the block isn't one
*/
public AbstractPipePart getPipePart(BlockState state) {
PipesItem type = PipesUtil.getPipesItem(state);
if (type == null) {
return null;
}
return pipePartCache.getOrDefault(
new SimpleLocation(state.getLocation()),
PipesUtil.convertToPipePart(state, type)
);
}
/**
* Get the pipes part. Will try to lookup the part in the cache first, if not found it will create a new one.
* @param location the block to get the part for
* @return the pipespart or
*/
public AbstractPipePart getCachedPipePart(SimpleLocation location) {
return pipePartCache.get(location);
}
private class PipeRemovalListener implements RemovalListener<SimpleLocation, Pipe> {
@Override
public void onRemoval(RemovalNotification<SimpleLocation, Pipe> notification) {
Pipe pipe = notification.getValue();
if (pipe == null) {
return;
}
if (pipe.getInputs().isEmpty() || notification.getCause() != RemovalCause.EXPLICIT) {
for (PipeInput input : pipe.getInputs().values()) {
pipeCache.invalidate(input.getLocation());
pipePartCache.remove(input.getLocation(), input);
}
for (SimpleLocation location : pipe.getPipeBlocks()) {
singleCache.remove(location);
}
for (PipeOutput output : pipe.getOutputs().values()) {
removeFromMultiCache(output.getLocation(), pipe);
if (multiCache.getOrDefault(output.getLocation(), Collections.emptySet()).isEmpty()) {
pipePartCache.remove(output.getLocation(), output);
}
}
for (ChunkLoader loader : pipe.getChunkLoaders().values()) {
removeFromMultiCache(loader.getLocation(), pipe);
if (multiCache.getOrDefault(loader.getLocation(), Collections.emptySet()).isEmpty()) {
pipePartCache.remove(loader.getLocation(), loader);
}
}
}
}
}
}
|
/*
* 文 件 名: UploadStatusRequest.java
* 描 述: UploadStatusRequest.java
* 时 间: 2013-6-21
*/
package com.babyshow.rest.uploadstatus;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.babyshow.rest.RestRequest;
/**
* <一句话功能简述>
*
* @author ztc
* @version [BABYSHOW V1R1C1, 2013-6-21]
*/
public class UploadStatusRequest extends RestRequest
{
/**
* 设备ID
*/
@NotNull(message = "{user.deviceid.null}")
@Size(min = 1, max = 64, message = "{user.deviceid.length}")
private String device_id;
/**
* 七牛上传路径,由服务器指派
*/
@NotNull(message = "{upload.qiniukey.null}")
@Size(min = 1, max = 128, message = "{upload.qiniukey.length}")
private String qiniu_key;
/**
* 上传状态
*/
@NotNull(message = "{upload.status.null}")
private Boolean upload_status;
/**
* 获取 device_id
*
* @return 返回 device_id
*/
public String getDevice_id()
{
return device_id;
}
/**
* 设置 device_id
*
* @param 对device_id进行赋值
*/
public void setDevice_id(String device_id)
{
this.device_id = device_id;
}
/**
* 获取 qiniu_key
*
* @return 返回 qiniu_key
*/
public String getQiniu_key()
{
return qiniu_key;
}
/**
* 设置 qiniu_key
*
* @param 对qiniu_key进行赋值
*/
public void setQiniu_key(String qiniu_key)
{
this.qiniu_key = qiniu_key;
}
/**
* 获取 upload_status
*
* @return 返回 upload_status
*/
public Boolean getUpload_status()
{
return upload_status;
}
/**
* 设置 upload_status
*
* @param 对upload_status进行赋值
*/
public void setUpload_status(Boolean upload_status)
{
this.upload_status = upload_status;
}
}
|
package httf.ui;
public class Bitmap {
public int width;
public int height;
public int[][] pixels;
public Bitmap(int width, int height) {
this.width = width;
this.height = height;
this.pixels = new int[width][height];
}
public void draw(Bitmap map, int xOffs, int yOffs) {
for(int x = 0; x < map.width; x++) {
for(int y = 0; y < map.height; y++) {
if(map.pixels[x][y] < 0) {
pixels[x + xOffs][y + yOffs] = map.pixels[x][y];
}
}
}
}
}
|
package nl.vu.datalayer.coprocessor.joins;
import org.apache.hadoop.hbase.util.Bytes;
/**ASSUMPTION: expecting the input qualifier bytes to be
* - 2 bytes - join id
* - 1 byte - triple id
* - 1 byte - encoding of join positions
* TODO add 3 bits to encode the order in which elements should go in the join key
* 0 - {0,1,2} 2
* 1 - {1,0,2} 4
* 2 - {2,0,1} 8
* 3 - {2,1,0} 10
* 4 - {0,2,1} 4
* 5 - {1,2,0} 8
* - 1 byte id - for each variable id in a non-join position (in SPOC order)
* example: S ?p ?o - join by ?o
* S - startRowkey
* inputQualifier
* tripleIdByte - e.g. 0x01
* joinByte - 0x02 (bit encoding of object position)
* id(?p) - 1 byte id which will be used in the join table
*/
class MetaInfo{
private static final int TRIPLE_SIZE = 3;
private short joinId;
private byte tripleId;
private byte joinPosition;
private byte[] variableIds;
private byte startRowKeyPositions;
private byte startRowNumberOfElems;
private int joinKeyLength;
private int joinNumberOfElems;
//private byte objectType;
public MetaInfo(byte[] inputQualifier, byte[] startRow, int tableIndex) {
super();
this.joinId = Bytes.toShort(inputQualifier);
this.tripleId = inputQualifier[2];
this.joinPosition = inputQualifier[3];
this.variableIds = Bytes.tail(inputQualifier, inputQualifier.length-4);
startRowNumberOfElems = (byte)(startRow.length/JoinObserver.BASE_ID_SIZE);
startRowKeyPositions = JoinObserver.KEY_ENCODINGS[tableIndex][startRowNumberOfElems];
joinNumberOfElems = bitCount(joinPosition);
joinKeyLength = joinNumberOfElems*JoinObserver.BASE_ID_SIZE;
}
private int bitCount(byte b){
int count = 0;
for (int i = 0; i < 4; i++) {
if ( (b & 1) == 1){
count++;
}
b = (byte)(b>>1);
}
return count;
}
public boolean checkLengthParamters(){
return (joinNumberOfElems+startRowNumberOfElems+variableIds.length==TRIPLE_SIZE);
}
public short getJoinId() {
return joinId;
}
public byte getTripleId() {
return tripleId;
}
public byte getJoinPosition(){
return joinPosition;
}
public byte[] getVariableIds(){
return variableIds;
}
public byte getStartRowKeyPositions(){
return startRowKeyPositions;
}
public int getJoinKeyLength() {
return joinKeyLength;
}
public void adjustJoinKeyLength(byte objectType){
if ((joinPosition & (byte) JoinObserver.O) == JoinObserver.O) {
if (objectType == JoinObserver.NUMERICAL_TYPE) {//join on object
joinKeyLength++;
}
}
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.preferences.autofill;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.android.i18n.addressinput.AddressData;
import com.android.i18n.addressinput.AddressField;
import com.android.i18n.addressinput.AddressWidget;
import com.android.i18n.addressinput.FormOptions;
import com.android.i18n.addressinput.SimpleClientCacheManager;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.autofill.PersonalDataManager;
import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile;
/**
* Provides the Java-ui for editing a Profile autofill entry.
*/
public class AutofillProfileEditor extends Fragment implements TextWatcher,
OnItemSelectedListener {
// GUID of the profile we are editing.
// May be the empty string if creating a new profile.
private String mGUID;
private AddressWidget mAddressWidget;
private boolean mNoCountryItemIsSelected;
private EditText mPhoneText;
private EditText mEmailText;
private String mLanguageCodeString;
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.autofill_profile_editor, container, false);
mPhoneText = (EditText) v.findViewById(R.id.autofill_profile_editor_phone_number_edit);
mEmailText = (EditText) v.findViewById(R.id.autofill_profile_editor_email_address_edit);
// We know which profile to edit based on the GUID stuffed in
// our extras by AutofillPreferences.
Bundle extras = getArguments();
if (extras != null) {
mGUID = extras.getString(AutofillPreferences.AUTOFILL_GUID);
}
if (mGUID == null) {
mGUID = "";
getActivity().setTitle(R.string.autofill_create_profile);
} else {
getActivity().setTitle(R.string.autofill_edit_profile);
}
addProfileDataToEditFields(v);
hookupSaveCancelDeleteButtons(v);
return v;
}
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
enableSaveButton();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mAddressWidget.onItemSelected(parent, view, position, id);
if (mNoCountryItemIsSelected) {
mNoCountryItemIsSelected = false;
return;
}
enableSaveButton();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
private void addProfileDataToEditFields(View v) {
AddressData.Builder address = new AddressData.Builder();
AutofillProfile profile = PersonalDataManager.getInstance().getProfile(mGUID);
if (profile != null) {
mPhoneText.setText(profile.getPhoneNumber());
mEmailText.setText(profile.getEmailAddress());
mLanguageCodeString = profile.getLanguageCode();
address.set(AddressField.ADMIN_AREA, profile.getRegion());
address.set(AddressField.LOCALITY, profile.getLocality());
address.set(AddressField.RECIPIENT, profile.getFullName());
address.set(AddressField.ORGANIZATION, profile.getCompanyName());
address.set(AddressField.DEPENDENT_LOCALITY, profile.getDependentLocality());
address.set(AddressField.POSTAL_CODE, profile.getPostalCode());
address.set(AddressField.SORTING_CODE, profile.getSortingCode());
address.set(AddressField.ADDRESS_LINE_1, profile.getStreetAddress());
address.set(AddressField.COUNTRY, profile.getCountryCode());
}
ViewGroup widgetRoot = (ViewGroup) v.findViewById(R.id.autofill_profile_widget_root);
mAddressWidget = new AddressWidget(getActivity(), widgetRoot,
(new FormOptions.Builder()).build(),
new SimpleClientCacheManager(),
address.build(),
new ChromeAddressWidgetUiComponentProvider(getActivity()));
if (profile == null) {
widgetRoot.requestFocus();
}
}
// Read edited data; save in the associated Chrome profile.
// Ignore empty fields.
private void saveProfile() {
AddressData input = mAddressWidget.getAddressData();
String addressLines = input.getAddressLine1();
if (!TextUtils.isEmpty(input.getAddressLine2())) {
addressLines += "\n" + input.getAddressLine2();
}
AutofillProfile profile = new PersonalDataManager.AutofillProfile(
mGUID,
AutofillPreferences.SETTINGS_ORIGIN,
input.getRecipient(),
input.getOrganization(),
addressLines,
input.getAdministrativeArea(),
input.getLocality(),
input.getDependentLocality(),
input.getPostalCode(),
input.getSortingCode(),
input.getPostalCountry(),
mPhoneText.getText().toString(),
mEmailText.getText().toString(),
mLanguageCodeString);
PersonalDataManager.getInstance().setProfile(profile);
}
private void deleteProfile() {
if (AutofillProfileEditor.this.mGUID != null) {
PersonalDataManager.getInstance().deleteProfile(mGUID);
}
}
private void hookupSaveCancelDeleteButtons(View v) {
Button button = (Button) v.findViewById(R.id.autofill_profile_delete);
if ((mGUID == null) || (mGUID.compareTo("") == 0)) {
// If this is a create, disable the delete button.
button.setEnabled(false);
} else {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AutofillProfileEditor.this.deleteProfile();
getActivity().finish();
}
});
}
button = (Button) v.findViewById(R.id.autofill_profile_cancel);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
button = (Button) v.findViewById(R.id.autofill_profile_save);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AutofillProfileEditor.this.saveProfile();
getActivity().finish();
}
});
button.setEnabled(false);
// Listen for changes to inputs. Enable the save button after something has changed.
mPhoneText.addTextChangedListener(this);
mEmailText.addTextChangedListener(this);
mNoCountryItemIsSelected = true;
for (AddressField field : AddressField.values()) {
View input = mAddressWidget.getViewForField(field);
if (input instanceof EditText) {
((EditText) input).addTextChangedListener(this);
} else if (input instanceof Spinner) {
((Spinner) input).setOnItemSelectedListener(this);
}
}
}
private void enableSaveButton() {
Button button = (Button) getView().findViewById(R.id.autofill_profile_save);
button.setEnabled(true);
}
}
|
package bnorm.timer;
/**
* A simple {@link ITimer} implementation.
*
* @author Brian Norman
*/
public class Timer implements ITimer {
/**
* The end time of the timer if it is running.
*/
public static final double RUNNING_END_TIME = -1.0;
/**
* The current state of the timer.
*/
private TimerState state;
/**
* The start time of the timer.
*/
private double startTime;
/**
* The end time of the timer.
*/
private double endTime;
/**
* Creates a new timer which is stopped and has no start time or end time.
*/
public Timer() {
super();
this.state = TimerState.STOPPED;
this.startTime = 0.0;
this.endTime = 0.0;
}
@Override
public TimerState getTimerState() {
return state;
}
@Override
public Timer start() {
state = TimerState.RUNNING;
startTime = getCurrentTime();
endTime = RUNNING_END_TIME;
return this;
}
@Override
public Timer stop() {
// Can only stop if the timer is running
if (TimerState.RUNNING == getTimerState()) {
state = TimerState.STOPPED;
endTime = getCurrentTime();
}
return this;
}
@Override
public Timer reset() {
if (TimerState.RUNNING == getTimerState()) {
return start();
} else {
startTime = 0.0;
endTime = 0.0;
return this;
}
}
@Override
public double getCurrentTime() {
return System.currentTimeMillis() / 1000.0;
}
@Override
public double getStartTime() {
return startTime;
}
@Override
public double getEndTime() {
return endTime;
}
@Override
public double getElapsedTime() {
if (TimerState.STOPPED == getTimerState()) {
return getEndTime() - getStartTime();
} else {
return getCurrentTime() - getStartTime();
}
}
}
|
package test.design.future;
/**
* Created by maguoqiang on 2016/9/12.
* Client主要实现了获取Futureata,开启构造RealData的线程,并在接收请求后,很快返回FutureData
*/
public class Client {
public Data request(final String queryStr){
final FutureData future=new FutureData();
new Thread(){
public void run(){
RealData realData=new RealData(queryStr);
future.setRealData(realData);
}
}.start();
return future; //FutureData会被立即返回。
}
}
|
package com.harrymt.productivitymapping;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Button;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.harrymt.productivitymapping.coredata.Zone;
import com.harrymt.productivitymapping.database.DatabaseAdapter;
/**
* Handles the polling for the users current location using the Google API.
*
* Based on the google demo class:
* https://github.com/googlesamples/android-play-location/blob/master/LocationUpdates/app/src/main/java/com/google/android/gms/location/sample/locationupdates/MainActivity.java
*/
public class LocationPoller implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final String TAG = PROJECT_GLOBALS.LOG_NAME + "LocationPoller";
// The desired interval for location updates. Inexact. Updates may be more or less frequent.
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
// The fastest rate for active location updates. Exact. Updates will never be more frequent than this value.
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// Keys for storing activity state in the Bundle.
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
// Provides the entry point to Google Play services.
public GoogleApiClient mGoogleApiClient;
// Stores parameters for requests to the FusedLocationProviderApi.
protected LocationRequest mLocationRequest;
// Represents the users current location.
public Location mCurrentLocation;
/**
* Tracks the status of the location updates request. Value changes when the user presses the
* Start Updates and Stop Updates buttons.
*/
protected Boolean mRequestingLocationUpdates = true;
// Reference to the activity.
private FragmentActivity activityReference;
/**
* Constructor.
*
* @param ref Activity reference.
* @param state Saved state.
*/
public LocationPoller(FragmentActivity ref, Bundle state) {
activityReference = ref;
mRequestingLocationUpdates = false;
// Update values using data stored in the Bundle.
updateValuesFromBundle(state);
// Building a GoogleApiClient and requesting the LocationServices API
buildGoogleApiClient();
}
/**
* Runs when Google API client successfully connects.
* Start polling for location.
*
* @param connectionHint Description of connection.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
if (mCurrentLocation == null) {
if (ActivityCompat.checkSelfPermission(activityReference, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(activityReference, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Permission ERROR");
return;
}
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
updateUI();
}
startLocationUpdates();
}
/**
* Callback that fires when location changes.
* @param location New location.
*/
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateUI();
}
/**
* Callback is called when connection is suspended.
* Try to connect again.
*
* @param cause Cause of suspension.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "onConnectionSuspended, cause: " + cause);
mGoogleApiClient.connect();
}
/**
* When connection fails.
*
* @param result Result of failure.
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/**
* Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(activityReference)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
/**
* Updates fields based on data stored in the bundle.
*
* @param savedInstanceState The activity state saved in the Bundle.
*/
private void updateValuesFromBundle(Bundle savedInstanceState) {
Log.i(TAG, "Updating values from bundle");
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
}
// Update the value of mCurrentLocation from the Bundle and update the ActionBarHandler to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
// Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
updateUI();
}
}
/**
* Sets up the location request. Android has two location request settings:
* {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
// The final argument to {@code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
if (ActivityCompat.checkSelfPermission(activityReference, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(activityReference, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Permission ERROR");
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
/**
* Starts polling for location updates.
*/
public void startPolling() {
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
/**
* Stop polling for location updates.
*/
public void stopPolling() {
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
/**
* Get the users current location.
*
* @return Users location in lat lng.
*/
public LatLng getCurrLocation() {
if (mCurrentLocation != null) {
return new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
} else {
// Return a random fallback as a location
return new LatLng(52.9532976, -1.187156);
}
}
/**
* Checks to see if a user is inside of a zone or not!
*/
private void setUsersCurrentZone() {
DatabaseAdapter dbAdapter;
dbAdapter = new DatabaseAdapter(activityReference); // Open and prepare the database
Zone zone = dbAdapter.getZoneInLocation(mCurrentLocation);
dbAdapter.close();
// Update current zone, could be null if no zone is found;
PROJECT_GLOBALS.CURRENT_ZONE = zone;
}
/**
* Updates the latitude, the longitude, and the last location time in the ActionBarHandler.
*/
private void updateUI() {
if(!PROJECT_GLOBALS.STUDYING) {
setUsersCurrentZone();
Button currentZone = (Button) activityReference.findViewById(R.id.btnCurrentZone);
// Set the current zone button to be enabled if we are in a current zone
currentZone.setEnabled(PROJECT_GLOBALS.CURRENT_ZONE != null);
}
}
/**
* Create a bundle for saved state.
*
* @return Bundle with info needing to be saved.
*/
public Bundle getBundleForSavedState() {
Bundle state = new Bundle();
state.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
state.putParcelable(LOCATION_KEY, mCurrentLocation);
return state;
}
}
|
package imports;
import java.util.NoSuchElementException;
public class GQueue<E> implements IQueue<E>{
private Node<E> firstNode,
lastNode;
private int size;
private String string;
public GQueue(){
firstNode=null;
lastNode=null;
size=0;
string="";
}
public boolean isEmpty(){
return size==0;
}
public void enqueue(E data){
if(isEmpty()){
Node<E> nuevo= new Node<E>(data,null);
this.lastNode=nuevo;
this.firstNode=nuevo;
}
else{
Node<E> nuevo= new Node<E>(data,null);
this.lastNode.setNext(nuevo);
this.lastNode=nuevo;
}
this.size++;
}
public E dequeue(){
if(isEmpty()){
throw new NoSuchElementException();
}
Node<E> temp=this.firstNode;
this.firstNode=temp.getNext();
this.size--;
if(isEmpty()){
this.lastNode=null;
}
return temp.getData();
}
public E peek(){
if(isEmpty()){
throw new NoSuchElementException();
}
return firstNode.getData();
}
public String toString(){
while(!isEmpty()){
string+=("$"+dequeue()+"\n");
}
return string;
}
public int size(){
return size;
}
}
|
package com.tencent.xweb.x5.sdk;
import android.content.Context;
import android.webkit.ValueCallback;
import com.tencent.xweb.r;
import java.util.HashMap;
import java.util.Map;
import org.xwalk.core.Log;
public final class d {
static a vDZ;
public interface a {
void onViewInitFinished(boolean z);
}
static {
r.initInterface();
}
public static void a(a aVar) {
vDZ = aVar;
}
public static synchronized void a(Context context, a aVar) {
synchronized (d.class) {
if (vDZ != null) {
vDZ.a(context, aVar);
} else {
Log.e("TbsDownloader", "preInit: sImp is null");
}
}
}
public static void clearAllWebViewCache(Context context, boolean z) {
if (vDZ != null) {
vDZ.clearAllWebViewCache(context, z);
} else {
Log.e("TbsDownloader", "clearAllWebViewCache: sImp is null");
}
}
public static void reset(Context context) {
if (vDZ != null) {
vDZ.reset(context);
} else {
Log.e("TbsDownloader", "reset: sImp is null");
}
}
public static boolean getTBSInstalling() {
if (vDZ != null) {
return vDZ.getTBSInstalling();
}
Log.e("TbsDownloader", "getTBSInstalling: sImp is null");
return false;
}
public static int getTbsVersion(Context context) {
if (vDZ != null) {
return vDZ.getTbsVersion(context);
}
Log.e("TbsDownloader", "getTbsVersion: sImp is null");
return 0;
}
public static void a(h hVar) {
if (vDZ != null) {
vDZ.a(hVar);
} else {
Log.e("TbsDownloader", "setTbsListener: sImp is null");
}
}
public static int startMiniQBToLoadUrl(Context context, String str, HashMap<String, String> hashMap, ValueCallback<String> valueCallback) {
if (vDZ != null) {
return vDZ.startMiniQBToLoadUrl(context, str, hashMap, valueCallback);
}
Log.e("TbsDownloader", "startMiniQBToLoadUrl: sImp is null");
return 0;
}
public static boolean a(Context context, String str, HashMap<String, String> hashMap, ValueCallback<String> valueCallback) {
if (vDZ != null) {
return vDZ.a(context, str, hashMap, valueCallback);
}
Log.e("TbsDownloader", "startQbOrMiniQBToLoadUrl: sImp is null");
return false;
}
public static void a(Context context, String str, ValueCallback<Boolean> valueCallback) {
if (vDZ != null) {
vDZ.a(context, str, valueCallback);
} else {
Log.e("TbsDownloader", "canOpenFile: sImp is null");
}
}
public static boolean isTbsCoreInited() {
if (vDZ != null) {
return vDZ.isTbsCoreInited();
}
Log.e("TbsDownloader", "isTbsCoreInited: sImp is null");
return false;
}
public static void initTbsSettings(Map<String, Object> map) {
if (vDZ != null) {
vDZ.initTbsSettings(map);
} else {
Log.e("TbsDownloader", "initTbsSettings: sImp is null");
}
}
public static boolean canOpenWebPlus(Context context) {
if (vDZ != null) {
return vDZ.canOpenWebPlus(context);
}
Log.e("TbsDownloader", "canOpenWebPlus: sImp is null");
return false;
}
public static void closeFileReader(Context context) {
if (vDZ != null) {
vDZ.closeFileReader(context);
} else {
Log.e("TbsDownloader", "closeFileReader: sImp is null");
}
}
public static void forceSysWebView() {
if (vDZ != null) {
vDZ.forceSysWebView();
} else {
Log.e("TbsDownloader", "forceSysWebView: sImp is null");
}
}
}
|
package io.sensesecure.hadoop.xz;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.compress.CompressionInputStream;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.apache.hadoop.io.compress.Compressor;
import org.apache.hadoop.io.compress.Decompressor;
import org.apache.hadoop.io.compress.SplitCompressionInputStream;
import org.apache.hadoop.io.compress.SplittableCompressionCodec.READ_MODE;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
*
* @author yongtang
*/
public class XZCodecTest {
private final int count = 10000;
private final int seed = new Random().nextInt();
private final byte[] compressedTestData = {
(byte) 0xfd, (byte) 0x37, (byte) 0x7a, (byte) 0x58,
(byte) 0x5a, (byte) 0x00, (byte) 0x00, (byte) 0x04,
(byte) 0xe6, (byte) 0xd6, (byte) 0xb4, (byte) 0x46,
(byte) 0x02, (byte) 0x00, (byte) 0x21, (byte) 0x01,
(byte) 0x1c, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x10, (byte) 0xcf, (byte) 0x58, (byte) 0xcc,
(byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x74,
(byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x00,
(byte) 0xa5, (byte) 0x75, (byte) 0x0c, (byte) 0xc1,
(byte) 0xa7, (byte) 0xfd, (byte) 0x15, (byte) 0xfa,
(byte) 0x00, (byte) 0x01, (byte) 0x1c, (byte) 0x04,
(byte) 0x6f, (byte) 0x2c, (byte) 0x9c, (byte) 0xc1,
(byte) 0x1f, (byte) 0xb6, (byte) 0xf3, (byte) 0x7d,
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x04, (byte) 0x59, (byte) 0x5a,
(byte) 0x0a};
private final byte[] uncompressedTestData = {'t', 'e', 's', 't'};
private final int numberOfStreams = 3;
private final long blocksize = 997;
public XZCodecTest() {
}
@Rule
public final TemporaryFolder folder = new TemporaryFolder();
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@org.junit.Test
public void testCreateOutputStream_OutputStream() throws Exception {
System.out.println("createOutputStream");
OutputStream out = new ByteArrayOutputStream();
XZCodec instance = new XZCodec();
Class<? extends CompressionOutputStream> expResult = XZCompressionOutputStream.class;
Class<? extends CompressionOutputStream> result = instance.createOutputStream(out).getClass();
assertEquals(expResult, result);
}
@org.junit.Test
public void testCreateOutputStream_OutputStream_Compressor() throws Exception {
System.out.println("createOutputStream");
OutputStream out = new ByteArrayOutputStream();
Compressor compressor = null;
XZCodec instance = new XZCodec();
Class<? extends CompressionOutputStream> expResult = XZCompressionOutputStream.class;
Class<? extends CompressionOutputStream> result = instance.createOutputStream(out, compressor).getClass();
assertEquals(expResult, result);
}
@org.junit.Test
public void testGetCompressorType() {
System.out.println("getCompressorType");
XZCodec instance = new XZCodec();
Class<? extends Compressor> expResult = XZCompressor.class;
Class<? extends Compressor> result = instance.getCompressorType();
assertEquals(expResult, result);
}
@org.junit.Test
public void testCreateCompressor() {
System.out.println("createCompressor");
XZCodec instance = new XZCodec();
Class<? extends Compressor> expResult = XZCompressor.class;
Class<? extends Compressor> result = instance.createCompressor().getClass();
assertEquals(expResult, result);
}
@org.junit.Test
public void testCreateInputStream_InputStream() throws Exception {
System.out.println("createInputStream");
InputStream in = new ByteArrayInputStream(compressedTestData);
XZCodec instance = new XZCodec();
Class<? extends CompressionInputStream> expResult = XZCompressionInputStream.class;
Class<? extends CompressionInputStream> result = instance.createInputStream(in).getClass();
assertEquals(expResult, result);
}
@org.junit.Test
public void testCreateInputStream_InputStream_Decompressor() throws Exception {
System.out.println("createInputStream");
InputStream in = new ByteArrayInputStream(compressedTestData);
Decompressor decompressor = null;
XZCodec instance = new XZCodec();
Class<? extends CompressionInputStream> expResult = XZCompressionInputStream.class;
Class<? extends CompressionInputStream> result = instance.createInputStream(in, decompressor).getClass();
assertEquals(expResult, result);
}
@org.junit.Test
public void testGetDecompressorType() {
System.out.println("getDecompressorType");
XZCodec instance = new XZCodec();
Class<? extends Decompressor> expResult = XZDecompressor.class;
Class<? extends Decompressor> result = instance.getDecompressorType();
assertEquals(expResult, result);
}
@org.junit.Test
public void testCreateDecompressor() {
System.out.println("createDecompressor");
XZCodec instance = new XZCodec();
Class<? extends Decompressor> expResult = XZDecompressor.class;
Class<? extends Decompressor> result = instance.createDecompressor().getClass();
assertEquals(expResult, result);
}
@org.junit.Test
public void testGetDefaultExtension() {
System.out.println("getDefaultExtension");
XZCodec instance = new XZCodec();
String expResult = ".xz";
String result = instance.getDefaultExtension();
assertEquals(expResult, result);
}
@org.junit.Test
public void testDecompression() throws IOException {
System.out.println("Decompression");
InputStream in = new ByteArrayInputStream(compressedTestData);
XZCodec instance = new XZCodec();
CompressionInputStream compressed = instance.createInputStream(in, null);
byte[] uncompressed = new byte[uncompressedTestData.length + 1];
assertEquals(compressed.read(uncompressed, 0, uncompressed.length), uncompressedTestData.length);
assertArrayEquals(Arrays.copyOfRange(uncompressed, 0, uncompressedTestData.length), uncompressedTestData);
}
@org.junit.Test
public void testCompressionDecompression() throws Exception {
System.out.println("Compression/Decompression");
XZCodec codec = new XZCodec();
// Generate data
DataOutputBuffer data = new DataOutputBuffer();
RandomDatum.Generator generator = new RandomDatum.Generator(seed);
for (int i = 0; i < count; ++i) {
generator.next();
RandomDatum key = generator.getKey();
RandomDatum value = generator.getValue();
key.write(data);
value.write(data);
}
// Compress data
DataOutputBuffer compressedDataBuffer = new DataOutputBuffer();
CompressionOutputStream deflateFilter
= codec.createOutputStream(compressedDataBuffer);
DataOutputStream deflateOut
= new DataOutputStream(new BufferedOutputStream(deflateFilter));
deflateOut.write(data.getData(), 0, data.getLength());
deflateOut.flush();
deflateFilter.finish();
// De-compress data
DataInputBuffer deCompressedDataBuffer = new DataInputBuffer();
deCompressedDataBuffer.reset(compressedDataBuffer.getData(), 0,
compressedDataBuffer.getLength());
CompressionInputStream inflateFilter
= codec.createInputStream(deCompressedDataBuffer);
DataInputStream inflateIn
= new DataInputStream(new BufferedInputStream(inflateFilter));
// Check
DataInputBuffer originalData = new DataInputBuffer();
originalData.reset(data.getData(), 0, data.getLength());
DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData));
for (int i = 0; i < count; ++i) {
RandomDatum k1 = new RandomDatum();
RandomDatum v1 = new RandomDatum();
k1.readFields(originalIn);
v1.readFields(originalIn);
RandomDatum k2 = new RandomDatum();
RandomDatum v2 = new RandomDatum();
k2.readFields(inflateIn);
v2.readFields(inflateIn);
assertTrue("original and compressed-then-decompressed-output not equal",
k1.equals(k2) && v1.equals(v2));
// original and compressed-then-decompressed-output have the same hashCode
Map<RandomDatum, String> m = new HashMap<>();
m.put(k1, k1.toString());
m.put(v1, v1.toString());
String result = m.get(k2);
assertEquals("k1 and k2 hashcode not equal", result, k1.toString());
result = m.get(v2);
assertEquals("v1 and v2 hashcode not equal", result, v1.toString());
}
// De-compress data byte-at-a-time
originalData.reset(data.getData(), 0, data.getLength());
deCompressedDataBuffer.reset(compressedDataBuffer.getData(), 0,
compressedDataBuffer.getLength());
inflateFilter
= codec.createInputStream(deCompressedDataBuffer);
// Check
originalIn = new DataInputStream(new BufferedInputStream(originalData));
int expected;
do {
expected = originalIn.read();
assertEquals("Inflated stream read by byte does not match",
expected, inflateFilter.read());
} while (expected != -1);
}
@org.junit.Test
public void testSequenceFileCompressionDecompression() throws Exception {
System.out.println("Sequence File Compression/Decompression");
XZCodec codec = new XZCodec();
// Generate data and sequence file
final DataOutputBuffer data = new DataOutputBuffer();
final Configuration conf = new Configuration();
final File file = new File(folder.getRoot(), "test.seq");
final Path path = new Path("file:" + file.getAbsolutePath());
try (Writer writer = SequenceFile.createWriter(conf,
Writer.file(path),
Writer.keyClass(RandomDatum.class),
Writer.valueClass(RandomDatum.class),
Writer.compression(CompressionType.BLOCK, codec))) {
RandomDatum.Generator generator = new RandomDatum.Generator(seed);
int numSyncs = 4;
for (int i = 0, syncEvery = count / (numSyncs + 1), nextSync = syncEvery; i < count; ++i) {
generator.next();
RandomDatum key = generator.getKey();
RandomDatum value = generator.getValue();
key.write(data);
value.write(data);
writer.append(key, value);
if (i >= nextSync) {
// Ensure that the codec copes with multiple blocks per file
writer.sync();
nextSync += syncEvery;
}
}
}
// Read the sequence file and check its contents
DataInputBuffer originalData = new DataInputBuffer();
originalData.reset(data.getData(), 0, data.getLength());
DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData));
try (SequenceFile.Reader reader = new SequenceFile.Reader(conf,
SequenceFile.Reader.file(path))) {
for (int i = 0; i < count; ++i) {
RandomDatum k1 = new RandomDatum();
RandomDatum v1 = new RandomDatum();
k1.readFields(originalIn);
v1.readFields(originalIn);
RandomDatum k2 = new RandomDatum();
RandomDatum v2 = new RandomDatum();
reader.next(k2, v2);
assertTrue("original and compressed-then-decompressed-output not equal",
k1.equals(k2) && v1.equals(v2));
// original and compressed-then-decompressed-output have the same hashCode
Map<RandomDatum, String> m = new HashMap<>();
m.put(k1, k1.toString());
m.put(v1, v1.toString());
String result = m.get(k2);
assertEquals("k1 and k2 hashcode not equal", result, k1.toString());
result = m.get(v2);
assertEquals("v1 and v2 hashcode not equal", result, v1.toString());
}
}
}
@Test
public void testSequenceFileCompressionCompressorPooling() throws Exception {
System.out.println("Sequence File Compression/Decompression Compressor Pooling");
XZCodec codec = new XZCodec();
// Generate data and sequence file
final DataOutputBuffer data = new DataOutputBuffer();
final Configuration conf = new Configuration();
for (int j = 0; j < 2; j++) {
final File file = new File(folder.getRoot(), "test" + j + ".seq");
final Path path = new Path("file:" + file.getAbsolutePath());
try (Writer writer = SequenceFile.createWriter(conf,
Writer.file(path),
Writer.keyClass(RandomDatum.class),
Writer.valueClass(RandomDatum.class),
Writer.compression(CompressionType.BLOCK, codec))) {
RandomDatum.Generator generator = new RandomDatum.Generator(seed);
int numSyncs = 4;
for (int i = 0, syncEvery = count / (numSyncs + 1), nextSync = syncEvery; i < count; ++i) {
generator.next();
RandomDatum key = generator.getKey();
RandomDatum value = generator.getValue();
key.write(data);
value.write(data);
writer.append(key, value);
if (i >= nextSync) {
// Ensure that the codec copes with multiple blocks per file
writer.sync();
nextSync += syncEvery;
}
}
}
// Read the sequence file and check its contents
DataInputBuffer originalData = new DataInputBuffer();
originalData.reset(data.getData(), 0, data.getLength());
DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData));
try (SequenceFile.Reader reader = new SequenceFile.Reader(conf,
SequenceFile.Reader.file(path))) {
for (int i = 0; i < count; ++i) {
RandomDatum k1 = new RandomDatum();
RandomDatum v1 = new RandomDatum();
k1.readFields(originalIn);
v1.readFields(originalIn);
RandomDatum k2 = new RandomDatum();
RandomDatum v2 = new RandomDatum();
reader.next(k2, v2);
assertTrue("original and compressed-then-decompressed-output not equal",
k1.equals(k2) && v1.equals(v2));
// original and compressed-then-decompressed-output have the same hashCode
Map<RandomDatum, String> m = new HashMap<>();
m.put(k1, k1.toString());
m.put(v1, v1.toString());
String result = m.get(k2);
assertEquals("k1 and k2 hashcode not equal", result, k1.toString());
result = m.get(v2);
assertEquals("v1 and v2 hashcode not equal", result, v1.toString());
}
}
}
}
@org.junit.Test
public void testSplittableCompressionDecompression() throws Exception {
System.out.println("SplittableCompression/Decompression");
Configuration conf = new Configuration();
conf.setLong("xz.presetlevel", 5);
conf.setLong("xz.blocksize", blocksize);
XZCodec codec = new XZCodec(conf);
Random random = new Random(seed);
byte[] datum = new byte[count];
for (int i = 0; i < count; i++) {
datum[i] = (byte) (random.nextInt() & 0xFF);
}
byte[] data = new byte[count * numberOfStreams];
byte[] checkData = new byte[count * numberOfStreams];
for (int streamIndex = 0; streamIndex < numberOfStreams; streamIndex++) {
System.arraycopy(datum, 0, data, count * streamIndex, count);
}
for (int streamIndex = 0; streamIndex < numberOfStreams; streamIndex++) {
for (int i = 0; i < count; i++) {
assertEquals(datum[i], data[count * streamIndex + i]);
}
}
DataOutputBuffer compressedDataBuffer = new DataOutputBuffer();
for (int streamIndex = 0; streamIndex < numberOfStreams; streamIndex++) {
// Compress data
CompressionOutputStream deflateFilter
= codec.createOutputStream(compressedDataBuffer);
DataOutputStream deflateOut
= new DataOutputStream(new BufferedOutputStream(deflateFilter));
deflateOut.write(datum, 0, datum.length);
deflateOut.flush();
deflateFilter.finish();
}
java.nio.file.Path tmp = Files.createTempFile("hadoop-xz-", "-tmp");
Files.write(tmp, Arrays.copyOf(compressedDataBuffer.getData(), compressedDataBuffer.size()));
tmp.toFile().deleteOnExit();
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.get(configuration);
FSDataInputStream inData = fileSystem.open(new Path(tmp.toAbsolutePath().toString()));
final int nextStep = 997;
long start = 0;
int offset = 0;
while (start < compressedDataBuffer.size()) {
long end = start + nextStep < compressedDataBuffer.size() ? start + nextStep : compressedDataBuffer.size();
// De-compress data
SplitCompressionInputStream inflateFilter = codec.createInputStream(inData, null, start, end, READ_MODE.BYBLOCK);
DataInputStream inflateIn = new DataInputStream(new BufferedInputStream(inflateFilter));
int chunk = inflateIn.read(checkData, offset, checkData.length - offset);
chunk = chunk == -1 ? 0 : chunk;
offset += chunk;
start = end;
}
assertEquals(offset, data.length);
assertArrayEquals(data, checkData);
// De-compress data
DataInputBuffer deCompressedDataBuffer = new DataInputBuffer();
deCompressedDataBuffer.reset(compressedDataBuffer.getData(), 0, compressedDataBuffer.getLength());
CompressionInputStream inflateFilter = codec.createInputStream(deCompressedDataBuffer);
DataInputStream inflateIn = new DataInputStream(new BufferedInputStream(inflateFilter));
// Check
inflateIn.readFully(checkData, 0, checkData.length);
assertArrayEquals(data, checkData);
}
}
|
package org.motechproject.server.strategy;
import org.motechproject.server.model.ExtractedMessage;
import org.motechproject.server.model.IncomingMessage;
public interface MessageContentExtractionStrategy {
public ExtractedMessage extractFrom(IncomingMessage message);
String extractDateFrom(String time);
String extractPhoneNumberFrom(String phoneNumber);
String extractSenderFrom(String text);
String extractDescriptionFrom(String text);
}
|
package com.hogai.webtest.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
public class KayakFlightSearchResultPage {
// Element lookups
@FindBy(xpath = "html/body/div[3]/div[1]/div/div[1]/div/div/div/div[2]/div[1]/div[1]/div[1]/span[1]")
private WebElement originInputTextResult;
@FindBy(xpath = "html/body/div[3]/div[1]/div/div[1]/div/div/div/div[2]/div[1]/div[1]/div[1]/span[3]")
private WebElement destinationInputTextResult;
@FindBy(xpath = "html/body/div[3]/div[1]/div/div[1]/div/div/div/div[2]/div[1]/div[1]/div[3]/span")
private WebElement startDateInputCalResult;
@FindBy(xpath = "html/body/div[3]/div[1]/div/div[1]/div/div/div/div[2]/div[1]/div[1]/div[5]/span")
private WebElement backDateInputCalResult;
// Check Flight Search Result
public boolean checkFlightResult (String originInput, String destinationInput) {
if (!originInputTextResult.getText().contains(originInput))
{ Assert.fail("verifyElementValue OriginCity failed"); return false;}
else if (!destinationInputTextResult.getText().contains(destinationInput))
{ Assert.fail("verifyElementValue OriginCity failed"); return false;}
// ToDO - Input Dates need to be formatted to use method input parameters for date verification format values here
else if (!startDateInputCalResult.getText().contains("Oct 21"))
{ Assert.fail("verifyElementValue DestinationCity failed"); return false;}
else if (!backDateInputCalResult.getText().contains("Nov 30"))
{ Assert.fail("verifyElementValue DestinationCity failed");return false;}
else return true;
}
}
|
package br.com.ranking;
import java.util.Calendar;
import java.util.List;
public class Jogador {
private String nome;
private String streak;
private List<Arma> arma;
private List<Calendar> assasinatos;
private List<Calendar> mortes;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getStreak() {
return streak;
}
public void setStreak(String streak) {
this.streak = streak;
}
public List<Calendar> getAssasinatos() {
return assasinatos;
}
public void setAssasinatos(List<Calendar> assasinatos) {
this.assasinatos = assasinatos;
}
public List<Calendar> getMortes() {
return mortes;
}
public void setMortes(List<Calendar> mortes) {
this.mortes = mortes;
}
public List<Arma> getArma() {
return arma;
}
public void setArma(List<Arma> arma) {
this.arma = arma;
}
}
|
package botenanna.behaviortree.guards;
import botenanna.behaviortree.ArgumentTranslator;
import botenanna.behaviortree.Leaf;
import botenanna.behaviortree.MissingNodeException;
import botenanna.behaviortree.NodeStatus;
import botenanna.game.Situation;
import botenanna.math.Vector3;
import java.util.function.Function;
public class GuardIsDistanceLessThan extends Leaf {
private Function<Situation, Object> toFunc;
private Function<Situation, Object> fromFunc;
private double distance;
/** The GuardIsDistanceLessThan compares to Vector3 ands returns whether the distance between those are less than
* a given distance. Can be inverted to check if distance is greater than instead.
*
* Its signature is {@code GuardIsDistanceLessThan <from:Vector3> <to:Vector3> <dist:DOUBLE>}*/
public GuardIsDistanceLessThan(String[] arguments) throws IllegalArgumentException {
super(arguments);
if (arguments.length != 3) throw new IllegalArgumentException();
fromFunc = ArgumentTranslator.get(arguments[0]);
toFunc = ArgumentTranslator.get(arguments[1]);
distance = Double.parseDouble(arguments[2]);
}
@Override
public void reset() {
// Irrelevant
}
@Override
public NodeStatus run(Situation input) throws MissingNodeException {
// Get points
Vector3 from = (Vector3) fromFunc.apply(input);
Vector3 to = (Vector3) toFunc.apply(input);
// Compare distance
double dist = from.minus(to).getMagnitudeSqr();
if (dist <= distance * distance) return NodeStatus.DEFAULT_SUCCESS;
return NodeStatus.DEFAULT_FAILURE;
}
}
|
package traffic_simulator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class NewRoadConstructor extends JFrame implements ActionListener {
final int WIDTH = 250;
final int HEIGHT = 250;
String initialDirection;
int roadType;
Road[] currentRoads;
TIntersection[] currentTIntersections;
CrossIntersection[] currentCrossIntersections;
JLabel test = new JLabel("Test complete");
JTextField newRoadName = new JTextField("Road name");
JTextField xCoOrdinate = new JTextField("X co-ordinate");
JTextField yCoOrdinate = new JTextField("y co-ordinate");
ButtonGroup group = new ButtonGroup();
JCheckBox north = new JCheckBox("North");
JCheckBox south = new JCheckBox("South");
JCheckBox east = new JCheckBox("East");
JCheckBox west = new JCheckBox("West");
JButton creation = new JButton("Create road");
String[] roadTypes = {"Road", "T Intersection", "Cross intersection"};
JComboBox<String> cb = new JComboBox<String>(roadTypes);
public NewRoadConstructor(Road[] roads, TIntersection[] tIntersections, CrossIntersection[] crossIntersections) {
super("ROAD CONSTRUCTOR");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new GridLayout(6, 1));
currentRoads = roads;
currentTIntersections = tIntersections;
currentCrossIntersections = crossIntersections;
add(newRoadName);
add(xCoOrdinate);
add(yCoOrdinate);
add(cb);
group.add(north);
group.add(south);
group.add(east);
group.add(west);
add(north);
add(south);
add(east);
add(west);
add(creation);
creation.addActionListener(this);
north.addActionListener(this);
south.addActionListener(this);
east.addActionListener(this);
west.addActionListener(this);
cb.addActionListener(this);
}
public void addCross(String newDirection) {
int xStart = 0;
int yStart = 0;
if (newDirection.equals("west")) {
xStart = Integer.parseInt(xCoOrdinate.getText()) - 36;
yStart = Integer.parseInt(yCoOrdinate.getText());
} else if (newDirection.equals("east")) {
xStart = Integer.parseInt(xCoOrdinate.getText());
yStart = Integer.parseInt(yCoOrdinate.getText());
} else if (newDirection.equals("north")) {
xStart = Integer.parseInt(xCoOrdinate.getText()) - 18;
yStart = Integer.parseInt(yCoOrdinate.getText()) - 18;
} else {
xStart = Integer.parseInt(xCoOrdinate.getText()) - 18;
yStart = Integer.parseInt(yCoOrdinate.getText()) + 18;
}
CrossIntersection crossToAdd = new CrossIntersection(newRoadName.getText(), xStart, yStart, newDirection);
if (validateCrossEnds(crossToAdd)) {
CrossIntersection[] tempArray = new CrossIntersection[currentCrossIntersections.length + 1];
for (int i = 0; i < currentCrossIntersections.length; i++) {
tempArray[i] = currentCrossIntersections[i];
}
tempArray[currentCrossIntersections.length] = crossToAdd;
currentCrossIntersections = tempArray;
}
}
public boolean validateCrossEnds(CrossIntersection judgingCross) {
boolean crossValidated = true;
for (int i = 0; i < currentRoads.length; i++) {
for (int j = 1; j < 36; j++) {
if (inBetween(judgingCross.road1StartX + j, currentRoads[i].getRoadEnd1X(), currentRoads[i].getRoadEnd2X()) && inBetween(judgingCross.road1StartY + j, currentRoads[i].getRoadEnd1Y(), currentRoads[i].getRoadEnd2Y())) {
crossValidated = false;
}
}
if (crossValidated) {
if (currentRoads[i].direction.equals("north-south")) {
if ((judgingCross.eastRoadX == currentRoads[i].getRoadEnd1X() && judgingCross.eastRoadY == currentRoads[i].getRoadEnd1Y()) || (judgingCross.eastRoadX == currentRoads[i].getRoadEnd2X() && judgingCross.eastRoadY == currentRoads[i].getRoadEnd2Y()) || (judgingCross.westRoadX == currentRoads[i].getRoadEnd1X() && judgingCross.westRoadY == currentRoads[i].getRoadEnd1Y()) || (judgingCross.westRoadX == currentRoads[i].getRoadEnd2X() && judgingCross.westRoadY == currentRoads[i].getRoadEnd2Y())) {
crossValidated = false;
}
}
}
}
if (crossValidated) {
for (int i = 0; i < currentCrossIntersections.length; i++) {
if (currentCrossIntersections[i] != null) {
for (int j = 1; j < 36; j++) {
if (inBetween(judgingCross.road1StartX + j, currentCrossIntersections[i].road1StartX, currentCrossIntersections[i].road1EndX) && inBetween(judgingCross.road2StartY + j, currentCrossIntersections[i].road2StartY, currentCrossIntersections[i].road2EndY)) {
crossValidated = false;
}
}
}
}
for(int i = 0; i < currentTIntersections.length; i++){
if(currentTIntersections[i] != null){
for(int j = 0; j < 36; j++){
if(inBetween(judgingCross.road1StartX+j, currentTIntersections[i].section1StartX, currentTIntersections[i].section1EndX) && inBetween(judgingCross.road2StartY+j, currentTIntersections[i].section2StartY, currentTIntersections[i].section2EndY)){
crossValidated = false;
}
}
}
}
}
return crossValidated;
}
public void addRoad(String newDirection) {
String direction;
int startX;
int startY;
if (newDirection.equals("north")){
direction = "north-south";
startX = Integer.parseInt(xCoOrdinate.getText());
startY = Integer.parseInt(yCoOrdinate.getText())-36;
} else if(newDirection.equals("south")){
direction = "north-south";
startX = Integer.parseInt(xCoOrdinate.getText());
startY = Integer.parseInt(yCoOrdinate.getText());
} else if (newDirection.equals("west")){
direction = "west-east";
startX = Integer.parseInt(xCoOrdinate.getText())-36;
startY = Integer.parseInt(yCoOrdinate.getText());
} else {
direction = "west-east";
startX = Integer.parseInt(xCoOrdinate.getText());
startY = Integer.parseInt(yCoOrdinate.getText());
}
Road roadToAdd = new Road(newRoadName.getText(), startX, startY, direction);
if (validateRoadEnds(roadToAdd)) {
Road[] tempArray = new Road[currentRoads.length + 1];
for (int i = 0; i < currentRoads.length; i++) {
tempArray[i] = currentRoads[i];
}
tempArray[currentRoads.length] = roadToAdd;
currentRoads = tempArray;
}
}
public boolean validateRoadEnds(Road judgingRoad) {
boolean roadValidated = true;
for (int i = 1; i < currentRoads.length; i++) {
for (int j = 0; j < 36; j++) {
if ((inBetween(judgingRoad.getRoadEnd1X() + j, currentRoads[i].getRoadEnd1X(),
currentRoads[i].getRoadEnd2X()) && inBetween(judgingRoad.getRoadEnd1Y(),
currentRoads[i].getRoadEnd1Y(), currentRoads[i].getRoadEnd2Y())) ||
(inBetween(judgingRoad.getRoadEnd1X(), currentRoads[i].getRoadEnd1X(),
currentRoads[i].getRoadEnd2X()) && inBetween(judgingRoad.getRoadEnd1Y() + j,
currentRoads[i].getRoadEnd1Y(), currentRoads[i].getRoadEnd2Y()))) {
roadValidated = false;
}
}
}
if (roadValidated) {
for (int i = 0; i < currentCrossIntersections.length; i++) {
for (int j = 1; j < 36; j++) {
if (currentCrossIntersections[i] != null) {
if ((inBetween(judgingRoad.getRoadEnd1X() + j, currentCrossIntersections[i].road1StartX, currentCrossIntersections[i].road1EndX) && inBetween(judgingRoad.getRoadEnd1Y()+j, currentCrossIntersections[i].road2StartY, currentCrossIntersections[i].road2EndY)) || (inBetween(judgingRoad.getRoadEnd1X()+j, currentCrossIntersections[i].road1StartX, currentCrossIntersections[i].road1EndX) && inBetween(judgingRoad.getRoadEnd1Y() + j, currentCrossIntersections[i].road2StartY, currentCrossIntersections[i].road2EndY))) {
roadValidated = false;
}
}
}
}
for(int i = 0; i < currentTIntersections.length; i++){
if(currentTIntersections[i] != null){
for(int j = 1; j < 36; j++){
if(inBetween(judgingRoad.roadEnd1X+j, currentTIntersections[i].section1StartX, currentTIntersections[i].section1EndX) && inBetween(judgingRoad.roadEnd1Y+j, currentTIntersections[i].section2StartY, currentTIntersections[i].section2EndY)){
roadValidated = false;
}
}
}
}
}
return roadValidated;
}
private boolean inBetween(int value, int min, int max) {
boolean isInBetween = true;
if (value < min || value > max) {
isInBetween = false;
}
return isInBetween;
}
public void addTIntersections(String initialDirection){
JOptionPane.showMessageDialog(null, "T-Intersections couldn't get working" +initialDirection, "Message", JOptionPane.INFORMATION_MESSAGE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == creation) {
if (roadType == 0) {
addRoad(initialDirection);
} else if (roadType == 2) {
addCross(initialDirection);
} else {
addTIntersections(initialDirection);
}
} else if (e.getSource() == north) {
initialDirection = "north";
} else if (e.getSource() == south) {
initialDirection = "south";
} else if (e.getSource() == east) {
initialDirection = "east";
} else if (e.getSource() == west) {
initialDirection = "west";
} else {
roadType = cb.getSelectedIndex();
}
}
}
|
package nio;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by zhoubo on 2017/4/25.
*/
public class BasicChannelTest {
@Test
public void channelDemo1() throws Exception {
BasicChannel.channelDemo1();
}
}
|
package com.javarush.task.task18.task1807;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/*
Подсчет запятых
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
FileInputStream inputStream = new FileInputStream(fileName);
char character = ',';
int ascii = (int) character;
int count = 0;
while (inputStream.available() > 0) {
int data = inputStream.read();
if (data == ascii)
count++;
}
inputStream.close();
System.out.print(count);
}
}
|
package zm.gov.moh.core.repository.database.entity.custom;
import com.squareup.moshi.Json;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class Identifier {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "identifier_id")
@Json(name = "identifier_id")
private long identifierId;
private String identifier;
private short assigned;
public long getIdentifierId() {
return identifierId;
}
public Identifier(String identifier){
this.identifier = identifier;
this.assigned = 0;
}
public void setIdentifierId(long identifierId) {
this.identifierId = identifierId;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public short getAssigned() {
return assigned;
}
public void setAssigned(short assigned) {
this.assigned = assigned;
}
public void markAsAssigned(){
this.assigned = 1;
}
}
|
package emmet.warehousing.operation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import emmet.core.data.entity.Inventory;
import emmet.warehousing.operation.exception.DataNotFoundException;
import emmet.warehousing.operation.service.InventoryService;
@RepositoryRestController
@RequestMapping("/inventories")
public class InventoryController {
@Autowired
InventoryService inventoryService;
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createInventory(@RequestParam String materialId) {
try {
return new ResponseEntity<Inventory>(inventoryService.createInventory(materialId), HttpStatus.CREATED);
} catch (DataNotFoundException e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.CONFLICT);
}
}
@RequestMapping(path = "/{id}/addStorage", method = RequestMethod.PUT)
public ResponseEntity<?> updateInventory(@PathVariable String id, @RequestParam String storageId) {
try {
return new ResponseEntity<Inventory>(inventoryService.addStorage(id, storageId), HttpStatus.OK);
} catch (DataNotFoundException e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.CONFLICT);
}
}
}
|
package de.jmda.gen.java;
import java.lang.annotation.Annotation;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.validation.constraints.NotNull;
import de.jmda.gen.java.ModifiersUtil.VisibilityModifier;
/**
* Generator for method declarations.
*
* @author rwegner
*/
public interface MethodGenerator extends DeclarationGenerator
{
DeclaredMethodGenerator getDeclaredMethodGenerator();
void setDeclaredMethodGenerator(DeclaredMethodGenerator generator);
void addAnnotation(@NotNull Class<? extends Annotation> annotation);
void setVisibility(VisibilityModifier modifier);
void setType(@NotNull Class<?> type);
void setType(@NotNull TypeMirror type);
void setType(@NotNull TypeElement type);
/**
* use this method for primitive types only
* @param typename
*/
void setType(@NotNull String typename);
void setTypeFrom(@NotNull VariableElement field);
void setName(@NotNull String methodName);
void setName(@NotNull Name methodName);
void addParameter(@NotNull Class<?> type, @NotNull String name);
void addParameter(@NotNull TypeMirror type, @NotNull String name);
void addParameter(@NotNull TypeElement type, @NotNull String name);
void addParameter(@NotNull String type, @NotNull String name);
void addParameterFrom(@NotNull VariableElement field, @NotNull String name);
void addParameterFrom(@NotNull VariableElement field, @NotNull Name name);
void setMethodBody(String methodBody);
}
|
package com.vti.backend.datalayer;
public interface IUserRepository {
}
|
/*
* 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 physics;
import actors.Actor;
import actors.Collision;
/**
*
* @author Perlt
*/
public class Gravity {
private Actor actor;
private double fallSpeed = 0;
private boolean falling;
public Gravity(Actor actor) {
this.actor = actor;
}
public void update() {
falling();
}
public void falling() {
Collision col = actor.getCollision();
if (!col.collisionWithSolidTile((int) (fallSpeed + 1), "down")) {
fallSpeed += 0.3;
actor.addToY((int) fallSpeed);
falling = true;
}else{
falling = false;
fallSpeed = 0;
}
}
public boolean isFalling() {
return falling;
}
}
|
package com.myproject.lab1.session;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
import java.util.Optional;
public interface SessionRepository extends MongoRepository<Session, String> {
List<Session> findByCreatorId(String creatorId);
Optional<Session> findByInviteId(String inviteId);
}
|
package javabasico.aula13labs;
import java.util.Scanner;
/**
* @author Kim Tsunoda
* Objetivo: Faša um programa que peša o tamanho de um arquivo para download (em MB) e a velocidade de um link de Internet (em Mbps),
* calcule e informe o tempo aproximado de download do arquivo usando este link (em minutos).
*/
public class Exercicio14 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Digite o tamanho do aquivo para download (em MB): ");
double arquivo = scan.nextDouble();
System.out.println("Digite a velocidade da internet (em MBps): ");
double internet = scan.nextDouble();
double tempo = (arquivo/internet);
System.out.println("O tempo de download Ú de aproximadamente (minutos): " + tempo);
}
}
|
package net.iz44kpvp.kitpvp.Comandos;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Spawn implements CommandExecutor {
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (cmd.getName().equalsIgnoreCase("spawn")) {
final Player p = (Player) sender;
p.chat("/warp spawn");
}
return false;
}
}
|
package org.nyer.sns.oauth.v1;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.log4j.Logger;
import org.nyer.sns.http.PrepareHttpClient;
import org.nyer.sns.http.PrepareRequest;
import org.nyer.sns.oauth.OAuthConstants;
import org.nyer.sns.oauth.OAuthDeveloperAccount;
import org.nyer.sns.token.OAuthTokenPair;
public class OAuth1EndPointImpl implements OAuth1EndPoint, OAuthConstants {
private static final Logger log = Logger.getLogger(LOG_NAME);
/** OAuth 1.0服务一般使用的加密算法(在调用Mac.getInstance时传入这个值) */
public static final String HMAC_SHA1 = "HmacSHA1";
/** OAuth 1.0服务一般使用的加密算法(在调用API时传入这个值) */
public static final String HMAC_SHA1_NAME = "HMAC-SHA1";
/**
* A Random object should be thread safe after JDK 1.4.2. See
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6362070 for details.
*/
private static final Random random = new Random();
private PrepareHttpClient httpClient;
private OAuth1 oauth;
public OAuth1EndPointImpl(OAuth1 oauth, PrepareHttpClient httpClient) {
this.oauth = oauth;
this.httpClient = httpClient;
}
@Override
public PrepareRequest post(String baseUri,
Map<String, String> additionalParams, HttpEntity requestEntity,
OAuthTokenPair accessToken) {
Map<String, String> params = generateParams(true, baseUri, additionalParams, oauth.getDeveloperAccount(), accessToken);
PrepareRequest req = httpClient.preparePost(baseUri);
req.httpParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
for (Entry<String, String> entry : params.entrySet()) {
req.parameter(entry.getKey(), entry.getValue());
}
if (requestEntity != null)
req.requestEntity(requestEntity);
return req;
}
@Override
public PrepareRequest post(String baseUri,
Map<String, String> additionalParams, OAuthTokenPair tokenPair) {
return post(baseUri, additionalParams, null, tokenPair);
}
@Override
public PrepareRequest post(String baseUri, HttpEntity requestEntity,
OAuthTokenPair tokenPair) {
return post(baseUri, null, requestEntity, tokenPair);
}
@Override
public PrepareRequest post(String baseUri, OAuthTokenPair tokenPair) {
return post(baseUri, (Map<String, String>)null, tokenPair);
}
@Override
public PrepareRequest get(String baseUri,
Map<String, String> additionalParams, OAuthTokenPair tokenPair) {
Map<String, String> params = generateParams(false, baseUri, additionalParams, oauth.getDeveloperAccount(), tokenPair);
PrepareRequest req = httpClient.prepareGet(baseUri);
for (Entry<String, String> entry : params.entrySet()) {
req.parameter(entry.getKey(), entry.getValue());
}
return req;
}
@Override
public PrepareRequest get(String baseUri,
Map<String, String> additionalParams) {
return get(baseUri, additionalParams, null);
}
@Override
public PrepareRequest get(String baseUri, OAuthTokenPair tokenPair) {
return get(baseUri, null, tokenPair);
}
/**
* 生成调用API接口的参数
*
* @param post 是否post请求。只允许两种请求类型:POST或GET
* @param baseUri API接口URL,不包含参数
* @param additionalParams 这个方法会自动设置OAuth 1.0需要的一些参数。如果调用者还需要传入其它参数,通过additionalParams传递。
* @param developerAccount 开发者账号
* @param tokenPair 接口不同,这个参数的意义也不一样。允许的值是request token and secret、access token and secret或null。
*/
private static Map<String, String> generateParams(boolean post, String baseUri,
Map<String, String> additionalParams,
OAuthDeveloperAccount developerAccount, OAuthTokenPair tokenPair) {
Map<String, String> params = new HashMap<String, String>();
params.put("oauth_consumer_key", developerAccount.getKey()); // Consumer Key
params.put("oauth_signature_method", HMAC_SHA1_NAME); // 签名方法,暂时只支持HMAC-SHA1
params.put("oauth_timestamp", generateTimestamp()); // 时间戳, 其值是距1970 00:00:00 GMT的秒数,必须是大于0的整数
params.put("oauth_nonce", generateNonce()); // 单次值,随机生成的32位字符串,防止重放攻击(每次请求必须不同)
params.put("oauth_version", "1.0"); // (可选)版本号,目前所有OAuth 1.0使用版本号1.0
if (tokenPair != null) {
params.put("oauth_token", tokenPair.getToken());
}
if (additionalParams != null) {
params.putAll(additionalParams);
}
String httpMethod = post ? "POST" : "GET";
String signatureSource = generateSignatureSource(httpMethod, baseUri, params);
String signature = generateSignature(signatureSource, developerAccount, tokenPair);
params.put("oauth_signature", signature); // 签名值,密钥为:Consumer Secret&Token Secret。
return params;
}
/**
* 生成用于签名的文本
*
* @param httpMethod http请求的method(GET或POST)
* @param baseUri 接口url,不包含参数
* @param params 参数
* @return 用于签名的文本
*/
private static String generateSignatureSource(String httpMethod, String baseUri, Map<String, String> params) {
StringBuilder signatureSource = new StringBuilder(httpMethod + "&" + normalizeParam4Signature(baseUri) + "&");
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
boolean first = true;
for (String key : keys) {
if (!first) {
signatureSource.append("%26");
}
String value = params.get(key);
value = normalizeParam4Signature(normalizeParam4Signature(value));
signatureSource.append(normalizeParam4Signature(key)).append("%3D").append(value);
first = false;
}
return signatureSource.toString();
}
/**
* 生成一段文本的签名
*
* @param text 需要生成签名的文本
* @param developerAccount 开发者账号
* @param tokenPair token & secret,视接口要求,可能是request token & secret或access token & secret。
* @return 签名
*/
private static String generateSignature(String text, OAuthDeveloperAccount developerAccount,
OAuthTokenPair tokenPair) {
try {
String oauthSignature = normalizeParam4Signature(developerAccount.getSecret()) + "&";
if (tokenPair != null && StringUtils.isNotBlank(tokenPair.getTokenSecret())) {
oauthSignature += normalizeParam4Signature(tokenPair.getTokenSecret());
}
SecretKeySpec spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(spec);
byte[] byteHMAC = mac.doFinal(text.getBytes());
return encodeBase64(byteHMAC);
} catch (InvalidKeyException e) {
// ignore
log.error("", e);
} catch (NoSuchAlgorithmException e) {
// ignore
log.error("", e);
}
return null;
}
/**
* 生成调用API接口需要的Authorization header
*
* @param params 调用API接口的所有参数
* @param authHeaderRealm Authorization header中realm的值
* @return 调用API接口需要的Authorization header
*/
@SuppressWarnings("unused")
private static String generateAuthorizationHeader(Map<String, String> params, String authHeaderRealm) {
StringBuilder authorizationHeader = new StringBuilder();
for (Entry<String, String> entry : params.entrySet()) {
if (authorizationHeader.length() != 0) {
authorizationHeader.append(",");
}
authorizationHeader.append(normalizeParam4Signature(entry.getKey()));
authorizationHeader.append("=\"").append(normalizeParam4Signature(entry.getValue())).append("\"");
}
return "OAuth " + (authHeaderRealm != null ? ("realm=\"" + authHeaderRealm + "\",") : "") +
authorizationHeader.toString();
}
/**
* <pre>
* 签名的各个组成部分,必须首先使用这个方法进行“转义”或者“规范化”
* 过程是:
* 1. 首先使用UTF-8对它进行url encode
* 2. 把结果中的*替换为%2A,把+替换为%20,把%7E替换为~
* </pre>
*
* @param value 需要“规范化”的字符串
* @return “规范化”后的字符串
*/
private static String normalizeParam4Signature(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("", e);
return null;
}
StringBuffer buf = new StringBuffer(encoded.length());
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buf.append("%2A");
} else if (focus == '+') {
buf.append("%20");
} else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7' &&
encoded.charAt(i + 2) == 'E') {
buf.append('~');
i += 2;
} else {
buf.append(focus);
}
}
return buf.toString();
}
/**
* @return 生成一个随机数,尽量避免重复
*/
private static String generateNonce() {
long timestamp = System.currentTimeMillis() / 1000;
return String.valueOf(timestamp + random.nextInt());
}
/**
* @return 当前时间,单位为秒
*/
private static String generateTimestamp() {
long timestamp = System.currentTimeMillis() / 1000;
return String.valueOf(timestamp);
}
/**
* 对一个字节数组进行Base64编码
*
* @param bytes 需要编码的字节数组
* @return 编码后的字符串
*/
private static String encodeBase64(byte[] bytes) {
try {
return new String(Base64.encodeBase64(bytes), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// ignore
log.error("", e);
return null;
}
}
}
|
package com.hesoyam.pharmacy.user.dto;
public class AllergiesDTO {
Long id;
String medicineName;
String manufacturerName;
public AllergiesDTO() {
//Empty ctor for JSON serializer
}
public AllergiesDTO(Long id, String medicineName, String manufacturerName) {
this.id = id;
this.medicineName = medicineName;
this.manufacturerName = manufacturerName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMedicineName() {
return medicineName;
}
public void setMedicineName(String medicineName) {
this.medicineName = medicineName;
}
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
}
|
package com.project.lrdn.contactslist;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by Lrdm on 12/27/2017.
*/
public class ViewDataActivity extends AppCompatActivity {
private static final String TAG = "ViewDataActivity";
private Button btnEdit, btnListView;
private TextView viewName, viewPhone, viewEmail, viewAddress, viewWeb;
DatabaseHelper mDatabaseHelper;
private String selectedName, selectedEmail, selectedPhone, selectedAddress, selectedWeb;
private int selectedID;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_data_layout);
btnEdit = findViewById(R.id.btnEdit);
btnListView = findViewById(R.id.btnListView);
viewName = findViewById(R.id.viewName);
viewPhone = findViewById(R.id.viewPhone);
viewEmail = findViewById(R.id.viewEmail);
viewAddress = findViewById(R.id.viewAddress);
viewWeb = findViewById(R.id.viewWeb);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
selectedEmail = receivedIntent.getStringExtra("email");
selectedPhone = receivedIntent.getStringExtra("phone");
selectedAddress = receivedIntent.getStringExtra("address");
selectedWeb = receivedIntent.getStringExtra("web");
//set the text to show the current selected contact
viewName.setText(selectedName);
viewEmail.setText(selectedEmail);
viewPhone.setText(selectedPhone);
viewAddress.setText(selectedAddress);
viewWeb.setText(selectedWeb);
btnEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (selectedID > -1) {
Log.d(TAG, "onItemClick: The ID is: " + selectedID);
Intent editScreenIntent = new Intent(ViewDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id", selectedID);
editScreenIntent.putExtra("name", selectedName);
editScreenIntent.putExtra("email", selectedEmail);
editScreenIntent.putExtra("web", selectedWeb);
editScreenIntent.putExtra("phone", selectedPhone);
editScreenIntent.putExtra("address", selectedAddress);
startActivity(editScreenIntent);
} else {
toastMessage("No ID associated with that name");
}
}
});
btnListView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ViewDataActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void phoneButton(View v) {
View.OnClickListener listSet = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + selectedPhone));
if (ActivityCompat.checkSelfPermission(ViewDataActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
toastMessage("You do not have permissions");
return;
}
startActivity(callIntent);
}
};
ImageButton phoneBtn = (ImageButton) findViewById(R.id.phoneImageButton);
phoneBtn.setOnClickListener(listSet);
}
public void emailButton(View v) {
View.OnClickListener listSet = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:"
+ selectedEmail
+ "?subject=" + "test" + "&body=" + "test");
intent.setData(data);
startActivity(intent);
}
};
ImageButton emailBtn = (ImageButton) findViewById(R.id.emailImageButton);
emailBtn.setOnClickListener(listSet);
}
public void addressButton(View v) {
View.OnClickListener listSet = new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri mapUri = Uri.parse("geo:0,0?q=" + Uri.encode(selectedAddress));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, mapUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
};
ImageButton addressBtn = (ImageButton) findViewById(R.id.addressImageButton);
addressBtn.setOnClickListener(listSet);
}
public void webButton(View v) {
View.OnClickListener listSet = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(selectedWeb));
startActivity(browserIntent);
}
};
ImageButton webBtn = (ImageButton) findViewById(R.id.webImageButton);
webBtn.setOnClickListener(listSet);
}
/**
* customizable toast
* @param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
|
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.Wearable;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
String TAG = "Mobile Activity";
Button enviar;
TextView mMensaje;
protected Handler myHandler;
int receivedMessageNumber = 1;
int sentMessageNumber = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enviar = findViewById(R.id.btnEnviar);
mMensaje = findViewById(R.id.txtMensaje);
myHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Bundle stuff = msg.getData();
messageText(stuff.getString("messageText"));
return true;
}
});
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
Receiver messageReceiver = new Receiver();
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
}
public void messageText(String newinfo) {
if (newinfo.compareTo("") != 0) {
mMensaje.append("\n" + newinfo);
}
}
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = "Mensaje recibido del wearable " + receivedMessageNumber++;
mMensaje.setText(message);
}
}
public void sendClick(View v) {
String message = "Enviando mensaje... ";
mMensaje.setText(message);
new NewThread("/my_path", message).start();
}
public void sendmessage(String messageText) {
Bundle bundle = new Bundle();
bundle.putString("messageText", messageText);
Message msg = myHandler.obtainMessage();
msg.setData(bundle);
myHandler.sendMessage(msg);
}
class NewThread extends Thread {
String path;
String message;
NewThread(String _path, String _message) {
path = _path;
message = _message;
}
public void run() {
Task<List<Node>> wearableList =
Wearable.getNodeClient(getApplicationContext()).getConnectedNodes();
try {
List<Node> nodes = Tasks.await(wearableList);
for (Node node : nodes) {
Task<Integer> sendMessageTask =
Wearable.getMessageClient(MainActivity.this).sendMessage(node.getId(), path, message.getBytes());
try {
Integer result = Tasks.await(sendMessageTask);
sendmessage("Mensaje enviado a Wearable " + sentMessageNumber++);
Log.v(TAG, "NewThread: Message send to: " + node.getDisplayName());
} catch (ExecutionException exception) {
//TO DO: Handle the exception//
sendmessage("NewThread: message failed to: " + node.getDisplayName());
Log.e(TAG, "New Task Failed: " + exception);
} catch (InterruptedException interruptedException) {
//TO DO: Handle the exception//
Log.e(TAG, "New Interrupt occurred: " + interruptedException);
}
}
} catch (ExecutionException exception) {
//TO DO: Handle the exception//
sendmessage("Node Task failed: " + exception);
Log.e(TAG, "Node Task failed: " + exception );
} catch (InterruptedException interruptedException) {
//TO DO: Handle the exception//
Log.e(TAG, "Node Interrupt occurred: " + interruptedException);
}
}
}
}
|
package com.accp.service.impl;
import com.accp.entity.PurchasereturnsDetaikstable;
import com.accp.dao.PurchasereturnsDetaikstableDao;
import com.accp.service.IPurchasereturnsDetaikstableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ljq
* @since 2019-08-28
*/
@Service
public class PurchasereturnsDetaikstableServiceImpl extends ServiceImpl<PurchasereturnsDetaikstableDao, PurchasereturnsDetaikstable> implements IPurchasereturnsDetaikstableService {
}
|
package com.kareo.ui.codingcapture.implementation.data;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
import org.scalastuff.scalabeans.sig.Mirror;
import java.util.UUID;
/**
* Created by narendral on 09/09/15.
*/
public class PMUser {
private long id;
private String guid;
private String email;
private String firstName;
private String lastName;
private boolean accountHidden;
private boolean accountLocked;
private DateTime createdDate;
private long createdUserId;
private DateTime modifiedDate;
private long modifiedUserId;
private boolean isKareoAdmin;
private boolean isCustomerAdmin;
private boolean isCare360Admin;
private boolean isCare360CustomerAdmin;
private boolean isRcmEmployee;
private boolean isRcmClient;
private int emailVerified;
public long getId() {
return id;
}
@JsonProperty("Id")
public void setId(long id) {
this.id = id;
}
public String getGuid() {
return guid;
}
@JsonProperty("Guid")
public void setGuid(String guid) {
this.guid = guid;
}
public String getEmail() {
return email;
}
@JsonProperty("Email")
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
@JsonProperty("FirstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
@JsonProperty("LastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isAccountHidden() {
return accountHidden;
}
@JsonProperty("IsAccountHidden")
public void setAccountHidden(boolean accountHidden) {
this.accountHidden = accountHidden;
}
public boolean isAccountLocked() {
return accountLocked;
}
@JsonProperty("IsAccountLocked")
public void setAccountLocked(boolean accountLocked) {
this.accountLocked = accountLocked;
}
public DateTime getCreatedDate() {
return createdDate;
}
@JsonProperty("CreatedDate")
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
public long getCreatedUserId() {
return createdUserId;
}
@JsonProperty("CreatedUserId")
public void setCreatedUserId(long createdUserId) {
this.createdUserId = createdUserId;
}
public DateTime getModifiedDate() {
return modifiedDate;
}
@JsonProperty("ModifiedDate")
public void setModifiedDate(DateTime modifiedDate) {
this.modifiedDate = modifiedDate;
}
public long getModifiedUserId() {
return modifiedUserId;
}
@JsonProperty("ModifiedUserId")
public void setModifiedUserId(long modifiedUserId) {
this.modifiedUserId = modifiedUserId;
}
public boolean isKareoAdmin() {
return isKareoAdmin;
}
@JsonProperty("IsKareoAdmin")
public void setIsKareoAdmin(boolean isKareoAdmin) {
this.isKareoAdmin = isKareoAdmin;
}
public boolean isCustomerAdmin() {
return isCustomerAdmin;
}
@JsonProperty("IsCustomerAdmin")
public void setIsCustomerAdmin(boolean isCustomerAdmin) {
this.isCustomerAdmin = isCustomerAdmin;
}
public boolean isCare360Admin() {
return isCare360Admin;
}
@JsonProperty("IsCare360Admin")
public void setIsCare360Admin(boolean isCare360Admin) {
this.isCare360Admin = isCare360Admin;
}
public boolean isCare360CustomerAdmin() {
return isCare360CustomerAdmin;
}
@JsonProperty("IsCare360CustomerAdmin")
public void setIsCare360CustomerAdmin(boolean isCare360CustomerAdmin) {
this.isCare360CustomerAdmin = isCare360CustomerAdmin;
}
public boolean isRcmEmployee() {
return isRcmEmployee;
}
@JsonProperty("IsRcmEmployee")
public void setIsRcmEmployee(boolean isRcmEmployee) {
this.isRcmEmployee = isRcmEmployee;
}
public boolean isRcmClient() {
return isRcmClient;
}
@JsonProperty("IsRcmClient")
public void setIsRcmClient(boolean isRcmClient) {
this.isRcmClient = isRcmClient;
}
public int getEmailVerified() {
return emailVerified;
}
@JsonProperty("EmailVerified")
public void setEmailVerified(int emailVerified) {
this.emailVerified = emailVerified;
}
}
|
package model.obstacle;
/**
* The possible unit types<br>
*
* <hr>
* Date created: Jun 6, 2010<br>
* Date last modified: Jun 6, 2010<br>
* <hr>
* @author Glen Watson
*/
public enum UnitType
{
Zergling,
Mareine,
Zealot
}
|
package org.houstondragonacademy.archer.exceptions;
import lombok.AllArgsConstructor;
import lombok.NonNull;
@AllArgsConstructor
public class CourseServiceException extends RuntimeException{
@NonNull String message;
}
|
import java.util.*;
import java.io.*;
public class ShatteredCake {
public static void main(String[] args) throws IOException {
Scanner nya = new Scanner(System.in);
int width = Integer.parseInt(nya.nextLine());
int pieces = Integer.parseInt(nya.nextLine());
long total = 0;
while(pieces-->0) {
String[] doop = nya.nextLine().split(" ");
total += Integer.parseInt(doop[0]) * Integer.parseInt(doop[1]);
}
System.out.printf("%.0f",(double)total/(double)width);
}
}
|
package com.kush.lib.expressions.evaluators;
import static com.kush.lib.expressions.ExpressionException.exceptionWithMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.kush.lib.expressions.ExpressionEvaluator;
import com.kush.lib.expressions.ExpressionEvaluatorFactory;
import com.kush.lib.expressions.ExpressionException;
import com.kush.lib.expressions.clauses.FunctionExpression;
import com.kush.lib.expressions.functions.FunctionExecutionFailedException;
import com.kush.lib.expressions.functions.FunctionExecutor;
import com.kush.lib.expressions.functions.FunctionSpec;
import com.kush.lib.expressions.functions.FunctonsRepository;
import com.kush.lib.expressions.types.Type;
import com.kush.lib.expressions.types.TypedValue;
// TODO avoid creation of new TypedValue instance on every evaluate call
class FunctionExpressionEvaluator<T> extends BaseExpressionEvaluator<FunctionExpression, T> {
private final Type returnType;
private final FunctionExecutor functionExecutor;
private final List<ExpressionEvaluator<T>> argEvaluators;
public FunctionExpressionEvaluator(FunctionExpression expression, ExpressionEvaluatorFactory<T> evaluatorFactory,
FunctonsRepository repository) throws ExpressionException {
super(expression);
Optional<FunctionSpec> functionSpec = repository.getFunctionSpec(expression.getFunctionName());
if (!functionSpec.isPresent()) {
throw exceptionWithMessage("No function found with name '%s'", expression.getFunctionName());
}
Class<?> returnTypeClass = functionSpec.get().getReturnType();
returnType = Type.forClass(returnTypeClass);
argEvaluators = new ArrayList<>(createEvaluators(evaluatorFactory, expression.getArguments()));
functionExecutor = functionSpec.get().getFunctionExecutor();
}
@Override
public TypedValue evaluate(T object) throws ExpressionException {
List<TypedValue> arguments = new ArrayList<>(argEvaluators.size());
for (ExpressionEvaluator<T> argEvaluator : argEvaluators) {
arguments.add(argEvaluator.evaluate(object));
}
return execute(arguments);
}
private TypedValue execute(List<TypedValue> arguments) throws ExpressionException {
try {
return functionExecutor.execute(arguments.toArray(new TypedValue[arguments.size()]));
} catch (FunctionExecutionFailedException e) {
throw new ExpressionException(e.getMessage(), e);
}
}
@Override
public Type evaluateType() throws ExpressionException {
return returnType;
}
}
|
package com.tencent.mm.view.footer;
import android.content.Context;
import android.graphics.Bitmap;
import com.tencent.mm.api.d;
import com.tencent.mm.bd.a.g;
import com.tencent.mm.bi.b;
public final class c extends a {
private Bitmap uVt;
private Bitmap uVu;
protected final void cCi() {
super.cCi();
this.uVt = com.tencent.mm.sdk.platformtools.c.s(getResources().getDrawable(g.crop_video_unselected));
this.uVu = com.tencent.mm.sdk.platformtools.c.s(getResources().getDrawable(g.crop_video_selected));
}
protected final Bitmap a(d dVar, boolean z) {
if (dVar == d.bwS) {
return z ? this.uVu : this.uVt;
} else {
return null;
}
}
public c(Context context, b bVar) {
super(context, bVar);
}
protected final boolean GU(int i) {
boolean GU = super.GU(i);
switch (1.qVw[GT(i).ordinal()]) {
case 1:
return false;
default:
return GU;
}
}
}
|
package com.bfchengnuo.security.core.properties;
import lombok.Data;
/**
* @author 冰封承諾Andy
* @date 2019-11-17
*/
@Data
public class OAuth2Properties {
/**
* JWT 的签名,密签与验签的时候用,配置文件配置,这里是默认值
*/
private String jwtSigningKey = "lxl";
private OAuth2ClientProperties[] clients = {};
}
|
package com.yto.tech.mail;
public class Contant {
public static final String CAT_SERVER_KEY = "catip";
public static final String CAT_ENV = "catenv";
public static final String CAT_SERVER_KEY_PROVIOUS = "cat-web-server";
public static String alertContentAddCatEnv(String content){
String serverIp = System.getProperty(Contant.CAT_SERVER_KEY);
if(serverIp != null && !"".equals(serverIp.trim()) && !"null".equals(serverIp.trim())) {
content = content.replaceFirst(Contant.CAT_SERVER_KEY_PROVIOUS, serverIp);
}else{
serverIp ="";
}
String catEnv = System.getProperty(Contant.CAT_ENV);
if(catEnv == null){
catEnv = "";
}
content = content + "<br>" +catEnv +"["+serverIp+"]";
return content;
}
public static void main(String[] args) {
// System.setProperty("catenv","DEV");
// System.setProperty("catip","192.168.1.2");
System.out.println(alertContentAddCatEnv("dsa"));
}
}
|
package codesum.lm.topicsum;
import java.io.IOException;
import java.io.Serializable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import com.esotericsoftware.kryo.DefaultSerializer;
import com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer;
@DefaultSerializer(CompatibleFieldSerializer.class)
public class Sentence implements Serializable {
private static final long serialVersionUID = 1104198323000292263L;
private final Document doc; // the document that this sentence is from
private final int nsent; // the sentence this is from the original document
private final int[] tokens; // the tokens in this sentence
private final int ntokens; // the number of tokens in the sentence
private final int[] topics; // the topics that generated these tokens
private final int[] topicCount; // the number of tokens in each topic in
// this sentence
public Sentence(final String sent, final int nsent, final Document doc,
final Tokens alphabet) {
this.nsent = nsent;
this.doc = doc;
tokens = alphabet.readSent(sent);
ntokens = tokens.length;
topics = new int[ntokens];
topicCount = new int[Topic.nTopics];
}
/**
* Set topic for token
*
* @param tokenIndex
* the index of the token we are updating
* @param topic
* the new topic being assigned
*/
public void setTopic(final int tokenIndex, final int topic) {
topics[tokenIndex] = topic; // update the assigned topic for this token
topicCount[topic]++; // add one to count of the new topic
}
public void decrementTopicCount(final int topic) {
topicCount[topic]--;
}
/**
* @param topic
* @return the number of tokens assigned to the topic in this sentence
*/
public int topicCount(final int topic) {
return topicCount[topic];
}
/**
* @return the number sentence this sentence is in the original document
*/
public int nsent() {
return nsent;
}
/**
* @return the original document that this sentence is from
*/
public Document getDoc() {
return doc;
}
/**
* @param tokenIndex
* index of the token
* @return token (as an integer)
*/
public int getToken(final int tokenIndex) {
return tokens[tokenIndex];
}
/**
* @param tokenIndex
* index of the token
* @return topic of the token
*/
public int getTopic(final int tokenIndex) {
return topics[tokenIndex];
}
/**
* @return the number of tokens in the sentence
*/
public int ntokens() {
return ntokens;
}
/**
* @return the original sentence
*/
public String getOriginal() {
String sent = null;
LineIterator iterator = null;
try {
iterator = FileUtils.lineIterator(doc.getDocLoc());
} catch (final IOException e) {
e.printStackTrace();
}
for (int sentID = 0; iterator.hasNext(); sentID++) {
if (sentID == nsent) {
sent = iterator.nextLine().trim();
break;
}
iterator.nextLine();
}
LineIterator.closeQuietly(iterator);
return sent;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.tools.rumen.JobStory;
import org.apache.hadoop.tools.rumen.Pre21JobHistoryConstants;
import org.apache.hadoop.tools.rumen.TaskAttemptInfo;
import org.apache.hadoop.tools.rumen.TaskInfo;
/**
* This class is a proxy class for JobStory/ZombieJob for a customized
* submission time. Because in the simulation, submission time is totally
* re-produced by the simulator, original submission time in job trace should be
* ignored.
*/
public class SimulatorJobStory implements JobStory {
private JobStory job;
private long submissionTime;
public SimulatorJobStory(JobStory job, long time) {
this.job = job;
this.submissionTime = time;
}
@Override
public long getSubmissionTime() {
return submissionTime;
}
@Override
public InputSplit[] getInputSplits() {
return job.getInputSplits();
}
@SuppressWarnings("deprecation")
@Override
public JobConf getJobConf() {
return job.getJobConf();
}
@Override
public TaskAttemptInfo getMapTaskAttemptInfoAdjusted(int taskNumber,
int taskAttemptNumber, int locality) {
return job.getMapTaskAttemptInfoAdjusted(taskNumber, taskAttemptNumber,
locality);
}
@Override
public String getName() {
return job.getName();
}
@Override
public org.apache.hadoop.mapreduce.JobID getJobID() {
return job.getJobID();
}
@Override
public int getNumberMaps() {
return job.getNumberMaps();
}
@Override
public int getNumberReduces() {
return job.getNumberReduces();
}
@Override
public TaskAttemptInfo getTaskAttemptInfo(TaskType taskType, int taskNumber,
int taskAttemptNumber) {
return job.getTaskAttemptInfo(taskType, taskNumber, taskAttemptNumber);
}
@Override
public TaskInfo getTaskInfo(TaskType taskType, int taskNumber) {
return job.getTaskInfo(taskType, taskNumber);
}
@Override
public String getUser() {
return job.getUser();
}
@Override
public Pre21JobHistoryConstants.Values getOutcome() {
return job.getOutcome();
}
@Override
public String getQueueName() {
return job.getQueueName();
}
}
|
package com.qiang.graduation.main.dao;
import com.qiang.graduation.main.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
/**
* 根据密码查找用户
*
* @param password
* @return
*/
List<User> findByPassword(String password);
/**
* 根据手机号码查找用户
*
* @param phone
* @return
*/
User findFirstByPhone(String phone);
/**
* 根据用户名和密码进行查找
*
* @param phone
* @param password
* @return
*/
User findByPhoneAndPassword(String phone, String password);
/**
* 根据用户名来检索用户
*
* @param name
* @return
*/
List<User> findByNameLike(String name, Pageable pa);
/**
* 检索用户计数
*
* @param name
* @return
*/
long countByNameLike(String name);
/**
* 获取所有用户
*
* @param id
* @param pa
* @return
*/
List<User> findByIdAfter(int id, Pageable pa);
}
|
package com.example.demo.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="cart")
public class Cart implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "status")
private boolean status;
@Column(name = "created_date")
private Date createdDate;
@Column(name = "total_money")
private int totalMoney;
@ManyToOne
@JoinColumn(name="user_id")
private User user;
@OneToMany(mappedBy = "cart")
private List<CartDetail> cartDetails;
// @JsonIgnore
// public List<CartDetail> getCartDetails() {
// return cartDetails;
// }
//
// @JsonIgnore
// public void setCartDetails(List<CartDetail> cartDetails) {
// this.cartDetails = cartDetails;
// }
}
|
package twilight.bgfx;
public enum Fatal {
DebugCheck, MinimumRequiredSpecs, InvalidShader, UnableToInitialize, UnableToCreateTexture,
}
|
package cn.canlnac.onlinecourse.presentation.presenter;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import cn.canlnac.onlinecourse.data.exception.ResponseStatusException;
import cn.canlnac.onlinecourse.domain.interactor.DefaultSubscriber;
import cn.canlnac.onlinecourse.domain.interactor.UseCase;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.model.LearnRecordListModel;
import cn.canlnac.onlinecourse.presentation.ui.activity.RegisterActivity;
@PerActivity
public class GetOtherUserLearnRecordPresenter implements Presenter {
RegisterActivity getOtherUserLearnRecordActivity;
private final UseCase getOtherUserLearnRecordUseCase;
@Inject
public GetOtherUserLearnRecordPresenter(UseCase getOtherUserLearnRecordUseCase) {
this.getOtherUserLearnRecordUseCase = getOtherUserLearnRecordUseCase;
}
public void setView(@NonNull RegisterActivity getOtherUserLearnRecordActivity) {
this.getOtherUserLearnRecordActivity = getOtherUserLearnRecordActivity;
}
public void initialize() {
this.getOtherUserLearnRecordUseCase.execute(new GetOtherUserLearnRecordPresenter.GetOtherUserLearnRecordSubscriber());
}
@Override
public void resume() {
}
@Override
public void pause() {
}
@Override
public void destroy() {
this.getOtherUserLearnRecordUseCase.unsubscribe();
}
private final class GetOtherUserLearnRecordSubscriber extends DefaultSubscriber<LearnRecordListModel> {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (e instanceof ResponseStatusException) {
switch (((ResponseStatusException)e).code) {
case 400:
GetOtherUserLearnRecordPresenter.this.getOtherUserLearnRecordActivity.showToastMessage("参数错误!");
break;
case 404:
GetOtherUserLearnRecordPresenter.this.getOtherUserLearnRecordActivity.showToastMessage("资源不存在!");
break;
case 409:
GetOtherUserLearnRecordPresenter.this.getOtherUserLearnRecordActivity.showToastMessage("用户名已被注册!");
break;
default:
GetOtherUserLearnRecordPresenter.this.getOtherUserLearnRecordActivity.showToastMessage("服务器错误:"+((ResponseStatusException)e).code);
}
} else {
GetOtherUserLearnRecordPresenter.this.getOtherUserLearnRecordActivity.showToastMessage("网络连接错误!");
}
}
@Override
public void onNext(LearnRecordListModel learnRecordListModel) {
GetOtherUserLearnRecordPresenter.this.getOtherUserLearnRecordActivity.showToastMessage("创建成功");
}
}
}
|
package moe.vergo.seasonalseiyuuapi.adapter.in.web.dto;
public class Views {
public interface Simple { }
public interface Detailed extends Simple { }
}
|
package com.smxknife.java2.thread.designpattern._01SingleThreadedExecution;
/**
* @author smxknife
* 2019/9/24
*/
public class _Run {
// Single Threaded Execution :能通过的只有一个人
// Single Threaded Execution模式是单线程执行,是多线程的基础
// Single Threaded Execution有时也称为临界区
// 归纳
/**
* 1. SharedResource(共享资源) 被多个线程访问
* 2. 存在死锁的可能
* 2.1 存在多个共享资源
* 2.2 并且一个线程需要获取多个资源
* 2.3 获取共享资源的顺序是不固定的
*/
/** 线程安全的的集合方法java.util.Collections
* Collections.synchronizedCollection(Collection);
* Collections.synchronizedList(List);
* - 该方法需要注意的是,add等操作是不需要加synchronized,但是遍历是需要加锁的
* - synchronized(this) {
* for(Obj obj : list) {}
* }
* Collections.synchronizedMap(Map);
* Collections.synchronizedNavigableMap(NavigableMap);
* Collections.synchronizedSet(Set);
* Collections.synchronizedSortedMap(SortedMap);
* Collections.synchronizedSortedSet(SortedSet);
*/
/** 相关的设计模式
* Guarded Suspension模式:在检查对象状态部分使用了Single Threaded Execution模式
* Read-Write Lock模式:多个线程可以同时执行read方法,write方法就需要等待;检查线程种类和个数也使用了Single Threaded Execution
* Immutable模式:
* Thread-Specific Storage模式:确保每个线程都有其固有的区域,且这块区域仅有一个线程访问,所以无需保护方法
* Before/After模式:try {} finally {}就是典型的before/after模式,try总是在前执行,无论是否正常,finally总是在try之后执行
* 信号量Semaphore
*/
public static void main(String[] args) {
}
}
|
package com.jim.multipos.ui.mainpospage.model;
import android.os.Parcel;
import com.jim.mpviews.suggestions.model.SearchSuggestion;
import com.jim.multipos.data.db.model.customer.Customer;
/**
* Created by Sirojiddin on 05.01.2018.
*/
public class CustomerSuggestion implements SearchSuggestion {
private Customer customer;
@Override
public String getBody() {
return customer.getName();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
}
public static final Creator<CustomerSuggestion> CREATOR = new Creator<CustomerSuggestion>() {
@Override
public CustomerSuggestion createFromParcel(Parcel parcel) {
return new CustomerSuggestion();
}
@Override
public CustomerSuggestion[] newArray(int i) {
return new CustomerSuggestion[i];
}
};
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Customer getCustomer() {
return customer;
}
}
|
import java.util.Scanner;
public class Monkey_Main
{
public static void main(String[] args) {
Monkey smiling = new Monkey();
boolean monk = smiling.monkeyTrouble(false, false);
System.out.println("my result is:" + monk);
}
}
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
public class MainMenu extends JFrame
{
static ImageIcon backgroundImage = new ImageIcon("res/background.jpg");
public MainMenu()
{
this.setTitle("Menu");
this.setPreferredSize(new Dimension(720, 720));
this.setBackground(Color.WHITE);
this.pack();
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
ZusatzButtons();
init();
}
private void init()
{
this.pack();
this.setLocation(200,25);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void ZusatzButtons()
{
ImagePanel panel=new ImagePanel(backgroundImage.getImage());
JButton play = new JButton(new AbstractAction("Play"){
@Override
public void actionPerformed(ActionEvent e)
{
Game.status="setzen";
Game.zeichneSpielbrett();
}
});
JButton options = new JButton(new AbstractAction("Optionen"){
@Override
public void actionPerformed(ActionEvent e)
{
Game.menu.setVisible(false);
Game.optionen.setVisible(true);
}
});
JButton quit = new JButton(new AbstractAction("Quit"){
@Override
public void actionPerformed(ActionEvent e)
{
Game.menu.dispose();
Game.optionen.dispose();
System.exit(0);
}
});
panel.setLayout(new GridLayout(3,1,25,25));
panel.add(play);
panel.add(options);
panel.add(quit);
this.add(panel,BorderLayout.CENTER);
}
}
|
package com.espendwise.manta.web.controllers;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import com.espendwise.manta.model.view.DistributorConfigurationView;
import com.espendwise.manta.service.DistributorService;
import com.espendwise.manta.spi.SuccessMessage;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.Pair;
import com.espendwise.manta.util.PropertyUtil;
import com.espendwise.manta.util.RefCodeNames;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.alert.ArgumentedMessage;
import com.espendwise.manta.util.arguments.MessageI18nArgument;
import com.espendwise.manta.util.validation.ValidationException;
import com.espendwise.manta.web.forms.DistributorConfigurationForm;
import com.espendwise.manta.web.resolver.DistributorConfigurationWebUpdateExceptionResolver;
import com.espendwise.manta.web.util.SessionKey;
import com.espendwise.manta.web.util.WebAction;
import com.espendwise.manta.web.util.WebErrors;
import com.espendwise.manta.web.util.WebFormUtil;
@Controller
@RequestMapping(UrlPathKey.DISTRIBUTOR.CONFIGURATION)
public class DistributorConfigurationController extends BaseController {
private static final Logger logger = Logger.getLogger(DistributorConfigurationController.class);
private DistributorService distributorService;
@Autowired
public DistributorConfigurationController(DistributorService distributorService) {
this.distributorService = distributorService;
}
public String handleValidationException(ValidationException ex, WebRequest request) {
WebErrors webErrors = new WebErrors(request);
webErrors.putErrors(ex, new DistributorConfigurationWebUpdateExceptionResolver());
return "distributor/configuration";
}
@RequestMapping(value = {""}, method = RequestMethod.GET)
public String show(HttpServletRequest request, @ModelAttribute(SessionKey.DISTRIBUTOR_CONFIGURATION) DistributorConfigurationForm form, @PathVariable("distributorId") Long distributorId, Model model) {
logger.info("show()=> BEGIN");
DistributorConfigurationView configuration = distributorService.findDistributorConfigurationInformation(distributorId);
if (configuration != null) {
form.setDistributorId(configuration.getDistributorId());
if(Utility.isSet(configuration.getPerformSalesTaxCheck())){
form.setPerformSalesTaxCheck(PropertyUtil.toValueNN(configuration.getPerformSalesTaxCheck()));
}
if(Utility.isSet(configuration.getExceptionOnOverchargedFreight())){
form.setExceptionOnOverchargedFreight(PropertyUtil.toValueNN(configuration.getExceptionOnOverchargedFreight()));
}
if(Utility.isSet(configuration.getInvoiceLoadingPricingModel())){
form.setInvoiceLoadingPricingModel(PropertyUtil.toValueNN(configuration.getInvoiceLoadingPricingModel()));
}
if(Utility.isSet(configuration.getAllowFreightOnBackOrders())){
form.setAllowFreightOnBackOrders(PropertyUtil.toValueNN(configuration.getAllowFreightOnBackOrders()));
}
if(Utility.isSet(configuration.getCancelBackorderedLines())){
form.setCancelBackorderedLines(PropertyUtil.toValueNN(configuration.getCancelBackorderedLines()));
}
if(Utility.isSet(configuration.getDisallowInvoiceEdits())){
form.setDisallowInvoiceEdits(PropertyUtil.toValueNN(configuration.getDisallowInvoiceEdits()));
}
if(Utility.isSet(configuration.getReceivingSystemTypeCode())){
form.setReceivingSystemTypeCode(PropertyUtil.toValueNN(configuration.getReceivingSystemTypeCode()));
}
if(Utility.isSet(configuration.getRejectedInvoiceEmailNotification())){
form.setRejectedInvoiceEmailNotification(Utility.strNN(configuration.getRejectedInvoiceEmailNotification().getEmailAddress()));
}
if(Utility.isSet(configuration.getIgnoreOrderMinimumForFreight())){
form.setIgnoreOrderMinimumForFreight(PropertyUtil.toValueNN(configuration.getIgnoreOrderMinimumForFreight()));
}
if(Utility.isSet(configuration.getInvoiceAmountPercentUndercharge())){
form.setInvoiceAmountPercentUndercharge(PropertyUtil.toValueNN(configuration.getInvoiceAmountPercentUndercharge()));
}
if(Utility.isSet(configuration.getInvoiceAmountPercentOvercharge())){
form.setInvoiceAmountPercentOvercharge(PropertyUtil.toValueNN(configuration.getInvoiceAmountPercentOvercharge()));
}
if(Utility.isSet(configuration.getInvoiceMaximumFreightAllowance())){
form.setInvoiceMaximumFreightAllowance(PropertyUtil.toValueNN(configuration.getInvoiceMaximumFreightAllowance()));
}
if(Utility.isSet(configuration.getInboundInvoiceHoldDays())){
form.setInboundInvoiceHoldDays(PropertyUtil.toValueNN(configuration.getInboundInvoiceHoldDays()));
}
if(Utility.isSet(configuration.getPrintCustomerContactInfoOnPurchaseOrder())){
form.setPrintCustomerContactInfoOnPurchaseOrder(PropertyUtil.toValueNN(configuration.getPrintCustomerContactInfoOnPurchaseOrder()));
}
if(Utility.isSet(configuration.getRequireManualPurchaseOrderAcknowledgement())){
form.setRequireManualPurchaseOrderAcknowledgement(PropertyUtil.toValueNN(configuration.getRequireManualPurchaseOrderAcknowledgement()));
}
if(Utility.isSet(configuration.getPurchaseOrderComments())){
form.setPurchaseOrderComments(PropertyUtil.toValueNN(configuration.getPurchaseOrderComments()));
}
}
populateFormReferenceData(form);
model.addAttribute(SessionKey.DISTRIBUTOR_CONFIGURATION, form);
logger.info("show()=> END.");
return "distributor/configuration";
}
@ModelAttribute(SessionKey.DISTRIBUTOR_CONFIGURATION)
public DistributorConfigurationForm initModel(@PathVariable("distributorId") Long distributorId) {
DistributorConfigurationForm form = new DistributorConfigurationForm(distributorId);
if (!form.isInitialized()) {
form.initialize();
}
return form;
}
@SuccessMessage
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(WebRequest request, @ModelAttribute(SessionKey.DISTRIBUTOR_CONFIGURATION) DistributorConfigurationForm distributorConfigurationForm,
@PathVariable("distributorId") Long distributorId, Model model) throws Exception {
logger.info("save()=> BEGIN, DistributorConfigurationForm: " + distributorConfigurationForm);
WebErrors webErrors = new WebErrors(request);
List<? extends ArgumentedMessage> validationErrors = WebAction.validate(distributorConfigurationForm);
if (!validationErrors.isEmpty()) {
webErrors.putErrors(validationErrors);
}
//validate values for fields that are restricted to an acceptable set (i.e. only true or false is allowed)
String performSalesTaxCheck = distributorConfigurationForm.getPerformSalesTaxCheck();
if (Utility.isSet(performSalesTaxCheck)) {
if (!Constants.TRUE.equalsIgnoreCase(performSalesTaxCheck) &&
!Constants.FALSE.equalsIgnoreCase(performSalesTaxCheck) &&
!Constants.TRUE_FOR_RESALE.equalsIgnoreCase(performSalesTaxCheck)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.performSalesTaxCheck"));
}
}
String exceptionOnOverchargedFreight = distributorConfigurationForm.getExceptionOnOverchargedFreight();
if (Utility.isSet(exceptionOnOverchargedFreight)) {
if (!Constants.TRUE.equalsIgnoreCase(exceptionOnOverchargedFreight) &&
!Constants.FALSE.equalsIgnoreCase(exceptionOnOverchargedFreight)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.exceptionOnOverchargedFreight"));
}
}
String invoiceLoadingPricingModel = distributorConfigurationForm.getInvoiceLoadingPricingModel();
if (Utility.isSet(invoiceLoadingPricingModel)) {
if (!RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.DISTRIBUTOR_INVOICE.equalsIgnoreCase(invoiceLoadingPricingModel) &&
!RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.EXCEPTION.equalsIgnoreCase(invoiceLoadingPricingModel) &&
!RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.HOLD_ALL.equalsIgnoreCase(invoiceLoadingPricingModel) &&
!RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.LOWEST.equalsIgnoreCase(invoiceLoadingPricingModel) &&
!RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.PREDETERMINED.equalsIgnoreCase(invoiceLoadingPricingModel)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.invoiceLoadingPricingModel"));
}
}
String allowFreightOnBackOrders = distributorConfigurationForm.getAllowFreightOnBackOrders();
if (Utility.isSet(allowFreightOnBackOrders)) {
if (!Constants.TRUE.equalsIgnoreCase(allowFreightOnBackOrders) &&
!Constants.FALSE.equalsIgnoreCase(allowFreightOnBackOrders)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.allowFreightOnBackorders"));
}
}
String cancelBackorderedLines = distributorConfigurationForm.getCancelBackorderedLines();
if (Utility.isSet(cancelBackorderedLines)) {
if (!Constants.TRUE.equalsIgnoreCase(cancelBackorderedLines) &&
!Constants.FALSE.equalsIgnoreCase(cancelBackorderedLines)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.cancelBackorderedLines"));
}
}
String disallowInvoiceEdits = distributorConfigurationForm.getDisallowInvoiceEdits();
if (Utility.isSet(disallowInvoiceEdits)) {
if (!Constants.TRUE.equalsIgnoreCase(disallowInvoiceEdits) &&
!Constants.FALSE.equalsIgnoreCase(disallowInvoiceEdits)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.disallowInvoiceEdits"));
}
}
String receivingSystemTypeCode = distributorConfigurationForm.getReceivingSystemTypeCode();
if (Utility.isSet(receivingSystemTypeCode)) {
if (!RefCodeNames.RECEIVING_SYSTEM_INVOICE_CD.DISABLED.equalsIgnoreCase(receivingSystemTypeCode) &&
!RefCodeNames.RECEIVING_SYSTEM_INVOICE_CD.ENTER_ERRORS_ONLY_FIRST_ONLY.equalsIgnoreCase(receivingSystemTypeCode) &&
!RefCodeNames.RECEIVING_SYSTEM_INVOICE_CD.REQUIRE_ENTRY_FIRST_ONLY.equalsIgnoreCase(receivingSystemTypeCode)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.receivingSystemTypeCode"));
}
}
String ignoreOrderMinimumForFreight = distributorConfigurationForm.getIgnoreOrderMinimumForFreight();
if (Utility.isSet(ignoreOrderMinimumForFreight)) {
if (!Constants.TRUE.equalsIgnoreCase(ignoreOrderMinimumForFreight) &&
!Constants.FALSE.equalsIgnoreCase(ignoreOrderMinimumForFreight)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.ignoreOrderMinimumForFreight"));
}
}
String printCustomerContactInfoOnPurchaseOrder = distributorConfigurationForm.getPrintCustomerContactInfoOnPurchaseOrder();
if (Utility.isSet(printCustomerContactInfoOnPurchaseOrder)) {
if (!Constants.TRUE.equalsIgnoreCase(printCustomerContactInfoOnPurchaseOrder) &&
!Constants.FALSE.equalsIgnoreCase(printCustomerContactInfoOnPurchaseOrder)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.printCustomerContactInfo"));
}
}
String requireManualPurchaseOrderAcknowledgement = distributorConfigurationForm.getRequireManualPurchaseOrderAcknowledgement();
if (Utility.isSet(requireManualPurchaseOrderAcknowledgement)) {
if (!Constants.TRUE.equalsIgnoreCase(requireManualPurchaseOrderAcknowledgement) &&
!Constants.FALSE.equalsIgnoreCase(requireManualPurchaseOrderAcknowledgement)) {
webErrors.putError("validation.web.error.invalidValue", new MessageI18nArgument("admin.distributor.label.configuration.manualPurchaseOrderAcknowledgementRequired"));
}
}
//if validation errors occurred then return the user to the input page so they can correct the problem(s)
if (!webErrors.isEmpty()) {
populateFormReferenceData(distributorConfigurationForm);
model.addAttribute(SessionKey.DISTRIBUTOR_CONFIGURATION, distributorConfigurationForm);
return "distributor/configuration";
}
DistributorConfigurationView configuration = new DistributorConfigurationView();
if (!distributorConfigurationForm.getIsNew()) {
configuration = distributorService.findDistributorConfigurationInformation(distributorId);
}
configuration = WebFormUtil.createDistributorConfigurationView(configuration, distributorConfigurationForm);
try {
configuration = distributorService.saveDistributorConfigurationInformation(distributorId, configuration);
} catch (ValidationException e) {
return handleValidationException(e, request);
}
logger.info("save()=> END, redirect to " + configuration.getDistributorId());
return redirect("../configuration");
}
private void populateFormReferenceData(DistributorConfigurationForm form) {
//populate the form with reference information (invoice loading pricing model choices,
//receiving system type code choices)
List<Pair<String, String>> invoiceLoadingPricingModels = new ArrayList<Pair<String, String>>();
invoiceLoadingPricingModels.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.invoiceLoadingPricingModel.option.exceptionOnCostDifference").resolve(), RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.EXCEPTION));
invoiceLoadingPricingModels.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.invoiceLoadingPricingModel.option.holdAllInvoicesForReview").resolve(), RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.HOLD_ALL));
invoiceLoadingPricingModels.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.invoiceLoadingPricingModel.option.useDistributorInvoiceCost").resolve(), RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.DISTRIBUTOR_INVOICE));
invoiceLoadingPricingModels.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.invoiceLoadingPricingModel.option.useLowestCost").resolve(), RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.LOWEST));
invoiceLoadingPricingModels.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.invoiceLoadingPricingModel.option.useOurCost").resolve(), RefCodeNames.INVOICE_LOADING_PRICE_MODEL_CD.PREDETERMINED));
form.setInvoiceLoadingPricingModelChoices(invoiceLoadingPricingModels);
List<Pair<String, String>> receivingSystemTypeCodes = new ArrayList<Pair<String, String>>();
receivingSystemTypeCodes.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.receivingSystemTypeCode.option.disabled").resolve(), RefCodeNames.RECEIVING_SYSTEM_INVOICE_CD.DISABLED));
receivingSystemTypeCodes.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.receivingSystemTypeCode.option.enterErrorsOnlyFirstOnly").resolve(), RefCodeNames.RECEIVING_SYSTEM_INVOICE_CD.ENTER_ERRORS_ONLY_FIRST_ONLY));
receivingSystemTypeCodes.add(new Pair<String, String>(new MessageI18nArgument("admin.distributor.configuration.receivingSystemTypeCode.option.requireEntryFirstOnly").resolve(), RefCodeNames.RECEIVING_SYSTEM_INVOICE_CD.REQUIRE_ENTRY_FIRST_ONLY));
form.setReceivingSystemTypeCodeChoices(receivingSystemTypeCodes);
}
}
|
package cn.com.ykse.santa.service;
import cn.com.ykse.santa.service.vo.LoginVO;
import cn.com.ykse.santa.service.vo.SignUpVO;
import java.util.Map;
/**
* Created by youyi on 2016/1/10.
*/
public interface SecurityService {
public Map<String, Object> login(LoginVO loginModel);
public Map<String, Object> signUp(SignUpVO signUpModel);
}
|
/*
* 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 users;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.servlet.http.Part;
/**
*
* @author Mert
*/
@ManagedBean(name = "photos")
@ApplicationScoped
public class photoBean {
Part photo;
@ManagedProperty(value = "#{user}")
User user;
public Part getPhoto() {
return photo;
}
public void setPhoto(Part photo) {
this.photo = photo;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
|
package engines;
import org.junit.Test;
public class TestLogger {
@Test
public void testLogger() {
Logger.setActivate(true);
Logger.printLine("lol");
}
}
|
package edu.kis.powp.jobs2d.events;
import edu.kis.powp.command.ComplexCommandFactory;
import edu.kis.powp.jobs2d.drivers.DriverManager;
import edu.kis.powp.jobs2d.magicpresets.FiguresJoe;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SelectTestCommandOptionListener implements ActionListener {
private DriverManager driverManager;
private ComplexCommandFactory complexCommandFactory = new ComplexCommandFactory();
int option;
public SelectTestCommandOptionListener(DriverManager driverManager, int i) {
this.driverManager = driverManager;
option=i;
}
@Override
public void actionPerformed(ActionEvent e) {
if (option==1)
complexCommandFactory.draw1(driverManager.getCurrentDriver()).execute();
else if(option==2)
complexCommandFactory.draw2(driverManager.getCurrentDriver()).execute();
}
}
|
package controler;
import javax.persistence.*;
public class Connexion {
private static EntityManagerFactory emf;
public static void init()
{
emf = Persistence.createEntityManagerFactory("initialisation");
}
public static void modification()
{
emf = Persistence.createEntityManagerFactory("modification");
}
static public EntityManager ouvrirconnexion() {
EntityManager em = emf.createEntityManager();
return em;
}
static public void fermerconnexion(EntityManager em) {
em.close();
}
}
|
package cn.edu.zucc.web.controller;
import cn.edu.zucc.web.model.ViewRun;
import cn.edu.zucc.web.security.RoleSign;
import cn.edu.zucc.web.service.LoadRunDataService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by zxy on 11/19/2016.
*/
@Controller("loadRunDataController")
public class LoadRunDataController {
private static final Log logger = LogFactory.getLog(LoadRunDataController.class);
@Resource
private LoadRunDataService loadRunDataService;
@RequestMapping(value = "/admin/main", method = RequestMethod.GET)
@RequiresRoles(value = RoleSign.ADMIN)
public ModelAndView loadDataForAdmin(Model model, @RequestParam("page") int page) {
logger.info("Receive load data request, page = " + page);
if (page <= 0) {
return new ModelAndView("admin/main?page=1");
}
int size = 50;
List<ViewRun> dataList = loadRunDataService.getRunDataByPageSize((page - 1) * size, size);
model.addAttribute("viewRunList", dataList);
return new ModelAndView("admin/main");
}
@RequestMapping(value = "/admin/getRunPage", method = RequestMethod.GET)
@RequiresRoles(value = RoleSign.ADMIN)
public
@ResponseBody
String getRunPage() {
Integer page = loadRunDataService.getPage();
if (page == null) {
page = 1;
}
if (page <= 50) {
page = 1;
} else {
page /= 50;
}
return "{\"page\":" + page + "}";
}
@RequestMapping(value = "/user/loadRunData", method = RequestMethod.GET)
@RequiresRoles(value = RoleSign.USER)
@ResponseBody
public String loadDataForUser(@RequestParam("no") String no) {
logger.info("Receive load data request, student no = " + no);
if (null == no || "".equals(no)) {
return "{\"data\":\"\"}";
}
return loadRunDataService.getRunDataByUserNo(no);
}
}
|
package pl.edu.amu.datasupplier.service;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.edu.amu.datasupplier.model.Status;
import pl.edu.amu.datasupplier.model.User;
import pl.edu.amu.datasupplier.model.Vacancy;
import pl.edu.amu.datasupplier.model.Worker;
import pl.edu.amu.datasupplier.repository.UserRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Slf4j
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User add(User user) {
log.info("save user to database: {}", user);
return userRepository.insert(user);
}
public User update(User user) {
log.info("update user in database: {}", user);
return userRepository.save(user);
}
public User findUserById(ObjectId id) {
log.info("Get user by id: {}", id);
return userRepository.findById(id);
}
public List<User> findOffDutyUsers(Optional<String> env, Optional<List<String>> roles) {
log.info("Get users by environment: {} and role: {}", env, roles);
if (roles.isPresent() && env.isPresent()) {
return userRepository.findByRolesInAndStatusAndEnvironment(roles.get(), Status.OFF_DUTY, env.get());
}
if (roles.isPresent()) {
return userRepository.findByRolesInAndStatus(roles.get(), Status.OFF_DUTY);
}
if (env.isPresent()) {
return userRepository.findByEnvironment(env.get());
}
return getAll();
}
public Set<String> getRoles() {
log.info("Get set of users roles.");
return userRepository.findAll()
.stream()
.map(User::getRoles)
.flatMap(roles -> roles.stream())
.distinct()
.collect(Collectors.toSet());
}
public List<User> getAll() {
log.info("Get all users");
return userRepository.findAll();
}
@Transactional
public void delete(User user) {
log.info("Remove user: {}", user);
userRepository.delete(user);
}
public List<Worker> findUsersByVacancy(String env, Set<Set<Vacancy>> vacancySet) {
log.info("Find users by vacancy on environment: {}", env);
List<Worker> workers = new ArrayList<>();
for (Set<Vacancy> vacancies : vacancySet) {
List<User> users = new ArrayList<>();
vacancies.forEach(vacancy -> {
users.addAll(userRepository.findByRolesInAndStatusAndEnvironment(vacancy.getRoles(), Status.OFF_DUTY, env));
});
workers.add(new Worker(vacancies, users));
}
return workers;
}
}
|
///////////////////////////////////////////////////////////////////////////////
//
// Main Class File: Receiver.java
// File: PacketLinkedList.java
// Semester: CS367 Data Structures Spring 2016
//
// Author: David Liang dliang23@wisc.edu
// CS Login: dliang
// Lecturer's Name: Skrentny
//
//////////////////////////////////////////////////////////////////////////////
/**
* A Single-linked linkedlist with a "dumb" header node (no data in the node),
* but without a tail node. It implements ListADT<E> and returns
* PacketLinkedListIterator when requiring a iterator.
*/
public class PacketLinkedList<E> implements ListADT<E>
{
// reference to head and number of items
Listnode<E> head;
int numItems;
/**
* Constructs a empty PacketLinkedList
*/
public PacketLinkedList()
{
// initialize fields
head = new Listnode<E>(null);
numItems = 0;
}
@Override
/**
* Add an item to end of PacketLinkedList.
*/
public void add(E item)
{
if (item == null)
throw new IllegalArgumentException();
Listnode<E> curr = head;
// traverse to end
while (curr.getNext() != null)
curr = curr.getNext();
curr.setNext(new Listnode<E>(item));
numItems++;
}
@Override
/**
* Add item at specific spot in a PacketLinkedList.
*/
public void add(int pos, E item)
{
if (pos > numItems || pos < 0)
throw new IndexOutOfBoundsException();
if (item == null)
throw new IllegalArgumentException();
Listnode<E> curr = head;
// traverse to pos
for (int i = 0; i < pos; i++)
curr = curr.getNext();
// create new node, insert it into PacketLinkedList, increment numItems
Listnode<E> newNode = new Listnode<E>(item);
newNode.setNext(curr.getNext());
curr.setNext(newNode);
numItems++;
}
@Override
/**
* Determines if the PacketLinkedList contains a node with matching data
*/
public boolean contains(E item)
{
// try to find item
Listnode<E> curr = head.getNext();
while (curr.getNext() != null)
{
if (curr.getData().equals(item)) return true;
curr = curr.getNext();
}
return false;
}
@Override
/**
* Gets the data from a node at a specific position.
*
* @return The data of the current node.
*/
public E get(int pos)
{
try
{
if (pos >= numItems || pos < 0) throw new IndexOutOfBoundsException();
Listnode<E> curr = head.getNext();
for (int i = 0; i < pos; i++)
if (curr.getNext() != null) curr = curr.getNext();
return curr.getData();
}
catch (Exception e)
{
System.out.println("\n***" + pos + ", " + numItems + "***");
throw e;
}
}
@Override
/**
* Determines if the given PacketLinkedList is empty.
*
* @return True if empty PacketLinnkedList.
*/
public boolean isEmpty()
{
return numItems == 0;
}
@Override
/**
* Removes the node at a particular position in the PacketLinkedList.
*
* @return The data of the removed node.
*/
public E remove(int pos)
{
if (pos >= numItems || pos < 0)
throw new IndexOutOfBoundsException();
Listnode<E> curr = head;
// traverse to pos
for (int i = 0; i < pos; i++)
curr = curr.getNext();
// remove node properly and decrement numItems
Listnode<E> returnNode = curr.getNext();
curr.setNext(curr.getNext().getNext());
numItems--;
return returnNode.getData();
}
@Override
/**
* Returns the number of nodes in the PacketLinkedList.
*
* @return The number of items in the PacketLinkedList.
*/
public int size()
{
return numItems;
}
@Override
/**
* Returns an iterator for the PacketLinkedList.
*
* @return Iterator over the PacketLinkedList
*/
public PacketLinkedListIterator<E> iterator()
{
return new PacketLinkedListIterator<E>(head);
}
}
|
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import java.util.ArrayList;
/*
* Show how to use an AbstractTableModel as part of your
* own application's model. There are a number of possibilities:
* -- Make the application's model extend AbstractTableModel
* -- Provide an inner class to JTable (the one shown here)
* -- Implement the TableModel interface yourself (but why, given
* AbstractTableModel?)
*/
public class CustomTableModel {
private ArrayList<Person> persons = new ArrayList<Person>();
private boolean DEBUG = true;
public CustomTableModel() {
// Initialize data
this.persons.add(new Person("Kathy", "Smith", "Snowboarding", 5, false));
this.persons.add(new Person("John", "Doe","Rowing", 3, true));
this.persons.add(new Person("Sue", "Black", "Knitting", 2, false));
this.persons.add(new Person("Jane", "White", "Speed reading", 20, true));
this.persons.add(new Person("Joe", "Brown", "Pool", 10, false));
this.persons.add(new Person("Kathy", "Smith", "Snowboarding", 5, false));
this.persons.add(new Person("John", "Doe", "Rowing", 3, true));
this.persons.add(new Person("Sue", "Black", "Knitting", 2, false));
this.persons.add(new Person("Jane", "White", "Speed reading", 20, true));
this.persons.add(new Person("Joe", "Brown", "Pool", 10, false));
}
/*
* This doesn't do anything; just illustrates that CustomTableModel interface now
* conforms much more closely to a pure MVC model, unpolluted by the
* AbstractTableModel stuff that's just there for one widget.
*/
public void addPerson(Person p) {
this.persons.add(p);
atmInstance.fireTableRowsInserted(this.persons.size(), this.persons.size());
}
/*
* Make an instance of an abstract table model to use with JTables.
*/
private AbstractTableModel atmInstance = new AbstractTableModel(){
// our data, note we can call these whatever we want
private String[] myDataColumnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
// need to define these three methods:
public int getColumnCount() {
return 5;
}
public int getRowCount() {
return persons.size();
}
public Object getValueAt(int row, int col) {
switch(col) {
case 0: return persons.get(row).firstName;
case 1: return persons.get(row).lastName;
case 2: return persons.get(row).sport;
case 3: return persons.get(row).years;
case 4: return persons.get(row).vegitarian;
}
return null; // for the compiler :(
}
// define this if you don't want default 'A', 'B', ... names
public String getColumnName(int col) {
return myDataColumnNames[col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass(); // reflection!
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell appendress is constant,
//no matter where the cell appears onscreen.
//(because it's the appendress in the MODEL, not the VIEW)
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
switch(col) {
// columns 0, 1 aren't editable
case 2: persons.get(row).sport = (String)value; break;
case 3: persons.get(row).years = (Integer)value; break;
case 4: persons.get(row).vegitarian = ((Boolean)value).booleanValue(); break;
}
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
};
public TableModel getTableModel() {
return atmInstance;
}
private void printDebugData() {
for(Person p : this.persons) {
System.out.println(p);
}
System.out.println("--------------------------");
}
}
class Person {
String firstName;
String lastName;
String sport;
int years;
boolean vegitarian;
public Person(String firstName, String lastName, String sport,
int years, boolean vegitarian) {
this.firstName = firstName;
this.lastName = lastName;
this.sport = sport;
this.years = years;
this.vegitarian = vegitarian;
}
public String toString() {
return "[" + this.firstName + ", " + this.lastName + ", " +
this.sport + ", " + this.years + ", " + this.vegitarian + "]";
}
}
|
package lpapps.ers.objects;
/**
*
* @author Laurence Parker
*
*/
public class Employee extends Person {
protected Date dateStarted;
protected float salary;
protected int id;
/**
* null constructor
*/
public Employee() {
super();
dateStarted = new Date();
id = 0;
salary= 0;
}
/**
* Defined constructor
* @param nme name
* @param sex gender
* @param dob date of birth
* @param number id number
* @param start start date
*/
public Employee(String nme,char sex,Date dob, int number, Date start) {
super(nme,sex,dob);
salary = 0;
id = number;
dateStarted = new Date(start);
}
/**
* Clone constructor
* @param other
*/
public Employee (Employee other) {
super(other.name, other.gender.trim().charAt(0), other.birthDate);
id = other.id;
dateStarted = new Date(other.dateStarted);
}
/**
* @param dateStarted the dateStarted to set
*/
public void setDateStarted(Date dateStarted) {
this.dateStarted = dateStarted;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @param sal the salary to set
*/
public void setSalary(float sal)
{
salary = sal;
}
public void copy(Employee other)
{
super.copyPerson(other);
dateStarted = new Date(other.dateStarted);
salary = other.salary;
id = other.id;
}
/**
* @return the dateStarted
*/
public Date getDateStarted() {
return dateStarted;
}
/**
* @return the salary
*/
public float getSalary() {
return salary;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* Override, Check if two employees are the same
* @param other employee in comparison
* @return boolean true if they are the same
*/
public boolean equalsEmployee (Employee other)
{
return super.equals(other) && id == other.id && salary == other.salary &&
dateStarted.equals(other.dateStarted);
}
public String toString()
{
return super.toString() + "Employee Number:"+ id + " salary:" + salary + " Started:" + dateStarted.toString();
}
}
|
package rjm.romek.awscourse.verifier.iam;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rjm.romek.awscourse.model.UserTask;
import rjm.romek.awscourse.service.AwsAssumedService;
import rjm.romek.awscourse.service.StsService;
@Service
public class CreateVolumeUpToSizeAllowedVerifier extends CreateVolumeVerifier {
@Autowired
public CreateVolumeUpToSizeAllowedVerifier(StsService stsService, AwsAssumedService awsAssumedService) {
super(stsService, awsAssumedService);
}
@Override
public Boolean isCompleted(UserTask userTask) {
Map<String, String> parameters = userTask.getTask().getParametersFromDescription();
Integer allowedSize = Integer.valueOf(parameters.getOrDefault("maxSize", "100"));
Integer disallowedSize = allowedSize + 1;
return checkCreateVolume(userTask, allowedSize) &&
!checkCreateVolume(userTask, disallowedSize);
}
}
|
package com.cos.services.interfaces;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import com.cos.entities.Discount;
public interface DiscountServiceInterface {
Discount createDiscount(String discountCode, String startDate, String endDate,
int amount) throws ParseException;
void deleteDiscount(int discountId);
Discount getDiscountById(int discountId);
List<Discount> getALLDiscount();
void applyDiscount(int discountId, ArrayList<Integer> listOfProductId);
}
|
package com.zhouyi.business.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @Author: first
* @Date: 上午6:23 2019/11/6
* @Description: 线程池配置
**/
@Configuration
public class TaskScheduledConfiguration {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
return new ThreadPoolTaskScheduler();
}
}
|
package il.ac.tau.cs.sw1.ex9.starfleet;
import java.util.Comparator;
public class mySpaceshipComparator implements Comparator<Spaceship> {
@Override
public int compare(Spaceship o1, Spaceship o2) {
if(o1.getFirePower() > o2.getFirePower()) { //compare fire power (descending)
return -1;
}else if(o1.getFirePower() < o2.getFirePower()) {
return 1;
}else if(o1.getCommissionYear() > o2.getCommissionYear()) { //fire power is equal, compare commission year (descending)
return -1;
}else if(o1.getCommissionYear() < o2.getCommissionYear()) {
return 1;
}
return o1.getName().compareTo(o2.getName()); //fire power and commission year are equal, compare name (lexi, ascending)
}
}
|
package org.zacharylavallee.file;
import org.junit.Test;
import org.zacharylavallee.test.FileUsageTest;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.zacharylavallee.file.FileUtils.getClasspathResource;
public class FileCompressUtilTest extends FileUsageTest {
@Test
public void testZip() throws IOException {
File zipExpected = getClasspathResource("org/zacharylavallee/batch/tasklet/zip.zip");
File zipStart = getClasspathResource("org/zacharylavallee/batch/tasklet/zip");
File zipActual = new File(getOutputDirectory(), "actual.zip");
FileCompressUtil.CompressionType.ZIP.compress(zipStart, zipActual);
assertTrue(zipActual.exists());
assertEquals(zipExpected.length(), zipActual.length());
}
@Test
public void testGZip() throws IOException {
File gZipExpected = getClasspathResource("org/zacharylavallee/batch/tasklet/gzip.gz");
File gZipStart = getClasspathResource("org/zacharylavallee/batch/tasklet/gzip");
File gZipActual = new File(getOutputDirectory(), "actual.gz");
FileCompressUtil.CompressionType.GZIP.compress(gZipStart, gZipActual);
assertTrue(gZipActual.exists());
assertEquals(gZipExpected.length(), gZipActual.length());
}
}
|
package com.facebook.react.views.art;
import com.facebook.react.module.annotations.ReactModule;
@ReactModule(name = "ARTText")
public class ARTTextViewManager extends ARTRenderableViewManager {
ARTTextViewManager() {
super("ARTText");
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\art\ARTTextViewManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.xweb.xwalk;
class g$4 implements Runnable {
final /* synthetic */ String ges;
final /* synthetic */ Object uRm;
final /* synthetic */ g vEV;
g$4(g gVar, Object obj, String str) {
this.vEV = gVar;
this.uRm = obj;
this.ges = str;
}
public final void run() {
if (this.vEV.vET != null) {
this.vEV.vET.addJavascriptInterface(this.uRm, this.ges);
}
}
}
|
package adapter.design.pattern.example1;
public class AdapterPatternTest {
public static void main(String args[]){
EuropeanCircularSocket euSocket=new EuropeanCircularSocket();
euSocket.circularSocket();
USRectangularPlug usRectangularPlug=new USRectangularPlug();
usRectangularPlug.rectangularPlug();
CircularSocket adapter=new RectangularPlugAdapter(usRectangularPlug);
adapter.circularSocket();
}
}
|
package com.example.pengawas.API;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.example.pengawas.LoginActivity;
import java.util.HashMap;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SessionManager {
private Context _context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public static final String IS_LOGIN = "isLogin";
public static final String TOKEN = "token";
public static final String NAME = "name";
public static final String NIP = "nip";
public SessionManager(Context context){
this._context=context;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = sharedPreferences.edit();
}
//Make Session
public void createLoginSession (String token, String name, String nip){
editor.putBoolean(IS_LOGIN, true);
editor.putString(TOKEN, "Bearer "+token);
editor.putString(NAME, name);
editor.putString(NIP, nip);
editor.commit();
}
//Save Key and Value (save Sesion)
public HashMap<String, String> getUserDetail(){
HashMap<String, String> user = new HashMap<>();
user.put(TOKEN, sharedPreferences.getString(TOKEN, null));
user.put(NAME, sharedPreferences.getString(NAME, null));
user.put(NIP, sharedPreferences.getString(NIP, null));
return user;
}
public void logoutSession(){
editor.clear();
editor.commit();
}
public boolean checkToken(){
return sharedPreferences.getBoolean(IS_LOGIN, false);
}
public void isLogin(){
String token = sharedPreferences.getString(TOKEN, null);
if (!token.equals("")){
ApiInterface apiInterface =ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> isLoginCall = apiInterface.isLogin(token);
isLoginCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code()!=200){
Intent intent = new Intent(_context, LoginActivity.class);
logoutSession();
_context.startActivity(intent);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("isLogin", t.getMessage());
}
});
}
}
}
|
package com.example.bgmmixer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BGMMixerTests {
@Test
void contextLoads() {
}
}
|
package com.tencent.mm.ui.transmit;
import com.tencent.mm.plugin.fts.a.a.g;
import com.tencent.mm.plugin.fts.a.a.l;
import java.util.List;
class a$a {
String bWm;
g jrx;
List<l> jsx;
int jta;
int jtc;
boolean jtf;
final /* synthetic */ a uDa;
String uDc;
private a$a(a aVar) {
this.uDa = aVar;
this.jta = Integer.MAX_VALUE;
this.jtc = Integer.MAX_VALUE;
this.jtf = true;
}
/* synthetic */ a$a(a aVar, byte b) {
this(aVar);
}
}
|
package gxc.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class User implements Serializable{
private static final long serialVersionUID = -4826871274157868169L;
private Integer uid;
private String username;
private String password;
private String realname;
private Integer gender;
private String sign; //签名
private String telephone;
private String email;
private String province;
private String city;
private String note; //简介
private String face; //头像
private Date registDate; //注册时间
private Date lastLoginDate; //最后登陆时间
private Integer loginNum; //登录次数
private Integer role;
/*
* User 和 Topic 一对多关系
* User 和 Reply 一对多关系
*/
private Set<Topic> topicSet = new HashSet<Topic>();
private Set<Reply> replySet = new HashSet<Reply>();
public Set<Topic> getTopicSet() {
return topicSet;
}
public void setTopicSet(Set<Topic> topicSet) {
this.topicSet = topicSet;
}
public Set<Reply> getReplySet() {
return replySet;
}
public void setReplySet(Set<Reply> replySet) {
this.replySet = replySet;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
public Date getRegistDate() {
return registDate;
}
public void setRegistDate(Date registDate) {
this.registDate = registDate;
}
public Integer getLoginNum() {
return loginNum;
}
public void setLoginNum(Integer loginNum) {
this.loginNum = loginNum;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
@Override
public String toString() {
return "User [uid=" + uid + ", username=" + username + ", password="
+ password + ", realname=" + realname + ", gender=" + gender
+ ", sign=" + sign + ", telephone=" + telephone + ", email="
+ email + ", province=" + province + ", city=" + city
+ ", note=" + note + ", face=" + face + ", registDate="
+ registDate + ", lastLoginDate=" + lastLoginDate
+ ", loginNum=" + loginNum + ", role=" + role + "]";
}
}
|
package lesson41.LinkedList;
/**
* List nói chung lưu trữ phần tử theo thứ tự được thêm vào
*/
import java.util.LinkedList;
public class LinkedListEx {
public static void main(String[] args) {
Student s1 = new Student("s1", "Cường");
Student s2 = new Student("s2", "Huy");
Student s3 = new Student("s3", "An");
Student s4 = new Student("s4", "Anh");
LinkedList<Student> studentLinkedList = new LinkedList<>();
studentLinkedList.add(s1);
studentLinkedList.add(s1);
studentLinkedList.addLast(s2);
studentLinkedList.add(2, s3); //vị trí thêm phải đảm bảo nhỏ hơn hoặc bằng size
studentLinkedList.addFirst(s4);
//...
studentLinkedList.remove(); //xóa phần tử đầu tiên
studentLinkedList.remove(s1); //xóa phần tử chỉ định
studentLinkedList.remove(4); //xóa phần tử tại vị trí chỉ định
studentLinkedList.removeFirstOccurrence(s1); //nếu có nhiều phần tử giống nhau, nó sẽ xóa cái đầu tiên
for (var e : studentLinkedList) {
System.out.println(e);
}
System.out.println("Người đầu: " + studentLinkedList.getFirst());
System.out.println("Người cuối: " + studentLinkedList.getLast());
System.out.println("Người ở vị trí bất kì: " + studentLinkedList.get(3));
//sử dụng Iterator
//iterator chỉ áp dụng cho duyệt từ đầu đến cuối
//muốn duyệt kiểu khác thì áp dụng với listIterator
var iter = studentLinkedList.iterator();
//các phương thức của iterator
// inter.hasNext();
// inter.remove();
// inter.next();
while (iter.hasNext()) {
System.out.println(iter.next());
}
//sử dụng listIterator để duyệt theo ý mình
//ở đây ví dụ duyệt từ cuối lên đầu
var listIter = studentLinkedList.listIterator(studentLinkedList.size());
//các phương thức của listIterator
// listIter.hasPrevious();
// listIter.add(s1);
// listIter.remove();
// listIter.hasNext();
// listIter.next();
// listIter.previousIndex();
while (listIter.hasPrevious()) {
System.out.println(listIter.hasPrevious());
}
}
}
|
package LeetCode.Trees;
public class MinimumDepthBinaryTree {
int min;
public int minDepth(TreeNode root) {
min = Integer.MAX_VALUE;
if(root == null) return 0;
helper(root, 1);
return min;
}
public void helper(TreeNode node, int curH) {
if(node == null) return;
if(node.left == null && node.right == null) {
min = Math.min(min, curH);
return;
}
if(min > curH) helper(node.left, curH+1);
if(min > curH) helper(node.right,curH+1);
}
public static void main(String[] args){
}
}
|
package com.coinhunter.utils.http;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Slf4j
public class HttpClient {
private RestTemplate rest;
private HttpHeaders headers;
private HttpStatus status;
public HttpClient() {
this.rest = new RestTemplate();
this.headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
headers.add("Accept", "*/*");
}
public HttpClient(HttpHeaders headers) {
this.rest = new RestTemplate();
this.headers = headers;
this.headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
this.headers.add("Accept", "*/*");
}
public String get(String uri) {
HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.GET, requestEntity, String.class);
this.setStatus(responseEntity.getStatusCode());
return responseEntity.getBody();
}
public String get(String uri, String params) {
HttpEntity<String> requestEntity = new HttpEntity<String>(params, headers);
ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.GET, requestEntity, String.class);
this.setStatus(responseEntity.getStatusCode());
return responseEntity.getBody();
}
public String post(String uri, Map<String, String> body) {
HttpEntity requestEntity = new HttpEntity(body, headers);
ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.POST, requestEntity, String.class);
this.setStatus(responseEntity.getStatusCode());
return responseEntity.getBody();
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
}
|
package org.nmrg.common.utils.log;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.nmrg.common.utils.verify.VerifyUtils;
import org.nmrg.entity.common.mongodb.OperateLogEntity;
/**
** Log转置
** @ClassName: StoreyLogUtil
** @Description: TODO
** @author CC
** @date 2017年11月17日 - 下午4:47:42
*/
public class StoreyLogUtil {
public OperateLogEntity saveControllerFootprint(HttpServletRequest req, JoinPoint joinPoint){
OperateLogEntity operateLog = new OperateLogEntity();
operateLog.setName("Mongodb");
StringBuffer strBuffer = req.getRequestURL();
String strUrl = new String();
if(VerifyUtils.isEmpty(strBuffer)){
strUrl = strBuffer.toString();
}
if(VerifyUtils.isEmpty(strUrl)){
operateLog.setReqURL(strUrl);
operateLog.setReqURLQuery(req.getQueryString());
}
return null;
}
}
|
package ru.myapp.storage;
import ru.myapp.models.User;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/*
* класс - сингльтон (приватный конструктор и статический метод для получения экземпляра класса)
* один объект в котором хранятся все пользователи, типа базы данных только в памяти
*/
public class Storage {
private static final Storage storage;
private List<User> users;
static{
storage = new Storage();
}
private Storage(){
/*
* хранилище
*/
users = new ArrayList<>();
User user = new User("Sunny", "qwerty7", LocalDate.parse("2015-07-14"));
User user1 = new User("Ringo", "qwerty", LocalDate.parse("2020-07-14"));
User user2 = new User("Nike", "qwerty1", LocalDate.parse("2010-07-14"));
users.add(user);
users.add(user1);
users.add(user2);
}
public static Storage getStorage(){
return storage;
}
public List<User> getUsers(){
return users;
}
}
|
package com.tencent.mm.plugin.exdevice.ui;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
import com.tencent.mm.R;
import com.tencent.mm.ab.l;
import com.tencent.mm.g.a.ll;
import com.tencent.mm.g.a.qt;
import com.tencent.mm.model.au;
import com.tencent.mm.model.q;
import com.tencent.mm.model.r;
import com.tencent.mm.plugin.exdevice.a.b;
import com.tencent.mm.plugin.exdevice.f.a.g;
import com.tencent.mm.plugin.exdevice.f.a.h;
import com.tencent.mm.plugin.exdevice.f.a.i;
import com.tencent.mm.plugin.exdevice.f.a.k;
import com.tencent.mm.plugin.exdevice.f.b.a.a;
import com.tencent.mm.plugin.exdevice.f.b.a.c;
import com.tencent.mm.plugin.exdevice.f.b.e;
import com.tencent.mm.plugin.exdevice.model.ac;
import com.tencent.mm.plugin.exdevice.model.ad;
import com.tencent.mm.plugin.sport.ui.SportChartView;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.protocal.c.bre;
import com.tencent.mm.protocal.c.cig;
import com.tencent.mm.protocal.c.kc;
import com.tencent.mm.protocal.c.xj;
import com.tencent.mm.sdk.platformtools.BackwardSupportUtil;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.MMPullDownView;
import com.tencent.mm.ui.base.n.d;
import com.tencent.mm.ui.base.p;
import com.tencent.mm.ui.contact.s;
import com.tencent.mm.ui.widget.MMSwitchBtn;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import junit.framework.Assert;
public class ExdeviceProfileUI extends MMActivity implements e, c {
private static int iEp = 0;
private boolean En = false;
private TextPaint dG = new TextPaint(1);
private int duy = 0;
private String gaG;
private String gtX;
private p iBL = null;
private List<kc> iDB;
private String iDS;
private a iDT;
private ArrayList<String> iDU;
private cig iDV;
private ExdeviceProfileAffectedUserView iDW;
private ImageView iDX;
private ListView iDY;
private ExdeviceProfileListHeader iDZ;
private boolean iDw;
private boolean iDx;
private int iDy;
private MMSwitchBtn iEa;
private SportChartView iEb;
private a iEc;
private View iEd;
private volatile boolean iEe;
private String iEf;
private String iEg;
private List<com.tencent.mm.plugin.sport.b.e> iEh;
private ArrayList<c> iEi;
private List<xj> iEj;
private int iEk;
private b<i> iEl = new 1(this);
private d iEm = new 29(this);
private b<h> iEn = new 31(this);
private b<g> iEo = new b<g>() {
public final /* synthetic */ void b(int i, int i2, String str, l lVar) {
x.i("MicroMsg.Sport.ExdeviceProfileUI", "on NetSceneAddFollow end,errType:" + i + " errCode:" + i2 + " errMsg:" + str);
if (i == 0 && i2 == 0) {
ExdeviceProfileUI.this.finish();
}
}
};
private Runnable iEq = new Runnable() {
public final void run() {
BackwardSupportUtil.c.a(ExdeviceProfileUI.this.iDY);
if (ExdeviceProfileUI.this.iDY.getCount() > 0) {
BackwardSupportUtil.c.b(ExdeviceProfileUI.this.iDY, ExdeviceProfileUI.this.iDY.getCount() - 1);
}
}
};
private b<g> iEr = new 15(this);
private List<String> iEs;
private b<k> iEt = new 17(this);
private com.tencent.mm.sdk.b.c<ll> iEu = new com.tencent.mm.sdk.b.c<ll>() {
{
this.sFo = ll.class.getName().hashCode();
}
public final /* synthetic */ boolean a(com.tencent.mm.sdk.b.b bVar) {
ll llVar = (ll) bVar;
x.i("MicroMsg.Sport.ExdeviceProfileUI", "count: %d ret: %s title: %s content: %s", new Object[]{Integer.valueOf(llVar.bVN.count), Integer.valueOf(llVar.bVN.ret), llVar.bVN.bVO, llVar.bVN.bVP});
if (ExdeviceProfileUI.this.iBL != null && ExdeviceProfileUI.this.iBL.isShowing()) {
ExdeviceProfileUI.this.iBL.dismiss();
}
ExdeviceProfileUI.this.iEu.dead();
Intent intent = new Intent();
intent.putExtra("KeyNeedUpdateRank", true);
ExdeviceProfileUI.this.setResult(-1, intent);
ExdeviceProfileUI.this.finish();
return false;
}
};
private GestureDetector iEv;
private MMPullDownView.a iEw = new MMPullDownView.a() {
public final boolean onInterceptTouchEvent(MotionEvent motionEvent) {
return ExdeviceProfileUI.this.iEv.onTouchEvent(motionEvent);
}
};
private boolean ixI;
private List<String> ixY;
private List<String> ixZ;
private String ixv;
private String mAppName;
private Context mContext;
static /* synthetic */ void A(ExdeviceProfileUI exdeviceProfileUI) {
if (VERSION.SDK_INT >= 11) {
View childAt = exdeviceProfileUI.iDY.getChildAt(0);
int[] iArr = new int[2];
if (childAt != null && exdeviceProfileUI.iDY.getFirstVisiblePosition() == 0) {
childAt.getLocationOnScreen(iArr);
if (iEp == 0) {
iEp = iArr[1];
}
int i = iArr[1];
if (i > (-iEp) / 2) {
exdeviceProfileUI.iDW.setAlpha(i > 0 ? ((float) (i * 2)) / (((float) iEp) * 2.0f) : ((float) i) / ((float) iEp));
exdeviceProfileUI.iDW.setVisibility(0);
return;
}
exdeviceProfileUI.iDW.setAlpha(0.0f);
exdeviceProfileUI.iDW.setVisibility(8);
}
}
}
static /* synthetic */ void B(ExdeviceProfileUI exdeviceProfileUI) {
com.tencent.mm.ui.widget.a.d dVar = new com.tencent.mm.ui.widget.a.d(exdeviceProfileUI.mController.tml, 1, false);
dVar.ofp = new 30(exdeviceProfileUI);
dVar.ofq = exdeviceProfileUI.iEm;
dVar.bXO();
}
static /* synthetic */ void E(ExdeviceProfileUI exdeviceProfileUI) {
Intent intent = new Intent();
String c = bi.c(exdeviceProfileUI.iEs, ",");
intent.putExtra("wechat_sport_contact", bi.c(exdeviceProfileUI.ixY, ","));
intent.putExtra("wechat_sport_recent_like", c);
c = bi.c(exdeviceProfileUI.ixZ, ",");
intent.putExtra("titile", exdeviceProfileUI.getString(R.l.exdevice_add_follower));
intent.putExtra("list_type", 12);
intent.putExtra("max_limit_num", 10);
intent.putExtra("too_many_member_tip_string", exdeviceProfileUI.getString(R.l.exdevice_add_follower_too_many_contact, new Object[]{Integer.valueOf(10)}));
intent.putExtra("list_attr", s.s(new int[]{2, 4, 1, 131072, 128, 64, 16384}));
intent.putExtra("always_select_contact", c);
com.tencent.mm.bg.d.b(exdeviceProfileUI, ".ui.contact.SelectContactUI", intent, 3);
}
static /* synthetic */ List aT(List list) {
List arrayList = new ArrayList();
for (bre bre : list) {
com.tencent.mm.plugin.sport.b.e eVar = new com.tencent.mm.plugin.sport.b.e();
eVar.field_step = bre.fHo;
eVar.field_timestamp = ((long) bre.timestamp) * 1000;
eVar.field_date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(eVar.field_timestamp));
arrayList.add(eVar);
}
return arrayList;
}
static /* synthetic */ void g(ExdeviceProfileUI exdeviceProfileUI) {
exdeviceProfileUI.mController.removeAllOptionMenu();
if (q.GF().equals(exdeviceProfileUI.gtX)) {
exdeviceProfileUI.addIconOptionMenu(0, R.g.mm_title_btn_menu, new 12(exdeviceProfileUI));
return;
}
au.HU();
boolean Yc = com.tencent.mm.model.c.FR().Yc(exdeviceProfileUI.gtX);
au.HU();
boolean BB = com.tencent.mm.model.c.FR().Yg(exdeviceProfileUI.gtX).BB();
if (exdeviceProfileUI.iDx && Yc) {
exdeviceProfileUI.addIconOptionMenu(0, R.g.mm_title_btn_menu, new 23(exdeviceProfileUI));
} else if (!BB) {
exdeviceProfileUI.addIconOptionMenu(0, R.g.mm_title_btn_menu, new 26(exdeviceProfileUI));
}
}
static /* synthetic */ void k(ExdeviceProfileUI exdeviceProfileUI) {
if (exdeviceProfileUI.iEb == null) {
exdeviceProfileUI.iEb = (SportChartView) exdeviceProfileUI.findViewById(R.h.exdevice_rank_step_chart);
}
if (exdeviceProfileUI.iEa == null) {
exdeviceProfileUI.iEa = (MMSwitchBtn) exdeviceProfileUI.findViewById(R.h.exdevice_step_chart_switch_btn);
}
if (exdeviceProfileUI.iEh == null || exdeviceProfileUI.iEh.size() <= 0) {
exdeviceProfileUI.iEb.setHasSwitchBtn(false);
exdeviceProfileUI.iEa.setVisibility(8);
exdeviceProfileUI.iEb.cy(null);
return;
}
if (exdeviceProfileUI.iDw) {
exdeviceProfileUI.iEb.setHasSwitchBtn(true);
exdeviceProfileUI.iEa.setVisibility(0);
exdeviceProfileUI.iEa.setSwitchListener(new 22(exdeviceProfileUI));
} else {
exdeviceProfileUI.iEb.setHasSwitchBtn(false);
exdeviceProfileUI.iEa.setVisibility(8);
exdeviceProfileUI.iEb.xT(SportChartView.a.opM);
exdeviceProfileUI.iEb.cy(exdeviceProfileUI.iEh);
}
exdeviceProfileUI.iEb.setTodayStep(((com.tencent.mm.plugin.sport.b.e) exdeviceProfileUI.iEh.get(exdeviceProfileUI.iEh.size() - 1)).field_step);
exdeviceProfileUI.iEb.cy(exdeviceProfileUI.iEh);
com.tencent.mm.plugin.sport.b.e bFy = ((com.tencent.mm.plugin.sport.b.b) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.sport.b.b.class)).bFy();
Calendar instance = Calendar.getInstance();
instance.add(5, -1);
instance.set(10, 23);
instance.set(12, 59);
instance.set(13, 59);
long timeInMillis = instance.getTimeInMillis();
instance.add(5, -120);
instance.set(10, 0);
instance.set(12, 0);
instance.set(13, 0);
long timeInMillis2 = instance.getTimeInMillis();
if (bFy != null) {
instance.setTimeInMillis(bFy.field_timestamp);
instance.add(5, 2);
if (instance.getTimeInMillis() > timeInMillis) {
exdeviceProfileUI.r(timeInMillis2, timeInMillis);
return;
}
}
((com.tencent.mm.plugin.sport.b.b) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.sport.b.b.class)).a(timeInMillis2, timeInMillis, new 24(exdeviceProfileUI, timeInMillis2, timeInMillis));
}
static /* synthetic */ void r(ExdeviceProfileUI exdeviceProfileUI) {
ac acVar = new ac();
String valueOf = String.valueOf(exdeviceProfileUI.iEk);
String str = "0";
if (exdeviceProfileUI.iDV != null) {
str = String.valueOf(exdeviceProfileUI.iDV.score);
}
acVar.a(exdeviceProfileUI, valueOf, str, exdeviceProfileUI.gaG, new 19(exdeviceProfileUI));
}
static /* synthetic */ void s(ExdeviceProfileUI exdeviceProfileUI) {
String valueOf = String.valueOf(exdeviceProfileUI.iEk);
String str = "0";
if (exdeviceProfileUI.iDV != null) {
str = String.valueOf(exdeviceProfileUI.iDV.score);
}
new ac().a(exdeviceProfileUI, valueOf, str, exdeviceProfileUI.gaG, new ac.a() {
public final void zZ(String str) {
ExdeviceProfileUI.d(ExdeviceProfileUI.this, str);
}
});
}
static /* synthetic */ void t(ExdeviceProfileUI exdeviceProfileUI) {
x.i("MicroMsg.Sport.ExdeviceProfileUI", "ap: start to del: %s", new Object[]{exdeviceProfileUI.gtX});
au.DF().a(new h(exdeviceProfileUI.gtX, exdeviceProfileUI.iEn), 0);
}
public void onCreate(Bundle bundle) {
CharSequence string;
super.onCreate(bundle);
this.mContext = this.mController.tml;
Intent intent = getIntent();
aHV();
this.gtX = intent.getStringExtra("username");
this.iDS = intent.getStringExtra("usernickname");
String GF = q.GF();
if (GF != null) {
this.iDw = GF.equals(this.gtX);
}
this.mAppName = getIntent().getStringExtra("app_username");
this.iDx = ad.aHg().Af(this.gtX);
x.d("MicroMsg.Sport.ExdeviceProfileUI", "is follow %s", new Object[]{Boolean.valueOf(this.iDx)});
Assert.assertTrue(!bi.oW(this.gtX));
this.iDT = ad.aHi().Ah(this.gtX);
this.iDU = getIntent().getStringArrayListExtra("key_affected_semi");
getString(R.l.app_tip);
this.iBL = com.tencent.mm.ui.base.h.b(this, getString(R.l.loading_tips), new OnCancelListener() {
public final void onCancel(DialogInterface dialogInterface) {
if (ExdeviceProfileUI.this.iBL != null) {
ExdeviceProfileUI.this.iBL.dismiss();
ExdeviceProfileUI.this.iBL = null;
}
ExdeviceProfileUI.this.finish();
}
});
this.iDW = (ExdeviceProfileAffectedUserView) findViewById(R.h.exdevice_affected_view);
this.iDX = (ImageView) findViewById(R.h.exdevice_bg_iv);
this.iDY = (ListView) findViewById(R.h.exdevice_profile_lv);
MMPullDownView mMPullDownView = (MMPullDownView) findViewById(R.h.pull_down_view);
this.iDW.setAffectedUserInfo(this.iDU);
aHZ();
this.iEd = findViewById(R.h.setCoverV);
this.iEv = new GestureDetector(this.mController.tml, new a(this, (byte) 0));
mMPullDownView.setIsBottomShowAll(false);
mMPullDownView.setTopViewVisible(false);
mMPullDownView.setBottomViewVisible(false);
mMPullDownView.setIsBottomShowAll(false);
mMPullDownView.setIsTopShowAll(false);
mMPullDownView.setCanOverScrool(true);
mMPullDownView.setOnInterceptTouchEventListener(this.iEw);
mMPullDownView.setAtBottomCallBack(new 5(this));
mMPullDownView.setAtTopCallBack(new 6(this));
mMPullDownView.setOnBottomLoadDataListener(new 7(this));
mMPullDownView.setOnScrollChangedListener(new 8(this));
ExdeviceProfileListHeader exdeviceProfileListHeader = new ExdeviceProfileListHeader(this);
int B = com.tencent.mm.plugin.exdevice.j.b.B(this, getResources().getDimensionPixelSize(R.f.ExdeviceDefaultStatusBarHeight));
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int dimensionPixelSize = displayMetrics.widthPixels > displayMetrics.heightPixels ? getResources().getDimensionPixelSize(R.f.DefaultActionbarHeightLand) : getResources().getDimensionPixelSize(R.f.DefaultActionbarHeightPort);
int dimensionPixelSize2 = getResources().getDimensionPixelSize(R.f.ExdeviceProfileAvatarSize);
int dimensionPixelSize3 = getResources().getDimensionPixelSize(R.f.ExdeviceProfileAvatarRoundStrokeWidth);
Display defaultDisplay = getWindowManager().getDefaultDisplay();
dimensionPixelSize2 = ((((defaultDisplay.getHeight() / 2) - B) - dimensionPixelSize) - (dimensionPixelSize2 / 2)) - dimensionPixelSize3;
if (defaultDisplay.getHeight() <= 0 || dimensionPixelSize2 <= 0) {
dimensionPixelSize2 = getResources().getDimensionPixelSize(R.f.ExdeviceChangeCoverClickAreaHeight);
}
exdeviceProfileListHeader.setMinimumHeight(dimensionPixelSize2);
exdeviceProfileListHeader.setMinimumWidth(defaultDisplay.getWidth());
exdeviceProfileListHeader.setTag(Integer.valueOf(((defaultDisplay.getHeight() / 2) - B) - dimensionPixelSize));
this.iDZ = exdeviceProfileListHeader;
this.iDY.addHeaderView(this.iDZ, null, false);
this.iEc = new a(this.mController.tml, this.mAppName, this.iDw, this.gtX);
this.iEc.iDv = this;
this.iDY.setAdapter(this.iEc);
this.iDY.setOnScrollListener(new 9(this));
this.iDW.setUsername(this.gtX);
this.iEd.setOnClickListener(new 10(this));
mMPullDownView.setCanOverScrool(false);
this.iDX.setLayoutParams(new LayoutParams(com.tencent.mm.bp.a.fk(this), ((Integer) this.iDZ.getTag()).intValue()));
aHY();
ad.aHn().a(this);
au.DF().a(new i(this.gtX, bi.oV(this.mAppName), this.iEl), 0);
try {
this.duy = getResources().getDimensionPixelSize(R.f.ExdeviceUserNameWidth);
if (this.duy <= 0) {
this.duy = 60;
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Sport.ExdeviceProfileUI", e, "", new Object[0]);
if (this.duy <= 0) {
this.duy = 60;
}
} catch (Throwable th) {
if (this.duy <= 0) {
this.duy = 60;
}
}
x.d("MicroMsg.Sport.ExdeviceProfileUI", "ap: ellipsizeWidth: %s", new Object[]{Integer.valueOf(this.duy)});
if (this.iDw) {
string = getString(R.l.exdevice_profile_my_title);
} else {
dimensionPixelSize = R.l.exdevice_profile_title;
Object[] objArr = new Object[1];
GF = this.gtX;
int i = this.duy;
CharSequence gT = r.gT(GF);
string = (!GF.equalsIgnoreCase(gT) || bi.oW(this.iDS)) ? j.a(this.mController.tml, gT) : j.a(this.mController.tml, this.iDS);
x.d("MicroMsg.Sport.ExdeviceProfileUI", " width: %d, ap: username %s, ellipseize username %s", new Object[]{Integer.valueOf(i), string, TextUtils.ellipsize(string, this.dG, (float) i, TruncateAt.END)});
objArr[0] = gT;
string = j.a(this, getString(dimensionPixelSize, objArr));
}
M(string);
setBackBtn(new 28(this));
x.i("MicroMsg.Sport.ExdeviceProfileUI", "mUsername:" + this.gtX);
if (q.GF().equals(this.gtX)) {
qt qtVar = new qt();
qtVar.cbp.action = 3;
com.tencent.mm.sdk.b.a.sFg.a(qtVar, Looper.getMainLooper());
}
}
private void aHV() {
this.iEi = ad.aHg().aHs();
if (this.iEi != null) {
x.d("MicroMsg.Sport.ExdeviceProfileUI", "ap: follow size:%s, %s", new Object[]{Integer.valueOf(this.iEi.size()), this.iEi.toString()});
} else {
x.d("MicroMsg.Sport.ExdeviceProfileUI", "ap: follow is null");
}
if (bi.cX(this.iEi)) {
this.iDy = 0;
} else {
this.iDy = this.iEi.size();
}
}
private void aHW() {
runOnUiThread(new 27(this));
}
public void onPause() {
super.onPause();
}
public void onResume() {
super.onResume();
x.v("MicroMsg.Sport.ExdeviceProfileUI", "ExdeviceProfileUI: onResume");
aHV();
aHW();
if (!this.iDw) {
ad.aHg().Af(this.gtX);
aHX();
}
}
private void aHX() {
runOnUiThread(new 3(this));
}
protected void onDestroy() {
this.iEu.dead();
this.En = true;
super.onDestroy();
ad.aHn().b(this);
}
private void aHY() {
String GF = q.GF();
if (this.iEd != null) {
this.iEd.setVisibility(8);
}
if (!bi.oW(GF) && GF.equals(this.gtX)) {
if (!(this.iDT == null || !bi.oW(this.iDT.field_championUrl) || this.iEd == null)) {
this.iEd.setVisibility(0);
}
if (this.iDZ != null) {
this.iDZ.setOnClickListener(new 11(this));
}
} else if (this.iDT != null && !bi.oW(this.iDT.field_championUrl) && this.iDZ != null) {
this.iDZ.setOnClickListener(new 13(this));
}
}
private void aHZ() {
if (this.iDT == null) {
this.iDX.setImageResource(R.e.darkgrey);
this.gaG = null;
} else if (this.gaG == this.iDT.field_championUrl) {
} else {
if (this.gaG == null || !this.gaG.equals(this.iDT.field_championUrl)) {
com.tencent.mm.plugin.exdevice.f.a.e.a(this, this.iDX, this.iDT.field_championUrl, R.e.darkgrey);
this.gaG = this.iDT.field_championUrl;
}
}
}
protected void onActivityResult(int i, int i2, Intent intent) {
super.onActivityResult(i, i2, intent);
if (!com.tencent.mm.plugin.exdevice.f.a.e.a(this, i, i2, intent, this.mAppName)) {
switch (i) {
case 1:
if (i2 == -1) {
String str;
if (intent == null) {
str = null;
} else {
str = intent.getStringExtra("Select_Conv_User");
}
String dc = ac.dc(this);
if (str == null || str.length() == 0) {
x.e("MicroMsg.Sport.ExdeviceProfileUI", "select conversation failed, toUser is null.");
return;
}
ac.a(this, str, dc, intent.getStringExtra("custom_send_text"), this.iEg);
com.tencent.mm.ui.base.h.bA(this.mController.tml, getResources().getString(R.l.app_shared));
return;
}
return;
case 2:
if (i2 == -1) {
Toast.makeText(this, R.l.share_ok, 1).show();
return;
}
return;
case 3:
if (i2 == -1) {
List F = bi.F(intent.getStringExtra("Select_Contact").split(","));
if (F != null) {
if (this.iBL != null) {
this.iBL.show();
}
au.DF().a(new g(F, this.iEr), 0);
return;
}
return;
}
return;
default:
return;
}
}
}
protected final int getLayoutId() {
return R.i.exdevice_profile_ui;
}
public final void b(String str, com.tencent.mm.plugin.exdevice.f.b.d dVar) {
if ("HardDeviceChampionInfo".equals(str) && this.gtX.equals(dVar.username)) {
x.d("MicroMsg.Sport.ExdeviceProfileUI", "hy: url may changed. maybe reload background");
this.iDT = ad.aHi().Ah(this.gtX);
runOnUiThread(new Runnable() {
public final void run() {
ExdeviceProfileUI.this.aHY();
ExdeviceProfileUI.this.iEc.notifyDataSetChanged();
ExdeviceProfileUI.this.aHZ();
}
});
}
}
public final void aIa() {
runOnUiThread(new 18(this));
au.DF().a(new k(this.iEt), 0);
}
public final void aIb() {
com.tencent.mm.plugin.sport.b.d.kB(17);
List arrayList = new ArrayList();
arrayList.add(this.gtX);
au.DF().a(new g(arrayList, this.iEo), 0);
}
private void r(long j, long j2) {
List<com.tencent.mm.plugin.sport.b.e> B = ((com.tencent.mm.plugin.sport.b.b) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.sport.b.b.class)).B(j, j2);
HashSet hashSet = new HashSet();
List arrayList = new ArrayList();
if (this.iEh != null) {
for (com.tencent.mm.plugin.sport.b.e eVar : this.iEh) {
if (hashSet.add(eVar.field_date)) {
arrayList.add(eVar);
}
}
}
for (com.tencent.mm.plugin.sport.b.e eVar2 : B) {
if (hashSet.add(eVar2.field_date)) {
arrayList.add(eVar2);
}
}
Collections.sort(arrayList);
this.iEh = arrayList;
this.iEb.cy(this.iEh);
}
}
|
/*
* 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 data.db;
import data.core.api.ApiData;
import data.core.api.ApiDatabase;
import java.util.HashMap;
/**
*
* @author Ryno
*/
public class DBPerson_person extends ApiDatabase{
//--------------------------------------------------------------------------
//properties
//--------------------------------------------------------------------------
public DBPerson_person(){
key = "pep_id";
table = "person_person";
fields = new HashMap < String, Object[] > ();
fields.put("pep_id", new Object[]{"id", "null", ApiData.INT});
fields.put("pep_ref_person_student", new Object[]{"fisrtname", "null", ApiData.INT});
fields.put("pep_ref_person_guardian", new Object[]{"lastname", "null", ApiData.INT});
}
//--------------------------------------------------------------------------
public static HashMap getStudentGuardian(String per_id_student){
HashMap<String, String> guardian = new DBPerson().get_fromdb(
"LEFT JOIN person_person ON (per_id = pep_ref_person_guardian) WHERE pep_ref_person_student = "+per_id_student,
new Object[]{true}
);
return guardian;
}
//--------------------------------------------------------------------------
public int create(int student_id, int guardian_id){
return create(String.valueOf(student_id), String.valueOf(guardian_id));
}
//--------------------------------------------------------------------------
public int create(String student_id, String guardian_id){
DBPerson_person person_person = new DBPerson_person();
HashMap person_person_obj = person_person.get_fromdefault();
person_person_obj.put("pep_ref_person_student", student_id);
person_person_obj.put("pep_ref_person_guardian", guardian_id);
return person_person.insert();
}
//--------------------------------------------------------------------------
}
|
/* 1: */ package com.kaldin.test.settest.Hibernate;
/* 2: */
/* 3: */ import com.kaldin.common.db.QueryHelper;
/* 4: */ import com.kaldin.common.util.HibernateUtil;
/* 5: */ import com.kaldin.common.util.PagingBean;
/* 6: */ import com.kaldin.common.utility.StringUtility;
/* 7: */ import com.kaldin.test.scheduletest.dto.QuestionPaperListDTO;
/* 8: */ import com.kaldin.test.settest.dto.QuestionPaperDTO;
/* 9: */ import com.kaldin.test.settest.dto.TopicQuestionDTO;
/* 10: */ import java.io.File;
/* 11: */ import java.io.PrintStream;
/* 12: */ import java.sql.ResultSet;
/* 13: */ import java.util.ArrayList;
/* 14: */ import java.util.Iterator;
/* 15: */ import java.util.List;
/* 16: */ import org.apache.commons.lang.StringUtils;
/* 17: */ import org.hibernate.Criteria;
/* 18: */ import org.hibernate.HibernateException;
/* 19: */ import org.hibernate.Query;
/* 20: */ import org.hibernate.Session;
/* 21: */ import org.hibernate.Transaction;
/* 22: */ import org.hibernate.criterion.Restrictions;
/* 23: */
/* 24: */ public class QuestionPaperHibernate
/* 25: */ {
/* 26: */ public boolean saveData(QuestionPaperDTO qpDTO)
/* 27: */ {
/* 28: 27 */ Session sesObj = null;
/* 29: 28 */ Transaction trObj = null;
/* 30: */ try
/* 31: */ {
/* 32: 30 */ sesObj = HibernateUtil.getSession();
/* 33: 31 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 34: */
/* 35: 33 */ sesObj.save(qpDTO);
/* 36: 34 */ trObj.commit();
/* 37: 35 */ return true;
/* 38: */ }
/* 39: */ catch (HibernateException e)
/* 40: */ {
/* 41: 38 */ trObj.rollback();
/* 42: */
/* 43: 40 */ e.printStackTrace();
/* 44: */ }
/* 45: */ finally
/* 46: */ {
/* 47: 44 */ sesObj.close();
/* 48: */ }
/* 49: 47 */ return false;
/* 50: */ }
/* 51: */
/* 52: */ public String getNewTestId()
/* 53: */ {
/* 54: 51 */ String tid = "";
/* 55: */
/* 56: 53 */ QueryHelper qh = new QueryHelper();
/* 57: */ try
/* 58: */ {
/* 59: 56 */ String sql = "SELECT CONVERT(SUBSTRING(testid,2,LENGTH(testid)),UNSIGNED INTEGER) as id FROM exm_test order by id desc limit 1";
/* 60: 57 */ ResultSet rs = qh.runQueryStreamResults(sql);
/* 61: 58 */ if (rs.next())
/* 62: */ {
/* 63: 59 */ int num = rs.getInt("id");
/* 64: 60 */ if (num < 9) {
/* 65: 61 */ tid = "T000";
/* 66: 62 */ } else if ((num >= 9) && (num < 100)) {
/* 67: 63 */ tid = "T00";
/* 68: 64 */ } else if ((num >= 99) && (num < 1000)) {
/* 69: 65 */ tid = "T0";
/* 70: 66 */ } else if ((num >= 999) && (num < 10000)) {
/* 71: 67 */ tid = "T";
/* 72: */ }
/* 73: 70 */ num += 1;
/* 74: 71 */ tid = tid + num;
/* 75: */ }
/* 76: 73 */ if (tid.equals("")) {
/* 77: 74 */ tid = "T0001";
/* 78: */ }
/* 79: */ }
/* 80: */ catch (Exception e)
/* 81: */ {
/* 82: 78 */ e.printStackTrace();
/* 83: */ }
/* 84: */ finally
/* 85: */ {
/* 86: 80 */ qh.releaseConnection();
/* 87: */ }
/* 88: 83 */ return tid;
/* 89: */ }
/* 90: */
/* 91: */ public String getNewTestId_Old()
/* 92: */ {
/* 93: 87 */ String tid = "";
/* 94: 88 */ Transaction trObj = null;
/* 95: 89 */ Session sesObj = null;
/* 96: */ try
/* 97: */ {
/* 98: 92 */ sesObj = HibernateUtil.getSession();
/* 99: 93 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 100: 94 */ String sql = "from QuestionPaperDTO";
/* 101: 95 */ List<?> listobj = sesObj.createQuery(sql).list();
/* 102: 96 */ Iterator<?> Itr = listobj.iterator();
/* 103: 98 */ while (Itr.hasNext())
/* 104: */ {
/* 105: 99 */ QuestionPaperDTO qpdto = (QuestionPaperDTO)Itr.next();
/* 106:100 */ tid = qpdto.getTestId();
/* 107: */ }
/* 108:102 */ trObj.commit();
/* 109: */ }
/* 110: */ catch (Exception e)
/* 111: */ {
/* 112:104 */ e.printStackTrace();
/* 113: */ }
/* 114: */ finally
/* 115: */ {
/* 116:106 */ sesObj.close();
/* 117: */ }
/* 118:108 */ if (tid.equals(""))
/* 119: */ {
/* 120:109 */ tid = "T0001";
/* 121: */ }
/* 122: */ else
/* 123: */ {
/* 124:111 */ int num = Integer.parseInt(tid.substring(1, 5));
/* 125:113 */ if (num < 9) {
/* 126:114 */ tid = "T000";
/* 127:115 */ } else if ((num >= 9) && (num < 100)) {
/* 128:116 */ tid = "T00";
/* 129:117 */ } else if ((num >= 99) && (num < 1000)) {
/* 130:118 */ tid = "T0";
/* 131:119 */ } else if ((num >= 999) && (num < 10000)) {
/* 132:120 */ tid = "T";
/* 133: */ }
/* 134:123 */ num += 1;
/* 135:124 */ tid = tid + num;
/* 136: */ }
/* 137:127 */ return tid;
/* 138: */ }
/* 139: */
/* 140: */ public boolean saveSelectedTopic(TopicQuestionDTO tpDTO)
/* 141: */ {
/* 142:131 */ Transaction trObj = null;
/* 143:132 */ Session sesObj = null;
/* 144: */ try
/* 145: */ {
/* 146:134 */ sesObj = HibernateUtil.getSession();
/* 147:135 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 148: */
/* 149:137 */ sesObj.save(tpDTO);
/* 150:138 */ trObj.commit();
/* 151:139 */ return true;
/* 152: */ }
/* 153: */ catch (HibernateException e)
/* 154: */ {
/* 155:142 */ trObj.rollback();
/* 156: */
/* 157:144 */ e.printStackTrace();
/* 158: */ }
/* 159: */ finally
/* 160: */ {
/* 161:148 */ sesObj.close();
/* 162: */ }
/* 163:151 */ return false;
/* 164: */ }
/* 165: */
/* 166: */ public QuestionPaperDTO getTest(String TestId)
/* 167: */ {
/* 168:156 */ Transaction trObj = null;
/* 169:157 */ Session sesObj = null;
/* 170:158 */ QuestionPaperDTO testDTO = null;
/* 171: */ try
/* 172: */ {
/* 173:160 */ sesObj = HibernateUtil.getSession();
/* 174:161 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 175:162 */ testDTO = (QuestionPaperDTO)sesObj.get(QuestionPaperDTO.class, TestId);
/* 176: */
/* 177:164 */ trObj.commit();
/* 178: */ }
/* 179: */ catch (HibernateException e)
/* 180: */ {
/* 181:166 */ trObj.rollback();
/* 182:167 */ e.printStackTrace();
/* 183: */ }
/* 184: */ finally
/* 185: */ {
/* 186:169 */ sesObj.close();
/* 187: */ }
/* 188:171 */ return testDTO;
/* 189: */ }
/* 190: */
/* 191: */ public List<?> getTestList(PagingBean pagingBean, int records, int companyid)
/* 192: */ {
/* 193:175 */ Transaction trObj = null;
/* 194:176 */ Session sesObj = null;
/* 195:177 */ List<?> listObj = null;
/* 196: */ try
/* 197: */ {
/* 198:180 */ sesObj = HibernateUtil.getSession();
/* 199:181 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 200:182 */ Query query = sesObj.createQuery("from QuestionPaperDTO queDTO where queDTO.companyId=? order by queDTO.testId desc ");
/* 201: */
/* 202:184 */ query.setParameter(0, Integer.valueOf(companyid));
/* 203:185 */ query.setFirstResult(pagingBean.getStartRec());
/* 204:186 */ query.setMaxResults(pagingBean.getPageSize());
/* 205:187 */ listObj = query.list();
/* 206:188 */ pagingBean.setCount(records);
/* 207:189 */ trObj.commit();
/* 208: */ }
/* 209: */ catch (HibernateException e)
/* 210: */ {
/* 211:192 */ trObj.rollback();
/* 212:193 */ e.printStackTrace();
/* 213: */ }
/* 214: */ finally
/* 215: */ {
/* 216:195 */ sesObj.close();
/* 217: */ }
/* 218:197 */ return listObj;
/* 219: */ }
/* 220: */
/* 221: */ public List<QuestionPaperDTO> getTestList(int companyid)
/* 222: */ {
/* 223:201 */ Transaction trObj = null;
/* 224:202 */ Session sesObj = null;
/* 225:203 */ List<QuestionPaperDTO> listObj = null;
/* 226: */ try
/* 227: */ {
/* 228:205 */ sesObj = HibernateUtil.getSession();
/* 229:206 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 230:207 */ Query query = sesObj.createQuery("from QuestionPaperDTO queDTO where queDTO.companyId=? order by queDTO.testId desc");
/* 231: */
/* 232:209 */ query.setParameter(0, Integer.valueOf(companyid));
/* 233:210 */ listObj = query.list();
/* 234: */
/* 235:212 */ trObj.commit();
/* 236: */ }
/* 237: */ catch (HibernateException e)
/* 238: */ {
/* 239:215 */ trObj.rollback();
/* 240:216 */ e.printStackTrace();
/* 241: */ }
/* 242: */ finally
/* 243: */ {
/* 244:218 */ sesObj.close();
/* 245: */ }
/* 246:220 */ return listObj;
/* 247: */ }
/* 248: */
/* 249: */ public List<QuestionPaperDTO> getTestFilter(String filtertest, int companyid)
/* 250: */ {
/* 251:224 */ Transaction trObj = null;
/* 252:225 */ Session sesObj = null;
/* 253:226 */ List<QuestionPaperDTO> listObj = null;
/* 254: */ try
/* 255: */ {
/* 256:228 */ sesObj = HibernateUtil.getSession();
/* 257:229 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 258:230 */ Query qr = sesObj.createQuery("from QuestionPaperDTO quest where quest.testName like :filtertest AND quest.companyId=:companyid");
/* 259: */
/* 260:232 */ qr.setString("filtertest", "%" + filtertest + "%");
/* 261:233 */ qr.setInteger("companyid", companyid);
/* 262:234 */ listObj = qr.list();
/* 263:235 */ trObj.commit();
/* 264: */ }
/* 265: */ catch (HibernateException e)
/* 266: */ {
/* 267:237 */ trObj.rollback();
/* 268:238 */ e.printStackTrace();
/* 269: */ }
/* 270: */ finally
/* 271: */ {
/* 272:240 */ sesObj.close();
/* 273: */ }
/* 274:242 */ return listObj;
/* 275: */ }
/* 276: */
/* 277: */ public List<QuestionPaperDTO> getTestFilter(String filtertest, PagingBean pagingBean, int records, int companyid)
/* 278: */ {
/* 279:247 */ Transaction trObj = null;
/* 280:248 */ Session sesObj = null;
/* 281:249 */ List<QuestionPaperDTO> listObj = null;
/* 282: */ try
/* 283: */ {
/* 284:251 */ sesObj = HibernateUtil.getSession();
/* 285:252 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 286:253 */ Query qr = sesObj.createQuery("from QuestionPaperDTO quest where quest.testName like :filtertest AND quest.companyId=:companyid");
/* 287: */
/* 288:255 */ qr.setString("filtertest", "%" + filtertest + "%");
/* 289:256 */ qr.setInteger("companyid", companyid);
/* 290:257 */ qr.setFirstResult(pagingBean.getStartRec());
/* 291:258 */ qr.setMaxResults(pagingBean.getPageSize());
/* 292:259 */ listObj = qr.list();
/* 293:260 */ pagingBean.setCount(records);
/* 294:261 */ trObj.commit();
/* 295: */ }
/* 296: */ catch (HibernateException e)
/* 297: */ {
/* 298:263 */ trObj.rollback();
/* 299:264 */ e.printStackTrace();
/* 300: */ }
/* 301: */ finally
/* 302: */ {
/* 303:266 */ sesObj.close();
/* 304: */ }
/* 305:268 */ return listObj;
/* 306: */ }
/* 307: */
/* 308: */ public String getTestId(String testURL)
/* 309: */ {
/* 310:272 */ String testid = "";
/* 311: */
/* 312:274 */ Session sesObj = null;
/* 313:275 */ Transaction trObj = null;
/* 314:276 */ List<?> listObj = null;
/* 315: */ try
/* 316: */ {
/* 317:278 */ sesObj = HibernateUtil.getSession();
/* 318:279 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 319:280 */ Query query = sesObj.createQuery("from QuestionPaperDTO where exmURL = ?");
/* 320: */
/* 321:282 */ query.setString(0, testURL);
/* 322:283 */ listObj = query.list();
/* 323:284 */ Iterator<?> itr = listObj.iterator();
/* 324:285 */ while (itr.hasNext())
/* 325: */ {
/* 326:286 */ QuestionPaperDTO groupdto = (QuestionPaperDTO)itr.next();
/* 327:287 */ testid = groupdto.getTestId();
/* 328: */ }
/* 329:289 */ trObj.commit();
/* 330: */ }
/* 331: */ catch (HibernateException e)
/* 332: */ {
/* 333:291 */ trObj.rollback();
/* 334:292 */ e.printStackTrace();
/* 335: */ }
/* 336: */ finally
/* 337: */ {
/* 338:294 */ sesObj.close();
/* 339: */ }
/* 340:297 */ return testid;
/* 341: */ }
/* 342: */
/* 343: */ public int getCompanyId(String testid)
/* 344: */ {
/* 345:301 */ int companyid = 0;
/* 346: */
/* 347:303 */ Session sesObj = null;
/* 348:304 */ Transaction trObj = null;
/* 349:305 */ List<?> listObj = null;
/* 350: */ try
/* 351: */ {
/* 352:307 */ sesObj = HibernateUtil.getSession();
/* 353:308 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 354:309 */ Query query = sesObj.createQuery("from QuestionPaperDTO where testid = ?");
/* 355: */
/* 356:311 */ query.setString(0, testid);
/* 357:312 */ listObj = query.list();
/* 358:313 */ Iterator<?> itr = listObj.iterator();
/* 359:314 */ while (itr.hasNext())
/* 360: */ {
/* 361:315 */ QuestionPaperDTO groupdto = (QuestionPaperDTO)itr.next();
/* 362:316 */ companyid = groupdto.getCompanyId();
/* 363: */ }
/* 364:318 */ trObj.commit();
/* 365: */ }
/* 366: */ catch (HibernateException e)
/* 367: */ {
/* 368:320 */ trObj.rollback();
/* 369:321 */ e.printStackTrace();
/* 370: */ }
/* 371: */ finally
/* 372: */ {
/* 373:323 */ sesObj.close();
/* 374: */ }
/* 375:326 */ return companyid;
/* 376: */ }
/* 377: */
/* 378: */ public List<QuestionPaperListDTO> getQuestionPaperWithExameCount(int companyid)
/* 379: */ {
/* 380:337 */ List<QuestionPaperListDTO> listObj = new ArrayList();
/* 381:338 */ QueryHelper qh = new QueryHelper();
/* 382: */ try
/* 383: */ {
/* 384:340 */ String sql = "select t.*, (select count(distinct ets.examid) from exm_test_schedule ets where ets.testid=t.testid and ets.examid > 0) as examecount from exm_test t left join exm_test_schedule ts on t.testid=ts.testid where t.companyid=? group by t.testid";
/* 385: */
/* 386:342 */ qh.addParam(companyid);
/* 387:343 */ ResultSet rs = qh.runQueryStreamResults(sql);
/* 388:344 */ while (rs.next())
/* 389: */ {
/* 390:345 */ QuestionPaperListDTO paperListDTO = new QuestionPaperListDTO();
/* 391:346 */ paperListDTO.setPaperId(rs.getString("testid"));
/* 392:347 */ paperListDTO.setQuestionPaperName(rs.getString("testname"));
/* 393:348 */ paperListDTO.setQuestions(rs.getString("noofquestions"));
/* 394:349 */ paperListDTO.setDuration(rs.getString("duration"));
/* 395:350 */ paperListDTO.setExamCount(rs.getInt("examecount"));
/* 396:351 */ paperListDTO.setTotalMarks(rs.getString("totalmarks"));
/* 397:352 */ paperListDTO.setPublicUrl(StringUtility.removeNull(rs.getString("exmurl")));
/* 398: */
/* 399:354 */ listObj.add(paperListDTO);
/* 400: */ }
/* 401: */ }
/* 402: */ catch (Exception e)
/* 403: */ {
/* 404:358 */ e.printStackTrace();
/* 405: */ }
/* 406: */ finally
/* 407: */ {
/* 408:360 */ qh.releaseConnection();
/* 409: */ }
/* 410:362 */ return listObj;
/* 411: */ }
/* 412: */
/* 413: */ public List<QuestionPaperListDTO> getQuestionPaperWithExameCount(PagingBean pagingBean, int companyid, String keyword)
/* 414: */ {
/* 415:367 */ List<QuestionPaperListDTO> listObj = new ArrayList();
/* 416:368 */ QueryHelper qh = new QueryHelper();
/* 417: */ try
/* 418: */ {
/* 419:370 */ String sql = "select t.*, (select count(distinct ets.examid) from exm_test_schedule ets where ets.testid=t.testid and ets.examid > 0) as examecount from exm_test t left join exm_test_schedule ts on t.testid=ts.testid where t.companyid=? ";
/* 420: */
/* 421:372 */ qh.addParam(companyid);
/* 422:373 */ if ((keyword != null) || (keyword != "")) {
/* 423:374 */ sql = sql + " AND t.testname LIKE '%" + keyword + "%'";
/* 424: */ }
/* 425:377 */ sql = sql + " group by t.testid order by t.testid desc";
/* 426: */
/* 427:379 */ ResultSet rs = qh.runQueryStreamResults(sql);
/* 428:380 */ int count = 0;
/* 429:381 */ while (rs.next()) {
/* 430:382 */ count++;
/* 431: */ }
/* 432:384 */ pagingBean.setCount(count);
/* 433: */
/* 434:386 */ sql = sql + " limit " + pagingBean.getStartRec() + ", " + pagingBean.getPageSize();
/* 435: */
/* 436:388 */ qh.clearParams();
/* 437:389 */ qh.addParam(companyid);
/* 438:390 */ rs = qh.runQueryStreamResults(sql);
/* 439:391 */ while (rs.next())
/* 440: */ {
/* 441:392 */ QuestionPaperListDTO paperListDTO = new QuestionPaperListDTO();
/* 442:393 */ paperListDTO.setPaperId(rs.getString("testid"));
/* 443:394 */ paperListDTO.setQuestionPaperName(rs.getString("testname"));
/* 444:395 */ paperListDTO.setQuestions(rs.getString("noofquestions"));
/* 445:396 */ paperListDTO.setDuration(rs.getString("duration"));
/* 446:397 */ paperListDTO.setExamCount(rs.getInt("examecount"));
/* 447:398 */ paperListDTO.setTotalMarks(rs.getString("totalmarks"));
/* 448:399 */ paperListDTO.setPublicUrl(StringUtility.removeNull(rs.getString("exmurl")));
/* 449: */
/* 450:401 */ listObj.add(paperListDTO);
/* 451: */ }
/* 452: */ }
/* 453: */ catch (Exception e)
/* 454: */ {
/* 455:405 */ e.printStackTrace();
/* 456: */ }
/* 457: */ finally
/* 458: */ {
/* 459:407 */ qh.releaseConnection();
/* 460: */ }
/* 461:409 */ return listObj;
/* 462: */ }
/* 463: */
/* 464: */ public ArrayList<TopicQuestionDTO> getTopicList(String testid, int companyid)
/* 465: */ {
/* 466:413 */ ArrayList<TopicQuestionDTO> listObj = new ArrayList();
/* 467:414 */ QueryHelper qh = new QueryHelper();
/* 468: */ try
/* 469: */ {
/* 470:416 */ String sql = "select es.subjectid , es.subjectname,eto.topicid, eto.topicname, el.levelid,el.level,ett.countofquestion from exm_test et, exm_subject es,exm_test_topic ett left outer join exm_topic eto on ett.topicid =eto.topicid left outer join exm_level el on ett.levelid = el.levelid where ett.testid= et.testid and ett.subjectid = es.subjectid and et.testid = ? and et.companyid = ?";
/* 471: */
/* 472: */
/* 473: */
/* 474:420 */ qh.addParam(testid);
/* 475:421 */ qh.addParam(companyid);
/* 476:422 */ ResultSet rs = qh.runQueryStreamResults(sql);
/* 477:423 */ while (rs.next())
/* 478: */ {
/* 479:424 */ TopicQuestionDTO listDTO = new TopicQuestionDTO();
/* 480:425 */ listDTO.setSubjectid(rs.getInt(1));
/* 481:426 */ listDTO.setSubjectName(rs.getString(2));
/* 482:427 */ listDTO.setTopicid(rs.getInt(3));
/* 483:428 */ listDTO.setTopicname(rs.getString(4));
/* 484:429 */ listDTO.setLevelid(rs.getInt(5));
/* 485:430 */ listDTO.setLevelName(rs.getString(6));
/* 486:431 */ listDTO.setQuestioncount(rs.getInt(7));
/* 487:432 */ listObj.add(listDTO);
/* 488: */ }
/* 489: */ }
/* 490: */ catch (Exception e)
/* 491: */ {
/* 492:435 */ e.printStackTrace();
/* 493: */ }
/* 494: */ finally
/* 495: */ {
/* 496:437 */ qh.releaseConnection();
/* 497: */ }
/* 498:439 */ return listObj;
/* 499: */ }
/* 500: */
/* 501: */ public boolean updateData(QuestionPaperDTO qpDTO)
/* 502: */ {
/* 503:443 */ Session sesObj = null;
/* 504:444 */ Transaction trObj = null;
/* 505: */ try
/* 506: */ {
/* 507:446 */ sesObj = HibernateUtil.getSession();
/* 508:447 */ trObj = HibernateUtil.getTrascation(sesObj);
/* 509:448 */ QuestionPaperDTO dtoObj = (QuestionPaperDTO)sesObj.createCriteria(QuestionPaperDTO.class).add(Restrictions.eq("testId", qpDTO.getTestId())).add(Restrictions.eq("companyId", Integer.valueOf(qpDTO.getCompanyId()))).uniqueResult();
/* 510: */
/* 511: */
/* 512: */
/* 513: */
/* 514: */
/* 515:454 */ dtoObj.setTestName(qpDTO.getTestName());
/* 516:455 */ dtoObj.setDuration(qpDTO.getDuration());
/* 517:456 */ dtoObj.setNoOfQuestions(qpDTO.getNoOfQuestions());
/* 518:457 */ dtoObj.setPassingMarks(qpDTO.getPassingMarks());
/* 519:458 */ dtoObj.setTotalMarks(qpDTO.getTotalMarks());
/* 520:459 */ dtoObj.setNegativeMarks(qpDTO.getNegativeMarks());
/* 521:460 */ dtoObj.setPerQuestionMarks(qpDTO.getPerQuestionMarks());
/* 522:461 */ dtoObj.setLevelid(qpDTO.getLevelid());
/* 523:462 */ dtoObj.setCompanyId(qpDTO.getCompanyId());
/* 524:463 */ dtoObj.setComments(qpDTO.getComments());
/* 525:464 */ dtoObj.setExmURL(qpDTO.getExmURL());
/* 526:465 */ dtoObj.setVideoURL(qpDTO.getVideoURL());
/* 527:466 */ if ((!StringUtils.isEmpty(qpDTO.getExamInfoFile())) && (qpDTO.getExamInfoFile() != null) && (!qpDTO.getExamInfoFile().equals(null)) && (!"".equals(qpDTO.getExamInfoFile())) && (qpDTO.getExamInfoFile() != "")) {
/* 528:470 */ dtoObj.setExamInfoFile(qpDTO.getExamInfoFile());
/* 529: */ }
/* 530:471 */ dtoObj.setSelectedQuestions(qpDTO.getSelectedQuestions());
/* 531:472 */ trObj.commit();
/* 532:473 */ return true;
/* 533: */ }
/* 534: */ catch (HibernateException e)
/* 535: */ {
/* 536:476 */ trObj.rollback();
/* 537: */
/* 538:478 */ e.printStackTrace();
/* 539: */ }
/* 540: */ finally
/* 541: */ {
/* 542:482 */ sesObj.close();
/* 543: */ }
/* 544:485 */ return false;
/* 545: */ }
/* 546: */
/* 547: */ public boolean deleteExistingTopic(String testId)
/* 548: */ {
/* 549:489 */ QueryHelper qh = new QueryHelper();
/* 550: */ try
/* 551: */ {
/* 552:491 */ String sql = "delete from exm_test_topic where testid = ?";
/* 553:492 */ qh.addParam(testId);
/* 554:493 */ qh.runQuery(sql);
/* 555: */ }
/* 556: */ catch (Exception e)
/* 557: */ {
/* 558:495 */ e.printStackTrace();
/* 559: */ }
/* 560: */ finally
/* 561: */ {
/* 562:497 */ qh.releaseConnection();
/* 563: */ }
/* 564:500 */ return false;
/* 565: */ }
/* 566: */
/* 567: */ public boolean deleteExistingDocument(String testId, int companyid, String filepath, String filename)
/* 568: */ {
/* 569:504 */ boolean result = false;
/* 570:505 */ QueryHelper qh = new QueryHelper();
/* 571: */ try
/* 572: */ {
/* 573:507 */ String sql = "update exm_test set examinfofile = NULL where testid = ? and companyid = ?";
/* 574:508 */ qh.addParam(testId);
/* 575:509 */ qh.addParam(companyid);
/* 576:510 */ qh.runQuery(sql);
/* 577:511 */ result = true;
/* 578:512 */ File file = new File(filepath + "uploads/examinfo/" + filename);
/* 579:513 */ if (file.delete()) {
/* 580:514 */ System.out.println(file.getName() + " is deleted!");
/* 581: */ }
/* 582: */ }
/* 583: */ catch (Exception e)
/* 584: */ {
/* 585:517 */ e.printStackTrace();
/* 586: */ }
/* 587: */ finally
/* 588: */ {
/* 589:519 */ qh.releaseConnection();
/* 590: */ }
/* 591:522 */ return result;
/* 592: */ }
/* 593: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.test.settest.Hibernate.QuestionPaperHibernate
* JD-Core Version: 0.7.0.1
*/
|
/*******************************************************************************
* Copyright 2020 Grégoire Martinetti
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.gmart.devtools.java.serdes.codeGen.javaGen.modelExtraction.parserGenTestForDebug;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.gmart.devtools.java.serdes.codeGen.javaGen.modelExtraction.parserGenTestForDebug.generatedParser.DataTypeHierarchy2Lexer;
import org.gmart.devtools.java.serdes.codeGen.javaGen.modelExtraction.parserGenTestForDebug.generatedParser.DataTypeHierarchy2Parser;
public class ParserFactory {
public static DataTypeHierarchy2Parser parse(String str){
DataTypeHierarchy2Lexer lexer = new DataTypeHierarchy2Lexer(CharStreams.fromString(str));
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
return new DataTypeHierarchy2Parser(tokenStream);
}
}
|
package com.tencent.mm.ui.chatting.gallery;
import com.tencent.mm.g.a.gj;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
class ImageGalleryGridUI$4 extends c<gj> {
final /* synthetic */ ImageGalleryGridUI tUJ;
ImageGalleryGridUI$4(ImageGalleryGridUI imageGalleryGridUI) {
this.tUJ = imageGalleryGridUI;
this.sFo = gj.class.getName().hashCode();
}
public final /* bridge */ /* synthetic */ boolean a(b bVar) {
gj gjVar = (gj) bVar;
ImageGalleryGridUI.a(this.tUJ, gjVar.bPx.bPA, gjVar);
return false;
}
}
|
package org.mvirtual.persistence.hibernate.dao;
import org.mvirtual.persistence.entity.relation.AuthorityHeritage;
import org.mvirtual.persistence.entity.relation.embedded.AuthorityHeritageId;
import org.mvirtual.persistence.dao.AuthorityHeritageDAO;
/**
* Hibernate-specific implementation of <tt>AuthorityHeritageDAO</tt>.
*
* @author Kiyoshi Murata <kbmurata@gmail.com>
*/
public class AuthorityHeritageHibernateDAO
extends GenericHibernateDAO<AuthorityHeritage, AuthorityHeritageId>
implements AuthorityHeritageDAO
{
// This class intentionally left blank
}
|
package com.bufeng.ratelimiter.strategy.impl;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.bufeng.ratelimiter.aop.RateLimiterType;
import com.bufeng.ratelimiter.strategy.RateLimiterStrategyFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.bufeng.ratelimiter.aop.RateLimiterMethod;
import com.bufeng.ratelimiter.strategy.RateLimiterStrategy;
/**
* 计数器算法限流实现
*
* @author liuhailong 2017/11/11
*/
@Service
public class CounterRateLimiterStrategy extends RateLimiterStrategy implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(CounterRateLimiterStrategy.class);
/**
* Guava Cache来存储计数器,过期时间设置为2秒(保证1秒内的计数器是有效的)
*/
private ConcurrentHashMap<String, LoadingCache<Long, AtomicLong>> counters
= new ConcurrentHashMap<>();
@Override
public Object handle(ProceedingJoinPoint pjp, RateLimiterMethod rateLimiterMethod) throws Throwable {
String rateLimiterKey = createRateLimiterKey(pjp, rateLimiterMethod);
logger.info("counterRateLimiter handle start,rateLimiterKey:{}", rateLimiterKey);
LoadingCache<Long, AtomicLong> counter = createCouter(rateLimiterKey, rateLimiterMethod);
//获取当前时间戳,然后取秒数来作为key进行计数统计和限流
long currentSecond = System.currentTimeMillis() / 1000;
long qps = rateLimiterMethod.qps();
AtomicLong atomicLong = counter.get(currentSecond);
if (atomicLong == null) {
logger.info("counter is null,method:{}", pjp.getSignature().toLongString());
return pjp.proceed();
}
if (atomicLong.incrementAndGet() <= qps) {
return pjp.proceed();
}
//被限流后,进入限流处理逻辑
return fallBackMethodExecute(rateLimiterKey, pjp, rateLimiterMethod);
}
/**
* 构造计数器,保证多线程环境下相同key对应的value不会被覆盖,且返回值相同
*
* @param key 相同key返回同一个计数器
* @param rateLimiterMethod
* @return
*/
private LoadingCache<Long, AtomicLong> createCouter(String key, RateLimiterMethod rateLimiterMethod) {
LoadingCache<Long, AtomicLong> result = counters.get(key);
if (result == null) {
//Guava Cache来存储计数器,过期时间设置为2秒(保证1秒内的计数器是有效的)
LoadingCache<Long, AtomicLong> value = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS)
.build(new CacheLoader<Long, AtomicLong>() {
@Override
public AtomicLong load(Long seconds) throws Exception {
return new AtomicLong(0);
}
});
result = value;
LoadingCache<Long, AtomicLong> putByOtherThread = counters.putIfAbsent(key, value);
//有其他线程写入了值
if (putByOtherThread != null) {
result = putByOtherThread;
}
}
return result;
}
@Override
public void afterPropertiesSet() throws Exception {
RateLimiterStrategyFactory.register(RateLimiterType.COUNTER_RATELIMITER, this);
}
}
|
package quizzlr.user;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import quizzlr.backend.Message;
import quizzlr.backend.User;
/**
* Servlet implementation class MessageReplyServlet
*/
@WebServlet("/MessageReplyServlet")
public class MessageReplyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MessageReplyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession userSession = request.getSession();
User user = (User) userSession.getAttribute("User");
if (user == null) return;
String nextPage = null;
Message message = Message.getMessageFromID(Integer.parseInt(request.getParameter("messageID")));
User fromUser = message.getFromUser();
if (message.getMessageType() == 1) {
if (request.getParameter("accept").equals("yes") && !user.isFriendOf(fromUser)) {
user.addFriend(fromUser);
}
//remove this and all previous friend requests from same user
List<Message> messages = user.getMessages();
for (Message m : messages) {
if (m.getMessageType() == 1 && m.getFromUser().equals(fromUser)) {
m.delete();
}
}
nextPage = "inbox.jsp";
} else if (message.getMessageType() == 3) {
if (request.getParameter("action").equals("delete")) {
message.delete();
nextPage = "inbox.jsp";
}
} else if (message.getMessageType() == 2) {
message.delete();
nextPage = "inbox.jsp";
}
RequestDispatcher dispatch = request.getRequestDispatcher(nextPage);
dispatch.forward(request, response);
}
}
|
package com.moon.institution.service;
import com.moon.dto.SpringDITest;
import com.moon.institution.entity.Institution;
public interface IInstitutionService {
/**
* 查询机构评价
* @return 机构信息
*/
Institution getInstitutionByItem(String id);
}
|
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.FailureMode;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.concurrent.CancellationException;
import javax.servlet.annotation.WebServlet;
/**
* Created by Bhuvie on 3/26/2017.
*/
@WebServlet("/checkperf")
public class checkperf extends javax.servlet.http.HttpServlet {
private static final String url = "jdbc:mysql://bhuviedbi.cwyiughlbpf0.us-west-2.rds.amazonaws.com:3306/bhuviedb";
private static final String user = "bhuvie93";
private static final String pass = "**************";
MemcachedClient mc;
//Statement DataBaseStatement;
Connection con;
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//ArrayList<String> teamlist =new ArrayList<String>();
String noqtimes=request.getParameter("txtquerytimes");
Memcache();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, pass);
//DataBaseStatement = con.createStatement();
PreparedStatement ps = con.prepareStatement("select * from bhuviedb.networktraffic " );
//ps.setString(1,"");
ResultSet rs;
long timebefore=System.currentTimeMillis();
String cond;
cond = (String) mc.get("mykey");
if(cond==null)
{
rs = ps.executeQuery();
String arr = "";
while (rs.next()) {
arr = arr+rs.getString("date");
//System.out.println(arr);
}
mc.set("mykey",10000,arr);
}
String a;
for (int i = 0; i < Integer.parseInt(noqtimes); i++)
{
a=(String) mc.get("mykey");
System.out.println("Out: "+a);
}
mc.flush();
long timeafter=System.currentTimeMillis();
long timetaken=timeafter-timebefore;
con.close();
PrintWriter pw = response.getWriter().append(Long.toString(timetaken));
pw.close();
// while(rs.next())
// {
// String tname=rs.getString("teamname");
// teamlist.add(tname);
// }
} catch (ClassNotFoundException e) {
e.printStackTrace();
// PrintWriter pw = response.getWriter().append(e.toString());
// pw.close();
} catch (SQLException e) {
e.printStackTrace();
// PrintWriter pw = response.getWriter().append(e.toString());
// pw.close();
}
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doPost(request,response);
}
public void Memcache()
{
//AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" },
// new PlainCallbackHandler("##############", "##################"));
try {
mc = new MemcachedClient(new ConnectionFactoryBuilder()
.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY).setDaemon(true).setFailureMode(FailureMode.Retry).build(), AddrUtil.getAddresses("dbccdemo.uwgzbd.cfg.usw2.cache.amazonaws.com:11211"));
// mc.set("mykey",10000,arr);
//System.out.println(mc.get("foo"));
} catch (IOException ioe) {
System.err.println("Couldn't create a connection to MemCachier: \nIOException "
+ ioe.getMessage());
}
}
}
|
package com.cmpickle.volumize.view.profile;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cmpickle.volumize.Inject.Injector;
import com.cmpickle.volumize.R;
import com.cmpickle.volumize.view.BaseFragment;
import com.cmpickle.volumize.view.BasePresenter;
import javax.inject.Inject;
import butterknife.BindView;
/**
* @author Cameron Pickle
* Copyright (C) Cameron Pickle (cmpickle) on 4/7/2017.
*/
public class ProfileFragment extends BaseFragment implements ProfileView {
@Inject
ProfilePresenter profilePresenter;
@BindView(R.id.fab_profile)
FloatingActionButton fabProfile;
public ProfileFragment() {
Injector.get().inject(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fabProfile.setOnClickListener(v -> profilePresenter.addProfileClicked());
}
@Override
protected void onSetViewAndRouterOnPresenter() {
profilePresenter.setView(this);
profilePresenter.setRouter((ProfileRouter) getActivity());
}
@Override
protected BasePresenter getPresenter() {
return profilePresenter;
}
}
|
package com.xiaoxiao.service.backend.impl;
import com.xiaoxiao.feign.BlogsFeignServiceClient;
import com.xiaoxiao.pojo.XiaoxiaoLabels;
import com.xiaoxiao.service.backend.LabelFeignService;
import com.xiaoxiao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/11/29:11:08
* @author:shinelon
* @Describe:
*/
@Service
public class LabelFeignServiceImpl implements LabelFeignService
{
@Autowired
private BlogsFeignServiceClient blogsFeignServiceClient;
/**
* 查询全部的标签
* @param page
* @param rows
* @return
*/
@Override
public Result findAllLabel(Integer page, Integer rows)
{
return this.blogsFeignServiceClient.findAllLabel(page,rows);
}
/**
* 修改
* @param labels
* @return
*/
@Override
public Result update(XiaoxiaoLabels labels)
{
return this.blogsFeignServiceClient.update(labels);
}
/**
* 查询一个ID
* @param labelId
* @return
*/
@Override
public Result findLabelById(Long labelId)
{
return this.blogsFeignServiceClient.findLabelById(labelId);
}
/**
* 删除
* @param labelId
* @return
*/
@Override
public Result delete(Long labelId)
{
return this.blogsFeignServiceClient.deleteLabelsById(labelId);
}
/**
* 插入信息
* @param labels
* @return
*/
@Override
public Result insert(XiaoxiaoLabels labels)
{
return this.blogsFeignServiceClient.insert(labels);
}
}
|
package com.dio.api.repositories;
import com.dio.api.model.TypeDate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TypeDateRepository extends JpaRepository<TypeDate, Long> {
}
|
/*
MachineFactory.java
Load and instantiate Machine objects.
Part of the ReplicatorG project - http://www.replicat.org
Copyright (c) 2008 Zach Smith
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package replicatorg.machine;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.Map.Entry;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import replicatorg.app.Base;
public class MachineFactory {
// private constructor: static access only!!!
private MachineFactory() {
// this prevents even the native class from
// calling this ctor as well :
throw new AssertionError();
}
/**
* If possible, create a machine controller for the specified device.
* @param name The name of the machine descriptor in one of the machine XML files.
* @return the machine controller, or null if no descriptor with the given name could be found.
*/
public static Machine load(String name, MachineCallbackHandler callbackHandler) {
Node machineNode = getMachineNode(name);
if (machineNode == null) {
Base.logger.log(Level.SEVERE, "Could not load machine '" + name + "' no machineNode found");
return null;
}
return new Machine(machineNode, callbackHandler);
}
public static Machine loadSimulator() {
return load("3-Axis Simulator", new MachineCallbackHandler());
}
public static Vector<String> getMachineNames() {
Vector<String> v = new Vector<String>();
boolean showExperimental =
Base.preferences.getBoolean("machine.showExperimental", false);
MachineMap mm = getMachineMap();
for (Entry<String, Element> entry : mm.entrySet()) {
// filter out experimental machines of needed
if (!showExperimental) {
String exp = entry.getValue().getAttribute("experimental");
if (exp.length() != 0 && !exp.equals("0")) {
continue;
}
}
v.add(entry.getKey());
}
Collections.sort(v);
return v;
}
static class MachineMap extends HashMap<String,Element> {
};
private static MachineMap machineMap = null;
private static MachineMap getMachineMap() {
if (machineMap == null) {
machineMap = loadMachinesConfig();
}
return machineMap;
}
// look for machine configuration node.
public static Node getMachineNode(String name) {
MachineMap mm = getMachineMap();
if (mm.containsKey(name)) {
return mm.get(name);
}
return null;
}
/** Load all machine descriptors from a single DOM object.
* @see loadMachinesConfig()
* @param dom The parsed XML to scan
* @param machineMap The map to add entries to
*/
private static void addMachinesForDocument(Document dom, MachineMap map) {
// get each machine
NodeList nl = dom.getElementsByTagName("machine");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element)nl.item(i);
NodeList names = e.getElementsByTagName("name");
if (names != null && names.getLength() > 0) {
String mname = names.item(0).getTextContent().trim();
Base.logger.log(Level.FINE,"Adding machine "+mname+" for node "+e.toString());
map.put(mname,e);
}
}
}
/** Load all machine descriptors from a single directory.
* @see loadMachinesConfig()
* @param dir The directory to scan
* @param machineMap The map to add entries to
* @param db A documentbuilder object for parsing
*/
private static void addMachinesForDirectory(File dir, MachineMap machineMap,DocumentBuilder db) {
try {
db.reset(); // Allow reuse of a single DocumentBuilder.
} catch (UnsupportedOperationException uoe) {
// In case they've got a rogue xerces. :(
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
Base.logger.log(Level.SEVERE, "Could not create document builder", e);
}
}
List<String> filenames = Arrays.asList(dir.list());
Collections.sort(filenames); // Files addressed in alphabetical order.
for (String filename : filenames) {
if (!filename.endsWith(".xml") && !filename.endsWith(".XML")) {
continue; // Skip anything with an improper extension
}
File f = new File(dir,filename);
if (f.exists() && f.isFile()) {
Base.logger.log(Level.FINE,"Scanning file "+filename);
try {
Document d = db.parse(f);
addMachinesForDocument(d,machineMap);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/** Load all the machine descriptors from XML. Machine descriptors are looked for in:
* <ol>
* <li>The "machines" directory under the ReplicatorG install directory</li>
* <li>The "~/.replicatorg/machines" directory</li>
* </ol>
* Any files with an .xml extension in these directories will be scanned for machine
* descriptors. Files are scanned in alphabetical order within each directory. If two
* machine descriptors have the same name, the latest-scanned one appears in the machine
* map.
* @return a map of strings to XML Node objects.
*/
private static MachineMap loadMachinesConfig() {
// Create the machine configuration map
MachineMap machineMap = new MachineMap();
try { // Catch unlikely parser configuration exception.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File f = new File("replicatorg/machines");
if (f.exists() && f.isDirectory()) {
addMachinesForDirectory(f, machineMap, db);
}
// f = Base.getUserFile("machines", false);
// if (f.exists() && f.isDirectory()) {
// addMachinesForDirectory(f, machineMap, db);
// }
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return machineMap;
}
}
|
package io.github.nabhosal.secureapp;
import io.github.nabhosal.secureapp.exception.SecurityContextException;
import io.github.nabhosal.secureapp.impl.DelimitedCertificateFormatImpl;
public class SecurityContextBuilder {
/* System property to get certificate path */
private static final String DEFAULT_CERT_SYS_FUNC_NAME = "cv.secureapp.certificate";
/* System property to get ntp server hostname */
// private static final String DEFAULT_NTP_FUNC_NAME = "cv.secureapp.ntpserver";
/* default network server */
private static final String DEFAULT_NS_SERVER = "time-a.nist.gov";
/* Max retry for getting time from ns server */
private static final int DEFAULT_MAX_RETRY_ATTEMPT = 3;
/* for adding exponential time delay between each retry */
private static final int DEFAULT_SEED_EXPONENTIAL_FACTOR = 3;
/**
* Set Periodic interval to refresh TApp time
* e.g. Every Minute = 1000L * 60L
* Hourly = 1000L * 60L * 60L
* Daily = 1000L * 60L * 60L * 24L
*/
private static final long DEFAULT_PERIODIC_INTERVAL = INTERVAL.SECOND.getTime();
private static final CertificateFormat DEFAULT_CERTIFICATE_FORMAT = new DelimitedCertificateFormatImpl();
private String nsServer;
private String certSysFuncName;
private int seedExponentialFactor;
private int maxRetryAttempt;
private long periodicInterval;
private String publicKey;
private boolean useLocalInstanceTime;
public CertificateFormat getCertificateFormat() {
return certificateFormat;
}
public SecurityContextBuilder withCertificateFormat(CertificateFormat certificateFormat) {
this.certificateFormat = certificateFormat;
return this;
}
private CertificateFormat certificateFormat;
private SecurityContextBuilder(String nsServer,
String certSysFuncName,
long periodicInterval,
int seedExponentialFactor,
int maxRetryAttempt,
String publicKey,
CertificateFormat certificateFormat,
boolean useLocalInstanceTime){
this.nsServer = nsServer;
this.certSysFuncName = certSysFuncName;
this.periodicInterval = periodicInterval;
this.seedExponentialFactor = seedExponentialFactor;
this.maxRetryAttempt = maxRetryAttempt;
this.publicKey = publicKey;
this.certificateFormat = certificateFormat;
this.useLocalInstanceTime = useLocalInstanceTime;
}
public static SecurityContextBuilder withDefault(){
return new SecurityContextBuilder(DEFAULT_NS_SERVER,
DEFAULT_CERT_SYS_FUNC_NAME,
DEFAULT_PERIODIC_INTERVAL,
DEFAULT_SEED_EXPONENTIAL_FACTOR,
DEFAULT_MAX_RETRY_ATTEMPT,
"",
DEFAULT_CERTIFICATE_FORMAT,
false);
}
public void initialize(){
if ("".equalsIgnoreCase(publicKey) || publicKey == null)
throw new SecurityContextException("public key is not defined");
SecurityContext.init(this);
}
public SecurityContextBuilder withNSServer(String ns_server) {
this.nsServer = ns_server;
return this;
}
public SecurityContextBuilder useCertificateVariableName(String cert_sys_func_name) {
this.certSysFuncName = cert_sys_func_name;
return this;
}
public SecurityContextBuilder withInterval(long intervalInSec ) {
this.periodicInterval = intervalInSec;
return this;
}
public SecurityContextBuilder withSeedFactor(int seed_exponential_factor) {
this.seedExponentialFactor = seed_exponential_factor;
return this;
}
public SecurityContextBuilder withMaxRetry(int max_retry_attempt) {
this.maxRetryAttempt = max_retry_attempt;
return this;
}
public SecurityContextBuilder withPublicKey(String publicKey) {
this.publicKey = publicKey;
return this;
}
public SecurityContextBuilder useInstanceTime(){
this.useLocalInstanceTime = true;
return this;
}
public String getNsServer() {
return nsServer;
}
public String getCertSysFuncName() {
return certSysFuncName;
}
public int getSeedExponentialFactor() {
return seedExponentialFactor;
}
public int getMaxRetryAttempt() {
return maxRetryAttempt;
}
public long getPeriodicInterval() {
return periodicInterval;
}
public String getPublicKey(){
return publicKey;
}
public boolean isUseLocalInstanceTime() {
return useLocalInstanceTime;
}
public enum INTERVAL
{
SECOND(1000L), MINUTE(SECOND.getTime() * 60L), HOURLY(MINUTE.getTime() * 60L), DAILY(HOURLY.getTime() * 24L);
// declaring private variable for getting values
private long time;
// getter method
public long getTime()
{
return this.time;
}
// enum constructor - cannot be public or protected
private INTERVAL(long time)
{
this.time = time;
}
}
}
|
package org.tibetjungle.web;
public interface WebService{
public Object echo( Object request );
}
|
package com.originspark.drp.models.projects.invoices;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.originspark.drp.models.projects.costs.StockOutCost;
/**
* 出库单
*/
@Entity
@Table(name="invoice_stock_out")
public class StockOutInvoice extends AbstractInvoice{
/**
* 商品列表
*/
@JsonIgnore
@OneToMany(mappedBy="invoice")
private List<StockOutCost> costs;
//TODO 将receiveMan、receiveAddress、receivePhone抽取为trader?
/**
* 联系地址
*/
private String receiveAddress;
/**
* 联系电话
*/
private String receivePhone;
public List<StockOutCost> getCosts() {
return costs;
}
public void setCosts(List<StockOutCost> costs) {
this.costs = costs;
}
public String getReceiveAddress() {
return receiveAddress;
}
public void setReceiveAddress(String receiveAddress) {
this.receiveAddress = receiveAddress;
}
public String getReceivePhone() {
return receivePhone;
}
public void setReceivePhone(String receivePhone) {
this.receivePhone = receivePhone;
}
public int getCostCount(){
return getCosts().size();
}
}
|
package pack1;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.border.MatteBorder;
import java.awt.Color;
import javax.swing.UIManager;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.DropMode;
import java.awt.Toolkit;
public class Admin_Page extends JFrame {
private JPanel contentPane;
private JTable table;
private JLayeredPane layeredPane;
private JPanel ATTENDENCE;
private JPanel USHEUDELE;
private JPanel HOME;
private JTable table_1;
private String val[] = new String[5];
private String val1[] =new String[6];
private String id;
ArrayList<Attendence_obj> userlist;
private JTable table_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Admin_Page frame = new Admin_Page();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void switchpanels(JPanel panel)
{
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
/**
* Create the frame.
*/
public Admin_Page() {
setFont(new Font("Arial Rounded MT Bold", Font.BOLD, 13));
setTitle(" STUDENT MONITERING SYSTEM");
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(Admin_Page.class.getResource("/pack1/images/clipboard-icon.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(560, 120, 750, 450);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
layeredPane = new JLayeredPane();
layeredPane.setBackground(Color.WHITE);
layeredPane.setBorder(new MatteBorder(5, 5, 5, 5, (Color) new Color(255, 0, 255)));
layeredPane.setBounds(10, 66, 722, 324);
contentPane.add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
HOME = new JPanel();
layeredPane.add(HOME, "name_20124511258334");
HOME.setBackground(new Color(255, 182, 193));
HOME.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBackground(new Color(176, 196, 222));
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setIcon(new ImageIcon(Admin_Page.class.getResource("/pack1/images/web.png")));
lblNewLabel_1.setBounds(0, 0, 317, 314);
HOME.add(lblNewLabel_1);
//from here
JLabel lblNewLabel_2 = new JLabel("ENTER ID TO UPDATE");
lblNewLabel_2.setFont(new Font("Tempus Sans ITC", Font.PLAIN, 17));
lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_2.setBounds(379, 74, 264, 60);
HOME.add(lblNewLabel_2);
JLabel lblHappyTeacherStudent = new JLabel("HAPPY TEACHER STUDENT RELATION");
lblHappyTeacherStudent.setFont(new Font("Sitka Subheading", Font.ITALIC, 15));
lblHappyTeacherStudent.setHorizontalAlignment(SwingConstants.CENTER);
lblHappyTeacherStudent.setBounds(336, 13, 338, 54);
HOME.add(lblHappyTeacherStudent);
JTextArea textArea_1 = new JTextArea();
textArea_1.setFont(new Font("Monospaced", Font.PLAIN, 18));
textArea_1.setBounds(432, 147, 166, 40);
HOME.add(textArea_1);
JButton btnNewButton = new JButton("ADDRECORD");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dilognew o = new dilognew();
o.setVisible(true);
for(int i=0; i<=2;i++)
{
id =textArea_1.getText().trim();
Attendence_obj r =new Attendence_obj(id, "","", "", "", "");
userlist = Database2.readDataFromFile();
userlist.add(r);
Database2.writeDatatoFile(userlist);
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 13));
btnNewButton.setIcon(new ImageIcon(Admin_Page.class.getResource("/pack1/images/pencil-icon.png")));
btnNewButton.setBounds(507, 231, 167, 40);
HOME.add(btnNewButton);
ATTENDENCE = new JPanel();
layeredPane.add(ATTENDENCE, "name_15212934468920");
ATTENDENCE.setLayout(null);
JLabel lblEnterUserId = new JLabel("UPDATE THE ATTENDENCE ");
lblEnterUserId.setForeground(new Color(128, 0, 128));
lblEnterUserId.setFont(new Font("Sitka Text", Font.BOLD, 15));
lblEnterUserId.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterUserId.setBounds(224, 13, 247, 24);
ATTENDENCE.add(lblEnterUserId);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 50, 676, 223);
ATTENDENCE.add(scrollPane);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"PAPER", "CLASS", "V CLASS", "PRESENT", "ABSENT"
}
));
/* for(int i=0;i<table.getRowCount();i++)
{
for(int j=0;j<table.getColumnCount();j++)
{
val =(String)table.getValueAt(j, i);
}
}*/
//here wait
scrollPane.setViewportView(table);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String paper,oclass,vclass,present,absent;
Attendence_obj r;
id =textArea_1.getText().trim();
ArrayList<Attendence_obj> userlist1;
//
new SearchAid();
int idfoundpos = SearchAid.searchId(id);
System.out.println("there id" +idfoundpos);
//
new duplicateval();
List<Integer> list1 = duplicateval.searchId(id);
if(idfoundpos == -1)
{
JOptionPane.showMessageDialog(null,"INVALID USER ID");
}
else {
ArrayList<Attendence_obj> list = Database2.readDataFromFile();
Attendence_obj obj;
List<Integer> arr = new ArrayList<>();
for(int z1=0;z1<list1.size();z1++)
{
int f =list1.get(z1);
arr.add(f);
}
int gd=arr.size();
for(int i=0;i<table.getRowCount();i++)
{
for(int j=0;j<table.getColumnCount();j++)
{
val[j] =(String)table.getValueAt(i,j);
}
paper = val[0];
oclass =val[1];
vclass = val[2];
present = val[3];
int v1=Integer.parseInt(val[1]);
int v2= Integer.parseInt(val[3]);
int val= v1-v2;
absent = Integer.toString(val);
if(gd>0)
{
int k=0;
obj = list.get(list1.get(k));
obj.setId(id);
obj.setPaper(paper);
obj.setVclass(vclass);
obj.setOclass(oclass);
obj.setPresent(present);
obj.setAbsent(absent);
userlist1 = Database2.readDataFromFile();
int z = arr.get(i);
userlist1.set(z,obj);
Database2.writeDatatoFile(userlist1);
k++;
gd--;
}
else
{
System.out.println("nnnnot in");
Attendence_obj obj1;
obj1 =new Attendence_obj(id, paper, oclass, vclass, present, absent);
userlist1 = Database2.readDataFromFile();
userlist1.add(obj1);
Database2.writeDatatoFile(userlist1);
}
}
dilognew ob =new dilognew();
ob.setVisible(true);
}
}
});
btnUpdate.setForeground(new Color(65, 105, 225));
btnUpdate.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnUpdate.setBounds(234, 276, 97, 25);
ATTENDENCE.add(btnUpdate);
JButton btnSearch = new JButton(" SEARCH");
btnSearch.setIcon(new ImageIcon(Admin_Page.class.getResource("/pack1/images/Zoom-icon.png")));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Searchid();
id =textArea_1.getText().trim();
int idfoundpos = Searchid.searchId(id);
if(idfoundpos==-1)
{
JOptionPane.showMessageDialog(null, "the user is not registered");
}
else
{
new duplicateval();
id =textArea_1.getText().trim();
List<Integer> list1 = duplicateval.searchId(id);
ArrayList<Attendence_obj> list = Database2.readDataFromFile();
Attendence_obj obj;
System.out.println("list size "+list1.size());
for(int i=0;i<list1.size();i++)
{
int f = list1.get(i);
obj = list.get(f);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{
obj.getPaper(),
obj.getOclass(),
obj.getVclass(),
obj.getPresent(),
obj.getAbsent(),
});
}
//
new duplicateval2();
id =textArea_1.getText().trim();
List<Integer> list2 = duplicateval2.searchId(id);
ArrayList<Marks_obj> lisst = Databse3.readDataFromFile();
Marks_obj obj1;
for(int i=0;i<list2.size();i++)
{
int f = list1.get(i);
obj1 = lisst.get(f);
DefaultTableModel model = (DefaultTableModel) table_1.getModel();
model.addRow(new Object[]{
obj1.getPapername(),
obj1.getPapercode(),
obj1.getTotalmarks(),
obj1.getMarksobtain(),
obj1.getP_f(),
});
}
new duplicateval3();
id =textArea_1.getText().trim();
List<Integer> listn= duplicateval3.searchId(id);
System.out.println(list1.size());
ArrayList<Routing_obj> listt = DataBase4.readDataFromFile();
Routing_obj objn;
System.out.println("list size"+listt.size());
for(int i=0;i<listn.size();i++)
{
int f = listn.get(i);
objn = listt.get(f);
DefaultTableModel model = (DefaultTableModel) table_2.getModel();
model.addRow(new Object[]{
objn.getPeriod(),
objn.getMrout(),
objn.getTrout(),
objn.getWrout(),
objn.getThrout(),
objn.getFrout(),
});
}
}
}//
});
btnSearch.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 13));
btnSearch.setBounds(348, 231, 147, 40);
HOME.add(btnSearch);
JButton button_2 = new JButton("");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
New_login nl =new New_login();
dispose();
nl.setVisible(true);
}
});
button_2.setIcon(new ImageIcon(Admin_Page.class.getResource("/pack1/images/Apps-Dialog-Logout-icon.png")));
button_2.setBackground(Color.PINK);
button_2.setFont(new Font("Rockwell Condensed", Font.BOLD, 15));
button_2.setBounds(666, 13, 34, 40);
HOME.add(button_2);
JButton btnAddrow = new JButton("ADDROW");
btnAddrow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//id to be set
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{
null,
null,
null,
null,
null,
});
}
});
btnAddrow.setForeground(new Color(65, 105, 225));
btnAddrow.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnAddrow.setBounds(365, 276, 114, 25);
ATTENDENCE.add(btnAddrow);
JButton btnLoadData = new JButton("LOAD DATA");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*ArrayList<Attendence_obj> list;
list = Database2.readDataFromFile();
for(Attendence_obj re : list)
{
DefaultTableModel model = (DefaultTableModel) table.getModel();
//all the content is added in the model type object
model.addRow(new Object[]{
re.getPaper(),
re.getOclass(),
re.getVclass(),
re.getPresent(),
re.getAbsent(),
});*/
new duplicateval();
id =textArea_1.getText().trim();
List<Integer> list1 = duplicateval.searchId(id);
ArrayList<Attendence_obj> list = Database2.readDataFromFile();
Attendence_obj obj;
System.out.println("list size "+list1.size());
for(int i=0;i<list1.size();i++)
{
int f = list1.get(i);
obj = list.get(f);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{
obj.getPaper(),
obj.getOclass(),
obj.getVclass(),
obj.getPresent(),
obj.getAbsent(),
});
}
}
});
btnLoadData.setFont(new Font("Stencil", Font.BOLD, 15));
btnLoadData.setBounds(535, 12, 153, 25);
ATTENDENCE.add(btnLoadData);
USHEUDELE = new JPanel();
layeredPane.add(USHEUDELE, "name_15614272559146");
USHEUDELE.setLayout(null);
JLabel lblUpdateTheShedule = new JLabel("UPDATE THE SHEDULE");
lblUpdateTheShedule.setBounds(258, 13, 201, 20);
lblUpdateTheShedule.setHorizontalAlignment(SwingConstants.CENTER);
lblUpdateTheShedule.setForeground(new Color(128, 0, 128));
lblUpdateTheShedule.setFont(new Font("Sitka Text", Font.BOLD, 15));
USHEUDELE.add(lblUpdateTheShedule);
JScrollPane scrollPane_2 = new JScrollPane();
scrollPane_2.setBounds(12, 46, 676, 210);
USHEUDELE.add(scrollPane_2);
table_2 = new JTable();
table_2.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"PERIOD", "MON", "TUE", "WED", "THUS", "FRI"
}
));
table_2.setFont(new Font("Times New Roman", Font.PLAIN, 13));
scrollPane_2.setViewportView(table_2);
JButton button = new JButton("ADDROW");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model = (DefaultTableModel) table_2.getModel();
model.addRow(new Object[]{
null,
null,
null,
null,
null,
null,
});
}
});
button.setForeground(new Color(65, 105, 225));
button.setFont(new Font("Times New Roman", Font.BOLD, 15));
button.setBounds(379, 269, 111, 25);
USHEUDELE.add(button);
JButton btnUpdate_1 = new JButton("UPDATE");
btnUpdate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String peroid,mrout,trour,wrout,throut,frout;
Routing_obj r;
id =textArea_1.getText().trim();
ArrayList<Routing_obj> userlist3;
//
new SearchAid();
int idfoundpos = Searchid.searchId(id);
//
new duplicateval3();
List<Integer> list1 = duplicateval3.searchId(id);
if(idfoundpos == -1)
{
JOptionPane.showMessageDialog(null,"INVALID USER ID");
}
else {
ArrayList<Routing_obj> list = DataBase4.readDataFromFile();
Routing_obj obj;
List<Integer> arr = new ArrayList<>();
for(int z1=0;z1<list1.size();z1++)
{
int f =list1.get(z1);
arr.add(f);
}
int gd=arr.size();
for(int i=0;i<table_2.getRowCount();i++)
{
for(int j=0;j<table_2.getColumnCount();j++)
{
val1[j] =(String)table_2.getValueAt(i,j);
}
peroid = val1[0];
mrout =val1[1];
trour= val1[2];
wrout= val1[3];
throut =val1[4];
frout = val1[5];
if(gd!=0)
{
int k=0;
obj = list.get(list1.get(k));
obj =new Routing_obj(id,peroid,mrout,trour,wrout,throut,frout);
userlist3 = DataBase4.readDataFromFile();
int z = arr.get(i);
userlist3.set(z,obj);
DataBase4.writeDatatoFile(userlist3);
k++;
gd--;
}
else
{
Routing_obj obj2;
obj2 =new Routing_obj(id,peroid,mrout,trour,wrout,throut,frout);
userlist3 = DataBase4.readDataFromFile();
userlist3.add(obj2);
DataBase4.writeDatatoFile(userlist3);
}
}
dilognew ob =new dilognew();
ob.setVisible(true);
}
}
});
btnUpdate_1.setForeground(new Color(65, 105, 225));
btnUpdate_1.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnUpdate_1.setBounds(232, 269, 111, 25);
USHEUDELE.add(btnUpdate_1);
JPanel UMARKS = new JPanel();
layeredPane.add(UMARKS, "name_20135810357652");
UMARKS.setLayout(null);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(12, 46, 676, 219);
UMARKS.add(scrollPane_1);
table_1 = new JTable();
table_1.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"PAPERCD", "PAPER NAME", "TOTAL MARKS ", "MARKS OBT", "P OR F"
}
));
table_1.getColumnModel().getColumn(1).setPreferredWidth(170);
table_1.getColumnModel().getColumn(2).setPreferredWidth(114);
table_1.getColumnModel().getColumn(3).setPreferredWidth(109);
scrollPane_1.setViewportView(table_1);
JLabel lblUpdateTheMarks = new JLabel("UPDATE THE MARKS");
lblUpdateTheMarks.setHorizontalAlignment(SwingConstants.CENTER);
lblUpdateTheMarks.setForeground(new Color(128, 0, 128));
lblUpdateTheMarks.setFont(new Font("Sitka Text", Font.BOLD, 15));
lblUpdateTheMarks.setBounds(214, 9, 247, 24);
UMARKS.add(lblUpdateTheMarks);
JButton btnAddrows = new JButton("ADDROW");
btnAddrows.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model1 = (DefaultTableModel) table_1.getModel();
model1.addRow(new Object[]{
null,
null,
null,
null,
null,
});
}
});
btnAddrows.setForeground(new Color(65, 105, 225));
btnAddrows.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnAddrows.setBounds(364, 278, 111, 25);
UMARKS.add(btnAddrows);
JButton button_1 = new JButton("UPDATE");
button_1.addActionListener(new ActionListener() {
private ArrayList<Routing_obj> obj2;
public void actionPerformed(ActionEvent e) {
String pcode,pname,tmarks,mobtain,p_f;
Marks_obj r;
id =textArea_1.getText().trim();
ArrayList<Marks_obj> userlist2;
new SearchAid();
int idfoundpos = SearchAid.searchId(id);
new duplicateval2();
List<Integer> list1 = duplicateval2.searchId(id);
if(idfoundpos == -1)
{
JOptionPane.showMessageDialog(null,"INVALID USER ID");
}
else {
ArrayList<Marks_obj> list = Databse3.readDataFromFile();
Marks_obj obj;
List<Integer> arr = new ArrayList<>();
for(int z1=0;z1<list1.size();z1++)
{
int f =list1.get(z1);
arr.add(f);
}
int gd=arr.size();
for(int i=0;i<table_1.getRowCount();i++)
{
for(int j=0;j<table_1.getColumnCount();j++)
{
val[j] =(String)table_1.getValueAt(i,j);
System.out.println("value of j is " +j);
}
pcode = val[0];
pname =val[1];
tmarks = val[2];
mobtain = val[3];
int v1=Integer.parseInt(val[2]);
int v2= Integer.parseInt(val[3]);
int d=v1-v2;
if(d>40)
{
p_f ="pass";
}
else
{
p_f ="fail";
}
if(gd!=0)
{
int k=0;
obj = list.get(list1.get(k));
obj.setId(id);
obj.setPapername(pname);;
obj.setPapercode(pcode);;
obj.setTotalmarks(tmarks);;
obj.setMarksobtain(mobtain);;
obj.setP_f(p_f);
userlist2 = Databse3.readDataFromFile();
int z = arr.get(i);
userlist2.set(z,obj);
Databse3.writeDatatoFile(userlist2);
k++;
gd--;
}
else
{
Marks_obj obj2;
obj2 =new Marks_obj(id, pname, pcode, tmarks, mobtain,p_f);
userlist2 = Databse3.readDataFromFile();
userlist2.add(obj2);
Databse3.writeDatatoFile(userlist2);
}
dilognew ob =new dilognew();
ob.setVisible(true);
}
}
}
});
button_1.setForeground(new Color(65, 105, 225));
button_1.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_1.setBounds(237, 278, 97, 25);
UMARKS.add(button_1);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new MatteBorder(4, 4, 4, 4, (Color) new Color(255, 255, 0)));
panel_1.setBackground(UIManager.getColor("Button.darkShadow"));
panel_1.setBounds(0, 0, 744, 53);
contentPane.add(panel_1);
panel_1.setLayout(null);
JButton btnRegister = new JButton("REGISTER");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
RegistrationForm registrationform = new RegistrationForm();
registrationform.setVisible(true);
dispose();
}
});
btnRegister.setFont(new Font("Rockwell Condensed", Font.BOLD, 15));
btnRegister.setBounds(121, 13, 127, 25);
panel_1.add(btnRegister);
JButton btnAttendence = new JButton("ATTENDENCE");
btnAttendence.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchpanels(ATTENDENCE);
}
});
btnAttendence.setFont(new Font("Rockwell Condensed", Font.BOLD, 15));
btnAttendence.setBounds(260, 13, 140, 25);
panel_1.add(btnAttendence);
JButton btnMarksU = new JButton("MARKS U");
btnMarksU.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
switchpanels(UMARKS);
}
});
btnMarksU.setFont(new Font("Rockwell Condensed", Font.BOLD, 15));
btnMarksU.setBounds(412, 13, 121, 25);
panel_1.add(btnMarksU);
JButton btnUshedule = new JButton("USHEDULE");
btnUshedule.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchpanels(USHEUDELE);
}
});
btnUshedule.setFont(new Font("Rockwell Condensed", Font.BOLD, 15));
btnUshedule.setBounds(545, 13, 155, 25);
panel_1.add(btnUshedule);
JButton btnHome = new JButton("HOME");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchpanels(HOME);
}
});
btnHome.setFont(new Font("Rockwell Condensed", Font.BOLD, 15));
btnHome.setBounds(12, 13, 97, 25);
panel_1.add(btnHome);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 744, 415);
contentPane.add(lblNewLabel);
lblNewLabel.setIcon(new ImageIcon(Admin_Page.class.getResource("/pack1/images/abstract-1846962_1280.jpg")));
}
}
|
package chapter_1_06_Interfaces;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.stream.Stream;
public class NewJava8 implements IFace{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(IFace.getStr());
NewJava8 obj = new NewJava8();
System.out.println(obj.getStrDefault());
Lambda lObj = () -> "lambda object return";
System.out.println(lObj.getStrLambda());
System.out.println(getStrFromLambda(()->"lambda string with no object"));
doSomeLambda(()->{
System.out.println("do lambda 1");
System.out.println("do lambda 2");
});
System.out.println(useBiFunctionWithAandB((a, b) -> a + " " + b));
String[] ss= {"vf", "avsvs", "F"};
Arrays.sort(ss, (a,b)->a.length()-b.length());
System.out.println(Arrays.toString(ss));
Arrays.sort(ss, String::compareToIgnoreCase);
System.out.println(Arrays.toString(ss));
List<String> ssList = Arrays.asList(ss);
Stream<String> ssStream = ssList.stream();
String[] ssFromStream = ssStream.toArray(String[]::new);
System.out.println("ssFromStream: " + Arrays.toString(ssFromStream));
ssList.sort(Comparator.comparingInt(s -> s.length()));
System.out.println("ssList sort by length: " + ssList);
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "one");
map.put(3, "three");
map.put(5, "five");
System.out.println("search map for value.lentgh=4: " + map.searchValues(5, v -> v.length()==4?v:null));
System.out.println("reduce all values.length>3: " + map.reduce(5, (k, v) -> v.length()>3? v+ " ": null, String::concat));
}
static String getStrFromLambda(Lambda l) {
return l.getStrLambda();
}
static void doSomeLambda(LambdaVoid lv) {
lv.doLambda();
}
static String useBiFunctionWithAandB(BiFunction<String, String, String> f) {
return f.apply("A", "B");
}
}
interface IFace {
public static String getStr() {
return "String from Interface";
}
default String getStrDefault() {
return "Defaule string from Interface";
}
}
interface Lambda {
String getStrLambda();
}
interface LambdaVoid {
void doLambda();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.