hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923d89a4a914fe70f0d3be68a1b5174405eabb05 | 217 | java | Java | src/main/java/gamma02/vtubersparadise/features/SussyBakaUwu.java | gamma-02/VTubersParadise | 0b39aee84592adf3f409a9108a59504ef9987b13 | [
"MIT"
] | null | null | null | src/main/java/gamma02/vtubersparadise/features/SussyBakaUwu.java | gamma-02/VTubersParadise | 0b39aee84592adf3f409a9108a59504ef9987b13 | [
"MIT"
] | null | null | null | src/main/java/gamma02/vtubersparadise/features/SussyBakaUwu.java | gamma-02/VTubersParadise | 0b39aee84592adf3f409a9108a59504ef9987b13 | [
"MIT"
] | null | null | null | 19.727273 | 42 | 0.801843 | 1,000,368 | package gamma02.vtubersparadise.features;
import net.minecraft.inventory.IInventory;
import net.minecraft.util.math.BlockPos;
import java.util.HashMap;
public interface SussyBakaUwu {
boolean loaded = false;
}
|
923d8a61d0a731aaa97da96ebd24a007c1f14980 | 4,891 | java | Java | components/camel-http/src/main/java/org/apache/camel/component/http/HttpEntityConverter.java | LittleEntity/camel | da0d257a983859c25add75047498aa2aa319d7e2 | [
"Apache-2.0"
] | 4,262 | 2015-01-01T15:28:37.000Z | 2022-03-31T04:46:41.000Z | components/camel-http/src/main/java/org/apache/camel/component/http/HttpEntityConverter.java | LittleEntity/camel | da0d257a983859c25add75047498aa2aa319d7e2 | [
"Apache-2.0"
] | 3,408 | 2015-01-03T02:11:17.000Z | 2022-03-31T20:07:56.000Z | components/camel-http/src/main/java/org/apache/camel/component/http/HttpEntityConverter.java | LittleEntity/camel | da0d257a983859c25add75047498aa2aa319d7e2 | [
"Apache-2.0"
] | 5,505 | 2015-01-02T14:58:12.000Z | 2022-03-30T19:23:41.000Z | 40.421488 | 115 | 0.653445 | 1,000,369 | /*
* 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.camel.component.http;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.camel.Converter;
import org.apache.camel.Exchange;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.GZIPHelper;
import org.apache.http.HttpEntity;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
/**
* Some converter methods to make it easier to convert the body to RequestEntity types.
*/
@Converter(generateLoader = true)
public final class HttpEntityConverter {
private HttpEntityConverter() {
}
@Converter
public static HttpEntity toHttpEntity(byte[] data, Exchange exchange) throws Exception {
return asHttpEntity(data, exchange);
}
@Converter
public static HttpEntity toHttpEntity(InputStream inStream, Exchange exchange) throws Exception {
return asHttpEntity(inStream, exchange);
}
@Converter
public static HttpEntity toHttpEntity(String str, Exchange exchange) throws Exception {
if (exchange != null && GZIPHelper.isGzip(exchange.getIn())) {
byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, str);
return asHttpEntity(data, exchange);
} else {
// will use the default StringRequestEntity
return null;
}
}
private static HttpEntity asHttpEntity(InputStream in, Exchange exchange) throws IOException {
InputStreamEntity entity;
if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
String contentEncoding = exchange.getIn().getHeader(Exchange.CONTENT_ENCODING, String.class);
InputStream stream = GZIPHelper.compressGzip(contentEncoding, in);
entity = new InputStreamEntity(
stream, stream instanceof ByteArrayInputStream
? stream.available() != 0 ? stream.available() : -1 : -1);
} else {
entity = new InputStreamEntity(in, -1);
}
if (exchange != null) {
String contentEncoding = exchange.getIn().getHeader(Exchange.CONTENT_ENCODING, String.class);
if (contentEncoding != null) {
entity.setContentEncoding(contentEncoding);
}
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null) {
entity.setContentType(contentType);
}
}
return entity;
}
private static HttpEntity asHttpEntity(byte[] data, Exchange exchange) throws Exception {
AbstractHttpEntity entity;
String contentEncoding = null;
if (exchange != null) {
contentEncoding = exchange.getIn().getHeader(Exchange.CONTENT_ENCODING, String.class);
}
if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
boolean gzip = GZIPHelper.isGzip(contentEncoding);
if (gzip) {
InputStream stream = GZIPHelper.compressGzip(contentEncoding, data);
entity = new InputStreamEntity(
stream, stream instanceof ByteArrayInputStream
? stream.available() != 0 ? stream.available() : -1 : -1);
} else {
// use a byte array entity as-is
entity = new ByteArrayEntity(data);
}
} else {
// create the Repeatable HttpEntity
entity = new ByteArrayEntity(data);
}
if (exchange != null) {
if (contentEncoding != null) {
entity.setContentEncoding(contentEncoding);
}
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null) {
entity.setContentType(contentType);
}
}
return entity;
}
}
|
923d8a7fe03f8beda0d3d32bde75b774e54d62f9 | 2,049 | java | Java | ph-oton-connect/src/main/java/com/helger/photon/connect/config/ThirdPartyModuleProvider_ph_oton_connect.java | Dafnik/ph-oton | 50b8cbebb57ca224fec8e9509d26b53a82377c2e | [
"Apache-2.0"
] | null | null | null | ph-oton-connect/src/main/java/com/helger/photon/connect/config/ThirdPartyModuleProvider_ph_oton_connect.java | Dafnik/ph-oton | 50b8cbebb57ca224fec8e9509d26b53a82377c2e | [
"Apache-2.0"
] | null | null | null | ph-oton-connect/src/main/java/com/helger/photon/connect/config/ThirdPartyModuleProvider_ph_oton_connect.java | Dafnik/ph-oton | 50b8cbebb57ca224fec8e9509d26b53a82377c2e | [
"Apache-2.0"
] | null | null | null | 40.98 | 125 | 0.664714 | 1,000,370 | /*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.photon.connect.config;
import javax.annotation.Nullable;
import com.helger.commons.annotation.IsSPIImplementation;
import com.helger.commons.thirdparty.ELicense;
import com.helger.commons.thirdparty.IThirdPartyModule;
import com.helger.commons.thirdparty.IThirdPartyModuleProviderSPI;
import com.helger.commons.thirdparty.ThirdPartyModule;
import com.helger.commons.version.Version;
import com.helger.jsch.config.ThirdPartyModuleProvider_ph_jsch;
/**
* Implement this SPI interface if your JAR file contains external third party
* modules.
*
* @author Philip Helger
*/
@IsSPIImplementation
public final class ThirdPartyModuleProvider_ph_oton_connect implements IThirdPartyModuleProviderSPI
{
public static final IThirdPartyModule COMMONS_NET = new ThirdPartyModule ("Apache Commons Net",
"Apache",
ELicense.APACHE2,
new Version (3, 8, 0),
"http://commons.apache.org/proper/commons-net/");
@Nullable
public IThirdPartyModule [] getAllThirdPartyModules ()
{
return new IThirdPartyModule [] { ThirdPartyModuleProvider_ph_jsch.JSCH, COMMONS_NET };
}
}
|
923d8b883b399c6f36aebae369be25fa769dc481 | 226 | java | Java | app/src/main/java/map_generator/MapGenerator.java | kapistelijaKrisu/a-stars-in-map | 7ad10a365303c72c8cee834c44081e3066fc3fc6 | [
"MIT"
] | null | null | null | app/src/main/java/map_generator/MapGenerator.java | kapistelijaKrisu/a-stars-in-map | 7ad10a365303c72c8cee834c44081e3066fc3fc6 | [
"MIT"
] | 1 | 2019-02-12T09:04:37.000Z | 2019-02-18T15:47:00.000Z | app/src/main/java/map_generator/MapGenerator.java | kapistelijaKrisu/a-stars-in-map | 7ad10a365303c72c8cee834c44081e3066fc3fc6 | [
"MIT"
] | 1 | 2019-02-20T18:05:54.000Z | 2019-02-20T18:05:54.000Z | 15.066667 | 55 | 0.668142 | 1,000,371 | package map_generator;
import model.web.WebMap;
/**
* Interface for generating a WebMap
*/
public interface MapGenerator {
/**
* @return WebMap for a AnalysableAlgorithm to use.
*/
WebMap createMap();
}
|
923d8c13d3ba086eb63592e1d342d8909aabf741 | 4,872 | java | Java | src/com/print_stack_trace/voogasalad/model/engine/physics/CollisionDetector.java | ngbalk/VOOGASalad | a43ebbf29f7e48f204f144b1165837c97f897cc3 | [
"MIT"
] | 1 | 2016-11-02T22:55:20.000Z | 2016-11-02T22:55:20.000Z | src/com/print_stack_trace/voogasalad/model/engine/physics/CollisionDetector.java | ngbalk/VOOGASalad | a43ebbf29f7e48f204f144b1165837c97f897cc3 | [
"MIT"
] | null | null | null | src/com/print_stack_trace/voogasalad/model/engine/physics/CollisionDetector.java | ngbalk/VOOGASalad | a43ebbf29f7e48f204f144b1165837c97f897cc3 | [
"MIT"
] | null | null | null | 45.53271 | 134 | 0.740764 | 1,000,372 | /**
* Date Created: 11/15/14
* Date Modified: 11/23/14
*/
package com.print_stack_trace.voogasalad.model.engine.physics;
import java.awt.Rectangle;
import com.print_stack_trace.voogasalad.model.engine.authoring.GameAuthorEngine.SpriteType;
import com.print_stack_trace.voogasalad.model.engine.runtime.RuntimeSpriteCharacteristics;
public class CollisionDetector {
/**
* Take in two sprite characteristics, spriteA and spriteB, and determine if a collision happened
* @param spriteA
* @param spriteB
* @return true if a collision happened, false otherwise
*/
public static boolean haveCollided(RuntimeSpriteCharacteristics spriteA, RuntimeSpriteCharacteristics spriteB) {
if(spriteA== null || spriteB==null) { //why does this work
return false;
}
Rectangle rect1 = new Rectangle((int) spriteA.getX(), (int) spriteA.getY(), (int) spriteA.getWidth(), (int) spriteA.getHeight());
Rectangle rect2 = new Rectangle((int) spriteB.getX(), (int) spriteB.getY(), (int) spriteB.getWidth(), (int) spriteB.getHeight());
return rect1.intersects(rect2);
}
public static boolean haveCollidedHorizontally(RuntimeSpriteCharacteristics spriteA, RuntimeSpriteCharacteristics spriteB){
Rectangle rect = makeIntersector(spriteA, spriteB);
return rect.getHeight() > rect.getWidth();
}
public static boolean haveCollidedVertically(RuntimeSpriteCharacteristics spriteA, RuntimeSpriteCharacteristics spriteB){
Rectangle rect = makeIntersector(spriteA, spriteB);
return rect.getWidth() >= rect.getHeight();
}
public static boolean haveCollidedFromTop(RuntimeSpriteCharacteristics hero,
RuntimeSpriteCharacteristics block){
if(incorrectSpriteType(hero)) return false;
Rectangle top = new Rectangle((int) hero.getX(), (int) hero.getY(), (int) hero.getWidth(), (int) hero.getHeight());
Rectangle bottom = new Rectangle((int) block.getX(), (int) block.getY(), (int) block.getWidth(), (int) block.getHeight());
Rectangle intersect = top.intersection(bottom);
setCollidingVertically(hero);
return(top.getY() < intersect.getY() && intersect.getWidth() > intersect.getHeight());
}
public static boolean haveCollidedFromBottom(RuntimeSpriteCharacteristics hero,
RuntimeSpriteCharacteristics block){
if(incorrectSpriteType(hero)) return false;
Rectangle bottom = new Rectangle((int) hero.getX(), (int) hero.getY(), (int) hero.getWidth(), (int) hero.getHeight());
Rectangle top = new Rectangle((int) block.getX(), (int) block.getY(), (int) block.getWidth(), (int) block.getHeight());
Rectangle intersect = top.intersection(bottom);
setCollidingVertically(hero);
return(bottom.getY() < intersect.getY() + intersect.getHeight() && intersect.getWidth() > intersect.getHeight());
}
public static boolean haveCollidedFromLeft(RuntimeSpriteCharacteristics hero,
RuntimeSpriteCharacteristics block){
if(incorrectSpriteType(hero)) return false;
Rectangle left = new Rectangle((int) hero.getX(), (int) hero.getY(), (int) hero.getWidth(), (int) hero.getHeight());
Rectangle right = new Rectangle((int) block.getX(), (int) block.getY(), (int) block.getWidth(), (int) block.getHeight());
Rectangle intersect = left.intersection(right);
setCollidingHorizontally(hero);
return(left.getX() < intersect.getX() && intersect.getHeight() > intersect.getWidth());
}
public static boolean haveCollidedFromRight(RuntimeSpriteCharacteristics hero,
RuntimeSpriteCharacteristics block){
if(incorrectSpriteType(hero)) return false;
Rectangle right = new Rectangle((int) hero.getX(), (int) hero.getY(), (int) hero.getWidth(), (int) hero.getHeight());
Rectangle left = new Rectangle((int) block.getX(), (int) block.getY(), (int) block.getWidth(), (int) block.getHeight());
Rectangle intersect = left.intersection(right);
setCollidingHorizontally(hero);
return(right.getX() >= intersect.getX() && intersect.getHeight() > intersect.getWidth());
}
public static boolean incorrectSpriteType(RuntimeSpriteCharacteristics hero) {
return (!(hero.getObjectType().equals(SpriteType.HERO) || (hero.getObjectType().equals(SpriteType.ENEMY))));
}
public static Rectangle makeIntersector(RuntimeSpriteCharacteristics rs1, RuntimeSpriteCharacteristics rs2) {
Rectangle rect1 = new Rectangle((int) rs1.getX(), (int) rs1.getY(), (int) rs1.getWidth(), (int) rs1.getHeight());
Rectangle rect2 = new Rectangle((int) rs2.getX(), (int) rs2.getY(), (int) rs2.getWidth(), (int) rs2.getHeight());
return rect1.intersection(rect2);
}
public static void setCollidingVertically(RuntimeSpriteCharacteristics hero) {
hero.isCollidingVertically = true;
hero.isCollidingHorizontally = false;
}
public static void setCollidingHorizontally(RuntimeSpriteCharacteristics hero) {
hero.isCollidingVertically = false;
hero.isCollidingHorizontally = true;
}
}
|
923d8cb0ac61d64968400e7aeb6667d997fea44c | 25,820 | java | Java | src/runtime/com/shtick/utils/scratch3/runner/impl/elements/TargetImplementation.java | seanmcox/scratch3-runner-implementation | 7bda630c3918012e862f026a1a30cb63f4009086 | [
"MIT"
] | null | null | null | src/runtime/com/shtick/utils/scratch3/runner/impl/elements/TargetImplementation.java | seanmcox/scratch3-runner-implementation | 7bda630c3918012e862f026a1a30cb63f4009086 | [
"MIT"
] | null | null | null | src/runtime/com/shtick/utils/scratch3/runner/impl/elements/TargetImplementation.java | seanmcox/scratch3-runner-implementation | 7bda630c3918012e862f026a1a30cb63f4009086 | [
"MIT"
] | null | null | null | 27.322751 | 205 | 0.726995 | 1,000,373 | /**
*
*/
package com.shtick.utils.scratch3.runner.impl.elements;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Area;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import javax.swing.SwingUtilities;
import com.shtick.utils.scratch3.runner.core.InvalidScriptDefinitionException;
import com.shtick.utils.scratch3.runner.core.Opcode;
import com.shtick.utils.scratch3.runner.core.OpcodeHat;
import com.shtick.utils.scratch3.runner.core.SoundMonitor;
import com.shtick.utils.scratch3.runner.core.ValueListener;
import com.shtick.utils.scratch3.runner.core.elements.Broadcast;
import com.shtick.utils.scratch3.runner.core.elements.Costume;
import com.shtick.utils.scratch3.runner.core.elements.List;
import com.shtick.utils.scratch3.runner.core.elements.RenderableChild;
import com.shtick.utils.scratch3.runner.core.elements.ScriptContext;
import com.shtick.utils.scratch3.runner.core.elements.Target;
import com.shtick.utils.scratch3.runner.core.elements.Variable;
import com.shtick.utils.scratch3.runner.impl.ScratchRuntimeImplementation;
import com.shtick.utils.scratch3.runner.impl.ScriptThread;
import com.shtick.utils.scratch3.runner.impl.elements.CostumeImplementation;
import com.shtick.utils.scratch3.runner.impl.elements.SoundImplementation;
import com.shtick.utils.scratch3.runner.impl.elements.VariableImplementation;
import com.shtick.utils.scratch3.runner.impl.elements.CostumeImplementation.ImageAndArea;
/**
* @author scox
*
*/
public class TargetImplementation implements Target{
private boolean isStage;
private String name;
private Map<String,ListImplementation> listsByName;
private Map<String,BroadcastImplementation> broadcastsByIDs;
private Map<String,BroadcastImplementation> broadcastsByName;
private ScriptCollection scriptCollection;
private Object comments;
private SoundImplementation[] sounds;
private Map<String,SoundImplementation> soundsByName;
private CostumeImplementation[] costumes;
private long currentCostumeIndex;
private double volume;
private long layerOrder;
// Stage only
private long tempo;
private long videoTransparency;
private String videoState;
private String textToSpeechLanguage;
// Non-stage only
private boolean visible;
private double x;
private double y;
private double size;
private double direction;
private boolean draggable;
private String rotationStyle;
private final Object LOCK = new Object();
private ScratchRuntimeImplementation runtime;
private Map<String,VariableImplementation> variablesByName;
private HashMap<String,LinkedList<ValueListener>> varListeners = new HashMap<>();
private LinkedList<SoundMonitor> activeSoundMonitors = new LinkedList<>();
private TargetImplementation cloneOf;
private HashSet<TargetImplementation> clones = new HashSet<>();
private LinkedList<RenderableChild> children;
private HashMap<String,Double> effects = new HashMap<>();
/**
*
* @param isStage
* @param name
* @param variables
* @param listsByName
* @param broadcastsByIDs
* @param blocks
* @param comments
* @param currentCostume
* @param costumes
* @param sounds
* @param volume
* @param layerOrder
* @param tempo
* @param videoTransparency
* @param videoState
* @param textToSpeechLanguage
* @param visible
* @param x
* @param y
* @param size
* @param direction
* @param draggable
* @param rotationStyle
* @param runtime
* @throws InvalidScriptDefinitionException
*/
public TargetImplementation(boolean isStage, String name, java.util.List<VariableImplementation> variables, Map<String,ListImplementation> listsByName, Map<String,BroadcastImplementation> broadcastsByIDs,
Map<String, BlockImplementation> blocks, Object comments, long currentCostume, CostumeImplementation[] costumes, SoundImplementation[] sounds, double volume,
long layerOrder, long tempo, long videoTransparency, String videoState, String textToSpeechLanguage,
boolean visible, double x, double y, double size, double direction, boolean draggable, String rotationStyle, ScratchRuntimeImplementation runtime) throws InvalidScriptDefinitionException{
this.isStage = isStage;
this.name = name;
if(variables==null) {
variablesByName = new HashMap<>();
}
else {
variablesByName = new HashMap<>(variables.size());
for(VariableImplementation variable:variables)
variablesByName.put(variable.getName(), variable);
}
this.listsByName = listsByName;
this.broadcastsByIDs = broadcastsByIDs;
this.broadcastsByName = new HashMap<>(broadcastsByIDs.size());
for(BroadcastImplementation broadcast:broadcastsByIDs.values())
broadcastsByName.put(broadcast.getName(), broadcast);
this.runtime = runtime;
this.scriptCollection = new ScriptCollection(blocks,this,runtime);
this.comments = comments;
this.currentCostumeIndex = currentCostume;
this.costumes = costumes;
this.sounds = sounds;
soundsByName = new HashMap<>(sounds.length);
for(SoundImplementation sound:sounds)
soundsByName.put(sound.getIdentifier(), sound);
this.volume = volume;
this.layerOrder = layerOrder;
this.tempo = tempo;
this.videoTransparency = videoTransparency;
this.videoState = videoState;
this.textToSpeechLanguage = textToSpeechLanguage;
this.visible = visible;
this.x = x;
this.y = y;
this.size = size;
this.direction = direction;
this.draggable = draggable;
this.rotationStyle = rotationStyle;
if(isStage) {
this.children = new LinkedList<>();
}
else {
this.children = null;
registerWithCostumeImagePool();
}
}
/**
*
* @param isStage
* @param name
* @param variables
* @param lists
* @param broadcastsByIDs
* @param scriptCollection
* @param comments
* @param currentCostume
* @param costumes
* @param sounds
* @param volume
* @param layerOrder
* @param tempo
* @param videoTransparency
* @param videoState
* @param textToSpeechLanguage
* @param visible
* @param x
* @param y
* @param size
* @param direction
* @param draggable
* @param rotationStyle
* @param runtime
*/
private TargetImplementation(boolean isStage, String name, java.util.List<VariableImplementation> variables, Map<String,ListImplementation> lists, Map<String,BroadcastImplementation> broadcastsByIDs,
ScriptCollection scriptCollection, Object comments, long currentCostume, CostumeImplementation[] costumes, SoundImplementation[] sounds, double volume,
long layerOrder, long tempo, long videoTransparency, String videoState, String textToSpeechLanguage,
boolean visible, double x, double y, double size, double direction, boolean draggable, String rotationStyle, ScratchRuntimeImplementation runtime) {
this.isStage = isStage;
this.name = name;
if(variables==null) {
variablesByName = new HashMap<>();
}
else {
variablesByName = new HashMap<>(variables.size());
for(VariableImplementation variable:variables)
variablesByName.put(variable.getName(), variable);
}
this.listsByName = lists;
this.broadcastsByIDs = broadcastsByIDs;
for(BroadcastImplementation broadcast:broadcastsByIDs.values())
broadcastsByName.put(broadcast.getName(), broadcast);
this.runtime = runtime;
this.scriptCollection = scriptCollection.clone(this);
this.comments = comments;
this.currentCostumeIndex = currentCostume;
this.costumes = costumes;
this.sounds = sounds;
soundsByName = new HashMap<>(sounds.length);
for(SoundImplementation sound:sounds)
soundsByName.put(sound.getIdentifier(), sound);
this.volume = volume;
this.layerOrder = layerOrder;
this.tempo = tempo;
this.videoTransparency = videoTransparency;
this.videoState = videoState;
this.textToSpeechLanguage = textToSpeechLanguage;
this.visible = visible;
this.x = x;
this.y = y;
this.size = size;
this.direction = direction;
this.draggable = draggable;
this.rotationStyle = rotationStyle;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#getContextObject()
*/
@Override
public ScriptContext getContextObject() {
if(isStage) {
return null;
}
return runtime.getCurrentStage();
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#getObjName()
*/
@Override
public String getObjName() {
return name;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#getContextListByName(java.lang.String)
*/
@Override
public List getContextListByName(String name) {
if(listsByName.containsKey(name))
return listsByName.get(name);
if(isStage)
return null;
return runtime.getCurrentStage().getContextListByName(name);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#getContextPropertyValueByName(java.lang.String)
*/
@Override
public Object getContextPropertyValueByName(String name) throws IllegalArgumentException {
switch(name) {
case "background#":
return currentCostumeIndex+1; // Translate from 0-index to 1-index
case "volume":
return volume;
}
return getContextVariableValueByName(name);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#playSoundByName(java.lang.String)
*/
@Override
public SoundMonitor playSoundByName(String soundName) {
if(!soundsByName.containsKey(soundName))
return null;
SoundImplementation sound = soundsByName.get(soundName);
return playSound(sound);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#playSoundByIndex(int)
*/
@Override
public SoundMonitor playSoundByIndex(int index) {
if(index<0)
return null;
if(index>=sounds.length)
return null;
SoundImplementation sound = sounds[index];
return playSound(sound);
}
private SoundMonitor playSound(SoundImplementation sound) {
try {
final SoundMonitor monitor = runtime.playSound(sound,volume);
if(monitor!=null) {
activeSoundMonitors.add(monitor);
monitor.addCloseListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
activeSoundMonitors.remove(monitor);
}
});
if(monitor.isDone())
activeSoundMonitors.remove(monitor);
return monitor;
}
}
catch(Throwable t) {
t.printStackTrace();
}
return new SoundMonitor() {
@Override
public boolean isDone() {
return true;
}
@Override
public void addCloseListener(ActionListener listener) {}
@Override
public void removeCloseListener(ActionListener listener) {}
@Override
public void setVolume(double volume) {}
@Override
public void stop() {}
};
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#setVolume(double)
*/
@Override
public void setVolume(double volume) {
this.volume = volume;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#getVolume()
*/
@Override
public double getVolume() {
return volume;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.RenderableChild#isVisible()
*/
@Override
public boolean isVisible() {
return visible;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.RenderableChild#setVisible(boolean)
*/
@Override
public void setVisible(boolean visible) {
this.visible = visible;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getCurrentCostume()
*/
@Override
public Costume getCurrentCostume() {
return costumes[(int)currentCostumeIndex];
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getCurrentCostumeIndex()
*/
@Override
public int getCurrentCostumeIndex() {
return (int)currentCostumeIndex;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#setCurrentCostumeIndex(int)
*/
@Override
public boolean setCurrentCostumeIndex(int i) {
if(currentCostumeIndex == i)
return true;
if((i<0)||(i>=costumes.length))
return false;
currentCostumeIndex = i;
registerWithCostumeImagePool();
runtime.repaintStage();
return true;
}
@Override
public boolean setCostumeByName(String name) {
if(name==null)
return false;
for(int i=0;i<costumes.length;i++) {
if(name.equals(costumes[i].getCostumeName())) {
if(i==currentCostumeIndex)
return true;
costumes[(int)currentCostumeIndex].unregisterSprite(this);
currentCostumeIndex = i;
registerWithCostumeImagePool();
runtime.repaintStage();
return true;
}
}
return false;
}
private void registerWithCostumeImagePool() {
switch(getRotationStyle()) {
case Target.ROTATION_STYLE_NORMAL:
costumes[(int)currentCostumeIndex].registerSprite(this, size,((getDirection()-90+360)%360)*Math.PI/180,false);
break;
case Target.ROTATION_STYLE_LEFT_RIGHT:
costumes[(int)currentCostumeIndex].registerSprite(this, size,0,getDirection()<0);
break;
default:
costumes[(int)currentCostumeIndex].registerSprite(this, size,0,false);
break;
}
}
/**
*
* @return An object containing the appropriate image, center, and bounds information for the identified sprite.
*/
public ImageAndArea getScaledAndRotatedImage() {
return costumes[(int)currentCostumeIndex].getScaledAndRotatedImage(this);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#gotoXY(double, double)
*/
@Override
public void gotoXY(double scratchX, double scratchY) {
x = scratchX;
y = scratchY;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getScratchX()
*/
@Override
public double getScratchX() {
return x;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#setScratchX(double)
*/
@Override
public void setScratchX(double scratchX) {
x = scratchX;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getScratchY()
*/
@Override
public double getScratchY() {
return y;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#setScratchY(double)
*/
@Override
public void setScratchY(double scratchY) {
y = scratchY;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getScale()
*/
@Override
public double getSize() {
return size;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#setScale(double)
*/
@Override
public void setSize(double size) {
if(this.size == size)
return;
this.size = size;
registerWithCostumeImagePool();
runtime.repaintStage();
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getDirection()
*/
@Override
public double getDirection() {
return direction;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#setDirection(double)
*/
@Override
public void setDirection(double direction) {
direction%=360;
if(direction>180)
direction-=360;
else if(direction<-180)
direction+=360;
if(this.direction == direction)
return;
this.direction = direction;
registerWithCostumeImagePool();
runtime.repaintStage();
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#getRotationStyle()
*/
@Override
public String getRotationStyle() {
return rotationStyle;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#setRotationStyle(java.lang.String)
*/
@Override
public void setRotationStyle(String rotationStyle) {
if(this.rotationStyle.equals(rotationStyle))
return;
this.rotationStyle = rotationStyle;
registerWithCostumeImagePool();
runtime.repaintStage();
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Target#isClone()
*/
@Override
public boolean isClone() {
return cloneOf != null;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#stopScripts()
*/
@Override
public void stopScripts() {
if(isStage()) {
runtime.stopAllSounds();
synchronized(children) {
for(Object child:children) {
if(!(child instanceof TargetImplementation))
continue;
((TargetImplementation)child).stopScripts();
}
}
}
ScriptThread scriptTupleThread = runtime.getScriptTupleThread();
scriptTupleThread.stopScriptsByContext(this);
}
/**
* @return the isStage
*/
public boolean isStage() {
return isStage;
}
@Override
public Object getContextVariableValueByName(String name) throws IllegalArgumentException {
if(variablesByName.containsKey(name))
return variablesByName.get(name).getValue();
if(isStage)
return null;
return runtime.getCurrentStage().getContextVariableValueByName(name);
}
@Override
public void setContextVariableValueByName(String name, Object value) throws IllegalArgumentException {
synchronized(LOCK) {
if(variablesByName.containsKey(name)) {
VariableImplementation variable = variablesByName.get(name);
final Object old = variable.getValue();
variable.setValue(value);
if(old.equals(value))
return;
SwingUtilities.invokeLater(()->{
synchronized(LOCK) {
LinkedList<ValueListener> valueListeners = varListeners.get(name);
if(valueListeners == null)
return;
for(ValueListener listener:valueListeners)
listener.valueUpdated(old, value);
}
});
return;
}
if(!isStage)
return;
try {
runtime.getCurrentStage().setContextVariableValueByName(name, value);
}
catch(IllegalArgumentException t) {
throw new IllegalArgumentException("No veriable with the name, "+name+", can be found on the sprite, "+this.name+".", t);
}
}
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.ScriptContext#getContextVariableByName(java.lang.String)
*/
@Override
public Variable getContextVariableByName(String name) {
if(variablesByName.containsKey(name))
return variablesByName.get(name);
if(isStage)
return null;
return runtime.getCurrentStage().getContextVariableByName(name);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.ScriptContext#getContextBroadcastByName(java.lang.String)
*/
@Override
public Broadcast getContextBroadcastByName(String name) {
if(broadcastsByName.containsKey(name))
return broadcastsByName.get(name);
if(isStage)
return null;
return runtime.getCurrentStage().getContextBroadcastByName(name);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#addVariableListener(java.lang.String, com.shtick.utils.scratch.runner.core.ValueListener)
*/
@Override
public void addVariableListener(String var, ValueListener listener) {
synchronized(LOCK) {
if(!variablesByName.containsKey(var)) {
if(!isStage)
runtime.getCurrentStage().addVariableListener(var, listener);
return;
}
if(!varListeners.containsKey(var))
varListeners.put(var,new LinkedList<>());
varListeners.get(var).add(listener);
}
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.ScriptContext#removeVariableListener(java.lang.String, com.shtick.utils.scratch.runner.core.ValueListener)
*/
@Override
public void removeVariableListener(String var, ValueListener listener) {
synchronized(LOCK) {
if(!varListeners.containsKey(var)) {
if(!isStage)
runtime.getCurrentStage().addVariableListener(var, listener);
return;
}
varListeners.get(var).remove(listener);
if(varListeners.get(var).isEmpty())
varListeners.remove(var);
}
}
/**
*
* @param child
*/
public void addChild(RenderableChild child) {
synchronized(children) {
if((child instanceof Target)&&((Target)child).isClone()) {
Target cloneParent = ((Target)child).getCloneParent();
int i = children.indexOf(cloneParent);
children.add(i, child);
}
else {
children.add(child);
}
}
}
/**
*
* @param child
* @return true if the child existed and was removed, and false otherwise.
*/
public boolean removeChild(RenderableChild child) {
synchronized(children) {
return children.remove(child);
}
}
/**
*
* @return An array of RenderableChild objects.
*/
public RenderableChild[] getAllRenderableChildren() {
return children.toArray(new RenderableChild[children.size()]);
}
/**
*
* @param target
* @return true if the target was found and false if not found.
*/
public boolean bringToFront(Target target) {
if(!children.contains(target))
return false;
children.remove(target);
children.add(target);
return true;
}
/**
*
* @param target
* @return true if the target was found and false if not found.
*/
public boolean sendToBack(Target target) {
if(!children.contains(target))
return false;
children.remove(target);
children.addFirst(target);
return true;
}
/**
*
* @param target
* @param n
* @return true if the target was found and false if not found.
*/
public boolean sendBackNLayers(Target target, int n) {
int i = children.indexOf(target);
if(i<0)
return false;
i-=n;
children.remove(target);
children.add(Math.min(Math.max(0, i),children.size()), target);
return true;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core.elements.Sprite#createClone()
*/
@Override
public void createClone() {
if(isStage)
return;
synchronized(LOCK) {
synchronized(this.listsByName) {
ArrayList<VariableImplementation> variables = new ArrayList<>(variablesByName.size());
for(VariableImplementation variable:variablesByName.values())
variables.add(new VariableImplementation(variable.getID(), variable.getValue(),variable.getName()));
HashMap<String, ListImplementation> listsByName = new HashMap<>(this.listsByName.size());
for(String name:this.listsByName.keySet()) {
try {
listsByName.put(name, (ListImplementation)this.listsByName.get(name).clone());
}
catch(CloneNotSupportedException t) {
throw new RuntimeException(t);
}
}
TargetImplementation clone = new TargetImplementation(
false,
name,
variables,
listsByName,
broadcastsByIDs,
scriptCollection,
comments,
currentCostumeIndex,
costumes,
sounds,
volume,
layerOrder,
tempo,
videoTransparency,
videoState,
textToSpeechLanguage,
visible,
x,
y,
size,
direction,
draggable,
rotationStyle,
runtime);
// Clone properties that aren't part of an initial definition in a project file
clone.cloneOf = this;
runtime.addClone(clone);
clones.add(clone);
for(ScriptImplementation script:clone.scriptCollection.getScripts()) {
if("control_start_as_clone".equals(script.getHead().getOpcode()))
runtime.startScript(script);
}
}
}
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#getCloneParent()
*/
@Override
public Target getCloneParent() {
return cloneOf;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#deleteClone()
*/
@Override
public void deleteClone() {
if(!isClone()) {
System.err.println("WARNING: deleteClone() called on non-clone.");
return;
}
// Set clone scripts.
stopScripts();
costumes[(int)currentCostumeIndex].unregisterSprite(this);
for(ScriptImplementation script:scriptCollection.getScripts()) {
BlockImplementation maybeHat = script.getHead();
String opcode = maybeHat.getOpcode();
Opcode opcodeImplementation = runtime.getFeatureSet().getOpcode(opcode);
if((opcodeImplementation != null)&&(opcodeImplementation instanceof OpcodeHat)) {
((OpcodeHat)opcodeImplementation).unregisterListeningScript(script, maybeHat.getArgMap(),maybeHat.getMutation());
}
}
cloneOf.clones.remove(this);
runtime.deleteClone(this);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#getClones()
*/
@Override
public Set<Target> getClones() {
HashSet<Target> retval = new HashSet<>(clones);
for(TargetImplementation clone:clones)
retval.addAll(clone.getClones());
return retval;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#getCostumeCount()
*/
@Override
public int getCostumeCount() {
return costumes.length;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#getEffect(java.lang.String)
*/
@Override
public double getEffect(String name) {
return effects.containsKey(name)?effects.get(name):0;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#setEffect(java.lang.String, double)
*/
@Override
public void setEffect(String name, double value) {
effects.put(name, value);
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#clearEffects()
*/
@Override
public void clearEffects() {
effects.clear();
}
/**
*
* @return
*/
public Map<String,Double> getEffects() {
return effects;
}
/* (non-Javadoc)
* @see com.shtick.utils.scratch.runner.core3.elements.Target#getShape()
*/
@Override
public Area getShape() {
if(!visible)
return new Area();
ImageAndArea imageAndArea = costumes[(int)currentCostumeIndex]
.getScaledAndRotatedImage(this);
if(imageAndArea==null)
return new Area();
return (Area)imageAndArea
.getCostumeArea()
.clone(); // Don't give the original to external entities. (Might have to simply depend on external entities to play nice if this becomes an important performance issue.)
}
}
|
923d8cd292ab077e8297a71ed389561e2aa4fc5c | 316 | java | Java | src/pl/juniorjavadeveloper/java/wwitc/CalculatorPhaseTwo.java | juniorjavadeveloper-pl/java-what-where-in-the-code | 25ba11ecca8afbee75c46ba68960bda86d948f4d | [
"MIT"
] | null | null | null | src/pl/juniorjavadeveloper/java/wwitc/CalculatorPhaseTwo.java | juniorjavadeveloper-pl/java-what-where-in-the-code | 25ba11ecca8afbee75c46ba68960bda86d948f4d | [
"MIT"
] | null | null | null | src/pl/juniorjavadeveloper/java/wwitc/CalculatorPhaseTwo.java | juniorjavadeveloper-pl/java-what-where-in-the-code | 25ba11ecca8afbee75c46ba68960bda86d948f4d | [
"MIT"
] | null | null | null | 28.727273 | 58 | 0.642405 | 1,000,374 | package pl.juniorjavadeveloper.java.wwitc;
public class CalculatorPhaseTwo {
public static int sum(CalculatorInputData inputData) {
System.out.println("sum(" + inputData + ")");
int sum = inputData.getA() + inputData.getB();
System.out.println("sum=" + sum);
return sum;
}
}
|
923d8e7e4d913f53dfcfdd5126c5cdd52d9460c4 | 3,577 | java | Java | src/org/intellij/erlang/ErlangFileType.java | cy6erGn0m/intellij-erlang | 38c5b6a57929a3aa63c4e36c7440eb6a10093b89 | [
"Apache-2.0"
] | 1 | 2015-04-18T12:05:05.000Z | 2015-04-18T12:05:05.000Z | src/org/intellij/erlang/ErlangFileType.java | cy6erGn0m/intellij-erlang | 38c5b6a57929a3aa63c4e36c7440eb6a10093b89 | [
"Apache-2.0"
] | null | null | null | src/org/intellij/erlang/ErlangFileType.java | cy6erGn0m/intellij-erlang | 38c5b6a57929a3aa63c4e36c7440eb6a10093b89 | [
"Apache-2.0"
] | null | null | null | 22.639241 | 75 | 0.684932 | 1,000,375 | /*
* Copyright 2012-2013 Sergey Ignatov
*
* 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.intellij.erlang;
import com.intellij.openapi.fileTypes.LanguageFileType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author ignatov
*/
public class ErlangFileType extends LanguageFileType {
public static ErlangFileType MODULE = new ErlangFileType();
public static HrlFileType HEADER = new HrlFileType();
public static AppFileType APP = new AppFileType();
public static ErlangTermsFileType TERMS = new ErlangTermsFileType();
protected ErlangFileType() {
super(ErlangLanguage.INSTANCE);
}
@NotNull
@Override
public String getName() {
return "Erlang";
}
@NotNull
@Override
public String getDescription() {
return "Erlang";
}
@NotNull
@Override
public String getDefaultExtension() {
return "erl";
}
@Override
public Icon getIcon() {
return ErlangIcons.FILE;
}
@Override
public boolean isJVMDebuggingSupported() {
// turn off for now
return false;
}
public static class HrlFileType extends ErlangFileType {
@NotNull
@Override
public String getName() {
return "Erlang Header";
}
@NotNull
@Override
public String getDescription() {
return "Erlang/OTP Header File";
}
@NotNull
@Override
public String getDefaultExtension() {
return "hrl";
}
@Override
public Icon getIcon() {
return ErlangIcons.HEADER;
}
}
public static class AppFileType extends ErlangFileType {
@NotNull
@Override
public String getName() {
return "Erlang/OTP app";
}
@NotNull
@Override
public String getDescription() {
return "Erlang/OTP Application Resource File";
}
@NotNull
@Override
public String getDefaultExtension() {
return "app";
}
@Override
public Icon getIcon() {
return ErlangIcons.OTP_APP_RESOURCE;
}
}
public static class ErlangTermsFileType extends ErlangFileType {
@NotNull
@Override
public String getName() {
return "Erlang Terms";
}
@NotNull
@Override
public String getDescription() {
return "Erlang Terms File";
}
@NotNull
@Override
public String getDefaultExtension() {
return "config";
}
@Override
public Icon getIcon() {
return ErlangIcons.TERMS;
}
}
@Nullable
public static ErlangFileType getFileType(String filename) {
if (filename == null) return null;
if (filename.endsWith(MODULE.getDefaultExtension())) return MODULE;
if (filename.endsWith(HEADER.getDefaultExtension())) return HEADER;
if (filename.endsWith(APP.getDefaultExtension())) return APP;
if (filename.endsWith(TERMS.getDefaultExtension())) return TERMS;
return null;
}
@Nullable
public static Icon getIconForFile(String filename) {
ErlangFileType fileType = getFileType(filename);
return fileType == null ? null : fileType.getIcon();
}
}
|
923d8ea15a8b180f9615694064f65f75d7226336 | 20,324 | java | Java | app/src/main/java/com/wis/activity/DetectActivity.java | shirdonl/faceAndroid | 632979af01080f3a23431e8fd58bfff50d1c7fd1 | [
"MIT"
] | 6 | 2019-07-28T04:29:22.000Z | 2021-09-16T15:20:38.000Z | app/src/main/java/com/wis/activity/DetectActivity.java | shirdonl/faceAndroid | 632979af01080f3a23431e8fd58bfff50d1c7fd1 | [
"MIT"
] | null | null | null | app/src/main/java/com/wis/activity/DetectActivity.java | shirdonl/faceAndroid | 632979af01080f3a23431e8fd58bfff50d1c7fd1 | [
"MIT"
] | null | null | null | 37.91791 | 179 | 0.557125 | 1,000,376 | package com.wis.activity;
/**
* Created by ybbz on 16/7/28.
*/
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.umeng.analytics.MobclickAgent;
import com.wis.R;
import com.wis.application.WisApplication;
import com.wis.bean.Person;
import com.wis.db.DBManager;
import com.wis.util.ImageUtils;
import com.wis.face.WisUtil;
import com.wis.view.CameraPreview;
import com.wis.view.DrawImageView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
public class DetectActivity extends Activity {
private WisApplication application;
private ImageView detectImageView, similarImageView;
private TextView nameView, resultView;
private FrameLayout previewLayout;
private ActionBar actionBar;
private Camera mCamera;
private CameraPreview mPreview;
public static final int FRONT = 1;
public static final int BACK = 2;
private int currentCameraType = -1;
private Handler handler;
private Runnable runnable;
private int counter = 1;
private Bitmap globalBitmap;
private int globalWidth, globalHeight = 0;
private final static float DIGREE_90 = 90;
private final static float DIGREE_270 = 270;
private DrawImageView drawImageView;
private List<Person> persons;
private DBManager dbManager;
private String globalMaxName = "";
private float globalMaxScore = 0;
private byte[] globalMaxImage = null;
private void test()
{
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/wis/images/1.jpg");
byte[] rgbData = WisUtil.getRGBByBitmap(bmp);
//detect face return face rect(x,y,width,height) in picture
long startTime = System.nanoTime();
int[] ret = application.getWisMobile().detectFace(rgbData, bmp.getWidth(),
bmp.getHeight(), bmp.getWidth() * 3);
long consumingTime = System.nanoTime() - startTime;
Log.i("wisMobile", "detect time " + consumingTime/1000);
Log.i("wisMobile", "detectFace size=" + ret[0] + ",rect(x,y,width,height) = " + ret[1] + "," + ret[2] + "," + ret[3] + "," + ret[4]);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detect);
Log.i("DetectActivity", "onCreate");
if (!checkCamera()) {
finish();
}
application = (WisApplication) getApplication();
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
initView();
initList();
try {
mCamera = openCamera(FRONT);
} catch (Exception e) {
e.printStackTrace();
}
mPreview = new CameraPreview(this, mCamera);
previewLayout.addView(mPreview);
drawImageView = new DrawImageView(DetectActivity.this, null);
drawImageView.setParam(1, 1, 10, 10);
previewLayout.addView(drawImageView);
// mCamera.startPreview();
// mCamera.setPreviewCallback(new Camera.PreviewCallback() {
// @Override
// public void onPreviewFrame(byte[] data, Camera camera) {
// //test();
// Log.i("wisMobile","onPreviewFrame");
// Bitmap bmp = decodeToBitMap(data,camera);
// byte[] rgbData = WisUtil.getRGBByBitmap(bmp);
// //detect face return face rect(x,y,width,height) in picture
// long startTime = System.nanoTime();
// int[] ret = application.getWisMobile().detectFace(rgbData, bmp.getWidth(),
// bmp.getHeight(), bmp.getWidth() * 3);
// long consumingTime = System.nanoTime() - startTime;
// Log.i("wisMobile", "detect time " + consumingTime/1000);
// Log.i("wisMobile", "detectFace size=" + ret[0] + ",rect(x,y,width,height) = " + ret[1] + "," + ret[2] + "," + ret[3] + "," + ret[4]);
//// //人脸标记
// int size = ret[0];
// if (size > 0) {
// int ret_x = ret[1];
// int ret_y = ret[2];
// int ret_width = ret[3];
// int ret_height = ret[4];
// Log.e("wisMobile", "detectFace size=" + size + ",rect(x,y,width,height) = " + ret_x + "," + ret_y + "," + ret_width + "," + ret_height);
//// //drawImageView.setParam(detectRetLeft(ret_x), detectRetTop(ret_y), detectRetRight(ret_x, ret_width), detectRetBottom(ret_y, ret_height));
//// //draw face rect
// Canvas _canvas = new Canvas(bmp);
// Paint _paint = new Paint();
// _paint.setColor(Color.GREEN);
// _paint.setStrokeWidth((float) 3.0); //线宽
// _paint.setStyle(Paint.Style.STROKE); //空心效果
// _canvas.drawRect(ret_x, ret_y, ret_x + ret_width, ret_y + ret_height, _paint);
// }
// //不用多说吧
// bmp.recycle();
// bmp = null;
// }
// });
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
//获取相机预览图
takeSnapPhoto();
if (globalBitmap != null) {
detectImageView.setImageBitmap(globalBitmap);
//人脸检测
//get rgb data buffer from bitmap
byte[] rgbData = WisUtil.getRGBByBitmap(globalBitmap);
//detect face return face rect(x,y,width,height) in picture
long startTime = System.nanoTime();
int[] ret = application.getWisMobile().detectFace(rgbData, globalBitmap.getWidth(), globalBitmap.getHeight(), globalBitmap.getWidth() * 3);
long consumingTime = System.nanoTime() - startTime;
Log.i("wisMobile", "detect time " + consumingTime/1000);
Log.i("wisMobile", "detectFace size=" + ret[0] + ",rect(x,y,width,height) = " + ret[1] + "," + ret[2] + "," + ret[3] + "," + ret[4]);
//人脸标记
int size = ret[0];
if (size > 0) {
int ret_x = ret[1];
int ret_y = ret[2];
int ret_width = ret[3];
int ret_height = ret[4];
Log.e("wisMobile", "detectFace size=" + size + ",rect(x,y,width,height) = " + ret_x + "," + ret_y + "," + ret_width + "," + ret_height);
drawImageView.setParam(detectRetLeft(ret_x), detectRetTop(ret_y), detectRetRight(ret_x, ret_width), detectRetBottom(ret_y, ret_height));
//draw face rect
Canvas _canvas = new Canvas(globalBitmap);
Paint _paint = new Paint();
_paint.setColor(Color.GREEN);
_paint.setStrokeWidth((float) 3.0); //线宽
_paint.setStyle(Paint.Style.STROKE); //空心效果
_canvas.drawRect(ret_x,ret_y, ret_x + ret_width, ret_y + ret_height, _paint);
//相似度计算
int faceRect[] = {ret_x, ret_y, ret_width, ret_height};
startTime = System.nanoTime();
float[] fea = application.getWisMobile().extractFeature(rgbData, globalBitmap.getWidth(), globalBitmap.getHeight(), globalBitmap.getWidth() * 3, faceRect);
consumingTime = System.nanoTime() - startTime;
Log.i("wisMobile", "extractFeature time " + consumingTime/1000);
similarPerson(fea);
//更新界面
if (globalMaxScore >= 0.55) {
similarImageView.setImageBitmap(ImageUtils.BytesToBitmap(globalMaxImage));
nameView.setText("姓名:" + globalMaxName);
resultView.setText("相似度:" + globalMaxScore + "\n" + "计数器:" + counter);
} else {
similarImageView.setImageBitmap(null);
nameView.setText("无匹配");
resultView.setText("无匹配结果" + "\n" + "计数器:" + counter);
}
} else {
similarImageView.setImageBitmap(null);
nameView.setText("无匹配");
resultView.setText("无匹配结果" + "\n" + "计数器:" + counter);
}
}
handler.postDelayed(this, 100);
counter++;
}
};
handler.postDelayed(runnable, 100);//每两秒执行一次
}
private void initView() {
detectImageView = (ImageView) findViewById(R.id.detect_image);
similarImageView = (ImageView) findViewById(R.id.similar_image);
nameView = (TextView) findViewById(R.id.name);
resultView = (TextView) findViewById(R.id.result);
previewLayout = (FrameLayout) findViewById(R.id.camera_preview);
}
private void initList() {
dbManager = new DBManager(this);
persons = dbManager.query();
}
private float[] StringToFloatArray(String feaStr) {
String[] strArray = feaStr.split(",");
float[] floatArray = new float[strArray.length];
for (int i = 0; i < strArray.length; i++) {
floatArray[i] = Float.parseFloat(strArray[i]);
}
return floatArray;
}
private void similarPerson(float[] feature) {
globalMaxScore = 0;
for (int i = 0; i < persons.size(); i++) {
Person person = persons.get(i);
long startTime = System.nanoTime();
float score = application.getWisMobile().compare2Feature(feature, StringToFloatArray(person.feature));
long consumingTime = System.nanoTime() - startTime;
Log.d("wisMobile", "compare2Feature time " + consumingTime/1000);
if (score >= 0.5 && score > globalMaxScore) {
globalMaxScore = score;
globalMaxName = person.name;
globalMaxImage = person.image;
}
}
}
// private Camera openFrontCamera() {
// int cameraCount = 0;
// Camera cam = null;
//
// Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
// cameraCount = Camera.getNumberOfCameras(); // get cameras number
//
// for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
// Camera.getCameraInfo(camIdx, cameraInfo); // get camerainfo
// // 代表摄像头的方位,目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
// if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// try {
// cam = Camera.open(camIdx);
// } catch (RuntimeException e) {
// Log.e("DetectActivity", "Camera failed to open: " + e.getLocalizedMessage());
// }
// }
// }
// return cam;
// }
private boolean checkCamera() {
return DetectActivity.this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
private Camera openCamera(int type) {
int frontIndex = -1;
int backIndex = -1;
int cameraCount = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int cameraIndex = 0; cameraIndex < cameraCount; cameraIndex++) {
Camera.getCameraInfo(cameraIndex, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
frontIndex = cameraIndex;
} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
backIndex = cameraIndex;
}
}
currentCameraType = type;
Camera mCameraDevice = null;
if (type == FRONT && frontIndex != -1) {
mCameraDevice = Camera.open(frontIndex);
Camera.Parameters mParameters = mCameraDevice.getParameters();
List<Camera.Size> size = mParameters.getSupportedPictureSizes();
for(Camera.Size s : size){
Log.i("wisMobile", " capture size width= " + s.width + ", height="+s.height);
}
mParameters.setPreviewSize(640,480);
mParameters.setPictureSize(640,480);
mCameraDevice.setParameters(mParameters);
} else if (type == BACK && backIndex != -1) {
mCameraDevice = Camera.open(backIndex);
}
return mCameraDevice;
}
private void changeCamera() throws IOException {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
if (currentCameraType == FRONT) {
Log.i("DetectActivity", "BACK");
mCamera = openCamera(BACK);
} else if (currentCameraType == BACK) {
Log.i("DetectActivity", "FRONT");
mCamera = openCamera(FRONT);
}
try {
mCamera.setPreviewDisplay(mPreview.getHolder());
mCamera.setDisplayOrientation(getPreviewDegree(DetectActivity.this));
} catch (IOException e) {
e.printStackTrace();
}
Camera.Parameters parameters = mCamera.getParameters(); // 获取各项参数
parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
parameters.setJpegQuality(50); // 设置照片质量
mCamera.startPreview();
}
/**
* http://stackoverflow.com/questions/17682345/how-to-get-android-camera-preview-data
* http://stackoverflow.com/questions/1893072/getting-frames-from-video-image-in-android
*/
private void takeSnapPhoto() {
Log.i("DetectActivity", "takeSnapPhoto");
mCamera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
globalBitmap = decodeToBitMap(data,camera);
Log.i("DetectActivity", "globalBitmap update");
}
});
}
public Bitmap decodeToBitMap(byte[] data, Camera _camera) {
Camera.Size size = mCamera.getParameters().getPreviewSize();
Bitmap bmp = null;
try {
YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
if (image != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, size.width, size.height),80, stream);
bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
stream.close();
Matrix matrix = new Matrix();
switch (currentCameraType) {
case FRONT://前
matrix.preRotate(DIGREE_270);
break;
case BACK://后
matrix.preRotate(DIGREE_90);
break;
}
Log.i("DetectActivity", "DecodeToBitmap");
bmp = Bitmap.createBitmap(bmp, 0, 0, size.width, size.height, matrix, true);
}
} catch (Exception ex) {
Log.e("Sys", "Error:" + ex.getMessage());
}
return bmp;
}
//这个方法存在内存泄漏,导致程序内存溢出,可以pass掉了.
public Allocation renderScriptNV21ToRGBA888(Context context, int width, int height, byte[] nv21) {
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);
Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
in.copyFrom(nv21);
yuvToRgbIntrinsic.setInput(in);
yuvToRgbIntrinsic.forEach(out);
in.destroy();
return out;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detect, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera_switch:
//切换摄像头
Toast.makeText(DetectActivity.this, R.string.camera_switch, Toast.LENGTH_SHORT).show();
try {
changeCamera();
} catch (IOException e) {
e.printStackTrace();
}
break;
case android.R.id.home:
finish();
break;
default:
break;
}
return true;
}
/**
* 用于根据手机方向获得相机预览画面旋转的角度
*
* @param activity
* @return
*/
public int getPreviewDegree(Activity activity) {
// 获得手机的方向
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
// 根据手机的方向计算相机预览画面应该选择的角度
switch (rotation) {
case Surface.ROTATION_0:
degree = 90;
break;
case Surface.ROTATION_90:
degree = 0;
break;
case Surface.ROTATION_180:
degree = 270;
break;
case Surface.ROTATION_270:
degree = 180;
break;
}
return degree;
}
private int detectRetLeft(int x) {
int result;
if (x < 0) {
result = 0;
} else if (x > globalWidth) {
result = globalWidth;
} else {
result = x;
}
return result;
}
private int detectRetTop(int y) {
int result;
if (y < 0) {
result = 0;
} else if (y > globalHeight) {
result = globalHeight;
} else {
result = y;
}
return result;
}
private int detectRetRight(int x, int w) {
int result;
if (x + w < 0) {
result = 0;
} else if (x + w > globalWidth) {
result = globalWidth;
} else {
result = x + w;
}
return result;
}
private int detectRetBottom(int y, int h) {
int result;
if (y + h < 0) {
result = 0;
} else if (y + h > globalHeight) {
result = globalHeight;
} else {
result = y + h;
}
return result;
}
@Override
public void onBackPressed() {
super.onBackPressed();
onDestroy();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("DetectActivity", "onDestroy");
handler.removeCallbacks(runnable);
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
} |
923d8f0d43868c85ce52564ae817184992b5e542 | 1,484 | java | Java | base/common/src/main/java/cn/ulyer/common/oauth/Oauth2User.java | JackGirl/start-base | 76ba1c26a91826a23613d56488dad9e79459141f | [
"Apache-2.0"
] | null | null | null | base/common/src/main/java/cn/ulyer/common/oauth/Oauth2User.java | JackGirl/start-base | 76ba1c26a91826a23613d56488dad9e79459141f | [
"Apache-2.0"
] | null | null | null | base/common/src/main/java/cn/ulyer/common/oauth/Oauth2User.java | JackGirl/start-base | 76ba1c26a91826a23613d56488dad9e79459141f | [
"Apache-2.0"
] | null | null | null | 18.55 | 68 | 0.692722 | 1,000,377 | package cn.ulyer.common.oauth;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
@Data
public class Oauth2User implements UserDetails {
private Long id;
private String account;
@JsonIgnore
private String password;
private String username;
private String orgId;
private Date createTime;
private Date updateTime;
private String remark;
private String avatar;
private Integer accountLocked;
private Integer accountExpired;
private Integer passwordExpired;
private Integer enable;
private Set<Oauth2Authority> authorities;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.account;
}
@Override
public boolean isAccountNonExpired() {
return accountExpired==0;
}
@Override
public boolean isAccountNonLocked() {
return accountLocked==0;
}
@Override
public boolean isCredentialsNonExpired() {
return passwordExpired==0;
}
@Override
public boolean isEnabled() {
return enable==1;
}
}
|
923d8f4d6ee2af98b00bd8c38ab0e98acc40d051 | 837 | java | Java | src/com/sasakirione/main/pokemon/clone/constant/CalculationConst.java | sasakirione/PokemonClone | 8de4057ea9145c72311ed331920d7d19407626d9 | [
"MIT"
] | null | null | null | src/com/sasakirione/main/pokemon/clone/constant/CalculationConst.java | sasakirione/PokemonClone | 8de4057ea9145c72311ed331920d7d19407626d9 | [
"MIT"
] | null | null | null | src/com/sasakirione/main/pokemon/clone/constant/CalculationConst.java | sasakirione/PokemonClone | 8de4057ea9145c72311ed331920d7d19407626d9 | [
"MIT"
] | null | null | null | 44.052632 | 77 | 0.724014 | 1,000,378 | package com.sasakirione.main.pokemon.clone.constant;
public class CalculationConst {
private CalculationConst() {throw new AssertionError("これはインスタンス化しないで!");}
public static final double ONE_POINT_FIVE = 6144.0 / 4096.0;
public static final double TWO = 8192.0 / 4096.0;
public static final double ONE_POINT_TWO = 4915.0 / 4096.0;
public static final double HALF = 2048.0 / 4096.0;
public static final double ONE_POINT_THREE = 5325.0 / 4096.0;
public static final double ONE_POINT_THREE_AURA = 5448.0 / 4096.0;
public static final double ONE_POINT_THREE_ORB = 5324.0 / 4096.0;
public static final double THREE_QUARTER = 3072.0 / 4096.0;
public static final double ONE = 1.0;
public static final double ONE_EIGHTH = 1.0 / 8.0;
public static final double ONE_POINT_SIXTEEN = 1.0 / 16.0;
}
|
923d903418db3061fc668a9899d44c6a52f058f3 | 1,068 | java | Java | Moves/UpdateVariable.java | nDerroitte/Klondike | 1451e4178280010a5bcb104a8431a5f05aeb8868 | [
"Apache-2.0"
] | null | null | null | Moves/UpdateVariable.java | nDerroitte/Klondike | 1451e4178280010a5bcb104a8431a5f05aeb8868 | [
"Apache-2.0"
] | null | null | null | Moves/UpdateVariable.java | nDerroitte/Klondike | 1451e4178280010a5bcb104a8431a5f05aeb8868 | [
"Apache-2.0"
] | null | null | null | 24.837209 | 70 | 0.685393 | 1,000,379 | package be.ac.ulg.montefiore.oop.Moves;
import be.ac.ulg.montefiore.oop.Handlers.Handler;
import be.ac.ulg.montefiore.oop.Klondike.Cards;
/**
* Classe servant à mettre a jour les variables de modifications
* du plateau de jeu
*
* @author Natan Derroitte
*/
public class UpdateVariable extends Handler
{
/**
* Méthode permettant d'obtenir la dernière carte du waste visuelle,
* soit la première à bouger en cas de mouvement à partir du waste.
*
* @param waste
* Le paquet 'waste'.
* @param stock
* Le stock de carte
* @return
* Première carte à bouger en cas de mouvement à partir du waste.
*/
public Cards firstWasteCard (Cards waste,Cards stock)
{
if(waste==null)
return null;
int compteur = super.getCount(waste);
Cards firstWasteCard;
if (compteur == 1 || ( stock == null && compteur%3==1))
firstWasteCard = waste;
else if (compteur ==2||( stock == null && compteur%3==2))
firstWasteCard = waste.cardAbove;
else
firstWasteCard = waste.cardAbove.cardAbove;
return firstWasteCard;
}
}
|
923d9312138ca8aac8517c5b1daf0526191632ca | 14,736 | java | Java | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/ListReservationsRequest.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 1 | 2019-02-08T21:30:20.000Z | 2019-02-08T21:30:20.000Z | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/ListReservationsRequest.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/ListReservationsRequest.java | vprus/aws-sdk-java | af5c13133d936aa0586772b14847064118150b27 | [
"Apache-2.0"
] | 1 | 2021-09-08T09:31:32.000Z | 2021-09-08T09:31:32.000Z | 32.819599 | 123 | 0.613735 | 1,000,380 | /*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.medialive.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* Placeholder documentation for ListReservationsRequest
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/ListReservations" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListReservationsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/** Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO' */
private String codec;
private Integer maxResults;
/**
* Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
*/
private String maximumBitrate;
/** Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS' */
private String maximumFramerate;
private String nextToken;
/** Filter by resolution, 'SD', 'HD', or 'UHD' */
private String resolution;
/** Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL' */
private String resourceType;
/**
* Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
*/
private String specialFeature;
/**
* Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
*/
private String videoQuality;
/**
* Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO'
*
* @param codec
* Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO'
*/
public void setCodec(String codec) {
this.codec = codec;
}
/**
* Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO'
*
* @return Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO'
*/
public String getCodec() {
return this.codec;
}
/**
* Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO'
*
* @param codec
* Filter by codec, 'AVC', 'HEVC', 'MPEG2', or 'AUDIO'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withCodec(String codec) {
setCodec(codec);
return this;
}
/**
* @param maxResults
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* @return
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* @param maxResults
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
*
* @param maximumBitrate
* Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
*/
public void setMaximumBitrate(String maximumBitrate) {
this.maximumBitrate = maximumBitrate;
}
/**
* Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
*
* @return Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
*/
public String getMaximumBitrate() {
return this.maximumBitrate;
}
/**
* Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
*
* @param maximumBitrate
* Filter by bitrate, 'MAX_10_MBPS', 'MAX_20_MBPS', or 'MAX_50_MBPS'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withMaximumBitrate(String maximumBitrate) {
setMaximumBitrate(maximumBitrate);
return this;
}
/**
* Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS'
*
* @param maximumFramerate
* Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS'
*/
public void setMaximumFramerate(String maximumFramerate) {
this.maximumFramerate = maximumFramerate;
}
/**
* Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS'
*
* @return Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS'
*/
public String getMaximumFramerate() {
return this.maximumFramerate;
}
/**
* Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS'
*
* @param maximumFramerate
* Filter by framerate, 'MAX_30_FPS' or 'MAX_60_FPS'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withMaximumFramerate(String maximumFramerate) {
setMaximumFramerate(maximumFramerate);
return this;
}
/**
* @param nextToken
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* @return
*/
public String getNextToken() {
return this.nextToken;
}
/**
* @param nextToken
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Filter by resolution, 'SD', 'HD', or 'UHD'
*
* @param resolution
* Filter by resolution, 'SD', 'HD', or 'UHD'
*/
public void setResolution(String resolution) {
this.resolution = resolution;
}
/**
* Filter by resolution, 'SD', 'HD', or 'UHD'
*
* @return Filter by resolution, 'SD', 'HD', or 'UHD'
*/
public String getResolution() {
return this.resolution;
}
/**
* Filter by resolution, 'SD', 'HD', or 'UHD'
*
* @param resolution
* Filter by resolution, 'SD', 'HD', or 'UHD'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withResolution(String resolution) {
setResolution(resolution);
return this;
}
/**
* Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL'
*
* @param resourceType
* Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL'
*/
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
/**
* Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL'
*
* @return Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL'
*/
public String getResourceType() {
return this.resourceType;
}
/**
* Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL'
*
* @param resourceType
* Filter by resource type, 'INPUT', 'OUTPUT', or 'CHANNEL'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withResourceType(String resourceType) {
setResourceType(resourceType);
return this;
}
/**
* Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
*
* @param specialFeature
* Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
*/
public void setSpecialFeature(String specialFeature) {
this.specialFeature = specialFeature;
}
/**
* Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
*
* @return Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
*/
public String getSpecialFeature() {
return this.specialFeature;
}
/**
* Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
*
* @param specialFeature
* Filter by special feature, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withSpecialFeature(String specialFeature) {
setSpecialFeature(specialFeature);
return this;
}
/**
* Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
*
* @param videoQuality
* Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
*/
public void setVideoQuality(String videoQuality) {
this.videoQuality = videoQuality;
}
/**
* Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
*
* @return Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
*/
public String getVideoQuality() {
return this.videoQuality;
}
/**
* Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
*
* @param videoQuality
* Filter by video quality, 'STANDARD', 'ENHANCED', or 'PREMIUM'
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListReservationsRequest withVideoQuality(String videoQuality) {
setVideoQuality(videoQuality);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCodec() != null)
sb.append("Codec: ").append(getCodec()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getMaximumBitrate() != null)
sb.append("MaximumBitrate: ").append(getMaximumBitrate()).append(",");
if (getMaximumFramerate() != null)
sb.append("MaximumFramerate: ").append(getMaximumFramerate()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getResolution() != null)
sb.append("Resolution: ").append(getResolution()).append(",");
if (getResourceType() != null)
sb.append("ResourceType: ").append(getResourceType()).append(",");
if (getSpecialFeature() != null)
sb.append("SpecialFeature: ").append(getSpecialFeature()).append(",");
if (getVideoQuality() != null)
sb.append("VideoQuality: ").append(getVideoQuality());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListReservationsRequest == false)
return false;
ListReservationsRequest other = (ListReservationsRequest) obj;
if (other.getCodec() == null ^ this.getCodec() == null)
return false;
if (other.getCodec() != null && other.getCodec().equals(this.getCodec()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getMaximumBitrate() == null ^ this.getMaximumBitrate() == null)
return false;
if (other.getMaximumBitrate() != null && other.getMaximumBitrate().equals(this.getMaximumBitrate()) == false)
return false;
if (other.getMaximumFramerate() == null ^ this.getMaximumFramerate() == null)
return false;
if (other.getMaximumFramerate() != null && other.getMaximumFramerate().equals(this.getMaximumFramerate()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getResolution() == null ^ this.getResolution() == null)
return false;
if (other.getResolution() != null && other.getResolution().equals(this.getResolution()) == false)
return false;
if (other.getResourceType() == null ^ this.getResourceType() == null)
return false;
if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false)
return false;
if (other.getSpecialFeature() == null ^ this.getSpecialFeature() == null)
return false;
if (other.getSpecialFeature() != null && other.getSpecialFeature().equals(this.getSpecialFeature()) == false)
return false;
if (other.getVideoQuality() == null ^ this.getVideoQuality() == null)
return false;
if (other.getVideoQuality() != null && other.getVideoQuality().equals(this.getVideoQuality()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCodec() == null) ? 0 : getCodec().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getMaximumBitrate() == null) ? 0 : getMaximumBitrate().hashCode());
hashCode = prime * hashCode + ((getMaximumFramerate() == null) ? 0 : getMaximumFramerate().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getResolution() == null) ? 0 : getResolution().hashCode());
hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType().hashCode());
hashCode = prime * hashCode + ((getSpecialFeature() == null) ? 0 : getSpecialFeature().hashCode());
hashCode = prime * hashCode + ((getVideoQuality() == null) ? 0 : getVideoQuality().hashCode());
return hashCode;
}
@Override
public ListReservationsRequest clone() {
return (ListReservationsRequest) super.clone();
}
}
|
923d9389d1c1047e4c2d26607feebafa3d73f72e | 4,295 | java | Java | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/event/internal/WrapVisitor.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/event/internal/WrapVisitor.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/event/internal/WrapVisitor.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | 29.417808 | 107 | 0.734109 | 1,000,381 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.event.internal;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.CollectionType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.Type;
/**
* Wrap collections in a Hibernate collection wrapper.
*
* @author Gavin King
*/
public class WrapVisitor extends ProxyVisitor {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( WrapVisitor.class );
boolean substitute;
boolean isSubstitutionRequired() {
return substitute;
}
WrapVisitor(EventSource session) {
super( session );
}
@Override
Object processCollection(Object collection, CollectionType collectionType)
throws HibernateException {
if ( collection != null && ( collection instanceof PersistentCollection ) ) {
final SessionImplementor session = getSession();
PersistentCollection coll = (PersistentCollection) collection;
if ( coll.setCurrentSession( session ) ) {
reattachCollection( coll, collectionType );
}
return null;
}
else {
return processArrayOrNewCollection( collection, collectionType );
}
}
final Object processArrayOrNewCollection(Object collection, CollectionType collectionType)
throws HibernateException {
final SessionImplementor session = getSession();
if ( collection == null ) {
//do nothing
return null;
}
else {
CollectionPersister persister = session.getFactory().getCollectionPersister( collectionType.getRole() );
final PersistenceContext persistenceContext = session.getPersistenceContext();
//TODO: move into collection type, so we can use polymorphism!
if ( collectionType.hasHolder() ) {
if ( collection == CollectionType.UNFETCHED_COLLECTION ) {
return null;
}
PersistentCollection ah = persistenceContext.getCollectionHolder( collection );
if ( ah == null ) {
ah = collectionType.wrap( session, collection );
persistenceContext.addNewCollection( persister, ah );
persistenceContext.addCollectionHolder( ah );
}
return null;
}
else {
PersistentCollection persistentCollection = collectionType.wrap( session, collection );
persistenceContext.addNewCollection( persister, persistentCollection );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Wrapped collection in role: {0}", collectionType.getRole() );
}
return persistentCollection; //Force a substitution!
}
}
}
@Override
void processValue(int i, Object[] values, Type[] types) {
Object result = processValue( values[i], types[i] );
if ( result != null ) {
substitute = true;
values[i] = result;
}
}
@Override
Object processComponent(Object component, CompositeType componentType) throws HibernateException {
if ( component != null ) {
Object[] values = componentType.getPropertyValues( component, getSession() );
Type[] types = componentType.getSubtypes();
boolean substituteComponent = false;
for ( int i = 0; i < types.length; i++ ) {
Object result = processValue( values[i], types[i] );
if ( result != null ) {
values[i] = result;
substituteComponent = true;
}
}
if ( substituteComponent ) {
componentType.setPropertyValues( component, values, EntityMode.POJO );
}
}
return null;
}
@Override
void process(Object object, EntityPersister persister) throws HibernateException {
final Object[] values = persister.getPropertyValues( object );
final Type[] types = persister.getPropertyTypes();
processEntityPropertyValues( values, types );
if ( isSubstitutionRequired() ) {
persister.setPropertyValues( object, values );
}
}
}
|
923d94a6ccc72dac7c8fc922de525d2131bfbc95 | 467 | java | Java | src/constants/FramePanelConstants.java | GiantSweetroll/Markindo-Ledger | b66c1f06d382626f59113a6c4452b84aaaecba3e | [
"Apache-2.0"
] | null | null | null | src/constants/FramePanelConstants.java | GiantSweetroll/Markindo-Ledger | b66c1f06d382626f59113a6c4452b84aaaecba3e | [
"Apache-2.0"
] | null | null | null | src/constants/FramePanelConstants.java | GiantSweetroll/Markindo-Ledger | b66c1f06d382626f59113a6c4452b84aaaecba3e | [
"Apache-2.0"
] | null | null | null | 33.357143 | 55 | 0.740899 | 1,000,382 | package constants;
public class FramePanelConstants
{
public static final String MAIN_MENU = "m";
public static final String STOCK_OVERVIEW = "s";
public static final String STOCK_INPUT = "si";
public static final String ALOKASI_INPUT = "ai";
public static final String ALOKASI_OVERVIEW = "a";
public static final String PENGIRIMAN_INPUT = "pi";
public static final String PENGIRIMAN_OVERVIEW = "p";
public static final String MISC = "misc";
}
|
923d96ea56842e4fbd0665d28d68cf3f078e34b7 | 2,233 | java | Java | luckymall-admin/src/main/java/com/ruoyi/project/domain/SysOrder.java | Threadalive/LuckyMall | ab5fc67a1983617ad1c472057d482e8a00dbf525 | [
"MIT"
] | 1 | 2020-05-15T12:35:21.000Z | 2020-05-15T12:35:21.000Z | luckymall-admin/src/main/java/com/ruoyi/project/domain/SysOrder.java | Threadalive/LuckyMall | ab5fc67a1983617ad1c472057d482e8a00dbf525 | [
"MIT"
] | 1 | 2020-12-03T11:01:06.000Z | 2020-12-03T11:01:06.000Z | luckymall-admin/src/main/java/com/ruoyi/project/domain/SysOrder.java | Threadalive/LuckyMall | ab5fc67a1983617ad1c472057d482e8a00dbf525 | [
"MIT"
] | null | null | null | 20.117117 | 72 | 0.585311 | 1,000,383 | package com.ruoyi.project.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
/**
* 订单对象 sys_order
*
* @author zhenxing.dong
* @date 2020-05-06
*/
public class SysOrder implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 订单ID
*/
private String id;
/**
* 订单号
*/
@Excel(name = "订单号")
private String orderCode;
/**
* 订单状态
*/
@Excel(name = "订单状态")
private Integer status;
@Excel(name = "订单创建时间")
private String createTime;
/**
* 订单总金额
*/
@Excel(name = "订单总金额")
private Double totalPrice;
/**
* 订单用户
*/
@Excel(name = "订单用户")
private Long userId;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setOrderCode(String orderCode) {
this.orderCode = orderCode;
}
public String getOrderCode() {
return orderCode;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getStatus() {
return status;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("orderCode", getOrderCode())
.append("createTime", getCreateTime())
.append("status", getStatus())
.append("totalPrice", getTotalPrice())
.append("userId", getUserId())
.toString();
}
}
|
923d977983c7abd88112f9df6128229bf7196604 | 1,228 | java | Java | provider/provider-admin-api/src/main/java/com/iscolt/micm/provider/entity/SysRole.java | Miners-ICU/micm-docs | aaddec218f9924b82065241adfc6cd7751f57884 | [
"Apache-2.0"
] | 2 | 2020-03-19T05:52:45.000Z | 2020-05-29T10:24:29.000Z | provider/provider-admin-api/src/main/java/com/iscolt/micm/provider/entity/SysRole.java | Miners-ICU/micm | aaddec218f9924b82065241adfc6cd7751f57884 | [
"Apache-2.0"
] | null | null | null | provider/provider-admin-api/src/main/java/com/iscolt/micm/provider/entity/SysRole.java | Miners-ICU/micm | aaddec218f9924b82065241adfc6cd7751f57884 | [
"Apache-2.0"
] | null | null | null | 21.172414 | 71 | 0.698697 | 1,000,384 | package com.iscolt.micm.provider.entity;
import com.iscolt.micm.commons.model.entity.BaseEntity;
import lombok.Data;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* xx
* <p>
* Description:
* </p>
*
* @author: https://github.com/isColt
* @date: 4/9/2020
* @see: com.iscolt.micm.provider.entity
* @version: v1.0.0
*/
@Data
@Entity
@Table(name = "sys_role", schema = "micm", catalog = "")
public class SysRole extends BaseEntity implements Serializable {
private static final long serialVersionUID = -7701240463698321086L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Basic
@Column(name = "parent_id")
private int parentId;
@Basic
@Column(name = "name")
private String name;
@Basic
@Column(name = "enname")
private String enname;
@Basic
@Column(name = "description")
private String description;
@Basic
@Column(name = "tenant_id")
private int tenantId;
}
|
923d97866567b26bcecd6ac4293f56a75be657b5 | 133 | java | Java | src/main/java/org/processmining/logfiltering/legacy/plugins/logfiltering/enumtypes/Combination.java | DataSystemsGroupUT/ConformanceCheckingUsingTries | 8e70b9d729b736fe06afa30a43cbf8f1842fa02a | [
"Apache-2.0"
] | 5 | 2021-08-04T07:50:59.000Z | 2022-03-01T10:51:29.000Z | src/main/java/org/processmining/logfiltering/legacy/plugins/logfiltering/enumtypes/Combination.java | DataSystemsGroupUT/ConformanceCheckingUsingTries | 8e70b9d729b736fe06afa30a43cbf8f1842fa02a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/processmining/logfiltering/legacy/plugins/logfiltering/enumtypes/Combination.java | DataSystemsGroupUT/ConformanceCheckingUsingTries | 8e70b9d729b736fe06afa30a43cbf8f1842fa02a | [
"Apache-2.0"
] | null | null | null | 22.166667 | 77 | 0.842105 | 1,000,385 | package org.processmining.logfiltering.legacy.plugins.logfiltering.enumtypes;
public enum Combination {
Conjunction, Disjunction
}
|
923d98421225092c75642485454750da164dc224 | 1,862 | java | Java | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/CustomFieldServiceInterfacegetCustomField.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/CustomFieldServiceInterfacegetCustomField.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/CustomFieldServiceInterfacegetCustomField.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | 25.861111 | 107 | 0.621912 | 1,000,386 |
package com.google.api.ads.dfp.jaxws.v201308;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Returns the {@link CustomField} uniquely identified by the given ID.
*
* @param customFieldId the ID of the custom field, which must already exist
* @return the {@code CustomField} uniquely identified by the given ID
*
*
* <p>Java class for getCustomField element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getCustomField">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="customFieldId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"customFieldId"
})
@XmlRootElement(name = "getCustomField")
public class CustomFieldServiceInterfacegetCustomField {
protected Long customFieldId;
/**
* Gets the value of the customFieldId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getCustomFieldId() {
return customFieldId;
}
/**
* Sets the value of the customFieldId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setCustomFieldId(Long value) {
this.customFieldId = value;
}
}
|
923d99347739b38a77307fac240592d9bb312ea1 | 1,965 | java | Java | Problem Solving/Drawing Book /Solution.java | rimjhimmaharishi/HackerRank | 850319e6f79e7473afbb847d28edde7b2cdfc37d | [
"MIT"
] | 2 | 2019-08-07T19:58:20.000Z | 2019-08-27T00:06:09.000Z | Problem Solving/Drawing Book /Solution.java | rimjhimmaharishi/HackerRank | 850319e6f79e7473afbb847d28edde7b2cdfc37d | [
"MIT"
] | 1 | 2020-06-11T19:09:48.000Z | 2020-06-11T19:09:48.000Z | Problem Solving/Drawing Book /Solution.java | rimjhimmaharishi/HackerRank | 850319e6f79e7473afbb847d28edde7b2cdfc37d | [
"MIT"
] | 7 | 2019-08-27T00:06:11.000Z | 2021-12-11T10:01:45.000Z | 22.848837 | 105 | 0.442748 | 1,000,387 | /**
* @author SANKALP SAXENA
*/
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the pageCount function below.
*/
static int pageCount(int n, int p) {
// If n is odd the last page will be on the right
// IF n is even the last page will be on the left
int minBeg = -1;
//Beginning
int turn = 0;
for(int i = 1; i <= n; i++) {
if(p == 1) {
minBeg = 0;
break;
}
else {
turn++;
if(p == i || p == i+1) {
minBeg = turn;
break;
}
}
}
//Ending
turn = 0;
int minEnd=-1;
for(int i = n; i >= 0; i--) {
if(p == n){
minEnd = 0;
break;
}
else {
turn++;
if(p == i || p == i-1) {
minEnd = turn;
break;
}
}
}
if(n%2 != 0){
int min = (minBeg < minEnd) ? minBeg-1: minEnd-1;
return min;}
if (minBeg < minEnd)
return minBeg;
return minEnd;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
int p = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
int result = pageCount(n, p);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
|
923d9a8fd5b767075a8f75a0978338bd330e3d79 | 499 | java | Java | langx-java/src/main/java/com/jn/langx/security/crypto/key/spec/der/Pkcs8PrivateKeySpecParser.java | fangjinuo/langx | 8b61fd3a339f6dfeb057f4db7157da09a1c28f75 | [
"Apache-2.0"
] | 48 | 2019-08-11T11:34:09.000Z | 2022-01-05T12:10:42.000Z | langx-java/src/main/java/com/jn/langx/security/crypto/key/spec/der/Pkcs8PrivateKeySpecParser.java | fangjinuo/langx | 8b61fd3a339f6dfeb057f4db7157da09a1c28f75 | [
"Apache-2.0"
] | 29 | 2019-08-13T14:50:15.000Z | 2022-03-19T08:53:27.000Z | langx-java/src/main/java/com/jn/langx/security/crypto/key/spec/der/Pkcs8PrivateKeySpecParser.java | fangjinuo/langx | 8b61fd3a339f6dfeb057f4db7157da09a1c28f75 | [
"Apache-2.0"
] | 6 | 2019-11-26T02:08:09.000Z | 2021-11-05T05:41:43.000Z | 33.266667 | 93 | 0.805611 | 1,000,388 | package com.jn.langx.security.crypto.key.spec.der;
import com.jn.langx.security.crypto.key.spec.PrivateKeySpecParser;
import java.security.spec.PKCS8EncodedKeySpec;
public class Pkcs8PrivateKeySpecParser implements PrivateKeySpecParser<PKCS8EncodedKeySpec> {
public static final Pkcs8PrivateKeySpecParser INSTANCE = new Pkcs8PrivateKeySpecParser();
@Override
public PKCS8EncodedKeySpec parse(byte[] derEncodedBytes) {
return new PKCS8EncodedKeySpec(derEncodedBytes);
}
}
|
923d9b18041852dbdeace4eb22ecee9e69a5952c | 519 | java | Java | api/src/main/java/au/com/digitalspider/biblegame/exception/ActionException.java | digitalspider/biblegame | 54105bca1c3560713530a4991edf61615510aa7b | [
"Apache-2.0"
] | null | null | null | api/src/main/java/au/com/digitalspider/biblegame/exception/ActionException.java | digitalspider/biblegame | 54105bca1c3560713530a4991edf61615510aa7b | [
"Apache-2.0"
] | null | null | null | api/src/main/java/au/com/digitalspider/biblegame/exception/ActionException.java | digitalspider/biblegame | 54105bca1c3560713530a4991edf61615510aa7b | [
"Apache-2.0"
] | null | null | null | 24.714286 | 91 | 0.766859 | 1,000,389 | package au.com.digitalspider.biblegame.exception;
import au.com.digitalspider.biblegame.model.ActionMain;
public class ActionException extends RuntimeException {
private static final long serialVersionUID = 8817352678366094492L;
public enum ActionExceptionType {
POOR, TIRED
}
public ActionException(ActionMain action, ActionExceptionType type) {
super("You are too " + type.name().toLowerCase() + " to " + action.name().toLowerCase());
}
public ActionException(String message) {
super(message);
}
}
|
923d9c428102f2fd5afe97b63675425c9bf44b76 | 6,415 | java | Java | hedron-core/src/test/java/au/com/breakpoint/hedron/core/TimedScopeTest.java | breakpoint-au/Hedron | 2cb1d6f8d0e1935a456089b651786c9faaff9fe0 | [
"Apache-2.0"
] | null | null | null | hedron-core/src/test/java/au/com/breakpoint/hedron/core/TimedScopeTest.java | breakpoint-au/Hedron | 2cb1d6f8d0e1935a456089b651786c9faaff9fe0 | [
"Apache-2.0"
] | null | null | null | hedron-core/src/test/java/au/com/breakpoint/hedron/core/TimedScopeTest.java | breakpoint-au/Hedron | 2cb1d6f8d0e1935a456089b651786c9faaff9fe0 | [
"Apache-2.0"
] | null | null | null | 34.86413 | 92 | 0.574279 | 1,000,390 | // __________________________________
// ______| Copyright 2008-2015 |______
// \ | Breakpoint Pty Limited | /
// \ | http://www.breakpoint.com.au | /
// / |__________________________________| \
// /_________/ \_________\
//
// 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 au.com.breakpoint.hedron.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.function.Supplier;
import org.junit.Test;
import au.com.breakpoint.hedron.core.HcUtil;
import au.com.breakpoint.hedron.core.TimedScope;
import au.com.breakpoint.hedron.core.TimedScopeStatistics;
import au.com.breakpoint.hedron.core.context.FaultException;
import au.com.breakpoint.hedron.core.context.ThreadContext;
import au.com.breakpoint.hedron.core.log.Logging;
public class TimedScopeTest
{
// Removed this to shut up the javac compiler warning in Ant build
//@Test (expected = FaultException.class)
//public void testFaultException_Exception ()
//{
// final TimedScope ts = TimedScope.getTimedScope ("Exception");
//
// ts.execute (new Supplier<Integer> ()
// {
// @Override
// public Integer execute ()
// {
// Unsafe unsafe = null;
// try
// {
// final Field field = Unsafe.class.getDeclaredField ("theUnsafe");
// field.setAccessible (true);
// unsafe = (Unsafe) field.get (null);
// }
// catch (final NoSuchFieldException e)
// {
// // Propagate exception as unchecked fault up to the fault barrier.
// ThreadContext.throwFault (e);
// }
// catch (final SecurityException e)
// {
// // Propagate exception as unchecked fault up to the fault barrier.
// ThreadContext.throwFault (e);
// }
// catch (final IllegalArgumentException e)
// {
// // Propagate exception as unchecked fault up to the fault barrier.
// ThreadContext.throwFault (e);
// }
// catch (final IllegalAccessException e)
// {
// // Propagate exception as unchecked fault up to the fault barrier.
// ThreadContext.throwFault (e);
// }
//
// //throw a checked exception without adding a "throws"
// unsafe.throwException (new IOException ());
// return 0;
// }
// });
//
// assertTrue (false);
//}
@Test (expected = FaultException.class)
public void testFaultException_RuntimeException ()
{
final TimedScope ts = TimedScope.getTimedScope ("RuntimeException");
final Runnable task = () ->
{
throw new RuntimeException ();
};
ts.execute (task);
assertTrue (false);
}
@Test (expected = FaultException.class)
public void testFaultException_Throwable ()
{
final TimedScope ts = TimedScope.getTimedScope ("Throwable");
final Runnable task = () ->
{
throw new Error ();
};
ts.execute (task);
assertTrue (false);
}
@Test
public void testGetResults ()
{
// Profiling wrapper. Timed wrapper for the inserts and the stored proc.
final int msecFast = 50;
final int msecSlow = 100;
final int msecLimit = (msecFast + msecSlow) / 2;
final Supplier<Integer> timedService1 = new Sleeper (msecFast);
final Supplier<Integer> timedService2 = new Sleeper (msecSlow);
final TimedScope ts1 = TimedScope.of (TimedScopeTest.class, "ts1");
final int nrThreads = 50;
final int nrTasks = nrThreads * 20;
final Runnable task = () ->
{
ts1.execute (timedService1, msecLimit, null);
ts1.execute (timedService2, msecLimit, null);
};
HcUtil.executeManyConcurrently (task, nrThreads, nrTasks);
final TimedScope ts2 = TimedScope.of (TimedScopeTest.class, "ts2");
ts2.execute (timedService1, msecLimit, null);
ts2.execute (timedService2, msecLimit, null);
Logging.logInfo (TimedScope.getResults (false));
}
@Test
public void testGetTimedScope ()
{
final TimedScope ts1 = TimedScope.getTimedScope ("drhrrfrrfrr");
final TimedScope ts2 = TimedScope.getTimedScope ("drhrr" + "frrfrr");
assertSame (ts1, ts2);
}
@Test
public void testInitialState ()
{
final TimedScope ts = TimedScope.of (TimedScopeTest.class, "ts");
final TimedScopeStatistics s = ts.getStatistics ();
assertEquals (0, s.getDurationMax ());
assertEquals (Long.MAX_VALUE, s.getDurationMin ());
assertEquals (0, s.getDurationTotal ());
assertEquals (0, s.getExecutionsCount ());
assertEquals (0, s.getSuccessfulExecutionsCount ());
}
private static final class Sleeper implements Supplier<Integer>
{
public Sleeper (final long msec)
{
m_msec = msec;
}
@Override
public Integer get ()
{
try
{
Thread.sleep (m_msec);
}
catch (final InterruptedException e)
{
// Propagate exception as unchecked fault up to the fault barrier.
ThreadContext.throwFault (e);
}
return 0;
}
private final long m_msec;
}
}
|
923d9c604122d600fb8a1ce72002a523d50fc144 | 295 | java | Java | src/main/java/frc/robot/commands/TestControl.java | dylan940126/FRC-2022 | 7e5d38f8b1fd8f23f217d0266e1849d2ece12933 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/TestControl.java | dylan940126/FRC-2022 | 7e5d38f8b1fd8f23f217d0266e1849d2ece12933 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/TestControl.java | dylan940126/FRC-2022 | 7e5d38f8b1fd8f23f217d0266e1849d2ece12933 | [
"BSD-3-Clause"
] | null | null | null | 15.526316 | 50 | 0.671186 | 1,000,391 | package frc.robot.commands;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class TestControl extends CommandBase {
@Override
public void initialize() {
}
@Override
public void execute() {
}
@Override
public void end(boolean interrupted) {
}
}
|
923d9c97ed24c317dee29b2fa1b36fb02ed48adc | 618 | java | Java | linker-common-lib/src/main/java/com/linker/common/router/Domain.java | disney007/linker | f470464d6d0687a850f9394a924408197d7a0074 | [
"MIT"
] | 2 | 2019-07-16T00:01:52.000Z | 2019-07-18T20:13:49.000Z | linker-common-lib/src/main/java/com/linker/common/router/Domain.java | disney007/linker | f470464d6d0687a850f9394a924408197d7a0074 | [
"MIT"
] | 7 | 2019-07-23T06:58:00.000Z | 2019-08-14T20:40:14.000Z | linker-common-lib/src/main/java/com/linker/common/router/Domain.java | disney007/linker | f470464d6d0687a850f9394a924408197d7a0074 | [
"MIT"
] | 1 | 2020-10-30T02:59:03.000Z | 2020-10-30T02:59:03.000Z | 22.071429 | 98 | 0.71521 | 1,000,392 | package com.linker.common.router;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import java.util.Set;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Domain {
String name;
Set<String> urls;
@JsonIgnore
public String getTcpUrl() {
return urls.stream().filter(u -> StringUtils.startsWith(u, "tcp")).findAny().orElse(null);
}
@Override
public String toString() {
return String.format("%s %s", this.name, this.urls);
}
}
|
923d9d1cc7e730101644bef04763e4a03538407e | 2,587 | java | Java | backend/de.metas.adempiere.adempiere/base/src/test/java/de/metas/email/EMailSentStatusTest.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/base/src/test/java/de/metas/email/EMailSentStatusTest.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/base/src/test/java/de/metas/email/EMailSentStatusTest.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | 34.493333 | 126 | 0.757634 | 1,000,393 | package de.metas.email;
import org.junit.Assert;
import org.junit.Test;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2016 metas GmbH
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public class EMailSentStatusTest
{
@Test
public void test_ok()
{
final EMailSentStatus status = EMailSentStatus.ok("1234");
Assert.assertEquals(true, status.isSentOK());
Assert.assertEquals(false, status.isSentConnectionError());
Assert.assertEquals(EMailSentStatus.SENT_OK, status.getSentMsg());
Assert.assertEquals("1234", status.getMessageId());
}
@Test
public void test_invalid()
{
final EMailSentStatus status = EMailSentStatus.invalid("invalidError1");
Assert.assertEquals(false, status.isSentOK());
Assert.assertEquals(false, status.isSentConnectionError());
Assert.assertEquals("invalidError1", status.getSentMsg());
Assert.assertEquals(null, status.getMessageId());
}
@Test
public void test_errorWithMessage()
{
final EMailSentStatus status = EMailSentStatus.error("errorMsg1");
Assert.assertEquals(false, status.isSentOK());
Assert.assertEquals(false, status.isSentConnectionError());
Assert.assertEquals("errorMsg1", status.getSentMsg());
Assert.assertEquals(null, status.getMessageId());
}
@Test
public void test_errorException_ConnectionError()
{
final java.net.ConnectException connectionEx = new java.net.ConnectException("test connection error");
final javax.mail.MessagingException exception = new javax.mail.MessagingException("test messaging exception", connectionEx);
final String expectedSentMsg = "(ME): test messaging exception - Connection error: test connection error";
final EMailSentStatus status = EMailSentStatus.error(exception);
Assert.assertEquals(false, status.isSentOK());
Assert.assertEquals(true, status.isSentConnectionError());
Assert.assertEquals(expectedSentMsg, status.getSentMsg());
Assert.assertEquals(null, status.getMessageId());
}
}
|
923d9de3bca671e04ec92116115d44d7b616210e | 6,196 | java | Java | talkback/src/main/java/com/google/android/accessibility/talkback/preference/TalkBackDumpAccessibilityEventActivity.java | hanyuliu/talkback | e7176065a9d88c199a96931cac21afa165bf0b8a | [
"Apache-2.0"
] | 350 | 2015-10-07T13:46:31.000Z | 2022-03-31T23:09:03.000Z | talkback/src/main/java/com/google/android/accessibility/talkback/preference/TalkBackDumpAccessibilityEventActivity.java | hanyuliu/talkback | e7176065a9d88c199a96931cac21afa165bf0b8a | [
"Apache-2.0"
] | 15 | 2015-10-23T19:57:21.000Z | 2022-01-15T09:05:58.000Z | talkback/src/main/java/com/google/android/accessibility/talkback/preference/TalkBackDumpAccessibilityEventActivity.java | hanyuliu/talkback | e7176065a9d88c199a96931cac21afa165bf0b8a | [
"Apache-2.0"
] | 198 | 2015-10-06T05:13:47.000Z | 2022-03-24T10:26:13.000Z | 36.880952 | 99 | 0.722886 | 1,000,394 | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.accessibility.talkback.preference;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TtsSpan;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.accessibility.AccessibilityEvent;
import androidx.preference.Preference;
import androidx.preference.Preference.OnPreferenceChangeListener;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceScreen;
import androidx.preference.SwitchPreference;
import com.google.android.accessibility.talkback.R;
import com.google.android.accessibility.utils.AccessibilityEventUtils;
import com.google.android.accessibility.utils.BasePreferencesActivity;
import com.google.android.accessibility.utils.PreferenceSettingsUtils;
import com.google.android.accessibility.utils.SharedPreferencesUtils;
import java.util.ArrayList;
import java.util.List;
/** Activity used to set TalkBack's dump events preferences. */
public class TalkBackDumpAccessibilityEventActivity extends BasePreferencesActivity {
private MenuItem.OnMenuItemClickListener listener;
@Override
protected PreferenceFragmentCompat createPreferenceFragment() {
TalkBackDumpAccessibilityEventFragment fragment = new TalkBackDumpAccessibilityEventFragment();
listener = fragment;
return fragment;
}
/**
* Finishes the activity when the up button is pressed on the action bar. Perform function in
* TalkBackAccessibilityEventFragment when clear_all/check_all button is pressed.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
return true;
} else if (itemId == R.id.disable_all || itemId == R.id.enable_all) {
return listener.onMenuItemClick(item);
} else {
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dump_a11y_event_menu, menu);
return true;
}
/** Fragment used to display TalkBack's dump events preferences. */
public static class TalkBackDumpAccessibilityEventFragment extends PreferenceFragmentCompat
implements MenuItem.OnMenuItemClickListener {
private final List<EventDumperSwitchPreference> switchPreferences = new ArrayList<>();
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
Context context = getActivity();
PreferenceSettingsUtils.addPreferencesFromResource(this, R.xml.dump_events_preferences);
PreferenceScreen screen = getPreferenceScreen();
for (int eventType : AccessibilityEventUtils.getAllEventTypes()) {
EventDumperSwitchPreference preference =
new EventDumperSwitchPreference(context, eventType);
switchPreferences.add(preference);
screen.addPreference(preference);
}
}
private void setDumpAllEvents(boolean enabled) {
Context context = getActivity().getApplicationContext();
SharedPreferences prefs = SharedPreferencesUtils.getSharedPreferences(context);
prefs
.edit()
.putInt(
context.getString(R.string.pref_dump_event_mask_key),
enabled ? AccessibilityEvent.TYPES_ALL_MASK : 0)
.apply();
for (EventDumperSwitchPreference preference : switchPreferences) {
preference.setChecked(enabled);
}
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
final int itemId = menuItem.getItemId();
if (itemId == R.id.disable_all) {
setDumpAllEvents(false);
return true;
} else if (itemId == R.id.enable_all) {
setDumpAllEvents(true);
return true;
} else {
return false;
}
}
private static class EventDumperSwitchPreference extends SwitchPreference
implements OnPreferenceChangeListener {
private final int eventType;
EventDumperSwitchPreference(Context context, int eventType) {
super(context);
this.eventType = eventType;
setOnPreferenceChangeListener(this);
String title = AccessibilityEvent.eventTypeToString(eventType);
// Add TtsSpan to the titles to improve readability.
SpannableString spannableString = new SpannableString(title);
TtsSpan ttsSpan = new TtsSpan.TextBuilder(title.replaceAll("_", " ")).build();
spannableString.setSpan(ttsSpan, 0, title.length(), 0 /* no flag */);
setTitle(spannableString);
// Set initial value.
SharedPreferences prefs = SharedPreferencesUtils.getSharedPreferences(getContext());
int value = prefs.getInt(getContext().getString(R.string.pref_dump_event_mask_key), 0);
setChecked((value & eventType) != 0);
}
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean enabled = (Boolean) o;
SharedPreferences prefs = SharedPreferencesUtils.getSharedPreferences(getContext());
int value = prefs.getInt(getContext().getString(R.string.pref_dump_event_mask_key), 0);
if (enabled) {
value |= eventType;
} else {
value &= ~eventType;
}
prefs
.edit()
.putInt(getContext().getString(R.string.pref_dump_event_mask_key), value)
.apply();
return true;
}
}
}
}
|
923d9e256236cd1f063a008dc9ebf544207b4b00 | 8,771 | java | Java | api/android/external2/src/main/java/org/societies/android/api/comms/XMPPAgent.java | EPapadopoulou/SOCIETIES-Platform | 7050936833dcadf5cf318921ba97154843a05a46 | [
"BSD-2-Clause"
] | 4 | 2015-01-30T12:55:10.000Z | 2021-08-24T12:21:58.000Z | api/android/external2/src/main/java/org/societies/android/api/comms/XMPPAgent.java | EPapadopoulou/SOCIETIES-Platform | 7050936833dcadf5cf318921ba97154843a05a46 | [
"BSD-2-Clause"
] | 1 | 2017-03-12T19:22:46.000Z | 2017-03-15T19:52:57.000Z | api/android/external2/src/main/java/org/societies/android/api/comms/XMPPAgent.java | EPapadopoulou/SOCIETIES-Platform | 7050936833dcadf5cf318921ba97154843a05a46 | [
"BSD-2-Clause"
] | 2 | 2015-03-03T15:23:31.000Z | 2015-08-17T06:09:18.000Z | 58.086093 | 139 | 0.781325 | 1,000,395 | package org.societies.android.api.comms;
import org.societies.android.api.comms.xmpp.VCardParcel;
/**
* Mirror interface of org.societies.api.comm.xmpp.interfaces.ICommManager, adapted for Android. Check javadoc there.
*
* @author Edgar Domingues
* @author Joao M. Goncalves
*/
public interface XMPPAgent {
String methodsArray [] = {"register(String client, String[] elementNames, String[] namespaces, long remoteCallId)",
"unregister(String client, String[] elementNames, String[] namespaces, long remoteCallId)",
"UnRegisterCommManager(String client, long remoteCallId)",
"sendMessage(String client, String messageXml, long remoteCallId)",
"sendIQ(String client, String xml, long remoteCallId)",
"getIdentity(String client, long remoteCallId)",
"getDomainAuthorityNode(String client, long remoteCallId)",
"getItems(String client, String entity, String node, long remoteCallId)",
"isConnected(String client, long remoteCallId)",
"newMainIdentity(String client, String identifier, String domain, String password, long remoteCallId, String host)",
"login(String client, String identifier, String domain, String password, long remoteCallId)",
"logout(String client, long remoteCallId)",
"destroyMainIdentity(String client, long remoteCallId)",
"configureAgent(String client, String domainAuthorityNode, int xmppPort, String resource, boolean debug, long remoteCallId)",
"login(String client, String identifier, String domain, String password, String host, long remoteCallId)",
"setVCard(String client, VCardParcel vCard)", //15
"getVCard(String client, long remoteCallId)", //16
"getVCard(String client, long remoteCallId, String userId)" //17
};
/**
* Android Comms intents
* Used to create to create Intents to signal return values of a called method
* If the method is locally bound it is possible to directly return a value but is discouraged
* as called methods usually involve making asynchronous calls.
*/
public static final String INTENT_RETURN_VALUE_KEY = "org.societies.android.platform.comms.ReturnValue";
public static final String INTENT_RETURN_EXCEPTION_KEY = "org.societies.android.platform.comms.ReturnException";
public static final String INTENT_RETURN_EXCEPTION_TRACE_KEY = "org.societies.android.platform.comms.ReturnExceptionTrace";
public static final String INTENT_RETURN_CALL_ID_KEY = "org.societies.android.platform.comms.ReturnCallId";
public static final String UN_REGISTER_COMM_MANAGER_RESULT = "org.societies.android.platform.comms.UN_REGISTER_COMM_MANAGER_RESULT";
public static final String UN_REGISTER_COMM_MANAGER_EXCEPTION = "org.societies.android.platform.comms.UN_REGISTER_COMM_MANAGER_EXCEPTION";
public static final String GET_IDENTITY = "org.societies.android.platform.comms.GET_IDENTITY";
public static final String GET_DOMAIN_AUTHORITY_NODE = "org.societies.android.platform.comms.GET_DOMAIN_AUTHORITY_NODE";
public static final String GET_ITEMS_RESULT = "org.societies.android.platform.comms.GET_ITEMS_RESULT";
public static final String GET_ITEMS_ERROR = "org.societies.android.platform.comms.GET_ITEMS_ERROR";
public static final String GET_ITEMS_EXCEPTION = "org.societies.android.platform.comms.GET_ITEMS_EXCEPTION";
public static final String IS_CONNECTED = "org.societies.android.platform.comms.IS_CONNECTED";
public static final String NEW_MAIN_IDENTITY = "org.societies.android.platform.comms.NEW_MAIN_IDENTITY";
public static final String NEW_MAIN_IDENTITY_EXCEPTION = "org.societies.android.platform.comms.NEW_MAIN_IDENTITY_EXCEPTION";
public static final String LOGIN_EXCEPTION = "org.societies.android.platform.comms.LOGIN_EXCEPTION";
public static final String LOGIN = "org.societies.android.platform.comms.LOGIN";
public static final String LOGOUT = "org.societies.android.platform.comms.LOGOUT";
public static final String DESTROY_MAIN_IDENTITY = "org.societies.android.platform.comms.DESTROY_MAIN_IDENTITY";
public static final String CONFIGURE_AGENT = "org.societies.android.platform.comms.CONFIGURE_AGENT";
public static final String UNREGISTER_RESULT = "org.societies.android.platform.comms.UNREGISTER_RESULT";
public static final String UNREGISTER_EXCEPTION = "org.societies.android.platform.comms.UNREGISTER_EXCEPTION";
public static final String REGISTER_RESULT = "org.societies.android.platform.comms.REGISTER_RESULT";
public static final String REGISTER_EXCEPTION = "org.societies.android.platform.comms.REGISTER_EXCEPTION";
public static final String SEND_IQ_RESULT = "org.societies.android.platform.comms.SEND_IQ_RESULT";
public static final String SEND_IQ_EXCEPTION = "org.societies.android.platform.comms.SEND_IQ_EXCEPTION";
public static final String SEND_IQ_ERROR = "org.societies.android.platform.comms.SEND_IQ_ERROR";
public static final String SEND_MESSAGE_RESULT = "org.societies.android.platform.comms.SEND_MESSAGE_RESULT";
public static final String SEND_MESSAGE_EXCEPTION = "org.societies.android.platform.comms.SEND_MESSAGE_EXCEPTION";
public static final String PUBSUB_EVENT = "org.societies.android.platform.comms.PUBSUB_EVENT";
public static final String SET_VCARD = "org.societies.android.platform.comms.SET_VCARD";
public static final String GET_VCARD = "org.societies.android.platform.comms.GET_VCARD";
public static final String GET_USER_VCARD = "org.societies.android.platform.comms.GET_USER_VCARD";
public boolean register(String client, String[] elementNames, String[] namespaces, long remoteCallId);
public boolean unregister(String client, String[] elementNames, String[] namespaces, long remoteCallId);
public boolean UnRegisterCommManager(String client, long remoteCallId);
public boolean sendMessage(String client, String messageXml, long remoteCallId);
public boolean sendIQ(String client, String xml, long remoteCallId);
public String getIdentity(String client, long remoteCallId);
public String getDomainAuthorityNode(String client, long remoteCallId);
public String getItems(String client, String entity, String node, long remoteCallId);
public boolean isConnected(String client, long remoteCallId);
/**
*
* @param client Calling component's app package. Used to restrict broadcast of return value via intent.
* @param identifier User's user name
* @param domain XMPP Domain server (service name)
* @param password User's password
* @param remoteCallId Callback identifier to allow ClientCommunicationMgr to invoke correct callback action
* @param host IP address of XMPP server. Prevents DNS lookup to resolve XMPP server address
* @return boolean via Intent
*/
public String newMainIdentity(String client, String identifier, String domain, String password, long remoteCallId, String host);
/**
* Allows a user to login to the designated XMPP server
*
* @param client Calling component's app package. Used to restrict broadcast of return value via intent.
* @param identifier User's user name
* @param domain XMPP Domain server (service name)
* @param password User's password
* @param remoteCallId Callback identifier to allow ClientCommunicationMgr to invoke correct callback action
* @return identity but via Intent
*/
public String login(String client, String identifier, String domain, String password, long remoteCallId);
/**
* Allows a user to login to the designated XMPP server
*
* @param client Calling component's app package. Used to restrict broadcast of return value via intent.
* @param identifier User's user name
* @param domain XMPP Domain server (service name)
* @param password User's password
* @param host IP address of XMPP server. Prevents DNS lookup to resolve XMPP server address
* @param remoteCallId Callback identifier to allow ClientCommunicationMgr to invoke correct callback action
* @return
*/
public String login(String client, String identifier, String domain, String password, String host, long remoteCallId);
public boolean logout(String client, long remoteCallId);
public boolean destroyMainIdentity(String client, long remoteCallId);
public boolean configureAgent(String client, String domainAuthorityNode, int xmppPort, String resource, boolean debug, long remoteCallId);
/**
* Sets the VCard for the current user
* @param vCard
*/
public void setVCard(String client, VCardParcel vCard);
/**
* Returns the VCard for the current user
* @return
*/
public VCardParcel getVCard(String client, long remoteCallId);
/**
* Returns the VCard for a given user
* @param userId
* @return
*/
public VCardParcel getVCard(String client, long remoteCallId, String userId);
}
|
923d9ee1822dc9f626010ae88cb15912e1c30275 | 1,294 | java | Java | competition-system/src/main/java/com/competition/system/service/ISysOfflineCompetitionService.java | Lucas-luwh/competition | c3bc86d8de116c297bd5ae03d4af65cc32190550 | [
"MIT"
] | null | null | null | competition-system/src/main/java/com/competition/system/service/ISysOfflineCompetitionService.java | Lucas-luwh/competition | c3bc86d8de116c297bd5ae03d4af65cc32190550 | [
"MIT"
] | null | null | null | competition-system/src/main/java/com/competition/system/service/ISysOfflineCompetitionService.java | Lucas-luwh/competition | c3bc86d8de116c297bd5ae03d4af65cc32190550 | [
"MIT"
] | null | null | null | 20.539683 | 116 | 0.650696 | 1,000,396 | package com.competition.system.service;
import com.competition.system.domain.SysOfflineCompetition;
import java.util.List;
/**
* 线下赛事Service接口
*
* @author competition
* @date 2022-03-12
*/
public interface ISysOfflineCompetitionService
{
/**
* 查询线下赛事
*
* @param id 线下赛事主键
* @return 线下赛事
*/
public SysOfflineCompetition selectSysOfflineCompetitionById(Long id);
/**
* 查询线下赛事列表
*
* @param sysOfflineCompetition 线下赛事
* @return 线下赛事集合
*/
public List<SysOfflineCompetition> selectSysOfflineCompetitionList(SysOfflineCompetition sysOfflineCompetition);
/**
* 新增线下赛事
*
* @param sysOfflineCompetition 线下赛事
* @return 结果
*/
public int insertSysOfflineCompetition(SysOfflineCompetition sysOfflineCompetition);
/**
* 修改线下赛事
*
* @param sysOfflineCompetition 线下赛事
* @return 结果
*/
public int updateSysOfflineCompetition(SysOfflineCompetition sysOfflineCompetition);
/**
* 批量删除线下赛事
*
* @param ids 需要删除的线下赛事主键集合
* @return 结果
*/
public int deleteSysOfflineCompetitionByIds(Long[] ids);
/**
* 删除线下赛事信息
*
* @param id 线下赛事主键
* @return 结果
*/
public int deleteSysOfflineCompetitionById(Long id);
}
|
923d9f026d7a17120fa8813bb84a501ff4a7648d | 310 | java | Java | src/main/java/se/liu/ida/hefquin/engine/query/BGP.java | LiUSemWeb/HeFQUIN | 5faf8bf2ebed03c2cfe5fa7877dbcf54673b5a21 | [
"Apache-2.0"
] | 2 | 2021-03-04T18:46:50.000Z | 2021-03-04T20:38:16.000Z | src/main/java/se/liu/ida/hefquin/engine/query/BGP.java | LiUSemWeb/HeFQUIN | 5faf8bf2ebed03c2cfe5fa7877dbcf54673b5a21 | [
"Apache-2.0"
] | 125 | 2021-04-22T22:43:46.000Z | 2022-03-30T14:35:50.000Z | src/main/java/se/liu/ida/hefquin/engine/query/BGP.java | LiUSemWeb/HeFQUIN | 5faf8bf2ebed03c2cfe5fa7877dbcf54673b5a21 | [
"Apache-2.0"
] | 1 | 2021-10-11T07:33:41.000Z | 2021-10-11T07:33:41.000Z | 16.315789 | 51 | 0.719355 | 1,000,397 | package se.liu.ida.hefquin.engine.query;
import java.util.Set;
public interface BGP extends SPARQLGraphPattern
{
/**
* Returns an unmodifiable set of triple patterns.
*/
Set<? extends TriplePattern> getTriplePatterns();
/**
* Returns a string representation of the BGP
*/
String toString();
}
|
923d9f2fa05a450d2313ffbd7a1adddcc3020a74 | 828 | java | Java | src/test/java/com/dnsite/security/user/utils/PasswordGeneratorTest.java | arokasprz100/DNSite | 1f29554a406e4b5b3f36b345eb0ba7be088273fd | [
"Apache-2.0"
] | null | null | null | src/test/java/com/dnsite/security/user/utils/PasswordGeneratorTest.java | arokasprz100/DNSite | 1f29554a406e4b5b3f36b345eb0ba7be088273fd | [
"Apache-2.0"
] | 8 | 2020-09-07T07:00:58.000Z | 2022-02-26T17:34:02.000Z | src/test/java/com/dnsite/security/user/utils/PasswordGeneratorTest.java | arokasprz100/DNSite | 1f29554a406e4b5b3f36b345eb0ba7be088273fd | [
"Apache-2.0"
] | null | null | null | 36 | 95 | 0.621981 | 1,000,398 | package com.dnsite.security.user.utils;
import org.junit.Test;
import static org.junit.Assert.*;
public class PasswordGeneratorTest {
@Test
public void testPasswordGenerator(){
PasswordGenerator passwordGenerator = new PasswordGenerator.PasswordGeneratorBuilder()
.useDigits(true)
.useLower(true)
.useUpper(true)
.build();
String tmpPasswd = passwordGenerator.generate(15);
assertTrue("wrong len: " + tmpPasswd,tmpPasswd.length() == 15);
assertTrue("no digits: "+ tmpPasswd, tmpPasswd.matches(".*[0-9]+.*")); //useDigits
assertTrue("no upper case: "+ tmpPasswd , tmpPasswd.matches(".*[A-Z]+.*")); // useUper
assertTrue("no lower case: " + tmpPasswd, tmpPasswd.matches(".*[a-z]+.*")); // useLower
}
} |
923da0b72db7a78c5de1779af9a8e0053c1eea78 | 2,331 | java | Java | opensrp-register/src/test/java/org/opensrp/register/service/scheduling/HHSchedulesServiceTest.java | fazries/opensrp-server | 9ad058aa6c5a38d9bf24deb9cf894e7e5495ac47 | [
"Apache-2.0"
] | 26 | 2015-03-05T15:44:34.000Z | 2018-11-03T20:01:39.000Z | opensrp-register/src/test/java/org/opensrp/register/service/scheduling/HHSchedulesServiceTest.java | fazries/opensrp-server | 9ad058aa6c5a38d9bf24deb9cf894e7e5495ac47 | [
"Apache-2.0"
] | 462 | 2015-02-23T17:10:38.000Z | 2020-10-23T10:37:04.000Z | opensrp-register/src/test/java/org/opensrp/register/service/scheduling/HHSchedulesServiceTest.java | fazries/opensrp-server | 9ad058aa6c5a38d9bf24deb9cf894e7e5495ac47 | [
"Apache-2.0"
] | 50 | 2015-02-20T12:07:52.000Z | 2020-07-09T11:36:57.000Z | 40.894737 | 134 | 0.750751 | 1,000,399 | package org.opensrp.register.service.scheduling;
import static org.mockito.Mockito.times;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.joda.time.LocalDate;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.opensrp.common.util.TestLoggerAppender;
import org.opensrp.register.service.handler.TestResourceLoader;
import org.opensrp.scheduler.HealthSchedulerService;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({ "org.apache.log4j.*", "org.apache.commons.logging.*" })
public class HHSchedulesServiceTest extends TestResourceLoader {
private HHSchedulesService hhSchedulesService;
@Mock
private HealthSchedulerService scheduler;
@Before
public void setUp() throws Exception {
initMocks(this);
hhSchedulesService = new HHSchedulesService(scheduler);
}
@Test
public void shouldTestAnteNatalCareSchedulesServiceMthods() {
final TestLoggerAppender appender = new TestLoggerAppender();
final Logger logger = Logger.getLogger(HHSchedulesService.class.toString());
logger.setLevel(Level.ALL);
logger.addAppender(appender);
hhSchedulesService.enrollIntoMilestoneOfCensus(entityId,LocalDate.now().toString(), provider,
scheduleName,eventId);
Mockito.verify(scheduler,times(1)).enrollIntoSchedule(entityId, scheduleName, LocalDate.now().toString(), eventId);
hhSchedulesService.fullfillMilestone(entityId, provider, scheduleName, LocalDate.now(), eventId);
Mockito.verify(scheduler,times(1)).fullfillMilestoneAndCloseAlert(entityId, provider, scheduleName, LocalDate.now(), eventId);
final List<LoggingEvent> log = appender.getLog();
final LoggingEvent firstLogEntry = log.get(0);
Assert.assertEquals(firstLogEntry.getRenderedMessage(), "Enrolling household into Census schedule. Id: entityId1");
logger.removeAllAppenders();
}
}
|
923da12e592392ebd6e4458db5a932f51d3da6bd | 2,714 | java | Java | src/main/java/net/jcom/adventofcode/aoc2021/Day2021_05.java | JoKrus/advent-of-code | 95f713dfedaa09c5305ff680404b90423986a897 | [
"Apache-2.0"
] | 2 | 2020-12-01T11:24:09.000Z | 2020-12-01T13:05:18.000Z | src/main/java/net/jcom/adventofcode/aoc2021/Day2021_05.java | JoKrus/advent-of-code | 95f713dfedaa09c5305ff680404b90423986a897 | [
"Apache-2.0"
] | 4 | 2021-04-02T19:38:29.000Z | 2022-03-14T20:04:42.000Z | src/main/java/net/jcom/adventofcode/aoc2021/Day2021_05.java | JoKrus/advent-of-code | 95f713dfedaa09c5305ff680404b90423986a897 | [
"Apache-2.0"
] | null | null | null | 37.178082 | 183 | 0.58364 | 1,000,400 | package net.jcom.adventofcode.aoc2021;
import net.jcom.adventofcode.Day;
import java.awt.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Day2021_05 extends Day {
@Override
public String part1Logic() {
List<Vent> straightVents = Arrays.stream(input.split("\n")).map(s -> {
var coordSplit = Arrays.stream(s.split("->")).map(String::trim)
.map(s1 -> Arrays.stream(s1.split(",")).mapToInt(Integer::parseInt).toArray())
.map(ints -> new Point(ints[0], ints[1])).toList();
return new Vent(coordSplit.get(0), coordSplit.get(1));
}).filter(Vent::isStraight).toList();
Map<Point, Long> collect = straightVents.stream().flatMap(vent -> vent.getPointsOfPipes().stream()).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
long count = collect.entrySet().stream().filter(pointLongEntry -> pointLongEntry.getValue() > 1).count();
return String.format("%d", count);
}
@Override
public String part2Logic() {
List<Vent> straightVents = Arrays.stream(input.split("\n")).map(s -> {
var coordSplit = Arrays.stream(s.split("->")).map(String::trim)
.map(s1 -> Arrays.stream(s1.split(",")).mapToInt(Integer::parseInt).toArray())
.map(ints -> new Point(ints[0], ints[1])).toList();
return new Vent(coordSplit.get(0), coordSplit.get(1));
}).toList();
Map<Point, Long> collect = straightVents.stream().flatMap(vent -> vent.getPointsOfPipes().stream()).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
long count = collect.entrySet().stream().filter(pointLongEntry -> pointLongEntry.getValue() > 1).count();
return String.format("%d", count);
}
public record Vent(Point from, Point to) {
public boolean isStraight() {
return from.x == to.x || from.y == to.y;
}
public HashSet<Point> getPointsOfPipes() {
HashSet<Point> ret = new HashSet<>();
int distX = to.x - from.x;
int distY = to.y - from.y;
int dx = Integer.signum(distX);
int dy = Integer.signum(distY);
int amounts = (Math.max(Math.abs(distX), Math.abs(distY))) + 1;
for (int i = 0; i < amounts; i++) {
int px = from.x + i * dx;
int py = from.y + i * dy;
var point = new Point(px, py);
ret.add(point);
}
return ret;
}
}
}
|
923da1b966eb2de9bc38f51df2064c1e153d45f1 | 891 | java | Java | netty-in-action/telnet-netty-in-action/src/main/java/com/photowey/netty/telnet/in/action/netty/server/RemotingServer.java | photowey/the-way-to-java | 37ec3e12aaebf8f63862837b9d4a506401eb1e38 | [
"Apache-2.0"
] | null | null | null | netty-in-action/telnet-netty-in-action/src/main/java/com/photowey/netty/telnet/in/action/netty/server/RemotingServer.java | photowey/the-way-to-java | 37ec3e12aaebf8f63862837b9d4a506401eb1e38 | [
"Apache-2.0"
] | 1 | 2022-01-28T04:48:47.000Z | 2022-02-20T06:20:44.000Z | netty-in-action/telnet-netty-in-action/src/main/java/com/photowey/netty/telnet/in/action/netty/server/RemotingServer.java | photowey/the-way-to-java | 37ec3e12aaebf8f63862837b9d4a506401eb1e38 | [
"Apache-2.0"
] | null | null | null | 28.774194 | 75 | 0.723094 | 1,000,401 | /*
* Copyright © 2021 the original author or authors (upchh@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.photowey.netty.telnet.in.action.netty.server;
/**
* {@code RemotingServer}
*
* @author photowey
* @date 2021/11/07
* @since 1.0.0
*/
public interface RemotingServer {
void run() throws InterruptedException;
void shutdown();
}
|
923da1ff440936b25cd87dd0d83cd55e9233bc1c | 3,108 | java | Java | scm-webapp/src/main/java/sonia/scm/search/IndexBootstrapListener.java | pmarkiewka/scm-manager | 0956bfc6056c203f1d2b8118c389539d932c55f2 | [
"MIT"
] | 79 | 2020-03-09T09:43:50.000Z | 2022-03-03T13:53:45.000Z | scm-webapp/src/main/java/sonia/scm/search/IndexBootstrapListener.java | pmarkiewka/scm-manager | 0956bfc6056c203f1d2b8118c389539d932c55f2 | [
"MIT"
] | 1,047 | 2020-03-11T10:33:41.000Z | 2022-03-31T13:59:28.000Z | scm-webapp/src/main/java/sonia/scm/search/IndexBootstrapListener.java | pmarkiewka/scm-manager | 0956bfc6056c203f1d2b8118c389539d932c55f2 | [
"MIT"
] | 25 | 2020-03-11T10:22:54.000Z | 2022-03-09T12:52:43.000Z | 34.533333 | 112 | 0.741634 | 1,000,402 | /*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.plugin.Extension;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Optional;
import java.util.Set;
@Singleton
@Extension
@SuppressWarnings("rawtypes")
public class IndexBootstrapListener implements ServletContextListener {
private static final Logger LOG = LoggerFactory.getLogger(IndexBootstrapListener.class);
private final SearchEngine searchEngine;
private final IndexLogStore indexLogStore;
private final Set<Indexer> indexers;
@Inject
public IndexBootstrapListener(SearchEngine searchEngine, IndexLogStore indexLogStore, Set<Indexer> indexers) {
this.searchEngine = searchEngine;
this.indexLogStore = indexLogStore;
this.indexers = indexers;
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
for (Indexer indexer : indexers) {
bootstrap(indexer);
}
}
private void bootstrap(Indexer indexer) {
Optional<IndexLog> indexLog = indexLogStore.defaultIndex().get(indexer.getType());
if (indexLog.isPresent()) {
int version = indexLog.get().getVersion();
if (version != indexer.getVersion()) {
LOG.debug(
"index version {} is older then {}, start reindexing of all {}",
version, indexer.getVersion(), indexer.getType()
);
indexAll(indexer);
}
} else {
LOG.debug("could not find log entry for {} index, start reindexing", indexer.getType());
indexAll(indexer);
}
}
@SuppressWarnings("unchecked")
private void indexAll(Indexer indexer) {
searchEngine.forType(indexer.getType()).update(indexer.getReIndexAllTask());
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// nothing to destroy here
}
}
|
923da27eb3b77199a2566d64e1115b8f176057b4 | 9,111 | java | Java | src/java/simpledb/TupleDesc.java | joker452/MySimpleDB | 813721f88aecd2eba8e818b6a36b26fd6756b573 | [
"MIT"
] | 2 | 2020-09-06T12:20:38.000Z | 2021-12-30T06:55:26.000Z | src/java/simpledb/TupleDesc.java | joker452/MySimpleDB | 813721f88aecd2eba8e818b6a36b26fd6756b573 | [
"MIT"
] | null | null | null | src/java/simpledb/TupleDesc.java | joker452/MySimpleDB | 813721f88aecd2eba8e818b6a36b26fd6756b573 | [
"MIT"
] | null | null | null | 32.655914 | 84 | 0.52958 | 1,000,403 | package simpledb;
import java.io.Serializable;
import java.util.*;
/**
* TupleDesc describes the schema of a tuple.
*/
public class TupleDesc implements Serializable {
/**
* A help class to facilitate organizing the information of each field
*/
public static class TDItem implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The type of the field
*/
public final Type fieldType;
/**
* The name of the field
*/
public final String fieldName;
public TDItem(Type t, String n) {
this.fieldName = n;
this.fieldType = t;
}
public String toString() {
return fieldName + "(" + fieldType + ")";
}
}
/**
* @return An iterator which iterates over all the field TDItems
* that are included in this TupleDesc
*/
public Iterator<TDItem> iterator() {
// some code goes here
Iterator<TDItem> it = new Iterator<TDItem>() {
private int currentIdx = 0;
@Override
public boolean hasNext() {
return currentIdx < fields.length;
}
@Override
public TDItem next() {
if (currentIdx < fields.length)
return fields[currentIdx++];
else
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
private static final long serialVersionUID = 1L;
private static int nullNum = 0;
private int size = 0;
TDItem[] fields;
/**
* Create a new TupleDesc with typeAr.length fields with fields of the
* specified types, with associated named fields.
*
* @param typeAr array specifying the number of and types of fields in this
* TupleDesc. It must contain at least one entry.
* @param fieldAr array specifying the names of the fields. Note that names may
* be null.
*/
public TupleDesc(Type[] typeAr, String[] fieldAr) {
// some code goes here
fields = new TDItem[typeAr.length];
for (int i = 0; i < typeAr.length; ++i) {
if (fieldAr[i] != null)
fields[i] = new TDItem(typeAr[i], fieldAr[i]);
else {
++nullNum;
fields[i] = new TDItem(typeAr[i], "__" + nullNum);
}
size += typeAr[i].getLen();
}
}
/**
* Constructor. Create a new tuple desc with typeAr.length fields with
* fields of the specified types, with anonymous (unnamed) fields.
*
* @param typeAr array specifying the number of and types of fields in this
* TupleDesc. It must contain at least one entry.
*/
public TupleDesc(Type[] typeAr) {
// some code goes here
fields = new TDItem[typeAr.length];
for (int i = 0; i < typeAr.length; ++i) {
++nullNum;
fields[i] = new TDItem(typeAr[i], "__" + nullNum);
size += typeAr[i].getLen();
}
}
/**
* @return the number of fields in this TupleDesc
*/
public int numFields() {
// some code goes here
return fields.length;
}
/**
* Gets the (possibly null) field name of the ith field of this TupleDesc.
*
* @param i index of the field name to return. It must be a valid index.
* @return the name of the ith field
* @throws NoSuchElementException if i is not a valid field reference.
*/
public String getFieldName(int i) throws NoSuchElementException {
// some code goes here
if (-1 < i && i < fields.length)
return fields[i].fieldName;
else
throw new NoSuchElementException();
}
/**
* Gets the type of the ith field of this TupleDesc.
*
* @param i The index of the field to get the type of. It must be a valid
* index.
* @return the type of the ith field
* @throws NoSuchElementException if i is not a valid field reference.
*/
public Type getFieldType(int i) throws NoSuchElementException {
// some code goes here
if (-1 < i && i < fields.length)
return fields[i].fieldType;
else
throw new NoSuchElementException();
}
/**
* Find the index of the field with a given name.
*
* @param name name of the field.
* @return the index of the field that is first to have the given name.
* @throws NoSuchElementException if no field with a matching name is found.
*/
public int fieldNameToIndex(String name) throws NoSuchElementException {
// some code goes here
if (name == null) {
for (int i = 0; i < fields.length; ++i)
if (fields[i].fieldName.startsWith("__"))
return i;
} else {
for (int i = 0; i < fields.length; ++i)
if (name.equals(fields[i].fieldName))
return i;
}
throw new NoSuchElementException();
}
/**
* @return The size (in bytes) of tuples corresponding to this TupleDesc.
* Note that tuples from a given TupleDesc are of a fixed size.
*/
public int getSize() {
// some code goes here
return size;
}
/**
* Merge two TupleDescs into one, with td1.numFields + td2.numFields fields,
* with the first td1.numFields coming from td1 and the remaining from td2.
*
* @param td1 The TupleDesc with the first fields of the new TupleDesc
* @param td2 The TupleDesc with the last fields of the TupleDesc
* @return the new TupleDesc
*/
public static TupleDesc merge(TupleDesc td1, TupleDesc td2) {
// some code goes here
if (td1 == null)
if (td2 == null)
return null;
else
return td2;
else if (td2 == null)
return td1;
else {
int td1Num = td1.numFields();
int td2Num = td2.numFields();
int numFields = td1Num + td2Num;
Type[] newTypes = new Type[numFields];
String[] newNames = new String[numFields];
for (int i = 0; i < td1Num; ++i) {
newTypes[i] = td1.fields[i].fieldType;
newNames[i] = td1.fields[i].fieldName;
}
for (int i = td1Num; i < numFields; ++i) {
newTypes[i] = td2.fields[i - td1Num].fieldType;
newNames[i] = td2.fields[i - td1Num].fieldName;
}
return new TupleDesc(newTypes, newNames);
}
}
/**
* Compares the specified object with this TupleDesc for equality. Two
* TupleDescs are considered equal if they have the same number of items
* and if the i-th type in this TupleDesc is equal to the i-th type in o
* for every i.
*
* @param o the Object to be compared for equality with this TupleDesc.
* @return true if the object is equal to this TupleDesc.
*/
public boolean equals(Object o) {
// some code goes here
// object equality
if (this == o)
return true;
if (o != null) {
TupleDesc other;
int i;
try {
other = (TupleDesc) o;
} catch (Exception e) {
return false;
}
if (fields.length == other.numFields()) {
for (i = 0; i < fields.length; ++i)
if (fields[i].fieldType != other.fields[i].fieldType)
break;
if (i == fields.length)
return true;
}
}
return false;
}
public int hashCode() {
// If you want to use TupleDesc as keys for HashMap, implement this so
// that equal objects have equals hashCode() results
throw new UnsupportedOperationException("unimplemented");
}
/**
* Returns a String describing this descriptor. It should be of the form
* "fieldType[0](fieldName[0]), ..., fieldType[M](fieldName[M])", although
* the exact format does not matter.
*
* @return String describing this descriptor.
*/
public String toString() {
// some code goes here
StringBuilder tdStr = new StringBuilder();
for (int i = 0; i < fields.length - 1; ++i) {
tdStr.append(fields[i].toString());
tdStr.append(", ");
}
tdStr.append(fields[fields.length - 1]);
return tdStr.toString();
}
}
|
923da3274616878e1eee882d400fc680906750df | 9,252 | java | Java | jgrapht-master/jgrapht-core/src/test/java/org/jgrapht/alg/matching/MaximumWeightBipartiteMatchingTest.java | jhroemer/AmodSimulator | 32845c0841f0f2c4ec3ef0263d05d8dba048ffca | [
"MIT"
] | 1 | 2020-09-03T04:33:50.000Z | 2020-09-03T04:33:50.000Z | jgrapht-master/jgrapht-core/src/test/java/org/jgrapht/alg/matching/MaximumWeightBipartiteMatchingTest.java | jhroemer/AmodSimulator | 32845c0841f0f2c4ec3ef0263d05d8dba048ffca | [
"MIT"
] | null | null | null | jgrapht-master/jgrapht-core/src/test/java/org/jgrapht/alg/matching/MaximumWeightBipartiteMatchingTest.java | jhroemer/AmodSimulator | 32845c0841f0f2c4ec3ef0263d05d8dba048ffca | [
"MIT"
] | null | null | null | 35.312977 | 87 | 0.596736 | 1,000,404 | /*
* (C) Copyright 2015-2018, by Graeme Ahokas and Contributors.
*
* JGraphT : a free Java graph-theory library
*
* This program and the accompanying materials are dual-licensed under
* either
*
* (a) the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation, or (at your option) any
* later version.
*
* or (per the licensee's choosing)
*
* (b) the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation.
*/
package org.jgrapht.alg.matching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.jgrapht.Graph;
import org.jgrapht.alg.interfaces.MatchingAlgorithm.Matching;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
public class MaximumWeightBipartiteMatchingTest
{
private SimpleWeightedGraph<String, DefaultWeightedEdge> graph;
private Set<String> partition1;
private Set<String> partition2;
private MaximumWeightBipartiteMatching<String, DefaultWeightedEdge> matcher;
@Before
public void setUpGraph()
{
graph = new SimpleWeightedGraph<>(DefaultWeightedEdge.class);
graph.addVertex("s1");
graph.addVertex("s2");
graph.addVertex("s3");
graph.addVertex("s4");
graph.addVertex("t1");
graph.addVertex("t2");
graph.addVertex("t3");
graph.addVertex("t4");
partition1 = new HashSet<>();
partition1.add("s1");
partition1.add("s2");
partition1.add("s3");
partition1.add("s4");
partition2 = new HashSet<>();
partition2.add("t1");
partition2.add("t2");
partition2.add("t3");
partition2.add("t4");
}
@Test
public void maximumWeightBipartiteMatching1()
{
DefaultWeightedEdge e1 = graph.addEdge("s1", "t1");
graph.setEdgeWeight(e1, 1);
matcher = new MaximumWeightBipartiteMatching<>(graph, partition1, partition2);
Matching<String, DefaultWeightedEdge> matchings = matcher.getMatching();
assertEquals(1, matchings.getEdges().size());
assertTrue(matchings.getEdges().contains(e1));
}
@Test
public void maximumWeightBipartiteMatching2()
{
DefaultWeightedEdge e1 = graph.addEdge("s1", "t1");
graph.setEdgeWeight(e1, 1);
DefaultWeightedEdge e2 = graph.addEdge("s2", "t1");
graph.setEdgeWeight(e2, 2);
matcher = new MaximumWeightBipartiteMatching<>(graph, partition1, partition2);
Matching<String, DefaultWeightedEdge> matchings = matcher.getMatching();
assertEquals(1, matchings.getEdges().size());
assertTrue(matchings.getEdges().contains(e2));
}
@Test
public void maximumWeightBipartiteMatching3()
{
DefaultWeightedEdge e1 = graph.addEdge("s1", "t1");
graph.setEdgeWeight(e1, 2);
DefaultWeightedEdge e2 = graph.addEdge("s1", "t2");
graph.setEdgeWeight(e2, 1);
DefaultWeightedEdge e3 = graph.addEdge("s2", "t1");
graph.setEdgeWeight(e3, 2);
matcher = new MaximumWeightBipartiteMatching<>(graph, partition1, partition2);
Matching<String, DefaultWeightedEdge> matchings = matcher.getMatching();
assertEquals(2, matchings.getEdges().size());
assertTrue(matchings.getEdges().contains(e2));
assertTrue(matchings.getEdges().contains(e3));
}
@Test
public void maximumWeightBipartiteMatching4()
{
DefaultWeightedEdge e1 = graph.addEdge("s1", "t1");
graph.setEdgeWeight(e1, 1);
DefaultWeightedEdge e2 = graph.addEdge("s1", "t2");
graph.setEdgeWeight(e2, 1);
DefaultWeightedEdge e3 = graph.addEdge("s2", "t2");
graph.setEdgeWeight(e3, 1);
matcher = new MaximumWeightBipartiteMatching<>(graph, partition1, partition2);
Matching<String, DefaultWeightedEdge> matchings = matcher.getMatching();
assertEquals(2, matchings.getEdges().size());
assertTrue(matchings.getEdges().contains(e1));
assertTrue(matchings.getEdges().contains(e3));
}
@Test
public void maximumWeightBipartiteMatching5()
{
DefaultWeightedEdge e1 = graph.addEdge("s1", "t1");
graph.setEdgeWeight(e1, 1);
DefaultWeightedEdge e2 = graph.addEdge("s1", "t2");
graph.setEdgeWeight(e2, 2);
DefaultWeightedEdge e3 = graph.addEdge("s2", "t2");
graph.setEdgeWeight(e3, 2);
DefaultWeightedEdge e4 = graph.addEdge("s3", "t2");
graph.setEdgeWeight(e4, 2);
DefaultWeightedEdge e5 = graph.addEdge("s3", "t3");
graph.setEdgeWeight(e5, 1);
DefaultWeightedEdge e6 = graph.addEdge("s4", "t1");
graph.setEdgeWeight(e6, 1);
DefaultWeightedEdge e7 = graph.addEdge("s4", "t4");
graph.setEdgeWeight(e7, 1);
matcher = new MaximumWeightBipartiteMatching<>(graph, partition1, partition2);
Matching<String, DefaultWeightedEdge> matchings = matcher.getMatching();
assertEquals(4, matchings.getEdges().size());
assertTrue(matchings.getEdges().contains(e1));
assertTrue(matchings.getEdges().contains(e3));
assertTrue(matchings.getEdges().contains(e5));
assertTrue(matchings.getEdges().contains(e7));
}
@Test
public void testRandomInstancesFixedSeed()
{
testRandomInstance(new Random(17), 100, 0.7, 2);
}
@Test
public void testRandomInstances()
{
Random rng = new Random();
testRandomInstance(rng, 100, 0.8, 1);
testRandomInstance(rng, 1000, 0.8, 1);
}
private void testRandomInstance(Random rng, int n, double p, int repeat)
{
for (int a = 0; a < repeat; a++) {
// generate random bipartite
Graph<Integer, DefaultWeightedEdge> g =
new SimpleWeightedGraph<>(DefaultWeightedEdge.class);
Set<Integer> partitionA = new LinkedHashSet<>(n);
for (int i = 0; i < n; i++) {
g.addVertex(i);
partitionA.add(i);
}
Set<Integer> partitionB = new LinkedHashSet<>(n);
for (int i = 0; i < n; i++) {
g.addVertex(n + i);
partitionB.add(n + i);
}
// create edges
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// s->t
if (rng.nextDouble() < p) {
g.addEdge(i, n + j);
}
}
}
// assign random weights
for (DefaultWeightedEdge e : g.edgeSet()) {
g.setEdgeWeight(e, 1000 * rng.nextInt());
}
// compute maximum weight matching
MaximumWeightBipartiteMatching<Integer, DefaultWeightedEdge> alg =
new MaximumWeightBipartiteMatching<>(g, partitionA, partitionB);
Matching<Integer, DefaultWeightedEdge> matching = alg.getMatching();
Map<Integer, BigDecimal> pot = alg.getPotentials();
Comparator<BigDecimal> comparator = Comparator.<BigDecimal> naturalOrder();
// assert matching
Map<Integer, Integer> degree = new HashMap<>();
for (Integer v : g.vertexSet()) {
degree.put(v, 0);
}
for (DefaultWeightedEdge e : matching.getEdges()) {
Integer s = g.getEdgeSource(e);
Integer t = g.getEdgeTarget(e);
degree.put(s, degree.get(s) + 1);
degree.put(t, degree.get(t) + 1);
}
for (Integer v : g.vertexSet()) {
assertTrue(degree.get(v) <= 1);
}
// assert non-negative potentials
for (Integer v : g.vertexSet()) {
assertTrue(comparator.compare(pot.get(v), BigDecimal.ZERO) >= 0);
}
// assert non-negative reduced cost for edges
for (DefaultWeightedEdge e : g.edgeSet()) {
Integer s = g.getEdgeSource(e);
Integer t = g.getEdgeTarget(e);
BigDecimal w = BigDecimal.valueOf(g.getEdgeWeight(e));
assertTrue(comparator.compare(w, pot.get(s).add(pot.get(t))) <= 0);
}
// assert tight edges in matching
for (DefaultWeightedEdge e : matching.getEdges()) {
Integer s = g.getEdgeSource(e);
Integer t = g.getEdgeTarget(e);
BigDecimal w = BigDecimal.valueOf(g.getEdgeWeight(e));
assertTrue(comparator.compare(w, pot.get(s).add(pot.get(t))) == 0);
}
// assert free nodes have zero potential
for (Integer v : g.vertexSet()) {
if (degree.get(v) == 0) {
assertEquals(pot.get(v), BigDecimal.ZERO);
}
}
}
}
}
|
923da3481f003cc7f730ff7f63be80af3936a7e9 | 3,599 | java | Java | src/plantuml-asl/src/net/sourceforge/plantuml/version/PSystemLicense.java | SandraBSofiaH/Final-UMldoclet | e27bef0356cecaf6bad55bd41d3a6a1ba943e0a2 | [
"Apache-2.0"
] | 174 | 2016-03-02T20:22:19.000Z | 2022-03-18T09:28:05.000Z | src/plantuml-asl/src/net/sourceforge/plantuml/version/PSystemLicense.java | SandraBSofiaH/Final-UMldoclet | e27bef0356cecaf6bad55bd41d3a6a1ba943e0a2 | [
"Apache-2.0"
] | 314 | 2016-03-01T06:59:04.000Z | 2022-03-21T19:59:08.000Z | src/plantuml-asl/src/net/sourceforge/plantuml/version/PSystemLicense.java | SandraBSofiaH/Final-UMldoclet | e27bef0356cecaf6bad55bd41d3a6a1ba943e0a2 | [
"Apache-2.0"
] | 29 | 2017-04-29T06:52:27.000Z | 2022-02-22T01:52:16.000Z | 34.941748 | 99 | 0.73576 | 1,000,405 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.version;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.PlainDiagram;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.UmlSource;
import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.graphic.UDrawable;
import net.sourceforge.plantuml.svek.TextBlockBackcolored;
import net.sourceforge.plantuml.ugraphic.AffineTransformType;
import net.sourceforge.plantuml.ugraphic.PixelImage;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UImage;
import net.sourceforge.plantuml.ugraphic.UTranslate;
public class PSystemLicense extends PlainDiagram implements UDrawable {
@Override
protected UDrawable getRootDrawable(FileFormatOption fileFormatOption) {
return this;
}
public static PSystemLicense create(UmlSource source) throws IOException {
return new PSystemLicense(source);
}
public PSystemLicense(UmlSource source) {
super(source);
}
private TextBlockBackcolored getGraphicStrings(List<String> strings) {
return GraphicStrings.createBlackOnWhite(strings);
}
public DiagramDescription getDescription() {
return new DiagramDescription("(License)");
}
public void drawU(UGraphic ug) {
final LicenseInfo licenseInfo = LicenseInfo.retrieveQuick();
final BufferedImage logo = LicenseInfo.retrieveDistributorImage(licenseInfo);
if (logo == null) {
final List<String> strings = new ArrayList<>();
strings.addAll(License.getCurrent().getText1(licenseInfo));
strings.addAll(License.getCurrent().getText2(licenseInfo));
getGraphicStrings(strings).drawU(ug);
} else {
final List<String> strings1 = new ArrayList<>();
final List<String> strings2 = new ArrayList<>();
strings1.addAll(License.getCurrent().getText1(licenseInfo));
strings2.addAll(License.getCurrent().getText2(licenseInfo));
final TextBlockBackcolored result1 = getGraphicStrings(strings1);
result1.drawU(ug);
ug = ug.apply(UTranslate.dy(4 + result1.calculateDimension(ug.getStringBounder()).getHeight()));
UImage im = new UImage(new PixelImage(logo, AffineTransformType.TYPE_BILINEAR));
ug.apply(UTranslate.dx(20)).draw(im);
ug = ug.apply(UTranslate.dy(im.getHeight()));
final TextBlockBackcolored result2 = getGraphicStrings(strings2);
result2.drawU(ug);
}
}
}
|
923da351a973a0356a4c2a7e62bf1ecaf48245ef | 16,230 | java | Java | Client/app/src/main/java/com/example/carlicense/MainActivity.java | YTMartian/Graphic-and-Image-LPR- | f5e08c685cf997e248a34b82e6138821f589d726 | [
"Unlicense"
] | null | null | null | Client/app/src/main/java/com/example/carlicense/MainActivity.java | YTMartian/Graphic-and-Image-LPR- | f5e08c685cf997e248a34b82e6138821f589d726 | [
"Unlicense"
] | null | null | null | Client/app/src/main/java/com/example/carlicense/MainActivity.java | YTMartian/Graphic-and-Image-LPR- | f5e08c685cf997e248a34b82e6138821f589d726 | [
"Unlicense"
] | null | null | null | 41.192893 | 140 | 0.597905 | 1,000,406 | package com.example.carlicense;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.alipay.sdk.app.PayTask;
import com.example.carlicense.ui.about.AboutFragment;
import com.example.carlicense.ui.home.HomeFragment;
import com.example.carlicense.ui.settings.SettingsFragment;
import com.github.clans.fab.FloatingActionMenu;
import com.github.clans.fab.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
boolean is_get_in = false;
Dialog myDialog;
String server_ip;
String username;
//支付宝api配置
private static final int SDK_PAY_FLAG = 1001;
private String RSA_PRIVATE = "";
public static final String APPID = "";
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//AndroidManifest.xml里MainActivity要设置android:theme="@style/AppTheme.NoActionBar"
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home,
R.id.nav_settings,
R.id.nav_about)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//设置监听导航按钮的点击
navigationView.setNavigationItemSelectedListener(this);
myDialog = new Dialog(this);
server_ip = "http://10.230.238.189:8000";
username = "test";
Intent intent = getIntent();
username = intent.getStringExtra("username"); //从LoginActivity传来的参数
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
//点击不同导航按钮的事件
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
FloatingActionMenu menu = findViewById(R.id.menu);
switch (menuItem.getItemId()) {
case R.id.nav_home:
menu.showMenu(true);
getSupportActionBar().setTitle("主页");//设置导航栏的text
//放入HomeFragment.
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
new HomeFragment()).commit();
break;
case R.id.nav_settings:
menu.hideMenu(true);
getSupportActionBar().setTitle("设置");
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
new SettingsFragment()).commit();
break;
case R.id.nav_about:
menu.hideMenu(true);
getSupportActionBar().setTitle("关于");
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
new AboutFragment()).commit();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//点击history按钮
public void clickHistory(View view) {
myDialog.setContentView(R.layout.popup_history_list);
ListView history_list = myDialog.findViewById(R.id.history_list);
//传入显示数据,MyAdapter构造函数的的五个参数
ArrayList<String>[] s = new ArrayList[5];
for (int i = 0; i < 5; i++) s[i] = new ArrayList<>();
ServerTools serverTools = new ServerTools(server_ip);
try {
String jsons = serverTools.doPost(this.username, "", "/system/get_history/");
StringBuilder sb = new StringBuilder(jsons);
//不知道怎么把python server返回的json字符串转为java的json格式,所以直接正则匹配,对每一部分分别转json
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length() - 1);//去掉收尾的大括号
jsons = new String(sb);
//正则匹配
Pattern p = Pattern.compile("\\{([^}])*\\}");
Matcher m = p.matcher(jsons);
while (m.find()) {
String json = m.group();
JSONObject jsonObject = new JSONObject(json);
s[0].add(jsonObject.optString("photograph"));
s[1].add(jsonObject.optString("license_plate"));
s[2].add(jsonObject.optString("type"));
s[3].add(jsonObject.optString("time"));
s[4].add(jsonObject.optString("price"));
}
} catch (Exception e) {
e.printStackTrace();
}
//反转ArrayList,将最新的记录显示在上边
for (ArrayList<String> i : s) Collections.reverse(i);
MyAdapter myAdapter = new MyAdapter(this, s[0], s[1], s[2], s[3], s[4]);
history_list.setAdapter(myAdapter);
myDialog.show();
}
//history列表显示类
class MyAdapter extends ArrayAdapter<String> {
Context context;
ArrayList<String> history_license_plate_image;
ArrayList<String> history_license_plate_text;
ArrayList<String> history_car_type;
ArrayList<String> history_time;
ArrayList<String> history_pay_toll;
MyAdapter(Context c, ArrayList<String> s1, ArrayList<String> s2, ArrayList<String> s3, ArrayList<String> s4, ArrayList<String> s5) {
//父类构造函数这里,得加上第三和第四个参数,大概类似于标识符以示区分?
super(c, R.layout.row, R.id.history_license_plate_text, s2);
this.context = c;
this.history_license_plate_image = s1;
this.history_license_plate_text = s2;
this.history_car_type = s3;
this.history_time = s4;
this.history_pay_toll = s5;
}
@SuppressLint("SetTextI18n")
@NonNull
@Override
public View getView(int position, @NonNull View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater =
(LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.row, parent, false);
MyImageView history_license_plate_image = row.findViewById(R.id.history_license_plate_image);
TextView history_license_plate_text = row.findViewById(R.id.history_license_plate_text);
TextView history_car_type = row.findViewById(R.id.history_car_type);
TextView history_time = row.findViewById(R.id.history_time);
TextView history_pay_toll = row.findViewById(R.id.history_pay_toll);
history_license_plate_image.setImageURL(server_ip + "/static/images/" + this.history_license_plate_image.get(position));
history_license_plate_text.setText(history_license_plate_text.getText() + this.history_license_plate_text.get(position));
history_car_type.setText(history_car_type.getText() + this.history_car_type.get(position));
history_time.setText(history_time.getText() + this.history_time.get(position));
history_pay_toll.setText(history_pay_toll.getText() + this.history_pay_toll.get(position) + "元");
return row;
}
}
//点击get_in按钮
@SuppressLint("SetTextI18n")
public void clickGetIn(View view) {
//弹出确认框
myDialog.setContentView(R.layout.popup);
//注意应在myDialog下find,否则就是空指针错误
MyImageView license_plate_image = myDialog.findViewById(R.id.license_plate_image);
TextView license_plate_text = myDialog.findViewById(R.id.license_plate_text);
TextView car_type = myDialog.findViewById(R.id.car_type);
TextView now_time = myDialog.findViewById(R.id.now_time);
TextView pay_toll = myDialog.findViewById(R.id.pay_toll);
//向服务器请求当前结果
ServerTools serverTools = new ServerTools(server_ip);
String json = "";
try {
if (is_get_in) {
//这里其实应该写"True",懒得改了。。。
json = serverTools.doPost("False", "", "/system/get_current_result/");
} else {
json = serverTools.doPost("True", "", "/system/get_current_result/");
}
} catch (Exception e) {
e.printStackTrace();
}
if (!json.isEmpty()) {
try {
//处理json数据
JSONObject jsonObject = new JSONObject(json);
String color = jsonObject.optString("color");
color = color.equals("黄") ? "大车" : color.equals("蓝") ? "小车" : "";
String license_plate = jsonObject.optString("license_plate");
String time = jsonObject.optString("time");
String image = jsonObject.optString("image");
String price = jsonObject.optString("price");
/**
* 太坑了!!!一直app内不能联网,但avd是能的,每次重新run依然不能联网,需要
* 在avd内把app卸载了,再run app就能联网了,可能是部分文件没更新?
*/
license_plate_image.setImageURL(server_ip + "/static/images/" + image);
license_plate_text.setText(license_plate_text.getText() + license_plate);
car_type.setText(car_type.getText() + color);
now_time.setText(now_time.getText() + time);
pay_toll.setText(pay_toll.getText() + price + "元");
if (is_get_in) {
pay_toll.setVisibility(View.VISIBLE);
} else {
pay_toll.setVisibility(View.GONE);
}
myDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//点击确定按钮
public void clickEnsure(View view) {
String state = "success";
if (is_get_in) {
//记录进入
ServerTools serverTools = new ServerTools(server_ip);
try {
String json = serverTools.doPost("False", "", "/system/get_in_and_out/");
JSONObject jsonObject = new JSONObject(json);
state = jsonObject.optString("state");
} catch (Exception e) {
e.printStackTrace();
}
} else {
//记录离开
ServerTools serverTools = new ServerTools(server_ip);
try {
String json = serverTools.doPost("True", "", "/system/get_in_and_out/");
JSONObject jsonObject = new JSONObject(json);
state = jsonObject.optString("state");
} catch (Exception e) {
e.printStackTrace();
}
}
myDialog.dismiss();
if (state.equals("failed")) {
showHint("保存失败!未检测到车牌", Boolean.FALSE);
} else {
FloatingActionButton button = findViewById(R.id.get_in);
//更改按钮图标和文字
if (is_get_in) {
button.setImageResource(R.drawable.ic_get_in);
button.setLabelText("进入");
/**
* 支付宝支付
*/
//秘钥验证的类型 true:RSA2 false:RSA
boolean rsa = false;
//构造支付订单参数列表
Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa);
//构造支付订单参数信息
String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//对支付参数信息进行签名
String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE, rsa);
//订单信息
final String orderInfo = orderParam + "&" + sign;
//异步处理
Runnable payRunnable = new Runnable() {
@Override
public void run() {
//新建任务
PayTask alipay = new PayTask(MainActivity.this);
//获取支付结果
Map<String, String> result = alipay.payV2(orderInfo, true);
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
// 必须异步调用
Thread payThread = new Thread(payRunnable);
payThread.start();
} else {
button.setImageResource(R.drawable.ic_get_out);
button.setLabelText("离开");
}
is_get_in = !is_get_in;
showHint("", true);
}
}
//弹窗信息显示
public void showHint(String s, Boolean play_video) {
myDialog.setContentView(R.layout.popup_hint);
//播放视频
VideoView videoView = myDialog.findViewById(R.id.railing_video);
videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.railing));
TextView hint = myDialog.findViewById(R.id.hint_text);
hint.setText(s);
if (play_video) {
videoView.setVisibility(View.VISIBLE);
} else {
videoView.setVisibility(View.GONE);
}
myDialog.show();
if (play_video) {
videoView.requestFocus();
videoView.start();
}
}
public void clickPlaySettingsVideo(View view) {
VideoView videoView = findViewById(R.id.settings_video);
videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.ape));
videoView.requestFocus();
videoView.start();
}
//参见支付宝api demo sdk:PayDemoActivity.java
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SDK_PAY_FLAG:
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
/**
对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
*/
String resultInfo = payResult.getResult();
Log.i("Pay", "Pay:" + resultInfo);
String resultStatus = payResult.getResultStatus();
// 判断resultStatus 为9000则代表支付成功
if (TextUtils.equals(resultStatus, "9000")) {
// 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
} else {
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
Toast.makeText(MainActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
}
break;
}
}
};
}
|
923da3a669701c9f35cd452ee09426959a26c845 | 9,200 | java | Java | AIJ/app/src/main/java/me/mitul/aij/Constants/JustifiedTextView.java | mitulvaghamshi/android-store | 147caab2622d15c52cd5b8cf21779c73481c9020 | [
"MIT"
] | null | null | null | AIJ/app/src/main/java/me/mitul/aij/Constants/JustifiedTextView.java | mitulvaghamshi/android-store | 147caab2622d15c52cd5b8cf21779c73481c9020 | [
"MIT"
] | null | null | null | AIJ/app/src/main/java/me/mitul/aij/Constants/JustifiedTextView.java | mitulvaghamshi/android-store | 147caab2622d15c52cd5b8cf21779c73481c9020 | [
"MIT"
] | null | null | null | 32.280702 | 106 | 0.613587 | 1,000,407 | package me.mitul.aij.Constants;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import java.util.ArrayList;
import java.util.List;
public class JustifiedTextView extends View {
private boolean hasTextBeenDrown = false;
private Context mContext;
private TextPaint textPaint;
private int lineSpace = 0;
private int lineHeight = 0;
private int textAreaWidth = 0;
private int measuredViewHeight = 0;
private int measuredViewWidth = 0;
private String text;
private List<String> lineList = new ArrayList<>();
public JustifiedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
constructor(context, attrs);
}
public JustifiedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
constructor(context, attrs);
}
public JustifiedTextView(Context context) {
super(context);
constructor(context, null);
}
private void constructor(Context context, AttributeSet attrs) {
mContext = context;
XmlToClassAttribHandler mXmlParser = new XmlToClassAttribHandler(mContext, attrs);
initTextPaint();
if (attrs != null) {
String text;
int textColor;
int textSize;
int textSizeUnit;
text = mXmlParser.getTextValue();
textColor = mXmlParser.getColorValue();
textSize = mXmlParser.getTextSize();
textSizeUnit = mXmlParser.gettextSizeUnit();
setText(text);
setTextColor(textColor);
if (textSizeUnit == -1) setTextSize(textSize);
else setTextSize(textSizeUnit, textSize);
// setText(XmlToClassAttribHandler.GetAttributeStringValue(mContext, attrs, namespace, key, ""));
setTypeFace(mXmlParser.getTypeFace());
//setTypeFace(Typeface.create("serif", Typeface.NORMAL));
}
ViewTreeObserver observer = getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (hasTextBeenDrown) return;
hasTextBeenDrown = true;
setTextAreaWidth(getWidth() - (getPaddingLeft() + getPaddingRight()));
calculate();
}
});
}
private void calculate() {
setLineHeight(getTextPaint());
lineList.clear();
lineList = divideOriginalTextToStringLineList(getText());
setMeasuredDimentions(lineList.size(), getLineHeight(), getLineSpace());
measure(getMeasuredViewWidth(), getMeasuredViewHeight());
}
private void initTextPaint() {
textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
textPaint.setTextAlign(Align.LEFT);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getMeasuredViewWidth() > 0) {
requestLayout();
setMeasuredDimension(getMeasuredViewWidth(), getMeasuredViewHeight());
} else super.onMeasure(widthMeasureSpec, heightMeasureSpec);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
int rowIndex = getPaddingTop();
int colIndex = 0;
if (getAlignment() == Align.RIGHT) colIndex = getPaddingLeft() + getTextAreaWidth();
else colIndex = getPaddingLeft();
for (int i = 0; i < lineList.size(); i++) {
rowIndex += getLineHeight() + getLineSpace();
canvas.drawText(lineList.get(i), colIndex, rowIndex, getTextPaint());
}
}
private List<String> divideOriginalTextToStringLineList(String originalText) {
ArrayList<String> listStringLine = new ArrayList<String>();
String line = "";
float textWidth;
String[] listParageraphes = originalText.split("\n");
for (String listParageraphe : listParageraphes) {
String[] arrayWords = listParageraphe.split(" ");
for (int i = 0; i < arrayWords.length; i++) {
line += arrayWords[i] + " ";
textWidth = getTextPaint().measureText(line);
if (getTextAreaWidth() == textWidth) {
listStringLine.add(line);
line = "";//make line clear
continue;
} else if (getTextAreaWidth() < textWidth) {
int lastWordCount = arrayWords[i].length();
line = line.substring(0, line.length() - lastWordCount - 1);
if (line.trim().length() == 0)
continue;
line = justifyTextLine(textPaint, line.trim(), getTextAreaWidth());
listStringLine.add(line);
line = "";
i++;
continue;
}
if (i == arrayWords.length - 1) {
listStringLine.add(line);
line = "";
}
}
}
return listStringLine;
}
private String justifyTextLine(TextPaint textPaint, String lineString, int textAreaWidth) {
int gapIndex = 0;
float lineWidth = textPaint.measureText(lineString);
while (lineWidth < textAreaWidth && lineWidth > 0) {
gapIndex = lineString.indexOf(" ", gapIndex + 2);
if (gapIndex == -1) {
gapIndex = 0;
gapIndex = lineString.indexOf(" ", gapIndex + 1);
if (gapIndex == -1) return lineString;
}
lineString = lineString.substring(0, gapIndex) + " " + lineString.substring(gapIndex + 1);
lineWidth = textPaint.measureText(lineString);
}
return lineString;
}
private void setLineHeight(TextPaint textPaint) {
Rect bounds = new Rect();
/*"این حسین کیست که عالم همه دیوانه اوست"*/
String sampleStr = "Hussein, who is the crazy world of all";
textPaint.getTextBounds(sampleStr, 0, sampleStr.length(), bounds);
setLineHeight(bounds.height());
}
public void setMeasuredDimentions(int lineListSize, int lineHeigth, int lineSpace) {
int mHeight = lineListSize * (lineHeigth + lineSpace) + lineSpace;
mHeight += getPaddingRight() + getPaddingLeft();
setMeasuredViewHeight(mHeight);
setMeasuredViewWidth(getWidth());
}
private int getTextAreaWidth() {
return textAreaWidth;
}
private void setTextAreaWidth(int textAreaWidth) {
this.textAreaWidth = textAreaWidth;
}
private int getLineHeight() {
return lineHeight;
}
private void setLineHeight(int lineHeight) {
this.lineHeight = lineHeight;
}
private int getMeasuredViewHeight() {
return measuredViewHeight;
}
private void setMeasuredViewHeight(int measuredViewHeight) {
this.measuredViewHeight = measuredViewHeight;
}
private int getMeasuredViewWidth() {
return measuredViewWidth;
}
private void setMeasuredViewWidth(int measuredViewWidth) {
this.measuredViewWidth = measuredViewWidth;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
calculate();
invalidate();
}
public void setText(int resid) {
setText(mContext.getResources().getString(resid));
}
public Typeface getTypeFace() {
return getTextPaint().getTypeface();
}
public void setTypeFace(Typeface typeFace) {
getTextPaint().setTypeface(typeFace);
}
public float getTextSize() {
return getTextPaint().getTextSize();
}
private void setTextSize(float textSize) {
getTextPaint().setTextSize(textSize);
calculate();
invalidate();
}
public void setTextSize(int unit, float textSize) {
textSize = TypedValue.applyDimension(unit, textSize, mContext.getResources().getDisplayMetrics());
setTextSize(textSize);
}
public TextPaint getTextPaint() {
return textPaint;
}
public void setTextPaint(TextPaint textPaint) {
this.textPaint = textPaint;
}
public void setLineSpacing(int lineSpace) {
this.lineSpace = lineSpace;
invalidate();
}
public int getTextColor() {
return getTextPaint().getColor();
}
public void setTextColor(int textColor) {
getTextPaint().setColor(textColor);
invalidate();
}
public int getLineSpace() {
return lineSpace;
}
public Align getAlignment() {
return getTextPaint().getTextAlign();
}
public void setAlignment(Align align) {
getTextPaint().setTextAlign(align);
invalidate();
}
}
|
923da4dda8d60e2434a4e44f139ad7bde834ba75 | 572 | java | Java | src/org/slf4j/LoggerFactory.java | paulpalaszewski/log2j | 9d65fea072d93ce0f18b3188c175265cbc2b3e3b | [
"Apache-2.0"
] | null | null | null | src/org/slf4j/LoggerFactory.java | paulpalaszewski/log2j | 9d65fea072d93ce0f18b3188c175265cbc2b3e3b | [
"Apache-2.0"
] | null | null | null | src/org/slf4j/LoggerFactory.java | paulpalaszewski/log2j | 9d65fea072d93ce0f18b3188c175265cbc2b3e3b | [
"Apache-2.0"
] | null | null | null | 28.6 | 123 | 0.706294 | 1,000,409 | package org.slf4j;
import org.apache.commons.logging.Log;
/**
* Drop-in replacement for simple logging facade 4 java (SLF4J). Not 100% complete/compatible with the original,
* jet it covers the most commonly used functionality so you can compile + run almost any java software depending on slf4j.
* @author Paul Palaszewski
* @since 2020-01-14
*/
public final class LoggerFactory {
public static Logger getLogger(Class<?> cl) {
return new Log(cl.getName());
}
public static Logger getLogger(String name) {
return new Log(name);
}
}
|
923da5ec24fd67654a653ebadf524244b4e8b66c | 2,877 | java | Java | gym/src/main/java/com/fokrys/gym/service/impl/PersonalDataServiceImpl.java | fokrys/gym-server | d1fdc06f88406923b375fe16c1ee1ec197dccb71 | [
"Apache-2.0"
] | null | null | null | gym/src/main/java/com/fokrys/gym/service/impl/PersonalDataServiceImpl.java | fokrys/gym-server | d1fdc06f88406923b375fe16c1ee1ec197dccb71 | [
"Apache-2.0"
] | null | null | null | gym/src/main/java/com/fokrys/gym/service/impl/PersonalDataServiceImpl.java | fokrys/gym-server | d1fdc06f88406923b375fe16c1ee1ec197dccb71 | [
"Apache-2.0"
] | null | null | null | 29.060606 | 111 | 0.793535 | 1,000,410 | package com.fokrys.gym.service.impl;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fokrys.gym.dto.PersonalDataDto;
import com.fokrys.gym.entity.PersonalData;
import com.fokrys.gym.entity.User;
import com.fokrys.gym.exceptions.NotExistException;
import com.fokrys.gym.repository.PersonalDataRepository;
import com.fokrys.gym.repository.UserRepository;
import com.fokrys.gym.service.PersonalDataService;
@Service
public class PersonalDataServiceImpl implements PersonalDataService{
private final PersonalDataRepository personalDataRepository;
private final UserRepository userRepository;
@Autowired
public PersonalDataServiceImpl(PersonalDataRepository personalDataRepository, UserRepository userRepository) {
super();
this.personalDataRepository = personalDataRepository;
this.userRepository = userRepository;
}
@Override
public PersonalData save(PersonalDataDto personalDataDto) throws NotExistException{
PersonalData actualPersonalData = new PersonalData();
actualPersonalData.setName(personalDataDto.getName());
actualPersonalData.setSurname(personalDataDto.getSurname());
actualPersonalData.setAddress(personalDataDto.getAddress());
actualPersonalData.setDescription(personalDataDto.getDescription());
return personalDataRepository.save(actualPersonalData);
}
@Override
public PersonalData save(PersonalData personalData){
return personalDataRepository.save(personalData);
}
@Override
public Iterable<PersonalData> findAll() throws NotExistException {
Iterable<PersonalData> personalDatas = personalDataRepository.findAll();
if(personalDatas == null) {
throw new NotExistException();
}
return personalDatas;
}
@Override
public PersonalData save() {
PersonalData personalData = new PersonalData();
return personalDataRepository.save(personalData);
}
@Override
public PersonalData findOneById(Long id) {
return personalDataRepository.findById(id).get();
}
@Override
public PersonalData edit(PersonalDataDto personalDataDto) throws NotExistException {
Optional<PersonalData> personalDataOp = personalDataRepository.findById(personalDataDto.getId());
if (!personalDataOp.isPresent()) {
throw new NotExistException();
}
PersonalData personalData = personalDataOp.get();
if (personalDataDto.getName() != null) {
personalData.setName(personalDataDto.getName());
}
if (personalDataDto.getSurname() != null) {
personalData.setSurname(personalDataDto.getSurname());
}
if (personalDataDto.getDescription() != null) {
personalData.setDescription(personalDataDto.getDescription());
}
if (personalDataDto.getAddress() != null) {
personalData.setAddress(personalDataDto.getAddress());
}
return personalDataRepository.save(personalData);
}
}
|
923da6a4824f16c1f4131fb77f0e1455ff97b5e1 | 3,828 | java | Java | src/com/armadialogcreator/gui/main/actions/mainMenu/help/CheckForUpdateAction.java | kayler-renslow/arma-dialog-creator | 706afc4382c02fffea87fb8bdee5e54ee851a3d8 | [
"MIT"
] | 90 | 2016-09-05T16:21:22.000Z | 2022-03-23T22:22:49.000Z | src/com/armadialogcreator/gui/main/actions/mainMenu/help/CheckForUpdateAction.java | kayler-renslow/arma-dialog-creator | 706afc4382c02fffea87fb8bdee5e54ee851a3d8 | [
"MIT"
] | 52 | 2017-07-02T21:48:40.000Z | 2021-03-29T00:08:51.000Z | src/com/armadialogcreator/gui/main/actions/mainMenu/help/CheckForUpdateAction.java | kayler-renslow/arma-dialog-creator | 706afc4382c02fffea87fb8bdee5e54ee851a3d8 | [
"MIT"
] | 17 | 2016-10-18T17:36:04.000Z | 2021-04-22T21:30:16.000Z | 31.121951 | 109 | 0.729101 | 1,000,411 | package com.armadialogcreator.gui.main.actions.mainMenu.help;
import com.armadialogcreator.ArmaDialogCreator;
import com.armadialogcreator.ExceptionHandler;
import com.armadialogcreator.application.ApplicationManager;
import com.armadialogcreator.gui.StageDialog;
import com.armadialogcreator.gui.main.AskSaveProjectDialog;
import com.armadialogcreator.lang.Lang;
import com.armadialogcreator.updater.github.ReleaseInfo;
import com.armadialogcreator.updater.tasks.AdcVersionCheckTask;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ResourceBundle;
/**
@author Kayler
@since 08/22/2017 */
public class CheckForUpdateAction implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
CheckForUpdateDialog d = new CheckForUpdateDialog();
d.show();
if (d.wasCancelled() || d.getReleaseInfo() == null || !d.isUpdateAvailable()) {
return;
}
AskSaveProjectDialog dialog = new AskSaveProjectDialog();
dialog.showAndWait();
if (dialog.wasCancelled()) {
return;
}
if (dialog.saveProgress()) {
ApplicationManager.instance.saveProject();
}
ApplicationManager.instance.closeApplication();
try {
//get the update
Runtime.getRuntime().exec("java -jar adc_updater.jar", null);
} catch (IOException e) {
ExceptionHandler.error(e);
}
}
private static class CheckForUpdateDialog extends StageDialog<VBox> {
private ReleaseInfo releaseInfo;
private final Label lblStatus = new Label();
private final ResourceBundle bundle = Lang.ApplicationBundle();
private boolean updateAvailable = false;
public CheckForUpdateDialog() {
super(ArmaDialogCreator.getPrimaryStage(), new VBox(5), null, true, true, false);
setTitle(bundle.getString("Popups.CheckForUpdate.popup-title"));
myRootElement.getChildren().add(lblStatus);
lblStatus.setText(bundle.getString("Popups.CheckForUpdate.checking"));
footer.getBtnCancel().setDisable(true);
footer.getBtnOk().setDisable(true);
setResizable(false);
myRootElement.setPrefWidth(400);
myRootElement.setPrefHeight(60);
}
@Override
public void show() {
Task<ReleaseInfo> task = new Task<ReleaseInfo>() {
@Override
protected ReleaseInfo call() throws Exception {
return AdcVersionCheckTask.getLatestRelease();
}
};
task.stateProperty().addListener((observable, oldValue, state) -> {
if (state == Worker.State.CANCELLED || state == Worker.State.FAILED || state == Worker.State.SUCCEEDED) {
releaseInfo = task.getValue();
if (releaseInfo == null || releaseInfo.getTagName().equals(Lang.Application.VERSION)) {
if (task.getState() == Worker.State.FAILED) {
lblStatus.setText(bundle.getString("Popups.CheckForUpdate.failed-to-get-info"));
} else {
lblStatus.setText(bundle.getString("Popups.CheckForUpdate.no-update"));
}
} else {
updateAvailable = true;
lblStatus.setText(
String.format(
bundle.getString("Popups.CheckForUpdate.update-available-f"),
releaseInfo.getTagName()
)
);
}
footer.getBtnCancel().setDisable(false);
footer.getBtnOk().setDisable(false);
}
});
Thread thread = new Thread(task);
thread.setName("Arma Dialog Creator - Check For Update Task");
thread.setDaemon(true);
thread.start();
//place super.show() at bottom or the dialog will freeze the current thread until dialog is closed
super.show();
}
@Nullable
public ReleaseInfo getReleaseInfo() {
return releaseInfo;
}
public boolean isUpdateAvailable() {
return updateAvailable;
}
}
}
|
923da7987b5d0adad1097ca4e6851e7ac7a35574 | 3,416 | java | Java | core/camel-core/src/test/java/org/apache/camel/impl/CamelProduceInterfaceTest.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | core/camel-core/src/test/java/org/apache/camel/impl/CamelProduceInterfaceTest.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | 23 | 2021-03-23T00:01:38.000Z | 2022-01-04T16:47:34.000Z | core/camel-core/src/test/java/org/apache/camel/impl/CamelProduceInterfaceTest.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | 18.26738 | 810 | 0.796253 | 1,000,412 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.impl
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|impl
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ContextTestSupport
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|ProxyBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_comment
comment|/** * */
end_comment
begin_class
DECL|class|CamelProduceInterfaceTest
specifier|public
class|class
name|CamelProduceInterfaceTest
extends|extends
name|ContextTestSupport
block|{
DECL|field|echo
specifier|private
name|Echo
name|echo
decl_stmt|;
annotation|@
name|Test
DECL|method|testCamelProduceInterface ()
specifier|public
name|void
name|testCamelProduceInterface
parameter_list|()
throws|throws
name|Exception
block|{
name|String
name|reply
init|=
name|echo
operator|.
name|hello
argument_list|(
literal|"Camel"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"Hello Camel"
argument_list|,
name|reply
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
throws|throws
name|Exception
block|{
comment|// we gotta cheat and use proxy builder as ContextTestSupport
comment|// doesnt do
comment|// all the IoC wiring we need when using @Produce on an
comment|// interface
name|echo
operator|=
operator|new
name|ProxyBuilder
argument_list|(
name|context
argument_list|)
operator|.
name|endpoint
argument_list|(
literal|"direct:hello"
argument_list|)
operator|.
name|build
argument_list|(
name|Echo
operator|.
name|class
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:hello"
argument_list|)
operator|.
name|transform
argument_list|(
name|body
argument_list|()
operator|.
name|prepend
argument_list|(
literal|"Hello "
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
block|}
end_class
end_unit
|
923da80435e96bacebbad8ff4c6adca779b7ff5a | 5,519 | java | Java | ballroom/src/main/java/org/jboss/hal/ballroom/Search.java | yersan/console | f191b056f853628813909524c40ff9d6846c8c2e | [
"Apache-2.0"
] | 25 | 2018-04-02T13:35:05.000Z | 2021-11-28T03:28:35.000Z | ballroom/src/main/java/org/jboss/hal/ballroom/Search.java | yersan/console | f191b056f853628813909524c40ff9d6846c8c2e | [
"Apache-2.0"
] | 160 | 2018-03-29T07:23:42.000Z | 2022-03-24T13:13:49.000Z | ballroom/src/main/java/org/jboss/hal/ballroom/Search.java | yersan/console | f191b056f853628813909524c40ff9d6846c8c2e | [
"Apache-2.0"
] | 63 | 2018-03-30T06:47:58.000Z | 2021-11-11T16:06:06.000Z | 38.326389 | 109 | 0.540134 | 1,000,413 | /*
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.hal.ballroom;
import com.google.common.base.Strings;
import com.google.gwt.core.client.GWT;
import elemental2.dom.HTMLElement;
import elemental2.dom.HTMLInputElement;
import org.jboss.gwt.elemento.core.Elements;
import org.jboss.gwt.elemento.core.IsElement;
import org.jboss.hal.resources.Constants;
import org.jboss.hal.resources.UIConstants;
import org.jboss.hal.spi.Callback;
import static org.jboss.gwt.elemento.core.Elements.label;
import static org.jboss.gwt.elemento.core.Elements.*;
import static org.jboss.gwt.elemento.core.EventType.click;
import static org.jboss.gwt.elemento.core.EventType.keyup;
import static org.jboss.gwt.elemento.core.InputType.search;
import static org.jboss.hal.resources.CSS.*;
public class Search implements IsElement<HTMLElement> {
private static final Constants CONSTANTS = GWT.create(Constants.class);
private final HTMLElement root;
private HTMLInputElement searchBox;
private HTMLElement clearSearch;
private Search(Builder builder) {
HTMLElement buttons;
root = div().css(halSearch, hasButton)
.add(div().css(formGroup, hasClear)
.add(div().css(searchPfInputGroup)
.add(label().css(srOnly)
.textContent(CONSTANTS.search())
.apply(label -> label.htmlFor = builder.id))
.add(searchBox = input(search)
.id(builder.id)
.css(formControl)
.attr(UIConstants.PLACEHOLDER, CONSTANTS.search())
.on(keyup, event -> {
setVisible(clearSearch, !Strings.isNullOrEmpty(searchBox.value));
if ("Enter".equals(event.key)) { //NON-NLS
builder.onSearch.search(searchBox.value);
}
}).element())
.add(clearSearch = button().css(clear)
.aria(UIConstants.HIDDEN, "true") //NON-NLS
.on(click, event -> {
clear();
if (builder.onClear != null) {
builder.onClear.execute();
}
focus();
})
.add(span().css(pfIcon("close"))).element())))
.add(buttons = div().css(formGroup, btnGroup)
.add(button().css(btn, btnDefault)
.on(click, event -> builder.onSearch.search(searchBox.value))
.add(span().css(fontAwesome("search")))).element()).element();
if (builder.onPrevious != null) {
buttons.appendChild(button().css(btn, btnDefault)
.on(click, event -> builder.onPrevious.search(searchBox.value))
.add(span().css(fontAwesome("angle-left"))).element());
}
if (builder.onNext != null) {
buttons.appendChild(button().css(btn, btnDefault)
.on(click, event -> builder.onNext.search(searchBox.value))
.add(span().css(fontAwesome("angle-right"))).element());
}
Elements.setVisible(clearSearch, false);
}
@Override
public HTMLElement element() {
return root;
}
public void clear() {
searchBox.value = "";
Elements.setVisible(clearSearch, false);
}
public void focus() {
searchBox.focus();
}
@FunctionalInterface
public interface SearchHandler {
void search(String query);
}
public static class Builder {
private final String id;
private final SearchHandler onSearch;
private Callback onClear;
private SearchHandler onPrevious;
private SearchHandler onNext;
public Builder(String id, SearchHandler onSearch) {
this.id = id;
this.onSearch = onSearch;
}
public Builder onClear(Callback onClear) {
this.onClear = onClear;
return this;
}
public Builder onPrevious(SearchHandler onPrevious) {
this.onPrevious = onPrevious;
return this;
}
public Builder onNext(SearchHandler onNext) {
this.onNext = onNext;
return this;
}
public Search build() {
return new Search(this);
}
}
}
|
923da89500fd1fa5b1bb3785c5e0dbc88ca019ac | 9,089 | java | Java | src/main/java/org/mmarini/routes/model2/MapEdge.java | m-marini/routes | 32858a52971ce6d5c3fb539e19c9dabdf0f7e224 | [
"MIT"
] | 1 | 2020-05-20T16:54:28.000Z | 2020-05-20T16:54:28.000Z | src/main/java/org/mmarini/routes/model2/MapEdge.java | m-marini/routes | 32858a52971ce6d5c3fb539e19c9dabdf0f7e224 | [
"MIT"
] | 96 | 2019-09-12T07:32:32.000Z | 2021-12-26T22:57:36.000Z | src/main/java/org/mmarini/routes/model2/MapEdge.java | m-marini/routes | 32858a52971ce6d5c3fb539e19c9dabdf0f7e224 | [
"MIT"
] | null | null | null | 30.242525 | 115 | 0.581676 | 1,000,414 | /*
* Copyright (c) 2019 Marco Marini, nnheo@example.com
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* END OF TERMS AND CONDITIONS
*
*/
package org.mmarini.routes.model2;
import java.awt.geom.Point2D;
import java.util.StringJoiner;
import static java.lang.Math.floor;
import static java.util.Objects.requireNonNull;
import static org.mmarini.routes.model2.Constants.*;
/**
* A map edge starting from the beginning node to the end node with speed limit and priority
*
* @author nnheo@example.com
*/
public class MapEdge implements MapElement {
private final MapNode begin;
private final MapNode end;
private final double speedLimit;
private final int priority;
/**
* @param begin the beginning node
* @param end the end node
* @param speedLimit the speed limit
* @param priority the priority
*/
public MapEdge(MapNode begin, MapNode end, double speedLimit, int priority) {
this.begin = requireNonNull(begin);
this.end = requireNonNull(end);
assert !begin.equals(end);
this.speedLimit = speedLimit;
this.priority = priority;
}
@Override
public <T> T apply(final MapElementVisitor<T> visitor) {
return visitor.visit(this);
}
/**
* Returns the closer point in the edge from a given point
*
* @param point the point
*/
Point2D closerFrom(final Point2D point) {
final double ka = ka(point);
if (ka <= 0) {
return begin.getLocation();
} else if (ka >= getLength()) {
return end.getLocation();
} else {
return locationAt(ka);
}
}
/**
* Returns the distance from the closer point in the edge
*
* @param point the point
*/
@Override
public double distanceSqFrom(final Point2D point) {
return point.distanceSq(closerFrom(point));
}
/**
* Returns the beginning node
*/
public MapNode getBegin() {
return begin;
}
/**
* Returns an edge with new beginning node
*
* @param begin the beginning node
*/
public MapEdge setBegin(MapNode begin) {
return new MapEdge(begin, end, speedLimit, priority);
}
/**
* Returns the beginning location
*/
public Point2D getBeginLocation() {
return begin.getLocation();
}
/**
* @return the edgeVector
*/
public Point2D getDirection() {
Point2D beginLocation = begin.getLocation();
Point2D endLocation = end.getLocation();
return new Point2D.Double(
endLocation.getX() - beginLocation.getX(),
endLocation.getY() - beginLocation.getY());
}
/**
* Returns the end node
*/
public MapNode getEnd() {
return end;
}
/**
* Returns an edge with new end node
*
* @param end the end node
*/
public MapEdge setEnd(MapNode end) {
return new MapEdge(begin, end, speedLimit, priority);
}
/**
* Returns the end location
*/
public Point2D getEndLocation() {
return end.getLocation();
}
/**
* Returns the length of edge
*/
public double getLength() {
return begin.getLocation().distance(end.getLocation());
}
/**
* Returns the priority
*/
public int getPriority() {
return priority;
}
/**
* Returns the edge with priority
*
* @param priority the priority
*/
public MapEdge setPriority(int priority) {
return new MapEdge(begin, end, speedLimit, priority);
}
/**
* Returns the safety distance in the edge
*/
public double getSafetyDistance() {
return computeSafetyDistance(speedLimit);
}
/**
* Returns the safety speed in the edge
* The safety speed is the speed with a safatey distance equal to the length of the edge
*/
public double getSafetySpeed() {
return computeSafetySpeed(getLength());
}
/**
* Returns the speedLimit
*/
public double getSpeedLimit() {
return speedLimit;
}
/**
* Returns the edge with speed limit
*
* @param speedLimit the speed limit
*/
public MapEdge setSpeedLimit(double speedLimit) {
return new MapEdge(begin, end, speedLimit, priority);
}
/**
* Returns the traffic level for a given number of vehicles
*
* @param vehicleCount the number of vehicles
*/
public double getTrafficLevel(int vehicleCount) {
if (vehicleCount == 0) {
return 0;
} else {
double length = getLength();
int maxVehicles = (int) floor(length / VEHICLE_LENGTH);
int optimalCount = (int) floor(length / (getSafetyDistance() + VEHICLE_LENGTH));
if (vehicleCount <= optimalCount) {
return 0.5 * vehicleCount / optimalCount;
} else {
/*
(vehicleCount - optimalCount) / (maxVehicles - optimalCount) * 0.5 + 0.5;
(vehicleCount - optimalCount) / (maxVehicles - optimalCount) / 2 + 1/2;
((vehicleCount - optimalCount) + (maxVehicles - optimalCount)) / (maxVehicles - optimalCount) /2;
(vehicleCount - optimalCount + maxVehicles - optimalCount) / (maxVehicles - optimalCount) /2;
(vehicleCount + maxVehicles - 2 * optimalCount) / (maxVehicles - optimalCount) /2;
*/
int n = vehicleCount + maxVehicles - 2 * optimalCount;
int d = maxVehicles - optimalCount;
return 0.5 * n / d;
}
}
}
/**
* Returns the transit time: length / speedLimit
*/
public double getTransitTime() {
return getLength() / speedLimit;
}
/**
* Returns true if the edge is crossing a node
*
* @param node the node
*/
public boolean isCrossingNode(MapNode node) {
return begin.equals(node) || end.equals(node);
}
/**
* Retuns true is the edge is located at same location of other
*
* @param other the other edge
*/
public boolean isSameLocation(MapEdge other) {
return begin.isSameLocation(other.begin) && end.isSameLocation(other.end);
}
/**
* Returns the distance from the beginning and the closer point in the edge direction
* from a given point
*
* @param point the point
*/
double ka(final Point2D point) {
final Point2D begin = getBeginLocation();
final double x0 = begin.getX();
final double y0 = begin.getY();
final Point2D ev = getDirection();
final double xe = ev.getX();
final double ye = ev.getY();
final double xp = point.getX() - x0;
final double yp = point.getY() - y0;
final double ep = xe * xp + ye * yp;
return ep / getLength();
}
/**
* Returns the location at a distance from the beginning
*
* @param distance the distance
*/
public Point2D locationAt(final double distance) {
final Point2D end = getEndLocation();
final Point2D begin = getBeginLocation();
final double k = distance / getLength();
final double x0 = begin.getX();
final double y0 = begin.getY();
return new Point2D.Double(
k * (end.getX() - x0) + x0,
k * (end.getY() - y0) + y0);
}
@Override
public String toString() {
return new StringJoiner(", ", MapEdge.class.getSimpleName() + "[", "]")
.add(begin.toString())
.add(end.toString())
.toString();
}
}
|
923da935493b5833f2d482887bbfd63f8b9c7546 | 1,466 | java | Java | src/org/springframework/beans/factory/config/DestructionAwareBeanPostProcessor.java | FanZhouk/spring1.1.1 | 214897f5a731a47ffc30996099afb9e1866ddc82 | [
"Apache-2.0"
] | 1 | 2019-12-17T09:14:02.000Z | 2019-12-17T09:14:02.000Z | src/org/springframework/beans/factory/config/DestructionAwareBeanPostProcessor.java | FanZhouk/spring1.1.1 | 214897f5a731a47ffc30996099afb9e1866ddc82 | [
"Apache-2.0"
] | null | null | null | src/org/springframework/beans/factory/config/DestructionAwareBeanPostProcessor.java | FanZhouk/spring1.1.1 | 214897f5a731a47ffc30996099afb9e1866ddc82 | [
"Apache-2.0"
] | null | null | null | 34.904762 | 83 | 0.764666 | 1,000,415 | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
/**
* Subinterface of BeanPostProcessor that adds a before-destruction callback.
*
* <p>The typical usage will be to invoke custom destruction callbacks on
* specific bean types, matching corresponding initialization callbacks.
*
* @author Juergen Hoeller
* @since 09.04.2004
*/
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given new bean instance before
* its destruction. Can invoke custom destruction callbacks.
* @param bean the new bean instance
* @param name the name of the bean
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeforeDestruction(Object bean, String name) throws BeansException;
}
|
923da9f19386087db20bb01b00d05b6994e734df | 3,644 | java | Java | Test/hxgraph/src/main/java/com/hxgraph/adapter/special/HXKLineAdapter.java | liulinru13/HXGraph | 5fc7726dfc537a540ebefeb6f2a4e71d92c26b68 | [
"MIT"
] | null | null | null | Test/hxgraph/src/main/java/com/hxgraph/adapter/special/HXKLineAdapter.java | liulinru13/HXGraph | 5fc7726dfc537a540ebefeb6f2a4e71d92c26b68 | [
"MIT"
] | null | null | null | Test/hxgraph/src/main/java/com/hxgraph/adapter/special/HXKLineAdapter.java | liulinru13/HXGraph | 5fc7726dfc537a540ebefeb6f2a4e71d92c26b68 | [
"MIT"
] | 1 | 2017-09-20T02:08:14.000Z | 2017-09-20T02:08:14.000Z | 37.183673 | 109 | 0.638858 | 1,000,416 | package com.hxgraph.adapter.special;
import com.hxgraph.adapter.KLineAdapter;
import com.hxgraph.graphstrategy.GraphStrategyImp;
import com.hxgraph.graphstrategy.special.HXKLineStrategy;
import com.hxgraph.model.Constant;
import com.hxgraph.model.imp.group.KLineModel;
import com.hxgraph.model.imp.group.special.HXKLineModel;
import com.hxgraph.model.imp.raw.HXKLinePointModel;
import com.hxgraph.model.imp.raw.KLinePointModel;
import com.hxgraph.model.param.KLineStrategyParam;
import com.hxgraph.model.param.special.HXKLineStrategyParam;
import java.util.ArrayList;
import java.util.List;
/**
* 带买入卖出点的k线图
* Created by liulinru on 2017/4/26.
*/
public class HXKLineAdapter extends KLineAdapter {
private int[] techArray;
@Override
protected KLineModel getNewModel() {
return new HXKLineModel();
}
@Override
public KLineModel wrapRawData(KLineStrategyParam params) {
super.wrapRawData(params);
if(params != null && params instanceof HXKLineStrategyParam){
techArray = ((HXKLineStrategyParam) params).getTechArray();
((HXKLineModel)mData).setmIArrowBodyLength(((HXKLineStrategyParam) params).getArrowBodyLength());
((HXKLineModel)mData).setmIArrowHeadLength(((HXKLineStrategyParam) params).getArrowHeadLength());
((HXKLineModel)mData).setmITechDownColor(((HXKLineStrategyParam) params).getTechDownColor());
}
return mData;
}
@Override
public GraphStrategyImp<KLineModel> getGraphStrategy() {
mStrategy = new HXKLineStrategy();
return mStrategy;
}
protected void calculateYcoordinateScale(){
List<KLinePointModel> list = new ArrayList<KLinePointModel>();
double diff = mDMaxValue - mDMinValue;
diff = diff <= 0.0 ? 1.0 : diff;
for (int i = 0; i < mDValues.length; i++) {
HXKLinePointModel point = new HXKLinePointModel();
point.setdOpenValue(mDValues[i][0]);//开
point.setdHighValue(mDValues[i][1]);//高
point.setdLowValue(mDValues[i][2]);//低
point.setdCloseValue(mDValues[i][3]);//收
if(techArray != null && techArray.length > i){
if(techArray[i] != Constant.NULLVALUE)
point.setTech(new HXKLinePointModel.HXKLineTechModel(techArray[i]));
else
point.setTech(null);
}
point.setfOpenCoordinate((float) calculateScale(point.getdOpenValue(),diff));
point.setfHighCoordinate((float) calculateScale(point.getdHighValue(),diff));
point.setfLowCoordinate((float) calculateScale(point.getdLowValue(),diff));
point.setfCloseCoordinate((float) calculateScale(point.getdCloseValue(),diff));
point.setbIsLine(mData.ismBIsUseLineNotBar());
// 涨的情况 开盘价 《 收盘价 或者 开盘价=收盘价 且 当日收盘 》= 前日收盘
if(mDValues[i][0] < mDValues[i][3]
|| (i > 0 && mDValues[i][0] == mDValues[i][3] && mDValues[i][3] >= mDValues[i-1][3])){
point.setmIColor(mData.getmIRiseColor());
}else{
point.setmIColor(mData.getmIDownColor());
}
list.add(point);
if(mIMinIndex == i){
mData.getmMaxMinPoints().setMinPoint(point,i);
}else if(mIMaxIndex == i){
mData.getmMaxMinPoints().setMaxPoint(point,i);
}
}
mData.setIPointSet(list);
}
public int[] getTechArray() {
return techArray;
}
public void setTechArray(int[] techArray) {
this.techArray = techArray;
}
}
|
923daa7b0cc265b48c8a1ec213e7c5d054137a4b | 1,474 | java | Java | src/main/java/it/smartcommunitylab/csengine/model/dto/OrganisationDTO.java | smartcommunitylab/cartella-studente-engine | 08dbbe1e8a276a21cf59a07556b0249eb80c118d | [
"Apache-2.0"
] | null | null | null | src/main/java/it/smartcommunitylab/csengine/model/dto/OrganisationDTO.java | smartcommunitylab/cartella-studente-engine | 08dbbe1e8a276a21cf59a07556b0249eb80c118d | [
"Apache-2.0"
] | null | null | null | src/main/java/it/smartcommunitylab/csengine/model/dto/OrganisationDTO.java | smartcommunitylab/cartella-studente-engine | 08dbbe1e8a276a21cf59a07556b0249eb80c118d | [
"Apache-2.0"
] | null | null | null | 19.394737 | 52 | 0.723202 | 1,000,417 | package it.smartcommunitylab.csengine.model.dto;
import it.smartcommunitylab.csengine.model.Address;
import it.smartcommunitylab.csengine.model.GeoPoint;
public class OrganisationDTO {
private String id;
private String fiscalCode;
private String name;
private String description;
private Address address;
private GeoPoint location;
private String phone;
private String email;
private String pec;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPec() {
return pec;
}
public void setPec(String pec) {
this.pec = pec;
}
public String getFiscalCode() {
return fiscalCode;
}
public void setFiscalCode(String fiscalCode) {
this.fiscalCode = fiscalCode;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public GeoPoint getLocation() {
return location;
}
public void setLocation(GeoPoint location) {
this.location = location;
}
}
|
923daaae9c9567df0e7ea3fddda63dbb6d1a27fc | 557 | java | Java | app/src/test/java/com/eusecom/samshopersung/TestBindingModule.java | eurosecom/samshopersung | c6716e4bf5ec8e7bc6d47be9a83baeb1b7af08d2 | [
"Apache-2.0"
] | null | null | null | app/src/test/java/com/eusecom/samshopersung/TestBindingModule.java | eurosecom/samshopersung | c6716e4bf5ec8e7bc6d47be9a83baeb1b7af08d2 | [
"Apache-2.0"
] | 18 | 2018-06-24T13:40:16.000Z | 2018-10-26T09:29:10.000Z | app/src/test/java/com/eusecom/samshopersung/TestBindingModule.java | eurosecom/samshopersung | c6716e4bf5ec8e7bc6d47be9a83baeb1b7af08d2 | [
"Apache-2.0"
] | null | null | null | 26.52381 | 146 | 0.813285 | 1,000,418 | package com.eusecom.samshopersung;
import android.app.Activity;
import dagger.Binds;
import dagger.Module;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
@Module(subcomponents = {
TestFlombulatorActivityComponent.class
})
public abstract class TestBindingModule {
@Binds
@IntoMap
@ActivityKey(FlombulatorActivity.class)
abstract AndroidInjector.Factory<? extends Activity> bindFlombulatorActivityInjectorFactory(TestFlombulatorActivityComponent.Builder builder);
} |
923dab027fffc8829df24fc01a1b67866f07d315 | 1,301 | java | Java | view-plugins/mysql-view-plugins/src/main/java/org/tview/visualization/common/impl/IDbLoginServiceImpl.java | t-view/all-view | e12537c0552f70446a37edc86401cb3c0b112528 | [
"Apache-2.0"
] | 1 | 2020-07-28T08:47:16.000Z | 2020-07-28T08:47:16.000Z | view-plugins/mysql-view-plugins/src/main/java/org/tview/visualization/common/impl/IDbLoginServiceImpl.java | t-view/all-view | e12537c0552f70446a37edc86401cb3c0b112528 | [
"Apache-2.0"
] | 1 | 2020-07-20T09:49:04.000Z | 2020-07-21T11:04:18.000Z | view-plugins/mysql-view-plugins/src/main/java/org/tview/visualization/common/impl/IDbLoginServiceImpl.java | t-view/all-view | e12537c0552f70446a37edc86401cb3c0b112528 | [
"Apache-2.0"
] | null | null | null | 22.824561 | 84 | 0.705611 | 1,000,419 | package org.tview.visualization.common.impl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.tview.visualization.common.cache.DblLoginCache;
import org.tview.visualization.inter.ConfigLoginService;
import org.tview.visualization.model.db.DBConnectionConfig;
import org.tview.visualization.mysql.factory.jdbc.JdbcTemplateCreate;
import org.tview.visualization.mysql.factory.jdbc.MysqlJdbcTemplateCreate;
public class IDbLoginServiceImpl implements ConfigLoginService<DBConnectionConfig> {
DblLoginCache cache = new DblLoginCache(10);
JdbcTemplateCreate mysql = new MysqlJdbcTemplateCreate();
/**
* 连接测试
*
* @param config 数据库链接配置
* @return true:连接成功,false:连接失败
*/
@Override
public boolean connection(DBConnectionConfig config) {
try {
JdbcTemplate jdbcTemplate = mysql.create(config);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 登录
*
* @param name
* @param config
*/
@Override
public void login(String name, DBConnectionConfig config) {
if (connection(config)) {
cache.put(name, config);
}
}
/**
* 获取链接配置
*
* @param name
* @return
*/
@Override
public DBConnectionConfig get(String name) {
return cache.get(name);
}
}
|
923dab4b899860d40a6770e4342aaa0bb84d0073 | 2,409 | java | Java | src/main/java/br/ufsc/ppgcc/experion/backend/AppConfig.java | keitarobr/experion-backend | 486af716c68988ec41eae7014a8d880b06f996c1 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/ufsc/ppgcc/experion/backend/AppConfig.java | keitarobr/experion-backend | 486af716c68988ec41eae7014a8d880b06f996c1 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/ufsc/ppgcc/experion/backend/AppConfig.java | keitarobr/experion-backend | 486af716c68988ec41eae7014a8d880b06f996c1 | [
"Apache-2.0"
] | null | null | null | 41.534483 | 106 | 0.743047 | 1,000,420 | package br.ufsc.ppgcc.experion.backend;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Configuration
@EnableSwagger2
@EntityScan(basePackages = {"br.ufsc.ppgcc.experion"})
public class AppConfig implements WebMvcConfigurer {
public static final String DEFAULT_INCLUDE_PATTERN = "/.*";
public static final String AUTHORIZATION_HEADER = "Authorization";
@Bean
public Docket api() {
List<SecurityScheme> schemeList = new ArrayList<>();
schemeList.add(new ApiKey("JWT", AUTHORIZATION_HEADER, "header"));
return new Docket(DocumentationType.SWAGGER_2)
.securityContexts(Arrays.asList(new SecurityContext[] {securityContext()}))
.securitySchemes(schemeList)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex(DEFAULT_INCLUDE_PATTERN))
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference[] {new SecurityReference("JWT", authorizationScopes)});
}
} |
923dab8d87cd46f620e83fa6943cd6e9c349d6c9 | 793 | java | Java | app/src/main/java/com/example/logcathealth/BottomNav/MenuUtil.java | adrishyantee/logcat-wizards | 33f5f9a8f742f85bf83e3f9f09fc491b90078784 | [
"MIT"
] | 1 | 2021-06-05T13:50:32.000Z | 2021-06-05T13:50:32.000Z | app/src/main/java/com/example/logcathealth/BottomNav/MenuUtil.java | adrishyantee/logcat-wizards | 33f5f9a8f742f85bf83e3f9f09fc491b90078784 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/logcathealth/BottomNav/MenuUtil.java | adrishyantee/logcat-wizards | 33f5f9a8f742f85bf83e3f9f09fc491b90078784 | [
"MIT"
] | null | null | null | 31.72 | 83 | 0.732661 | 1,000,421 | package com.example.logcathealth.BottomNav;
import com.example.logcathealth.R;
import java.util.ArrayList;
import java.util.List;
public class MenuUtil {
public static final int DOCCORNER_FRAGMENT=0;
public static final int MARKETPLACE_FRAGMENT=1;
public static final int FEED_FRAGMENT= 2;
public static final int PROFILE_FRAGMENT=3;
public static List<MenuItem> getMenuList() {
List<MenuItem> list = new ArrayList<>();
list.add(new MenuItem(R.drawable.doctorcorner,DOCCORNER_FRAGMENT,false));
list.add(new MenuItem(R.drawable.marcketplace,MARKETPLACE_FRAGMENT,false));
list.add(new MenuItem(R.drawable.feed,FEED_FRAGMENT,false));
list.add(new MenuItem(R.drawable.profile,PROFILE_FRAGMENT,false));
return list;
}
}
|
923dac28b371753ede516ca4db8907825c870220 | 2,967 | java | Java | legacy/src/test/java/com/amazon/opendistroforelasticsearch/sql/legacy/unittest/AggregationOptionTest.java | chyun/sql | 0bb88d0595a6076dff4883b546d9aed90355ce75 | [
"Apache-2.0"
] | 574 | 2019-03-11T16:02:24.000Z | 2022-03-30T13:21:59.000Z | legacy/src/test/java/com/amazon/opendistroforelasticsearch/sql/legacy/unittest/AggregationOptionTest.java | chyun/sql | 0bb88d0595a6076dff4883b546d9aed90355ce75 | [
"Apache-2.0"
] | 802 | 2019-03-11T14:43:20.000Z | 2022-03-17T07:46:03.000Z | legacy/src/test/java/com/amazon/opendistroforelasticsearch/sql/legacy/unittest/AggregationOptionTest.java | chyun/sql | 0bb88d0595a6076dff4883b546d9aed90355ce75 | [
"Apache-2.0"
] | 197 | 2019-03-11T20:52:28.000Z | 2022-03-30T12:59:05.000Z | 36.182927 | 95 | 0.714189 | 1,000,422 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistroforelasticsearch.sql.legacy.unittest;
import com.alibaba.druid.sql.ast.expr.SQLAggregateOption;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.amazon.opendistroforelasticsearch.sql.legacy.domain.Field;
import com.amazon.opendistroforelasticsearch.sql.legacy.domain.Select;
import com.amazon.opendistroforelasticsearch.sql.legacy.exception.SqlParseException;
import com.amazon.opendistroforelasticsearch.sql.legacy.parser.SqlParser;
import com.amazon.opendistroforelasticsearch.sql.legacy.util.SqlParserUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
* Unit test class for feature of aggregation options: DISTINCT, ALL, UNIQUE, DEDUPLICATION
*/
public class AggregationOptionTest {
@Test
public void selectDistinctFieldsShouldHaveAggregationOption() {
List<Field> fields = getSelectFields("SELECT DISTINCT gender, city FROM accounts");
for (Field field: fields) {
Assert.assertEquals(field.getOption(), SQLAggregateOption.DISTINCT);
}
}
@Test
public void selectWithoutDistinctFieldsShouldNotHaveAggregationOption() {
List<Field> fields = getSelectFields("SELECT gender, city FROM accounts");
for (Field field: fields) {
Assert.assertNull(field.getOption());
}
}
@Test
public void selectDistinctWithoutGroupByShouldHaveGroupByItems() {
List<List<Field>> groupBys = getGroupBys("SELECT DISTINCT gender, city FROM accounts");
Assert.assertFalse(groupBys.isEmpty());
}
@Test
public void selectWithoutDistinctWithoutGroupByShouldNotHaveGroupByItems() {
List<List<Field>> groupBys = getGroupBys("SELECT gender, city FROM accounts");
Assert.assertTrue(groupBys.isEmpty());
}
private List<List<Field>> getGroupBys(String query) {
return getSelect(query).getGroupBys();
}
private List<Field> getSelectFields(String query) {
return getSelect(query).getFields();
}
private Select getSelect(String query) {
SQLQueryExpr queryExpr = SqlParserUtils.parse(query);
Select select = null;
try {
select = new SqlParser().parseSelect(queryExpr);
} catch (SqlParseException e) {
e.printStackTrace();
}
return select;
}
}
|
923daeb24d62f12a7399bab87e6359ff05c66462 | 5,688 | java | Java | sources/org/apache/batik/dom/svg/SVGOMScriptElement.java | Real-Currents/batik | 06c47721787ef543bd5a9ca38585747fe28c32dd | [
"Apache-2.0"
] | 1 | 2018-12-29T08:16:07.000Z | 2018-12-29T08:16:07.000Z | sources/org/apache/batik/dom/svg/SVGOMScriptElement.java | Real-Currents/batik | 06c47721787ef543bd5a9ca38585747fe28c32dd | [
"Apache-2.0"
] | null | null | null | sources/org/apache/batik/dom/svg/SVGOMScriptElement.java | Real-Currents/batik | 06c47721787ef543bd5a9ca38585747fe28c32dd | [
"Apache-2.0"
] | null | null | null | 31.97191 | 78 | 0.613952 | 1,000,423 | /*
Copyright 2000-2001,2003-2004,2006 The Apache Software Foundation
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.apache.batik.dom.svg;
import org.apache.batik.dom.AbstractDocument;
import org.apache.batik.anim.values.AnimatableValue;
import org.apache.batik.dom.util.XLinkSupport;
import org.apache.batik.dom.util.XMLSupport;
import org.apache.batik.util.SVGTypes;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.svg.SVGAnimatedBoolean;
import org.w3c.dom.svg.SVGScriptElement;
/**
* This class implements {@link org.w3c.dom.svg.SVGScriptElement}.
*
* @author <a href="mailto:efpyi@example.com">Stephane Hillion</a>
* @version $Id$
*/
public class SVGOMScriptElement
extends SVGOMURIReferenceElement
implements SVGScriptElement {
/**
* The attribute initializer.
*/
protected final static AttributeInitializer attributeInitializer;
static {
attributeInitializer = new AttributeInitializer(1);
attributeInitializer.addAttribute(XMLSupport.XMLNS_NAMESPACE_URI,
null, "xmlns:xlink",
XLinkSupport.XLINK_NAMESPACE_URI);
attributeInitializer.addAttribute(XLinkSupport.XLINK_NAMESPACE_URI,
"xlink", "type", "simple");
attributeInitializer.addAttribute(XLinkSupport.XLINK_NAMESPACE_URI,
"xlink", "show", "other");
attributeInitializer.addAttribute(XLinkSupport.XLINK_NAMESPACE_URI,
"xlink", "actuate", "onLoad");
}
/**
* Creates a new SVGOMScriptElement object.
*/
protected SVGOMScriptElement() {
}
/**
* Creates a new SVGOMScriptElement object.
* @param prefix The namespace prefix.
* @param owner The owner document.
*/
public SVGOMScriptElement(String prefix, AbstractDocument owner) {
super(prefix, owner);
}
/**
* <b>DOM</b>: Implements {@link Node#getLocalName()}.
*/
public String getLocalName() {
return SVG_SCRIPT_TAG;
}
/**
* <b>DOM</b>: Implements {@link SVGScriptElement#getType()}.
*/
public String getType() {
return getAttributeNS(null, SVG_TYPE_ATTRIBUTE);
}
/**
* <b>DOM</b>: Implements {@link SVGScriptElement#setType(String)}.
*/
public void setType(String type) throws DOMException {
setAttributeNS(null, SVG_TYPE_ATTRIBUTE, type);
}
// SVGExternalResourcesRequired support /////////////////////////////
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.svg.SVGExternalResourcesRequired}.
*/
public SVGAnimatedBoolean getExternalResourcesRequired() {
return SVGExternalResourcesRequiredSupport.
getExternalResourcesRequired(this);
}
/**
* Returns the AttributeInitializer for this element type.
* @return null if this element has no attribute with a default value.
*/
protected AttributeInitializer getAttributeInitializer() {
return attributeInitializer;
}
/**
* Returns a new uninitialized instance of this object's class.
*/
protected Node newNode() {
return new SVGOMScriptElement();
}
// ExtendedTraitAccess ///////////////////////////////////////////////////
/**
* Returns whether the given XML attribute is animatable.
*/
public boolean isAttributeAnimatable(String ns, String ln) {
if (ns == null) {
if (ln.equals(SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE)) {
return true;
}
}
return super.isAttributeAnimatable(ns, ln);
}
/**
* Returns the type of the given attribute.
*/
public int getAttributeType(String ns, String ln) {
if (ns == null) {
if (ln.equals(SVG_TYPE_ATTRIBUTE)) {
return SVGTypes.TYPE_CDATA;
} else if (ln.equals(SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE)) {
return SVGTypes.TYPE_BOOLEAN;
}
}
return super.getAttributeType(ns, ln);
}
// AnimationTarget ///////////////////////////////////////////////////////
/**
* Updates an attribute value in this target.
*/
public void updateAttributeValue(String ns, String ln,
AnimatableValue val) {
if (ns == null) {
if (ln.equals(SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE)) {
updateBooleanAttributeValue(getExternalResourcesRequired(),
val);
return;
}
}
super.updateAttributeValue(ns, ln, val);
}
/**
* Returns the underlying value of an animatable XML attribute.
*/
public AnimatableValue getUnderlyingValue(String ns, String ln) {
if (ns == null) {
if (ln.equals(SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE)) {
return getBaseValue(getExternalResourcesRequired());
}
}
return super.getUnderlyingValue(ns, ln);
}
}
|
923daebdd47359b4205113c30492d14187dd439f | 1,240 | java | Java | happy-code-starters/happy-code-starter-mybatis/src/main/java/cool/happycoding/code/mybatis/AutoFieldFillHandler.java | happy-coding-cool/happy-code | 80794294e522ad28730b69307357defeab34dc10 | [
"Apache-2.0"
] | 9 | 2020-12-27T18:00:37.000Z | 2022-01-07T04:07:30.000Z | happy-code-starters/happy-code-starter-mybatis/src/main/java/cool/happycoding/code/mybatis/AutoFieldFillHandler.java | happy-coding-cool/happy-code | 80794294e522ad28730b69307357defeab34dc10 | [
"Apache-2.0"
] | 1 | 2021-04-06T03:50:20.000Z | 2021-04-16T10:10:39.000Z | happy-code-starters/happy-code-starter-mybatis/src/main/java/cool/happycoding/code/mybatis/AutoFieldFillHandler.java | happy-coding-cool/happy-code | 80794294e522ad28730b69307357defeab34dc10 | [
"Apache-2.0"
] | null | null | null | 19.375 | 60 | 0.58629 | 1,000,424 | package cool.happycoding.code.mybatis;
import cool.happycoding.code.base.user.User;
import cool.happycoding.code.user.DefaultUser;
import cool.happycoding.code.user.context.UserContextHolder;
/**
* description
*
* @author lanlanhappy 2020/12/06 11:23 上午
*/
public interface AutoFieldFillHandler {
String DEFAULT_USERNAME = "system";
String DEFAULT_USER_ID = "-1";
String DEFAULT_TENANT_ID = "null";
String CREATED_BY = "createdBy";
String CREATED_BY_ID = "createdById";
String CREATED_TIME = "createdTime";
String UPDATED_BY = "updatedBy";
String UPDATED_BY_ID = "updatedById";
String UPDATED_TIME = "updatedTime";
/**
* 记录创建人:名称
* @return
*/
String createdBy();
/**
* 记录创建人Id
* @return
*/
String createdById();
/**
* 记录修改人:名称
* @return
*/
String updatedBy();
/**
* 记录修改人Id
* @return
*/
String updatedById();
/**
* 获取的租户
* @return
*/
String tenantId();
/**
* 获取当前上下文用户
* @return
*/
default User currentUser(){
User user = UserContextHolder.getUser();
return user == null ? new DefaultUser() : user;
}
}
|
923daec38788810e0d066e77d0e943e18d36db61 | 2,409 | java | Java | sqlapp-core-postgres/src/main/java/com/sqlapp/data/db/dialect/postgres/metadata/PostgresSettingReader.java | satotatsu/sqlapp | 2df2e0331b02c41afa1f588b6a43edcd81404cd3 | [
"MIT"
] | 1 | 2018-05-04T00:14:54.000Z | 2018-05-04T00:14:54.000Z | sqlapp-core-postgres/src/main/java/com/sqlapp/data/db/dialect/postgres/metadata/PostgresSettingReader.java | satotatsu/sqlapp | 2df2e0331b02c41afa1f588b6a43edcd81404cd3 | [
"MIT"
] | null | null | null | sqlapp-core-postgres/src/main/java/com/sqlapp/data/db/dialect/postgres/metadata/PostgresSettingReader.java | satotatsu/sqlapp | 2df2e0331b02c41afa1f588b6a43edcd81404cd3 | [
"MIT"
] | 1 | 2018-05-04T00:14:33.000Z | 2018-05-04T00:14:33.000Z | 32.173333 | 80 | 0.76378 | 1,000,425 | /**
* Copyright (C) 2007-2017 Tatsuo Satoh <lyhxr@example.com>
*
* This file is part of sqlapp-core-postgres.
*
* sqlapp-core-postgres is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sqlapp-core-postgres is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with sqlapp-core-postgres. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sqlapp.data.db.dialect.postgres.metadata;
import static com.sqlapp.util.CommonUtils.list;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import com.sqlapp.data.db.dialect.Dialect;
import com.sqlapp.data.db.metadata.SettingReader;
import com.sqlapp.data.parameter.ParametersContext;
import com.sqlapp.data.schemas.ProductVersionInfo;
import com.sqlapp.data.schemas.Setting;
import com.sqlapp.jdbc.ExResultSet;
import com.sqlapp.jdbc.sql.ResultSetNextHandler;
import com.sqlapp.jdbc.sql.node.SqlNode;
/**
* PostgresのSettingReader
*
* @author satoh
*
*/
public class PostgresSettingReader extends SettingReader {
protected PostgresSettingReader(final Dialect dialect) {
super(dialect);
}
@Override
protected List<Setting> doGetAll(final Connection connection,
ParametersContext context,
final ProductVersionInfo productVersionInfo) {
SqlNode node = getSqlSqlNode(productVersionInfo);
final List<Setting> result = list();
execute(connection, node, context, new ResultSetNextHandler() {
@Override
public void handleResultSetNext(ExResultSet rs) throws SQLException {
Setting obj = createSetting(rs);
result.add(obj);
}
});
return result;
}
protected SqlNode getSqlSqlNode(ProductVersionInfo productVersionInfo) {
return getSqlNodeCache().getString("settings.sql");
}
protected Setting createSetting(ExResultSet rs) throws SQLException {
Setting obj = new Setting(getString(rs, "name"));
obj.setValue(getString(rs, "setting"));
obj.setRemarks(getString(rs, "short_desc"));
return obj;
}
}
|
923daece1373295988ddb9d2856a0f8a82b3da06 | 760 | java | Java | app/src/main/java/com/litchiny/camera/TakePhoto.java | litchiny/Camera | 9e11f04899788f22f704ecda4503eb5b64997f3c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/litchiny/camera/TakePhoto.java | litchiny/Camera | 9e11f04899788f22f704ecda4503eb5b64997f3c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/litchiny/camera/TakePhoto.java | litchiny/Camera | 9e11f04899788f22f704ecda4503eb5b64997f3c | [
"Apache-2.0"
] | null | null | null | 29.230769 | 85 | 0.685526 | 1,000,426 | package com.litchiny.camera;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class TakePhoto extends Activity {
private static final String TAG = "TakePhoto";
public static final String TAKE_PHOTO = "net.sourceforge.opencamera.TAKE_PHOTO";
@SuppressLint("WrongConstant")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(335544320);
intent.putExtra(TAKE_PHOTO, true);
startActivity(intent);
finish();
}
protected void onResume() {
super.onResume();
}
}
|
923dafadc59dccd172a233604e134579b43b2575 | 646 | java | Java | src/main/java/com/examw/collector/dao/IPackDao.java | vigo2013/examw-collector | c48b64263e9a51f0034fb71f7a93b7826a05c15d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/examw/collector/dao/IPackDao.java | vigo2013/examw-collector | c48b64263e9a51f0034fb71f7a93b7826a05c15d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/examw/collector/dao/IPackDao.java | vigo2013/examw-collector | c48b64263e9a51f0034fb71f7a93b7826a05c15d | [
"Apache-2.0"
] | null | null | null | 15.756098 | 59 | 0.656347 | 1,000,427 | package com.examw.collector.dao;
import java.util.List;
import com.examw.collector.domain.Pack;
import com.examw.collector.model.PackInfo;
/**
* 套餐数据接口
* @author fengwei.
* @since 2014年7月1日 上午9:55:58.
*/
public interface IPackDao extends IBaseDao<Pack>{
/**
* 查询分类数据。
* @return
* 结果数据。
*/
List<Pack> findPacks(PackInfo info);
/**
* 查询数据总数。
* @param info
* 查询条件。
* @return
* 数据总数。
*/
Long total(PackInfo info);
/**
* 根据已存在的ID查找被删除的套餐
* @param existIds
* @return
*/
List<Pack> findDeletePacks(String existIds,PackInfo info);
/**
* 根据科目id删除套餐
* @param subjectId
*/
void delete(String subjectId);
}
|
923db002fece8d47d91313d820793e75c048b634 | 4,363 | java | Java | maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java | smagill/maven-5558a3 | 0c8414d8e3bfc3ece4430a743f76e682e0ec60b6 | [
"Apache-2.0"
] | null | null | null | maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java | smagill/maven-5558a3 | 0c8414d8e3bfc3ece4430a743f76e682e0ec60b6 | [
"Apache-2.0"
] | null | null | null | maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainManagerPrivate.java | smagill/maven-5558a3 | 0c8414d8e3bfc3ece4430a743f76e682e0ec60b6 | [
"Apache-2.0"
] | null | null | null | 36.057851 | 96 | 0.671098 | 1,000,428 | package org.apache.maven.toolchain;
/*
* 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.
*/
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.maven.building.FileSource;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.toolchain.building.DefaultToolchainsBuildingRequest;
import org.apache.maven.toolchain.building.ToolchainsBuildingException;
import org.apache.maven.toolchain.building.ToolchainsBuildingResult;
import org.apache.maven.toolchain.model.PersistedToolchains;
import org.apache.maven.toolchain.model.ToolchainModel;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
/**
* @author mkleint
* @author Robert Scholte
*/
@Component( role = ToolchainManagerPrivate.class )
public class DefaultToolchainManagerPrivate
extends DefaultToolchainManager
implements ToolchainManagerPrivate
{
@Requirement
private org.apache.maven.toolchain.building.ToolchainsBuilder toolchainsBuilder;
public ToolchainPrivate[] getToolchainsForType( String type, MavenSession context )
throws MisconfiguredToolchainException
{
DefaultToolchainsBuildingRequest buildRequest = new DefaultToolchainsBuildingRequest();
File globalToolchainsFile = context.getRequest().getGlobalToolchainsFile();
if ( globalToolchainsFile != null && globalToolchainsFile.isFile() )
{
buildRequest.setGlobalToolchainsSource( new FileSource( globalToolchainsFile ) );
}
File userToolchainsFile = context.getRequest().getUserToolchainsFile();
if ( userToolchainsFile != null && userToolchainsFile.isFile() )
{
buildRequest.setUserToolchainsSource( new FileSource( userToolchainsFile ) );
}
ToolchainsBuildingResult buildResult;
try
{
buildResult = toolchainsBuilder.build( buildRequest );
}
catch ( ToolchainsBuildingException e )
{
throw new MisconfiguredToolchainException( e.getMessage(), e );
}
PersistedToolchains pers = buildResult.getEffectiveToolchains();
List<ToolchainPrivate> toRet = new ArrayList<ToolchainPrivate>();
ToolchainFactory fact = factories.get( type );
if ( fact == null )
{
logger.error( "Missing toolchain factory for type: " + type
+ ". Possibly caused by misconfigured project." );
}
else if ( pers != null )
{
List<ToolchainModel> lst = pers.getToolchains();
if ( lst != null )
{
for ( ToolchainModel toolchainModel : lst )
{
if ( type.equals( toolchainModel.getType() ) )
{
toRet.add( fact.createToolchain( toolchainModel ) );
}
}
}
}
for ( ToolchainFactory toolchainFactory : factories.values() )
{
ToolchainPrivate tool = toolchainFactory.createDefaultToolchain();
if ( tool != null )
{
toRet.add( tool );
}
}
return toRet.toArray( new ToolchainPrivate[toRet.size()] );
}
public void storeToolchainToBuildContext( ToolchainPrivate toolchain, MavenSession session )
{
Map<String, Object> context = retrieveContext( session );
context.put( getStorageKey( toolchain.getType() ), toolchain.getModel() );
}
}
|
923db09c60a88fc44df30af9700c004c1d822627 | 2,510 | java | Java | aura-impl/src/main/java/org/auraframework/impl/adapter/GlobalValueProviderAdapterImpl.java | augustyakaravat/aura | 98d7ba491172c7ea44cbbf74be5eb858040c9c46 | [
"Apache-2.0"
] | 587 | 2015-01-01T00:42:17.000Z | 2022-01-23T00:14:13.000Z | aura-impl/src/main/java/org/auraframework/impl/adapter/GlobalValueProviderAdapterImpl.java | augustyakaravat/aura | 98d7ba491172c7ea44cbbf74be5eb858040c9c46 | [
"Apache-2.0"
] | 156 | 2015-02-06T17:56:21.000Z | 2019-02-27T05:19:11.000Z | aura-impl/src/main/java/org/auraframework/impl/adapter/GlobalValueProviderAdapterImpl.java | augustyakaravat/aura | 98d7ba491172c7ea44cbbf74be5eb858040c9c46 | [
"Apache-2.0"
] | 340 | 2015-01-13T14:13:38.000Z | 2022-03-21T04:05:29.000Z | 30.987654 | 100 | 0.744622 | 1,000,429 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.adapter;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.auraframework.adapter.GlobalValueProviderAdapter;
import org.auraframework.adapter.LocalizationAdapter;
import org.auraframework.annotations.Annotations.ServiceComponent;
import org.auraframework.instance.AuraValueProviderType;
import org.auraframework.instance.GlobalValueProvider;
import org.auraframework.instance.ValueProviderType;
import org.auraframework.service.ContextService;
import org.auraframework.service.DefinitionService;
import org.auraframework.service.LocalizationService;
import com.google.common.collect.Sets;
/**
*/
@ServiceComponent
public class GlobalValueProviderAdapterImpl implements GlobalValueProviderAdapter {
@Inject
private LocalizationAdapter localizationAdapter;
@Inject
private DefinitionService definitionService;
@Inject
private ContextService contextService;
@Inject
private LocalizationService localizationService;
@Override
public List<GlobalValueProvider> createValueProviders() {
List<GlobalValueProvider> l = new LinkedList<>();
// $Label.Section.Key
l.add(new LabelValueProvider(localizationAdapter, definitionService));
// $Locale
l.add(new LocaleValueProvider(localizationService, localizationAdapter, definitionService));
// $Browser
l.add(new BrowserValueProvider(contextService));
// $Global
l.add(new ContextValueProvider(contextService));
return l;
}
@Override
public Set<ValueProviderType> getKeys() {
return Sets.<ValueProviderType>newHashSet(
AuraValueProviderType.LABEL,
AuraValueProviderType.LOCALE,
AuraValueProviderType.BROWSER,
AuraValueProviderType.GLOBAL);
}
}
|
923db0a8e65ff036f3bc5842f450633fc4ae6ccf | 633 | java | Java | dice-server/blog/src/main/java/com/bihell/dice/blog/service/task/JobService.java | bihell/Dice | bcc8660ad58c8888624003a74bd6591eeb3ec4bc | [
"MIT"
] | 326 | 2019-07-14T11:55:06.000Z | 2022-03-29T07:06:30.000Z | dice-server/blog/src/main/java/com/bihell/dice/blog/service/task/JobService.java | bihell/dice | 618296d7ae64d4a9ee48cafe32797ef7d3a3c722 | [
"MIT"
] | 14 | 2019-09-27T05:41:53.000Z | 2022-01-09T16:01:48.000Z | dice-server/blog/src/main/java/com/bihell/dice/blog/service/task/JobService.java | bihell/dice | 618296d7ae64d4a9ee48cafe32797ef7d3a3c722 | [
"MIT"
] | 101 | 2019-10-08T09:34:33.000Z | 2022-03-27T16:24:57.000Z | 19.181818 | 80 | 0.685624 | 1,000,430 | package com.bihell.dice.blog.service.task;
import com.bihell.dice.blog.model.dto.QuartzJob;
import com.bihell.dice.blog.model.tool.Task;
import org.quartz.SchedulerException;
import java.util.List;
/**
* @author haseochen
*/
public interface JobService {
/**
* @return
*/
List<QuartzJob> getTaskList();
/**
* 添加任务
*
* @param job
* @throws SchedulerException
*/
boolean addJob(QuartzJob job) throws SchedulerException;
QuartzJob getJob(Task task);
QuartzJob getJob(String jobName, String jobGroup) throws SchedulerException;
boolean deleteJob(QuartzJob job);
}
|
923db1d7960057798cab4addfa1f4a83d5f35513 | 50,905 | java | Java | craft-atom-util/src/main/java/io/craft/atom/util/buffer/AdaptiveByteBuffer.java | PlayBoyFly/craft-atom | 6c72a2f1669da35bb06c184d7952e4cf2e1297f6 | [
"MIT"
] | 403 | 2015-01-07T02:13:46.000Z | 2022-03-21T05:21:30.000Z | craft-atom-util/src/main/java/io/craft/atom/util/buffer/AdaptiveByteBuffer.java | zxhprogram/craft-atom | 6c72a2f1669da35bb06c184d7952e4cf2e1297f6 | [
"MIT"
] | 7 | 2015-01-14T01:57:54.000Z | 2017-10-19T11:02:20.000Z | craft-atom-util/src/main/java/io/craft/atom/util/buffer/AdaptiveByteBuffer.java | zxhprogram/craft-atom | 6c72a2f1669da35bb06c184d7952e4cf2e1297f6 | [
"MIT"
] | 164 | 2015-01-30T02:19:34.000Z | 2022-01-04T03:43:43.000Z | 31.935383 | 130 | 0.625656 | 1,000,431 | package io.craft.atom.util.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.ShortBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.EnumSet;
import java.util.Set;
/**
* A byte buffer transplant from MINA projects.
* <p>
* This is a replacement for {@link ByteBuffer}. Please refer to
* {@link ByteBuffer} documentation for preliminary usage. We does not use NIO
* {@link ByteBuffer} directly for two reasons:
* <ul>
* <li>It doesn't provide useful getters and putters such as <code>fill</code>,
* <code>get/putString</code>, and <code>get/putAsciiInt()</code> enough.</li>
* <li>It is difficult to write variable-length data due to its fixed capacity</li>
* </ul>
* </p>
*
* <h2>Allocation</h2>
* <p>
* You can allocate a new heap buffer.
*
* <pre>
* AdaptiveByteBuffer buf = AdaptiveByteBuffer.allocate(1024, false);
* </pre>
*
* you can also allocate a new direct buffer:
*
* <pre>
* AdaptiveByteBuffer buf = AdaptiveByteBuffer.allocate(1024, true);
* </pre>
*
* or you can set the default buffer type.
*
* <pre>
* // Allocate heap buffer by default.
* AdaptiveByteBuffer.setUseDirectBuffer(false);
* // A new heap buffer is returned.
* AdaptiveByteBuffer buf = AdaptiveByteBuffer.allocate(1024);
* </pre>
*
* </p>
*
* <h2>Wrapping existing NIO buffers and arrays</h2>
* <p>
* This class provides a few <tt>wrap(...)</tt> methods that wraps any NIO
* buffers and byte arrays.
*
* <h2>AutoExpand</h2>
* <p>
* Writing variable-length data using NIO <tt>ByteBuffers</tt> is not really
* easy, and it is because its size is fixed. {@link AdaptiveByteBuffer} introduces
* <tt>autoExpand</tt> property. If <tt>autoExpand</tt> property is true, you
* never get {@link BufferOverflowException} or
* {@link IndexOutOfBoundsException} (except when index is negative). It
* automatically expands its capacity and limit value. For example:
*
* <pre>
* String greeting = messageBundle.getMessage("hello");
* AdaptiveByteBuffer buf = AdaptiveByteBuffer.allocate(16);
* // Turn on autoExpand (it is off by default)
* buf.setAutoExpand(true);
* buf.putString(greeting, utf8encoder);
* </pre>
*
* The underlying {@link ByteBuffer} is reallocated by {@link AdaptiveByteBuffer} behind
* the scene if the encoded data is larger than 16 bytes in the example above.
* Its capacity will double, and its limit will increase to the last position
* the string is written.
* </p>
*
* <h2>AutoShrink</h2>
* <p>
* You might also want to decrease the capacity of the buffer when most of the
* allocated memory area is not being used. {@link AdaptiveByteBuffer} provides
* <tt>autoShrink</tt> property to take care of this issue. If
* <tt>autoShrink</tt> is turned on, {@link AdaptiveByteBuffer} halves the capacity of the
* buffer when {@link #compact()} is invoked and only 1/4 or less of the current
* capacity is being used.
* <p>
* You can also {@link #shrink()} method manually to shrink the capacity of the
* buffer.
* <p>
* The underlying {@link ByteBuffer} is reallocated by {@link AdaptiveByteBuffer} behind
* the scene, and therefore {@link #buf()} will return a different
* {@link ByteBuffer} instance once capacity changes. Please also note
* {@link #compact()} or {@link #shrink()} will not decrease the capacity if the
* new capacity is less than the {@link #minimumCapacity()} of the buffer.
*
* <h2>Derived Buffers</h2>
* <p>
* Derived buffers are the buffers which were created by {@link #duplicate()},
* {@link #slice()}, or {@link #asReadOnlyBuffer()}.
* Please note that the buffer derived from and its derived buffers are not both
* auto-expandable neither auto-shrinkable. Trying to call
* {@link #setAutoExpand(boolean)} or {@link #setAutoShrink(boolean)} with
* <tt>true</tt> parameter will raise an {@link IllegalStateException}.
* </p>
*
* <h2>Changing Buffer Allocation Policy</h2>
* <p>
* {@link BufferAllocator} interface lets you override the default buffer
* management behavior. There are two allocators provided out-of-the-box:
* <ul>
* <li>{@link SimpleBufferAllocator} (default)</li>
* <li>{@link CachedBufferAllocator}</li>
* </ul>
* You can implement your own allocator and use it by calling
* {@link #setAllocator(BufferAllocator)}.
* </p>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
* @author mindwind
* @version 1.0, 2013/10/09
*/
public abstract class AdaptiveByteBuffer implements Comparable<AdaptiveByteBuffer> {
/**
* <pre>
* allocator : The allocator used to create new buffers
* useDirectBuffer: A flag indicating which type of buffer we are using: heap or direct
* </pre>
*/
private static BufferAllocator allocator = new SimpleBufferAllocator();
private static boolean useDirectBuffer = false ;
// ~ ----------------------------------------------------------------------------------------------------------
/**
* Returns the allocator used by existing and new buffers
*/
public static BufferAllocator getAllocator() {
return allocator;
}
/**
* Sets the allocator used by existing and new buffers
*/
public static void setAllocator(BufferAllocator newAllocator) {
if (newAllocator == null) {
throw new IllegalArgumentException("allocator");
}
BufferAllocator oldAllocator = allocator;
allocator = newAllocator;
if (null != oldAllocator) {
oldAllocator.dispose();
}
}
/**
* Returns <tt>true</tt> if and only if a direct buffer is allocated by
* default when the type of the new buffer is not specified. The default
* value is <tt>false</tt>.
*/
public static boolean isUseDirectBuffer() {
return useDirectBuffer;
}
/**
* Sets if a direct buffer should be allocated by default when the type of
* the new buffer is not specified. The default value is <tt>false</tt>.
*/
public static void setUseDirectBuffer(boolean useDirectBuffer) {
AdaptiveByteBuffer.useDirectBuffer = useDirectBuffer;
}
/**
* Returns the direct or heap buffer which is capable to store the specified
* amount of bytes.
*
* @param capacity
* the capacity of the buffer
*
* @see #setUseDirectBuffer(boolean)
*/
public static AdaptiveByteBuffer allocate(int capacity) {
return allocate(capacity, useDirectBuffer);
}
/**
* Returns the buffer which is capable of the specified size.
*
* @param capacity
* the capacity of the buffer
* @param direct
* <tt>true</tt> to get a direct buffer, <tt>false</tt> to get a
* heap buffer.
*/
public static AdaptiveByteBuffer allocate(int capacity, boolean direct) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity: " + capacity);
}
return allocator.allocate(capacity, direct);
}
/**
* Wraps the specified NIO {@link ByteBuffer} into MINA buffer.
*/
public static AdaptiveByteBuffer wrap(ByteBuffer nioBuffer) {
return allocator.wrap(nioBuffer);
}
/**
* Wraps the specified byte array into MINA heap buffer.
*/
public static AdaptiveByteBuffer wrap(byte[] byteArray) {
return wrap(ByteBuffer.wrap(byteArray));
}
/**
* Wraps the specified byte array into MINA heap buffer.
*/
public static AdaptiveByteBuffer wrap(byte[] byteArray, int offset, int length) {
return wrap(ByteBuffer.wrap(byteArray, offset, length));
}
/**
* Normalizes the specified capacity of the buffer to power of 2, which is
* often helpful for optimal memory usage and performance. If it is greater
* than or equal to {@link Integer#MAX_VALUE}, it returns
* {@link Integer#MAX_VALUE}. If it is zero, it returns zero.
*/
protected static int normalizeCapacity(int requestedCapacity) {
if (requestedCapacity < 0) {
return Integer.MAX_VALUE;
}
int newCapacity = Integer.highestOneBit(requestedCapacity);
newCapacity <<= (newCapacity < requestedCapacity ? 1 : 0);
return newCapacity < 0 ? Integer.MAX_VALUE : newCapacity;
}
/**
* Creates a new instance. This is an empty constructor.
*/
protected AdaptiveByteBuffer() {
// Do nothing
}
/**
* Declares this buffer and all its derived buffers are not used anymore so
* that it can be reused by some {@link BufferAllocator} implementations.
* It is not mandatory to call this method, but you might want to invoke
* this method for maximum performance.
*/
public abstract void free();
/**
* Returns the underlying NIO buffer instance.
*/
public abstract ByteBuffer buf();
/**
* @see ByteBuffer#isDirect()
*/
public abstract boolean isDirect();
/**
* returns <tt>true</tt> if and only if this buffer is derived from other
* buffer via {@link #duplicate()}, {@link #slice()} or
* {@link #asReadOnlyBuffer()}.
*/
public abstract boolean isDerived();
/**
* @see ByteBuffer#isReadOnly()
*/
public abstract boolean isReadOnly();
/**
* Returns the minimum capacity of this buffer which is used to determine
* the new capacity of the buffer shrunk by {@link #compact()} and
* {@link #shrink()} operation. The default value is the initial capacity of
* the buffer.
*/
public abstract int minimumCapacity();
/**
* Sets the minimum capacity of this buffer which is used to determine the
* new capacity of the buffer shrunk by {@link #compact()} and
* {@link #shrink()} operation. The default value is the initial capacity of
* the buffer.
*/
public abstract AdaptiveByteBuffer minimumCapacity(int minimumCapacity);
/**
* @see ByteBuffer#capacity()
*/
public abstract int capacity();
/**
* Increases the capacity of this buffer. If the new capacity is less than
* or equal to the current capacity, this method returns silently. If the
* new capacity is greater than the current capacity, the buffer is
* reallocated while retaining the position, limit, mark and the content of
* the buffer.
*/
public abstract AdaptiveByteBuffer capacity(int newCapacity);
/**
* Returns <tt>true</tt> if and only if <tt>autoExpand</tt> is turned on.
*/
public abstract boolean isAutoExpand();
/**
* Turns on or off <tt>autoExpand</tt>.
*/
public abstract AdaptiveByteBuffer setAutoExpand(boolean autoExpand);
/**
* Returns <tt>true</tt> if and only if <tt>autoShrink</tt> is turned on.
*/
public abstract boolean isAutoShrink();
/**
* Turns on or off <tt>autoShrink</tt>.
*/
public abstract AdaptiveByteBuffer setAutoShrink(boolean autoShrink);
/**
* Changes the capacity and limit of this buffer so this buffer get the
* specified <tt>expectedRemaining</tt> room from the current position. This
* method works even if you didn't set <tt>autoExpand</tt> to <tt>true</tt>.
*/
public abstract AdaptiveByteBuffer expand(int expectedRemaining);
/**
* Changes the capacity and limit of this buffer so this buffer get the
* specified <tt>expectedRemaining</tt> room from the specified
* <tt>position</tt>. This method works even if you didn't set
* <tt>autoExpand</tt> to <tt>true</tt>.
*/
public abstract AdaptiveByteBuffer expand(int position, int expectedRemaining);
/**
* Changes the capacity of this buffer so this buffer occupies as less
* memory as possible while retaining the position, limit and the buffer
* content between the position and limit. The capacity of the buffer never
* becomes less than {@link #minimumCapacity()}. The mark is discarded once
* the capacity changes.
*/
public abstract AdaptiveByteBuffer shrink();
/**
* @see java.nio.Buffer#position()
*/
public abstract int position();
/**
* @see java.nio.Buffer#position(int)
*/
public abstract AdaptiveByteBuffer position(int newPosition);
/**
* @see java.nio.Buffer#limit()
*/
public abstract int limit();
/**
* @see java.nio.Buffer#limit(int)
*/
public abstract AdaptiveByteBuffer limit(int newLimit);
/**
* @see java.nio.Buffer#mark()
*/
public abstract AdaptiveByteBuffer mark();
/**
* Returns the position of the current mark. This method returns <tt>-1</tt>
* if no mark is set.
*/
public abstract int markValue();
/**
* @see java.nio.Buffer#reset()
*/
public abstract AdaptiveByteBuffer reset();
/**
* @see java.nio.Buffer#clear()
*/
public abstract AdaptiveByteBuffer clear();
/**
* Clears this buffer and fills its content with <tt>NUL</tt>. The position
* is set to zero, the limit is set to the capacity, and the mark is
* discarded.
*/
public abstract AdaptiveByteBuffer sweep();
/**
* double Clears this buffer and fills its content with <tt>value</tt>. The
* position is set to zero, the limit is set to the capacity, and the mark
* is discarded.
*/
public abstract AdaptiveByteBuffer sweep(byte value);
/**
* @see java.nio.Buffer#flip()
*/
public abstract AdaptiveByteBuffer flip();
/**
* @see java.nio.Buffer#rewind()
*/
public abstract AdaptiveByteBuffer rewind();
/**
* @see java.nio.Buffer#remaining()
*/
public abstract int remaining();
/**
* @see java.nio.Buffer#hasRemaining()
*/
public abstract boolean hasRemaining();
/**
* @see ByteBuffer#duplicate()
*/
public abstract AdaptiveByteBuffer duplicate();
/**
* @see ByteBuffer#slice()
*/
public abstract AdaptiveByteBuffer slice();
/**
* @see ByteBuffer#asReadOnlyBuffer()
*/
public abstract AdaptiveByteBuffer asReadOnlyBuffer();
/**
* @see ByteBuffer#hasArray()
*/
public abstract boolean hasArray();
/**
* @see ByteBuffer#array()
*/
public abstract byte[] array();
/**
* @see ByteBuffer#arrayOffset()
*/
public abstract int arrayOffset();
/**
* @see ByteBuffer#get()
*/
public abstract byte get();
/**
* Reads one unsigned byte as a short integer.
*/
public abstract short getUnsigned();
/**
* @see ByteBuffer#put(byte)
*/
public abstract AdaptiveByteBuffer put(byte b);
/**
* @see ByteBuffer#get(int)
*/
public abstract byte get(int index);
/**
* Reads one byte as an unsigned short integer.
*/
public abstract short getUnsigned(int index);
/**
* @see ByteBuffer#put(int, byte)
*/
public abstract AdaptiveByteBuffer put(int index, byte b);
/**
* @see ByteBuffer#get(byte[], int, int)
*/
public abstract AdaptiveByteBuffer get(byte[] dst, int offset, int length);
/**
* @see ByteBuffer#get(byte[])
*/
public abstract AdaptiveByteBuffer get(byte[] dst);
/**
* TODO document me.
*/
public abstract AdaptiveByteBuffer getSlice(int index, int length);
/**
* TODO document me.
*/
public abstract AdaptiveByteBuffer getSlice(int length);
/**
* Writes the content of the specified <tt>src</tt> into this buffer.
*/
public abstract AdaptiveByteBuffer put(ByteBuffer src);
/**
* Writes the content of the specified <tt>src</tt> into this buffer.
*/
public abstract AdaptiveByteBuffer put(AdaptiveByteBuffer src);
/**
* @see ByteBuffer#put(byte[], int, int)
*/
public abstract AdaptiveByteBuffer put(byte[] src, int offset, int length);
/**
* @see ByteBuffer#put(byte[])
*/
public abstract AdaptiveByteBuffer put(byte[] src);
/**
* @see ByteBuffer#compact()
*/
public abstract AdaptiveByteBuffer compact();
/**
* @see ByteBuffer#order()
*/
public abstract ByteOrder order();
/**
* @see ByteBuffer#order(ByteOrder)
*/
public abstract AdaptiveByteBuffer order(ByteOrder bo);
/**
* @see ByteBuffer#getChar()
*/
public abstract char getChar();
/**
* @see ByteBuffer#putChar(char)
*/
public abstract AdaptiveByteBuffer putChar(char value);
/**
* @see ByteBuffer#getChar(int)
*/
public abstract char getChar(int index);
/**
* @see ByteBuffer#putChar(int, char)
*/
public abstract AdaptiveByteBuffer putChar(int index, char value);
/**
* @see ByteBuffer#asCharBuffer()
*/
public abstract CharBuffer asCharBuffer();
/**
* @see ByteBuffer#getShort()
*/
public abstract short getShort();
/**
* Reads two bytes unsigned integer.
*/
public abstract int getUnsignedShort();
/**
* @see ByteBuffer#putShort(short)
*/
public abstract AdaptiveByteBuffer putShort(short value);
/**
* @see ByteBuffer#getShort()
*/
public abstract short getShort(int index);
/**
* Reads two bytes unsigned integer.
*/
public abstract int getUnsignedShort(int index);
/**
* @see ByteBuffer#putShort(int, short)
*/
public abstract AdaptiveByteBuffer putShort(int index, short value);
/**
* @see ByteBuffer#asShortBuffer()
*/
public abstract ShortBuffer asShortBuffer();
/**
* @see ByteBuffer#getInt()
*/
public abstract int getInt();
/**
* Reads four bytes unsigned integer.
*/
public abstract long getUnsignedInt();
/**
* Relative <i>get</i> method for reading a medium int value.
*
* <p>
* Reads the next three bytes at this buffer's current position, composing
* them into an int value according to the current byte order, and then
* increments the position by three.
* </p>
*
* @return The medium int value at the buffer's current position
*/
public abstract int getMediumInt();
/**
* Relative <i>get</i> method for reading an unsigned medium int value.
*
* <p>
* Reads the next three bytes at this buffer's current position, composing
* them into an int value according to the current byte order, and then
* increments the position by three.
* </p>
*
* @return The unsigned medium int value at the buffer's current position
*/
public abstract int getUnsignedMediumInt();
/**
* Absolute <i>get</i> method for reading a medium int value.
*
* <p>
* Reads the next three bytes at this buffer's current position, composing
* them into an int value according to the current byte order.
* </p>
*
* @param index
* The index from which the medium int will be read
* @return The medium int value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative or not smaller than the
* buffer's limit
*/
public abstract int getMediumInt(int index);
/**
* Absolute <i>get</i> method for reading an unsigned medium int value.
*
* <p>
* Reads the next three bytes at this buffer's current position, composing
* them into an int value according to the current byte order.
* </p>
*
* @param index
* The index from which the unsigned medium int will be read
* @return The unsigned medium int value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative or not smaller than the
* buffer's limit
*/
public abstract int getUnsignedMediumInt(int index);
/**
* Relative <i>put</i> method for writing a medium int value.
*
* <p>
* Writes three bytes containing the given int value, in the current byte
* order, into this buffer at the current position, and then increments the
* position by three.
* </p>
*
* @param value
* The medium int value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than three bytes remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract AdaptiveByteBuffer putMediumInt(int value);
/**
* Absolute <i>put</i> method for writing a medium int value.
*
* <p>
* Writes three bytes containing the given int value, in the current byte
* order, into this buffer at the given index.
* </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The medium int value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative or not smaller than the
* buffer's limit, minus three
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract AdaptiveByteBuffer putMediumInt(int index, int value);
/**
* @see ByteBuffer#putInt(int)
*/
public abstract AdaptiveByteBuffer putInt(int value);
/**
* Writes an unsigned byte into the ByteBuffer
* @param value the byte to write
*/
public abstract AdaptiveByteBuffer putUnsigned(byte value);
/**
* Writes an unsigned byte into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the byte to write
*/
public abstract AdaptiveByteBuffer putUnsigned(int index, byte value);
/**
* Writes an unsigned byte into the ByteBuffer
* @param value the short to write
*/
public abstract AdaptiveByteBuffer putUnsigned(short value);
/**
* Writes an unsigned byte into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the short to write
*/
public abstract AdaptiveByteBuffer putUnsigned(int index, short value);
/**
* Writes an unsigned byte into the ByteBuffer
* @param value the int to write
*/
public abstract AdaptiveByteBuffer putUnsigned(int value);
/**
* Writes an unsigned byte into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the int to write
*/
public abstract AdaptiveByteBuffer putUnsigned(int index, int value);
/**
* Writes an unsigned byte into the ByteBuffer
* @param value the long to write
*/
public abstract AdaptiveByteBuffer putUnsigned(long value);
/**
* Writes an unsigned byte into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the long to write
*/
public abstract AdaptiveByteBuffer putUnsigned(int index, long value);
/**
* Writes an unsigned int into the ByteBuffer
* @param value the byte to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(byte value);
/**
* Writes an unsigned int into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the byte to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(int index, byte value);
/**
* Writes an unsigned int into the ByteBuffer
* @param value the short to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(short value);
/**
* Writes an unsigned int into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the short to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(int index, short value);
/**
* Writes an unsigned int into the ByteBuffer
* @param value the int to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(int value);
/**
* Writes an unsigned int into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the int to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(int index, int value);
/**
* Writes an unsigned int into the ByteBuffer
* @param value the long to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(long value);
/**
* Writes an unsigned int into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the long to write
*/
public abstract AdaptiveByteBuffer putUnsignedInt(int index, long value);
/**
* Writes an unsigned short into the ByteBuffer
* @param value the byte to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(byte value);
/**
* Writes an unsigned Short into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the byte to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(int index, byte value);
/**
* Writes an unsigned Short into the ByteBuffer
* @param value the short to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(short value);
/**
* Writes an unsigned Short into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the short to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(int index, short value);
/**
* Writes an unsigned Short into the ByteBuffer
* @param value the int to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(int value);
/**
* Writes an unsigned Short into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the int to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(int index, int value);
/**
* Writes an unsigned Short into the ByteBuffer
* @param value the long to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(long value);
/**
* Writes an unsigned Short into the ByteBuffer at a specified position
* @param index the position in the buffer to write the value
* @param value the long to write
*/
public abstract AdaptiveByteBuffer putUnsignedShort(int index, long value);
/**
* @see ByteBuffer#getInt(int)
*/
public abstract int getInt(int index);
/**
* Reads four bytes unsigned integer.
* @param index the position in the buffer to write the value
*/
public abstract long getUnsignedInt(int index);
/**
* @see ByteBuffer#putInt(int, int)
*/
public abstract AdaptiveByteBuffer putInt(int index, int value);
/**
* @see ByteBuffer#asIntBuffer()
*/
public abstract IntBuffer asIntBuffer();
/**
* @see ByteBuffer#getLong()
*/
public abstract long getLong();
/**
* @see ByteBuffer#putLong(int, long)
*/
public abstract AdaptiveByteBuffer putLong(long value);
/**
* @see ByteBuffer#getLong(int)
*/
public abstract long getLong(int index);
/**
* @see ByteBuffer#putLong(int, long)
*/
public abstract AdaptiveByteBuffer putLong(int index, long value);
/**
* @see ByteBuffer#asLongBuffer()
*/
public abstract LongBuffer asLongBuffer();
/**
* @see ByteBuffer#getFloat()
*/
public abstract float getFloat();
/**
* @see ByteBuffer#putFloat(float)
*/
public abstract AdaptiveByteBuffer putFloat(float value);
/**
* @see ByteBuffer#getFloat(int)
*/
public abstract float getFloat(int index);
/**
* @see ByteBuffer#putFloat(int, float)
*/
public abstract AdaptiveByteBuffer putFloat(int index, float value);
/**
* @see ByteBuffer#asFloatBuffer()
*/
public abstract FloatBuffer asFloatBuffer();
/**
* @see ByteBuffer#getDouble()
*/
public abstract double getDouble();
/**
* @see ByteBuffer#putDouble(double)
*/
public abstract AdaptiveByteBuffer putDouble(double value);
/**
* @see ByteBuffer#getDouble(int)
*/
public abstract double getDouble(int index);
/**
* @see ByteBuffer#putDouble(int, double)
*/
public abstract AdaptiveByteBuffer putDouble(int index, double value);
/**
* @see ByteBuffer#asDoubleBuffer()
*/
public abstract DoubleBuffer asDoubleBuffer();
/**
* Returns an {@link InputStream} that reads the data from this buffer.
* {@link InputStream#read()} returns <tt>-1</tt> if the buffer position
* reaches to the limit.
*/
public abstract InputStream asInputStream();
/**
* Returns an {@link OutputStream} that appends the data into this buffer.
* Please note that the {@link OutputStream#write(int)} will throw a
* {@link BufferOverflowException} instead of an {@link IOException} in case
* of buffer overflow. Please set <tt>autoExpand</tt> property by calling
* {@link #setAutoExpand(boolean)} to prevent the unexpected runtime
* exception.
*/
public abstract OutputStream asOutputStream();
/**
* Returns hexdump of this buffer. The data and pointer are not changed as a
* result of this method call.
*
* @return hexidecimal representation of this buffer
*/
public abstract String getHexDump();
/**
* Return hexdump of this buffer with limited length.
*
* @param lengthLimit
* The maximum number of bytes to dump from the current buffer
* position.
* @return hexidecimal representation of this buffer
*/
public abstract String getHexDump(int lengthLimit);
// //////////////////////////////
// String getters and putters //
// //////////////////////////////
/**
* Reads a <code>NUL</code>-terminated string from this buffer using the
* specified <code>decoder</code> and returns it. This method reads until
* the limit of this buffer if no <tt>NUL</tt> is found.
*/
public abstract String getString(CharsetDecoder decoder) throws CharacterCodingException;
/**
* Reads a <code>NUL</code>-terminated string from this buffer using the
* specified <code>decoder</code> and returns it.
*
* @param fieldSize
* the maximum number of bytes to read
*/
public abstract String getString(int fieldSize, CharsetDecoder decoder) throws CharacterCodingException;
/**
* Writes the content of <code>in</code> into this buffer using the
* specified <code>encoder</code>. This method doesn't terminate string with
* <tt>NUL</tt>. You have to do it by yourself.
*
* @throws BufferOverflowException
* if the specified string doesn't fit
*/
public abstract AdaptiveByteBuffer putString(CharSequence val, CharsetEncoder encoder) throws CharacterCodingException;
/**
* Writes the content of <code>in</code> into this buffer as a
* <code>NUL</code>-terminated string using the specified
* <code>encoder</code>.
* <p>
* If the charset name of the encoder is UTF-16, you cannot specify odd
* <code>fieldSize</code>, and this method will append two <code>NUL</code>s
* as a terminator.
* <p>
* Please note that this method doesn't terminate with <code>NUL</code> if
* the input string is longer than <tt>fieldSize</tt>.
*
* @param fieldSize
* the maximum number of bytes to write
*/
public abstract AdaptiveByteBuffer putString(CharSequence val, int fieldSize, CharsetEncoder encoder)
throws CharacterCodingException;
/**
* Reads a string which has a 16-bit length field before the actual encoded
* string, using the specified <code>decoder</code> and returns it. This
* method is a shortcut for <tt>getPrefixedString(2, decoder)</tt>.
*/
public abstract String getPrefixedString(CharsetDecoder decoder) throws CharacterCodingException;
/**
* Reads a string which has a length field before the actual encoded string,
* using the specified <code>decoder</code> and returns it.
*
* @param prefixLength
* the length of the length field (1, 2, or 4)
*/
public abstract String getPrefixedString(int prefixLength, CharsetDecoder decoder) throws CharacterCodingException;
/**
* Writes the content of <code>in</code> into this buffer as a string which
* has a 16-bit length field before the actual encoded string, using the
* specified <code>encoder</code>. This method is a shortcut for
* <tt>putPrefixedString(in, 2, 0, encoder)</tt>.
*
* @throws BufferOverflowException
* if the specified string doesn't fit
*/
public abstract AdaptiveByteBuffer putPrefixedString(CharSequence in, CharsetEncoder encoder) throws CharacterCodingException;
/**
* Writes the content of <code>in</code> into this buffer as a string which
* has a 16-bit length field before the actual encoded string, using the
* specified <code>encoder</code>. This method is a shortcut for
* <tt>putPrefixedString(in, prefixLength, 0, encoder)</tt>.
*
* @param prefixLength
* the length of the length field (1, 2, or 4)
*
* @throws BufferOverflowException
* if the specified string doesn't fit
*/
public abstract AdaptiveByteBuffer putPrefixedString(CharSequence in, int prefixLength, CharsetEncoder encoder)
throws CharacterCodingException;
/**
* Writes the content of <code>in</code> into this buffer as a string which
* has a 16-bit length field before the actual encoded string, using the
* specified <code>encoder</code>. This method is a shortcut for
* <tt>putPrefixedString(in, prefixLength, padding, ( byte ) 0, encoder)</tt>
* .
*
* @param prefixLength
* the length of the length field (1, 2, or 4)
* @param padding
* the number of padded <tt>NUL</tt>s (1 (or 0), 2, or 4)
*
* @throws BufferOverflowException
* if the specified string doesn't fit
*/
public abstract AdaptiveByteBuffer putPrefixedString(CharSequence in, int prefixLength, int padding, CharsetEncoder encoder)
throws CharacterCodingException;
/**
* Writes the content of <code>in</code> into this buffer as a string which
* has a 16-bit length field before the actual encoded string, using the
* specified <code>encoder</code>.
*
* @param prefixLength
* the length of the length field (1, 2, or 4)
* @param padding
* the number of padded bytes (1 (or 0), 2, or 4)
* @param padValue
* the value of padded bytes
*
* @throws BufferOverflowException
* if the specified string doesn't fit
*/
public abstract AdaptiveByteBuffer putPrefixedString(CharSequence val, int prefixLength, int padding, byte padValue,
CharsetEncoder encoder) throws CharacterCodingException;
/**
* Reads a Java object from the buffer using the context {@link ClassLoader}
* of the current thread.
*/
public abstract Object getObject() throws ClassNotFoundException;
/**
* Reads a Java object from the buffer using the specified
* <tt>classLoader</tt>.
*/
public abstract Object getObject(final ClassLoader classLoader) throws ClassNotFoundException;
/**
* Writes the specified Java object to the buffer.
*/
public abstract AdaptiveByteBuffer putObject(Object o);
/**
* Returns <tt>true</tt> if this buffer contains a data which has a data
* length as a prefix and the buffer has remaining data as enough as
* specified in the data length field. This method is identical with
* <tt>prefixedDataAvailable( prefixLength, Integer.MAX_VALUE )</tt>. Please
* not that using this method can allow DoS (Denial of Service) attack in
* case the remote peer sends too big data length value. It is recommended
* to use {@link #prefixedDataAvailable(int, int)} instead.
*
* @param prefixLength
* the length of the prefix field (1, 2, or 4)
*
* @throws IllegalArgumentException
* if prefixLength is wrong
* @throws BufferDataException
* if data length is negative
*/
public abstract boolean prefixedDataAvailable(int prefixLength);
/**
* Returns <tt>true</tt> if this buffer contains a data which has a data
* length as a prefix and the buffer has remaining data as enough as
* specified in the data length field.
*
* @param prefixLength
* the length of the prefix field (1, 2, or 4)
* @param maxDataLength
* the allowed maximum of the read data length
*
* @throws IllegalArgumentException
* if prefixLength is wrong
* @throws BufferDataException
* if data length is negative or greater then
* <tt>maxDataLength</tt>
*/
public abstract boolean prefixedDataAvailable(int prefixLength, int maxDataLength);
// ///////////////////
// IndexOf methods //
// ///////////////////
/**
* Returns the first occurence position of the specified byte from the
* current position to the current limit.
*
* @return <tt>-1</tt> if the specified byte is not found
*/
public abstract int indexOf(byte b);
// ////////////////////////
// Skip or fill methods //
// ////////////////////////
/**
* Forwards the position of this buffer as the specified <code>size</code>
* bytes.
*/
public abstract AdaptiveByteBuffer skip(int size);
/**
* Fills this buffer with the specified value. This method moves buffer
* position forward.
*/
public abstract AdaptiveByteBuffer fill(byte value, int size);
/**
* Fills this buffer with the specified value. This method does not change
* buffer position.
*/
public abstract AdaptiveByteBuffer fillAndReset(byte value, int size);
/**
* Fills this buffer with <code>NUL (0x00)</code>. This method moves buffer
* position forward.
*/
public abstract AdaptiveByteBuffer fill(int size);
/**
* Fills this buffer with <code>NUL (0x00)</code>. This method does not
* change buffer position.
*/
public abstract AdaptiveByteBuffer fillAndReset(int size);
// ////////////////////////
// Enum methods //
// ////////////////////////
/**
* Reads a byte from the buffer and returns the correlating enum constant
* defined by the specified enum type.
*
* @param <E>
* The enum type to return
* @param enumClass
* The enum's class object
*/
public abstract <E extends Enum<E>> E getEnum(Class<E> enumClass);
/**
* Reads a byte from the buffer and returns the correlating enum constant
* defined by the specified enum type.
*
* @param <E>
* The enum type to return
* @param index
* the index from which the byte will be read
* @param enumClass
* The enum's class object
*/
public abstract <E extends Enum<E>> E getEnum(int index, Class<E> enumClass);
/**
* Reads a short from the buffer and returns the correlating enum constant
* defined by the specified enum type.
*
* @param <E>
* The enum type to return
* @param enumClass
* The enum's class object
*/
public abstract <E extends Enum<E>> E getEnumShort(Class<E> enumClass);
/**
* Reads a short from the buffer and returns the correlating enum constant
* defined by the specified enum type.
*
* @param <E>
* The enum type to return
* @param index
* the index from which the bytes will be read
* @param enumClass
* The enum's class object
*/
public abstract <E extends Enum<E>> E getEnumShort(int index, Class<E> enumClass);
/**
* Reads an int from the buffer and returns the correlating enum constant
* defined by the specified enum type.
*
* @param <E>
* The enum type to return
* @param enumClass
* The enum's class object
*/
public abstract <E extends Enum<E>> E getEnumInt(Class<E> enumClass);
/**
* Reads an int from the buffer and returns the correlating enum constant
* defined by the specified enum type.
*
* @param <E>
* The enum type to return
* @param index
* the index from which the bytes will be read
* @param enumClass
* The enum's class object
*/
public abstract <E extends Enum<E>> E getEnumInt(int index, Class<E> enumClass);
/**
* Writes an enum's ordinal value to the buffer as a byte.
*
* @param e
* The enum to write to the buffer
*/
public abstract AdaptiveByteBuffer putEnum(Enum<?> e);
/**
* Writes an enum's ordinal value to the buffer as a byte.
*
* @param index
* The index at which the byte will be written
* @param e
* The enum to write to the buffer
*/
public abstract AdaptiveByteBuffer putEnum(int index, Enum<?> e);
/**
* Writes an enum's ordinal value to the buffer as a short.
*
* @param e
* The enum to write to the buffer
*/
public abstract AdaptiveByteBuffer putEnumShort(Enum<?> e);
/**
* Writes an enum's ordinal value to the buffer as a short.
*
* @param index
* The index at which the bytes will be written
* @param e
* The enum to write to the buffer
*/
public abstract AdaptiveByteBuffer putEnumShort(int index, Enum<?> e);
/**
* Writes an enum's ordinal value to the buffer as an integer.
*
* @param e
* The enum to write to the buffer
*/
public abstract AdaptiveByteBuffer putEnumInt(Enum<?> e);
/**
* Writes an enum's ordinal value to the buffer as an integer.
*
* @param index
* The index at which the bytes will be written
* @param e
* The enum to write to the buffer
*/
public abstract AdaptiveByteBuffer putEnumInt(int index, Enum<?> e);
// ////////////////////////
// EnumSet methods //
// ////////////////////////
/**
* Reads a byte sized bit vector and converts it to an {@link EnumSet}.
*
* <p>
* Each bit is mapped to a value in the specified enum. The least
* significant bit maps to the first entry in the specified enum and each
* subsequent bit maps to each subsequent bit as mapped to the subsequent
* enum value.
* </p>
*
* @param <E>
* the enum type
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSet(Class<E> enumClass);
/**
* Reads a byte sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param index
* the index from which the byte will be read
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSet(int index, Class<E> enumClass);
/**
* Reads a short sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSetShort(Class<E> enumClass);
/**
* Reads a short sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param index
* the index from which the bytes will be read
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSetShort(int index, Class<E> enumClass);
/**
* Reads an int sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSetInt(Class<E> enumClass);
/**
* Reads an int sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param index
* the index from which the bytes will be read
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSetInt(int index, Class<E> enumClass);
/**
* Reads a long sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSetLong(Class<E> enumClass);
/**
* Reads a long sized bit vector and converts it to an {@link EnumSet}.
*
* @see #getEnumSet(Class)
* @param <E>
* the enum type
* @param index
* the index from which the bytes will be read
* @param enumClass
* the enum class used to create the EnumSet
* @return the EnumSet representation of the bit vector
*/
public abstract <E extends Enum<E>> EnumSet<E> getEnumSetLong(int index, Class<E> enumClass);
/**
* Writes the specified {@link Set} to the buffer as a byte sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSet(Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as a byte sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param index
* the index at which the byte will be written
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSet(int index, Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as a short sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSetShort(Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as a short sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param index
* the index at which the bytes will be written
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSetShort(int index, Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as an int sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSetInt(Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as an int sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param index
* the index at which the bytes will be written
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSetInt(int index, Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as a long sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSetLong(Set<E> set);
/**
* Writes the specified {@link Set} to the buffer as a long sized bit
* vector.
*
* @param <E>
* the enum type of the Set
* @param index
* the index at which the bytes will be written
* @param set
* the enum set to write to the buffer
*/
public abstract <E extends Enum<E>> AdaptiveByteBuffer putEnumSetLong(int index, Set<E> set);
}
|
923db2984100d41d255f88de16eddd77789a98c6 | 5,635 | java | Java | chrome/android/java/src/org/chromium/chrome/browser/preferences/ManagedPreferencesUtils.java | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/android/java/src/org/chromium/chrome/browser/preferences/ManagedPreferencesUtils.java | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/android/java/src/org/chromium/chrome/browser/preferences/ManagedPreferencesUtils.java | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | 42.052239 | 100 | 0.687311 | 1,000,432 | // 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;
import android.content.Context;
import android.preference.Preference;
import android.support.annotation.Nullable;
import android.view.View;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.util.ViewUtils;
import org.chromium.ui.widget.Toast;
/**
* Utilities and common methods to handle settings managed by policies.
*/
public class ManagedPreferencesUtils {
/**
* Shows a toast indicating that the previous action is managed by the system administrator.
*
* This is usually used to explain to the user why a given control is disabled in the settings.
*
* @param context The context where the Toast will be shown.
*/
public static void showManagedByAdministratorToast(Context context) {
Toast.makeText(context, context.getString(R.string.managed_by_your_administrator),
Toast.LENGTH_LONG).show();
}
/**
* Shows a toast indicating that the previous action is managed by the parent(s) of the
* supervised user.
* This is usually used to explain to the user why a given control is disabled in the settings.
*
* @param context The context where the Toast will be shown.
*/
public static void showManagedByParentToast(Context context) {
boolean singleParentIsManager =
PrefServiceBridge.getInstance().getSupervisedUserSecondCustodianName().isEmpty();
Toast.makeText(context, context.getString(singleParentIsManager
? R.string.managed_by_your_parent : R.string.managed_by_your_parents),
Toast.LENGTH_LONG).show();
}
/**
* @return the resource ID for the Managed By Enterprise icon.
*/
public static int getManagedByEnterpriseIconId() {
return R.drawable.controlled_setting_mandatory;
}
/**
* Initializes the Preference based on the state of any policies that may affect it,
* e.g. by showing a managed icon or disabling clicks on the preference.
*
* This should be called once, before the preference is displayed.
*
* @param delegate The delegate that controls whether the preference is managed. May be null,
* then this method does nothing.
* @param preference The Preference that is being initialized
*/
public static void initPreference(
@Nullable ManagedPreferenceDelegate delegate, Preference preference) {
if (delegate == null) return;
if (delegate.isPreferenceControlledByPolicy(preference)) {
preference.setIcon(getManagedByEnterpriseIconId());
} else if (delegate.isPreferenceControlledByCustodian(preference)) {
preference.setIcon(R.drawable.ic_account_child_grey600_36dp);
}
if (delegate.isPreferenceClickDisabledByPolicy(preference)) {
// Disable the views and prevent the Preference from mucking with the enabled state.
preference.setShouldDisableView(false);
// Prevent default click behavior.
preference.setFragment(null);
preference.setIntent(null);
preference.setOnPreferenceClickListener(null);
}
}
/**
* Disables the Preference's views if the preference is not clickable.
*
* Note: this disables the View instead of disabling the Preference, so that the Preference
* still receives click events, which will trigger a "Managed by your administrator" toast.
*
* This should be called from the Preference's onBindView() method.
*
* @param delegate The delegate that controls whether the preference is managed. May be null,
* then this method does nothing.
* @param preference The Preference that owns the view
* @param view The View that was bound to the Preference
*/
public static void onBindViewToPreference(
@Nullable ManagedPreferenceDelegate delegate, Preference preference, View view) {
if (delegate != null && delegate.isPreferenceClickDisabledByPolicy(preference)) {
ViewUtils.setEnabledRecursive(view, false);
}
}
/**
* Intercepts the click event if the given Preference is managed and shows a toast in that case.
*
* This should be called from the Preference's onClick() method.
*
* @param delegate The delegate that controls whether the preference is managed. May be null,
* then this method does nothing and returns false.
* @param preference The Preference that was clicked.
* @return true if the click event was handled by this helper and shouldn't be further
* propagated; false otherwise.
*/
public static boolean onClickPreference(
@Nullable ManagedPreferenceDelegate delegate, Preference preference) {
if (delegate == null || !delegate.isPreferenceClickDisabledByPolicy(preference)) {
return false;
}
if (delegate.isPreferenceControlledByPolicy(preference)) {
showManagedByAdministratorToast(preference.getContext());
} else if (delegate.isPreferenceControlledByCustodian(preference)) {
showManagedByParentToast(preference.getContext());
} else {
// If the preference is disabled, it should be either because it's managed by enterprise
// policy or by the custodian.
assert false;
}
return true;
}
}
|
923db33a56f1b78bcf3aa6111100c405885bd439 | 15,809 | java | Java | app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | mailtoabhi15/MySunshine | 508bc96d38a4873050bced0f56bf7a62f2673995 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | mailtoabhi15/MySunshine | 508bc96d38a4873050bced0f56bf7a62f2673995 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java | mailtoabhi15/MySunshine | 508bc96d38a4873050bced0f56bf7a62f2673995 | [
"Apache-2.0"
] | null | null | null | 38.747549 | 169 | 0.596559 | 1,000,433 | package com.example.android.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by abhishek.dixit on 1/5/2016.
* A ForcastFragment fragment containing a simple view.
*/
public class ForecastFragment extends Fragment{
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Dixit:Add this line inorder for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// String[] forecast = {"Monday-Sunny-88/63",
// "Tuesday-Windy-78/63",
// "Wednesday-Foggy-68/63",
// "Thursday-Rainy-58/63",
// "Friday-Stromy-48/63",
// "Saturday-Sunny-98/63"};
// List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecast));//converting forecast to an Array list data
mForecastAdapter = new ArrayAdapter<String>(
getActivity(),//Current Context:this fragmant's parent activity
R.layout.list_item_forecast,//ID of List item layout
R.id.list_item_forecast_textview,//ID of text View
new ArrayList<String >());
//weekForecast); //forecast data
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//Get a refrence to the ListView, and attach this adapter to it
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String forecast = mForecastAdapter.getItem(position);
Toast.makeText(getActivity(), forecast, Toast.LENGTH_SHORT).show();
Intent detailAct = new Intent(getActivity(), DetailActivity.class);
detailAct.putExtra(Intent.EXTRA_TEXT, forecast);
//if (detailAct.resolveActivity(getPackageManager()) != null) {
startActivity(detailAct);
//}
}
});
return rootView;
}
//Dixit:Function Creating FetchWeatherTask & reading data from SharedPrefer on Refresh & AppStart
public void updateWeather(){
FetchWeatherTask weatherTask = new FetchWeatherTask();
//Dixit::Fetching Location value from Shared Prefernces
SharedPreferences locPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String location = locPref.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
weatherTask.execute(location);
}
@Override
//Dixit::Calling UpdateWeather in OnStart so that when Application Start it fetches the Latest Data & Display
public void onStart() {
super.onStart();
updateWeather();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
public class FetchWeatherTask extends AsyncTask<String,Void,String[]>
{
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low, String unitType) {
if (unitType.equals(getString(R.string.pref_temp_units_imperial)))
{
high = (high * 1.8) + 32;
low = (low * 1.8) + 32;
}
else if (!unitType.equals(getString(R.string.pref_temp_units_metrics)))
{
Log.d(LOG_TAG, "Unit type not found: " + unitType);
}
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
//Dixit: Data is fetched in Celsius by default.
// If user prefers to see in Fahrenheit, convert the values here.
// We do this rather than fetching in Fahrenheit so that the user can
// change this option without us having to re-fetch the data once
// we start storing the values in a database.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String unitType = sharedPrefs.getString(getString(R.string.pref_temp_units_key), getString(R.string.pref_temp_units_metrics));
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low,unitType);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
if(params.length==0)
{
return null;
}
//Dixit: These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
//URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&APPID=e8f8e55e165af32fafa39ad2c3837fc0");
String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
//String cityId= "201204";
String mode = "json";
String units = "metric";
String count = "7";
String apiKey = "e8f8e55e165af32fafa39ad2c3837fc0";
Uri.Builder nUrl = new Uri.Builder();
nUrl.scheme("http").authority("api.openweathermap.org");
nUrl.appendPath("data");
nUrl.appendPath("2.5");
nUrl.appendPath("forecast");
nUrl.appendPath("daily");
nUrl.appendQueryParameter("q", params[0]);
nUrl.appendQueryParameter("mode",mode);
nUrl.appendQueryParameter("units",units);
nUrl.appendQueryParameter("cnt",count);
nUrl.appendQueryParameter("APPID",BuildConfig.OPEN_WEATHER_MAP_API_KEY);
URL url = new URL(nUrl.build().toString());
Log.v("ForecastFragment","URL: " + url);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
// forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG,"Forecast JSON String: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
}
try{
//Dixit: to parse(as required) response data from server we call below function
if(forecastJsonStr != null)
return getWeatherDataFromJson(forecastJsonStr, 7);
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
if(result!=null){
mForecastAdapter.clear();
for(String dayForeCastStr : result ) {
mForecastAdapter.addAll(dayForeCastStr);
}
}
else
Toast.makeText(getActivity(),"Please check Network Connection",Toast.LENGTH_SHORT).show();
}
}
}
|
923db3b149ed9a9c25772ef7b3a413ba57c337d5 | 1,133 | java | Java | test-framework/junit5-mockito/src/main/java/io/quarkus/test/junit/mockito/internal/SetMockitoMockAsBeanMockCallback.java | mzezulka/quarkus | b83b40de202e8b7306b6b71bd57c0a890b2bd757 | [
"Apache-2.0"
] | 2 | 2021-10-07T06:58:36.000Z | 2021-11-08T11:43:14.000Z | test-framework/junit5-mockito/src/main/java/io/quarkus/test/junit/mockito/internal/SetMockitoMockAsBeanMockCallback.java | mzezulka/quarkus | b83b40de202e8b7306b6b71bd57c0a890b2bd757 | [
"Apache-2.0"
] | 3 | 2021-11-15T23:27:59.000Z | 2022-02-16T01:09:23.000Z | test-framework/junit5-mockito/src/main/java/io/quarkus/test/junit/mockito/internal/SetMockitoMockAsBeanMockCallback.java | mzezulka/quarkus | b83b40de202e8b7306b6b71bd57c0a890b2bd757 | [
"Apache-2.0"
] | null | null | null | 34.333333 | 120 | 0.661959 | 1,000,434 | package io.quarkus.test.junit.mockito.internal;
import java.lang.reflect.Method;
import io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback;
public class SetMockitoMockAsBeanMockCallback implements QuarkusTestBeforeEachCallback {
private volatile Method installMocksMethod;
@Override
public void beforeEach(Object testInstance) {
MockitoMocksTracker.getMocks(testInstance).forEach(m -> {
installMocks(m, m.beanInstance);
});
}
// call MockSupport.installMock using reflection since it is not public
private void installMocks(MockitoMocksTracker.Mocked m, Object beanInstance) {
try {
if (installMocksMethod == null) {
installMocksMethod = Class.forName("io.quarkus.test.junit.MockSupport").getDeclaredMethod("installMock",
Object.class,
Object.class);
installMocksMethod.setAccessible(true);
}
installMocksMethod.invoke(null, beanInstance, m.mock);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
923db4064e533f2ddb3c9768f388331ce475065d | 149 | java | Java | app/src/main/java/com/example/javiosyc/todoapp/model/enums/ToDoItemAction.java | javiosyc/ToDoApp | 1093c7ea03b08bafd5cf7a1822836a02c17ac35e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/javiosyc/todoapp/model/enums/ToDoItemAction.java | javiosyc/ToDoApp | 1093c7ea03b08bafd5cf7a1822836a02c17ac35e | [
"Apache-2.0"
] | 1 | 2017-01-29T12:09:04.000Z | 2017-01-29T12:09:04.000Z | app/src/main/java/com/example/javiosyc/todoapp/model/enums/ToDoItemAction.java | javiosyc/ToDoApp | 1093c7ea03b08bafd5cf7a1822836a02c17ac35e | [
"Apache-2.0"
] | null | null | null | 14.9 | 49 | 0.704698 | 1,000,435 | package com.example.javiosyc.todoapp.model.enums;
/**
* Created by javiosyc on 2017/1/17.
*/
public enum ToDoItemAction {
ADD, EDIT,DELETE
}
|
923db5517061b16432e62ee9754eef61abf89f37 | 5,145 | java | Java | src/main/java/com/onquantum/rockstar/methods/GetSoundPacks.java | saiber/RockStarServer | fcc9f4bd331d1ecf492fc8c3a876ced236bc5362 | [
"Unlicense"
] | null | null | null | src/main/java/com/onquantum/rockstar/methods/GetSoundPacks.java | saiber/RockStarServer | fcc9f4bd331d1ecf492fc8c3a876ced236bc5362 | [
"Unlicense"
] | null | null | null | src/main/java/com/onquantum/rockstar/methods/GetSoundPacks.java | saiber/RockStarServer | fcc9f4bd331d1ecf492fc8c3a876ced236bc5362 | [
"Unlicense"
] | null | null | null | 36.232394 | 128 | 0.585034 | 1,000,436 | package com.onquantum.rockstar.methods;
import com.onquantum.rockstar.common.SQLDBConnector;
import com.onquantum.rockstar.model.PackageStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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 java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by Admin on 7/7/15.
*/
@WebServlet("/get_sound_packs")
public class GetSoundPacks extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=cp1251");
response.setCharacterEncoding("UTF-8");
String fromId = request.getParameter("fromId");
String statusId = request.getParameter("status_id");
String select_query = " = 2";
if(fromId == null)
fromId = "1";
if(statusId == null) {
select_query = " = 2";
}else {
if(statusId.equals("0")) {
select_query = " >= 1";
} else if(statusId.equals("1")) {
select_query = " = 1";
} else if(statusId.equals("2")) {
select_query = " = 2";
} else if(statusId.equals("3")) {
select_query = " = 3";
}
}
String query = "SELECT * FROM guitar_tb WHERE id >= " + fromId + " AND status_id " + select_query;
JSONArray guitarsArray = new JSONArray();
Statement statement = SQLDBConnector.getStatement();
ResultSet resultSet = null;
try {
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
JSONObject guitar = new JSONObject();
guitar.put("_id",resultSet.getInt("id"));
guitar.put("_name",resultSet.getString("name"));
guitar.put("_article", resultSet.getString("article"));
guitar.put("_icon",resultSet.getString("icon"));
guitar.put("_purchase_id", resultSet.getInt("purchase_id"));
guitar.put("_sample_sound", resultSet.getString("sample_sound"));
guitar.put("_description", resultSet.getString("description"));
guitar.put("_status", PackageStatus.Status.values()[Integer.parseInt(resultSet.getString("status_id"))].name());
guitarsArray.put(guitar);
}
response.getWriter().write(guitarsArray.toString());
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=cp1251");
request.setCharacterEncoding("UTF-8");
String fromId = request.getParameter("fromId");
String statusId = request.getParameter("status_id");
String select_query = " = 2";
if(fromId == null)
fromId = "1";
if(statusId == null) {
select_query = " = 2";
}else {
if(statusId.equals("0")) {
select_query = " >= 1";
} else if(statusId.equals("1")) {
select_query = " = 1";
} else if(statusId.equals("2")) {
select_query = " = 2";
} else if(statusId.equals("3")) {
select_query = " = 3";
}
}
String query = "SELECT * FROM guitar_tb WHERE id >= " + fromId + " AND status_id " + select_query;
JSONArray guitarsArray = new JSONArray();
Statement statement = SQLDBConnector.getStatement();
ResultSet resultSet = null;
try {
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
JSONObject guitar = new JSONObject();
guitar.put("_id",resultSet.getInt("id"));
guitar.put("_name",resultSet.getString("name"));
guitar.put("_article", resultSet.getString("article"));
guitar.put("_icon",resultSet.getString("icon"));
guitar.put("_purchase_id", resultSet.getInt("purchase_id"));
guitar.put("_sample_sound", resultSet.getString("sample_sound"));
guitar.put("_description", resultSet.getString("description"));
guitar.put("_status", PackageStatus.Status.values()[Integer.parseInt(resultSet.getString("status_id"))].name());
guitarsArray.put(guitar);
}
response.getWriter().write(guitarsArray.toString());
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
923db55bad400da4950acae3ef246e9b989b8d86 | 10,303 | java | Java | hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,194 | 2015-01-01T23:22:15.000Z | 2020-12-12T19:27:42.000Z | hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,994 | 2015-01-04T10:06:26.000Z | 2020-12-13T22:19:41.000Z | hapi-fhir-jpaserver-test-utilities/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,088 | 2015-01-04T19:31:43.000Z | 2020-12-12T20:56:04.000Z | 38.588015 | 147 | 0.844317 | 1,000,437 | package ca.uhn.fhir.jpa.dao.dstu2;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoPatient;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoSubscription;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoValueSet;
import ca.uhn.fhir.jpa.api.dao.IFhirSystemDao;
import ca.uhn.fhir.jpa.api.svc.ISearchCoordinatorSvc;
import ca.uhn.fhir.jpa.bulk.export.api.IBulkDataExportJobSchedulingHelper;
import ca.uhn.fhir.jpa.test.config.TestDstu2Config;
import ca.uhn.fhir.jpa.test.BaseJpaTest;
import ca.uhn.fhir.jpa.dao.IFulltextSearchSvc;
import ca.uhn.fhir.jpa.dao.data.IResourceIndexedSearchParamStringDao;
import ca.uhn.fhir.jpa.dao.data.IResourceIndexedSearchParamTokenDao;
import ca.uhn.fhir.jpa.dao.data.IResourceLinkDao;
import ca.uhn.fhir.jpa.dao.data.IResourceTableDao;
import ca.uhn.fhir.jpa.model.entity.ModelConfig;
import ca.uhn.fhir.jpa.provider.JpaSystemProviderDstu2;
import ca.uhn.fhir.jpa.search.DatabaseBackedPagingProvider;
import ca.uhn.fhir.jpa.search.reindex.IResourceReindexingSvc;
import ca.uhn.fhir.jpa.searchparam.registry.ISearchParamRegistryController;
import ca.uhn.fhir.jpa.sp.ISearchParamPresenceSvc;
import ca.uhn.fhir.jpa.subscription.match.registry.SubscriptionLoader;
import ca.uhn.fhir.jpa.util.ResourceCountCache;
import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
import ca.uhn.fhir.model.dstu2.composite.MetaDt;
import ca.uhn.fhir.model.dstu2.resource.Appointment;
import ca.uhn.fhir.model.dstu2.resource.Binary;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.dstu2.resource.Communication;
import ca.uhn.fhir.model.dstu2.resource.ConceptMap;
import ca.uhn.fhir.model.dstu2.resource.Conformance;
import ca.uhn.fhir.model.dstu2.resource.Device;
import ca.uhn.fhir.model.dstu2.resource.DiagnosticOrder;
import ca.uhn.fhir.model.dstu2.resource.DiagnosticReport;
import ca.uhn.fhir.model.dstu2.resource.Encounter;
import ca.uhn.fhir.model.dstu2.resource.Group;
import ca.uhn.fhir.model.dstu2.resource.Immunization;
import ca.uhn.fhir.model.dstu2.resource.Location;
import ca.uhn.fhir.model.dstu2.resource.Media;
import ca.uhn.fhir.model.dstu2.resource.Medication;
import ca.uhn.fhir.model.dstu2.resource.MedicationAdministration;
import ca.uhn.fhir.model.dstu2.resource.MedicationOrder;
import ca.uhn.fhir.model.dstu2.resource.Observation;
import ca.uhn.fhir.model.dstu2.resource.Organization;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.dstu2.resource.Practitioner;
import ca.uhn.fhir.model.dstu2.resource.Questionnaire;
import ca.uhn.fhir.model.dstu2.resource.QuestionnaireResponse;
import ca.uhn.fhir.model.dstu2.resource.SearchParameter;
import ca.uhn.fhir.model.dstu2.resource.StructureDefinition;
import ca.uhn.fhir.model.dstu2.resource.Subscription;
import ca.uhn.fhir.model.dstu2.resource.Substance;
import ca.uhn.fhir.model.dstu2.resource.ValueSet;
import ca.uhn.fhir.rest.server.provider.ResourceProviderFactory;
import ca.uhn.fhir.rest.server.util.ISearchParamRegistry;
import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import javax.persistence.EntityManager;
import static org.junit.jupiter.api.Assertions.fail;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {TestDstu2Config.class})
public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@Autowired
@Qualifier("myResourceCountsCache")
protected ResourceCountCache myResourceCountsCache;
@Autowired
protected ISearchParamRegistry mySearchParamRegistry;
@Autowired
protected ISearchParamRegistryController mySearchParamRegistryController;
@Autowired
protected ApplicationContext myAppCtx;
@Autowired
protected IResourceReindexingSvc myResourceReindexingSvc;
@Autowired
@Qualifier("myAppointmentDaoDstu2")
protected IFhirResourceDao<Appointment> myAppointmentDao;
@Autowired
@Qualifier("mySearchParameterDaoDstu2")
protected IFhirResourceDao<SearchParameter> mySearchParameterDao;
@Autowired
@Qualifier("myCommunicationDaoDstu2")
protected IFhirResourceDao<Communication> myCommunicationDao;
@Autowired
@Qualifier("myBundleDaoDstu2")
protected IFhirResourceDao<Bundle> myBundleDao;
@Autowired
@Qualifier("myConceptMapDaoDstu2")
protected IFhirResourceDao<ConceptMap> myConceptMapDao;
@Autowired
protected ModelConfig myModelConfig;
@Autowired
@Qualifier("myDeviceDaoDstu2")
protected IFhirResourceDao<Device> myDeviceDao;
@Autowired
@Qualifier("myDiagnosticOrderDaoDstu2")
protected IFhirResourceDao<DiagnosticOrder> myDiagnosticOrderDao;
@Autowired
@Qualifier("myDiagnosticReportDaoDstu2")
protected IFhirResourceDao<DiagnosticReport> myDiagnosticReportDao;
@Autowired
@Qualifier("myBinaryDaoDstu2")
protected IFhirResourceDao<Binary> myBinaryDao;
@Autowired
@Qualifier("myEncounterDaoDstu2")
protected IFhirResourceDao<Encounter> myEncounterDao;
// @PersistenceContext()
@Autowired
protected EntityManager myEntityManager;
@Autowired
protected FhirContext myFhirContext;
@Autowired
@Qualifier("myImmunizationDaoDstu2")
protected IFhirResourceDao<Immunization> myImmunizationDao;
@Autowired
@Qualifier("myLocationDaoDstu2")
protected IFhirResourceDao<Location> myLocationDao;
@Autowired
@Qualifier("myMediaDaoDstu2")
protected IFhirResourceDao<Media> myMediaDao;
@Autowired
@Qualifier("myMedicationAdministrationDaoDstu2")
protected IFhirResourceDao<MedicationAdministration> myMedicationAdministrationDao;
@Autowired
@Qualifier("myMedicationDaoDstu2")
protected IFhirResourceDao<Medication> myMedicationDao;
@Autowired
@Qualifier("myMedicationOrderDaoDstu2")
protected IFhirResourceDao<MedicationOrder> myMedicationOrderDao;
@Autowired
@Qualifier("myObservationDaoDstu2")
protected IFhirResourceDao<Observation> myObservationDao;
@Autowired
@Qualifier("myOrganizationDaoDstu2")
protected IFhirResourceDao<Organization> myOrganizationDao;
@Autowired
protected DatabaseBackedPagingProvider myPagingProvider;
@Autowired
@Qualifier("myPatientDaoDstu2")
protected IFhirResourceDaoPatient<Patient> myPatientDao;
@Autowired
@Qualifier("myConformanceDaoDstu2")
protected IFhirResourceDao<Conformance> myConformanceDao;
@Autowired
@Qualifier("myGroupDaoDstu2")
protected IFhirResourceDao<Group> myGroupDao;
@Autowired
@Qualifier("myPractitionerDaoDstu2")
protected IFhirResourceDao<Practitioner> myPractitionerDao;
@Autowired
@Qualifier("myQuestionnaireDaoDstu2")
protected IFhirResourceDao<Questionnaire> myQuestionnaireDao;
@Autowired
@Qualifier("myQuestionnaireResponseDaoDstu2")
protected IFhirResourceDao<QuestionnaireResponse> myQuestionnaireResponseDao;
@Autowired
@Qualifier("myResourceProvidersDstu2")
protected ResourceProviderFactory myResourceProviders;
@Autowired
protected ISearchCoordinatorSvc mySearchCoordinatorSvc;
@Autowired(required = false)
protected IFulltextSearchSvc mySearchDao;
@Autowired
protected ISearchParamPresenceSvc mySearchParamPresenceSvc;
@Autowired
@Qualifier("myStructureDefinitionDaoDstu2")
protected IFhirResourceDao<StructureDefinition> myStructureDefinitionDao;
@Autowired
@Qualifier("mySubscriptionDaoDstu2")
protected IFhirResourceDaoSubscription<Subscription> mySubscriptionDao;
@Autowired
@Qualifier("mySubstanceDaoDstu2")
protected IFhirResourceDao<Substance> mySubstanceDao;
@Autowired
protected IResourceIndexedSearchParamStringDao myResourceIndexedSearchParamStringDao;
@Autowired
protected IResourceIndexedSearchParamTokenDao myResourceIndexedSearchParamTokenDao;
@Autowired
protected IResourceLinkDao myResourceLinkDao;
@Autowired
protected IResourceTableDao myResourceTableDao;
@Autowired
@Qualifier("mySystemDaoDstu2")
protected IFhirSystemDao<Bundle, MetaDt> mySystemDao;
@Autowired
@Qualifier("mySystemProviderDstu2")
protected JpaSystemProviderDstu2 mySystemProvider;
@Autowired
protected PlatformTransactionManager myTxManager;
@Autowired
@Qualifier("myValueSetDaoDstu2")
protected IFhirResourceDaoValueSet<ValueSet, CodingDt, CodeableConceptDt> myValueSetDao;
@Autowired
protected SubscriptionLoader mySubscriptionLoader;
@Autowired
private IBulkDataExportJobSchedulingHelper myBulkExportJobSchedulingHelper;
@Autowired
private ValidationSupportChain myJpaValidationSupportChain;
@BeforeEach
public void beforeFlushFT() {
purgeHibernateSearch(myEntityManager);
myDaoConfig.setSchedulingDisabled(true);
myDaoConfig.setIndexMissingFields(DaoConfig.IndexEnabledEnum.ENABLED);
}
@BeforeEach
@Transactional()
public void beforePurgeDatabase() {
purgeDatabase(myDaoConfig, mySystemDao, myResourceReindexingSvc, mySearchCoordinatorSvc, mySearchParamRegistry, myBulkExportJobSchedulingHelper);
}
@BeforeEach
public void beforeResetConfig() {
myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences());
}
@AfterEach
public void afterResetInterceptors() {
myInterceptorRegistry.unregisterAllInterceptors();
}
@Override
public FhirContext getFhirContext() {
return myFhirContext;
}
@Override
protected PlatformTransactionManager getTxManager() {
return myTxManager;
}
@Override
public TransactionTemplate newTxTemplate() {
TransactionTemplate retVal = new TransactionTemplate(myTxManager);
retVal.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
retVal.afterPropertiesSet();
return retVal;
}
@AfterEach
public void afterEachClearCaches() {
myValueSetDao.purgeCaches();
myJpaValidationSupportChain.invalidateCaches();
}
}
|
923db5955780f00838556341fed90d375bb5dedf | 6,767 | java | Java | src/main/java/com/magitechserver/magibridge/chat/ServerMessageBuilder.java | Sayakie/MagiBridge | 49c04c7661305ea1eab26d014a36fb366ec54cde | [
"MIT"
] | 56 | 2017-07-09T16:22:31.000Z | 2022-03-16T16:54:12.000Z | src/main/java/com/magitechserver/magibridge/chat/ServerMessageBuilder.java | Sayakie/MagiBridge | 49c04c7661305ea1eab26d014a36fb366ec54cde | [
"MIT"
] | 235 | 2017-07-10T03:19:59.000Z | 2022-03-21T20:46:38.000Z | src/main/java/com/magitechserver/magibridge/chat/ServerMessageBuilder.java | Eufranio/MagiShat | cf33fd700fff7dce0642844754d5531196b03cb3 | [
"MIT"
] | 54 | 2017-07-09T16:23:37.000Z | 2022-03-08T08:16:52.000Z | 39.115607 | 124 | 0.63721 | 1,000,438 | package com.magitechserver.magibridge.chat;
import br.net.fabiozumbi12.UltimateChat.Sponge.UCChannel;
import br.net.fabiozumbi12.UltimateChat.Sponge.UChat;
import com.google.common.collect.Maps;
import com.magitechserver.magibridge.MagiBridge;
import com.magitechserver.magibridge.common.NucleusBridge;
import com.magitechserver.magibridge.config.FormatType;
import com.magitechserver.magibridge.config.categories.ConfigCategory;
import com.magitechserver.magibridge.config.categories.Messages;
import com.magitechserver.magibridge.events.DiscordMessageEvent;
import com.magitechserver.magibridge.util.TextHelper;
import com.magitechserver.magibridge.util.Utils;
import flavor.pie.boop.BoopableChannel;
import net.dv8tion.jda.api.entities.Message;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.text.format.TextColors;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Created by Frani on 26/04/2019.
*/
public class ServerMessageBuilder implements MessageBuilder {
public static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)[§&][0-9A-FK-OR]");
private boolean staff = false;
private boolean colors = true;
private FormatType format;
private Map<String, String> placeholders = Maps.newHashMap();
private List<Message.Attachment> attachments;
private String channel;
public static ServerMessageBuilder create() {
return new ServerMessageBuilder();
}
public ServerMessageBuilder staff(boolean staff) {
this.staff = staff;
return this;
}
public ServerMessageBuilder format(FormatType format) {
this.format = format;
return this;
}
public ServerMessageBuilder placeholder(String name, String value) {
this.placeholders.put("%" + name + "%", value);
return this;
}
public ServerMessageBuilder attachments(List<Message.Attachment> attachments) {
this.attachments = attachments;
return this;
}
public ServerMessageBuilder channel(String channel) {
this.channel = channel;
return this;
}
public ServerMessageBuilder colors(boolean colors) {
this.colors = colors;
return this;
}
public Type getType() {
return Type.DISCORD_TO_SERVER;
}
public void send() {
if (Sponge.getEventManager().post(new DiscordMessageEvent(this)))
return;
if (!this.colors) {
this.placeholders.compute("%message%", (k, v) -> v != null ? STRIP_COLOR_PATTERN.matcher(v).replaceAll("") : v);
}
boolean isUchat = this.channel != null;
ConfigCategory config = MagiBridge.getInstance().getConfig();
Text prefix = Text.of();
// Prefix enabled
if (config.MESSAGES.PREFIX.ENABLED) {
Messages.PrefixCategory category = config.MESSAGES.PREFIX;
try {
prefix = Utils.toText(category.TEXT)
.toBuilder()
.onHover(TextActions.showText(Utils.toText(category.HOVER)))
.onClick(TextActions.openUrl(new URL(category.LINK)))
.build();
} catch (MalformedURLException e) {
MagiBridge.getLogger().error(category.LINK + " is an invalid prefix URL! Fix it on your config!");
return;
}
}
Text attachment = Text.of();
// Message contains attachments
if (this.attachments != null && !this.attachments.isEmpty()) {
Text.Builder hover = Text.builder("Attachments: ").append(Text.NEW_LINE);
for (Message.Attachment att : this.attachments) {
hover.append(Text.of(att.getFileName(), Text.NEW_LINE));
}
hover.append(Text.of(TextColors.AQUA, "Click to open this attachment!"));
URL url = null;
try {
url = new URL(attachments.get(0).getUrl());
} catch (MalformedURLException exception) {}
attachment = Text.builder()
.append(Utils.toText(config.MESSAGES.ATTACHMENT_NAME))
.onHover(TextActions.showText(hover.build()))
.onClick(url != null ? TextActions.openUrl(url) : null)
.build();
}
// implementation specific sending code
if (isUchat && config.CHANNELS.USE_UCHAT && Sponge.getPluginManager().isLoaded("ultimatechat")) {
String rawFormat = config.CHANNELS.UCHAT.UCHAT_OVERRIDES.getOrDefault(channel, this.format.get());
UCChannel chatChannel = UChat.get().getAPI().getChannels().stream()
.filter(c -> c.getName().equalsIgnoreCase(channel))
.findFirst().orElse(null);
if (chatChannel == null) {
MagiBridge.getLogger().error("The channel " + channel + " specified in the config doesn't exist in-game!");
return;
}
Text text = Text.of(prefix, Utils.toText(Utils.replaceEach(rawFormat, this.placeholders)), attachment);
text = TextHelper.replaceLink(text);
chatChannel.sendMessage(Sponge.getServer().getConsole(), text, true);
} else if (config.CHANNELS.USE_NUCLEUS && Sponge.getPluginManager().isLoaded("nucleus")) {
MessageChannel messageChannel;
if (!this.staff) {
if (Sponge.getPluginManager().getPlugin("boop").isPresent() && config.CORE.USE_BOOP) {
messageChannel = new BoopableChannel(MessageChannel.TO_ALL);
} else {
messageChannel = MessageChannel.TO_ALL;
}
} else {
messageChannel = NucleusBridge.getInstance().getStaffChannel();
this.format = FormatType.DISCORD_TO_SERVER_STAFF_FORMAT;
}
Text toSend = Text.of(prefix, Utils.toText(this.format.format(this.placeholders)), attachment);
toSend = TextHelper.replaceLink(toSend);
messageChannel.send(toSend);
} else {
MessageChannel messageChannel = Sponge.getPluginManager().getPlugin("boop").isPresent() ?
new BoopableChannel(MessageChannel.TO_ALL) :
MessageChannel.TO_ALL;
Text toSend = Text.of(prefix, Utils.toText(this.format.format(this.placeholders)), attachment);
toSend = TextHelper.replaceLink(toSend);
messageChannel.send(toSend);
}
}
}
|
923db5f5890bdf7f7fdddb6bb13462bdef2c6cc6 | 1,627 | java | Java | components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/TaskLocationResolver.java | RakhithaRR/carbon-commons | 0462442920d930db57385367534b0aa41a576af8 | [
"Apache-2.0"
] | 15 | 2015-02-28T12:38:52.000Z | 2022-02-17T14:07:13.000Z | components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/TaskLocationResolver.java | RakhithaRR/carbon-commons | 0462442920d930db57385367534b0aa41a576af8 | [
"Apache-2.0"
] | 97 | 2015-01-04T15:27:39.000Z | 2022-02-01T09:10:27.000Z | components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/TaskLocationResolver.java | RakhithaRR/carbon-commons | 0462442920d930db57385367534b0aa41a576af8 | [
"Apache-2.0"
] | 223 | 2015-01-05T13:55:28.000Z | 2022-03-04T01:40:45.000Z | 34.617021 | 91 | 0.71973 | 1,000,439 | /**
* Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.ntask.core;
import java.util.Map;
import org.wso2.carbon.ntask.common.TaskException;
/**
* This interface represents the contract that must be implemented to retrieve
* the location that a given task should be scheduled.
*/
public interface TaskLocationResolver {
/**
* Initializes the task location resolver with the given properties.
* @param properties The property map
* @throws TaskException
*/
public void init(Map<String, String> properties) throws TaskException;
/**
* Returns the location the given task should be scheduled in.
*
* @param ctx The task context, which contains environmental information on
* other tasks etc..
* @param taskInfo The task information of the task to be scheduled
* @return The location of the task to be scheduled
* @throws TaskException
*/
public int getLocation(TaskServiceContext ctx, TaskInfo taskInfo) throws TaskException;
}
|
923db6aa6748a01da6a3946b61e050bef75213ce | 1,193 | java | Java | lambda-expressions/src/eu/rtakacs/le/MethodReference.java | rtkcs/java-8 | bb82242486f7d0d7a8128f6ec65343d0e2b510c7 | [
"Apache-2.0"
] | null | null | null | lambda-expressions/src/eu/rtakacs/le/MethodReference.java | rtkcs/java-8 | bb82242486f7d0d7a8128f6ec65343d0e2b510c7 | [
"Apache-2.0"
] | null | null | null | lambda-expressions/src/eu/rtakacs/le/MethodReference.java | rtkcs/java-8 | bb82242486f7d0d7a8128f6ec65343d0e2b510c7 | [
"Apache-2.0"
] | null | null | null | 26.511111 | 145 | 0.694887 | 1,000,440 | package eu.rtakacs.le;
import java.util.Arrays;
import java.util.List;
interface Carnivore{
default int calories(List<String> food) {
System.out.println("Calories " + food.size()*100);
return food.size() * 100;
}
int eat(List<String> foods);
}
class Tiger implements Carnivore{
public int eat(List<String> foods) {
System.out.println("Eating "+foods);
return foods.size() * 200;
}
}
public class MethodReference {
public static int size(List<String> names) {
System.out.println("Size " + names.size() * 2);
return names.size() * 2;
}
public static void process(List<String> names, Carnivore c) {
c.eat(names);
}
public static void main(String[] args) {
List<String> fnames = Arrays.asList("beeg", "veal", "chicken", "pork");
Tiger t = new Tiger();
process(fnames, t::eat);
process(fnames, t::calories);
process(fnames, MethodReference::size);
process(fnames, t);
//process(fnames, Carnivore::calories);//Cannot make a static reference to the non-static method calories(List<String>) from the type Carnivore
//process(fnames, Tiger::eat);//Cannot make a static reference to the non-static method eat(List<String>) from the type Tiger
}
}
|
923db76705122d36dd36c28b77c2b891f649c20c | 3,296 | java | Java | TutorTrader/app/src/main/java/com/teamname/tutortrader/MyProfileActivity.java | CMPUT301W16T07/TeamName | ab221574e46afc811afdd144a9b2b0ee8d4951e4 | [
"Apache-2.0"
] | null | null | null | TutorTrader/app/src/main/java/com/teamname/tutortrader/MyProfileActivity.java | CMPUT301W16T07/TeamName | ab221574e46afc811afdd144a9b2b0ee8d4951e4 | [
"Apache-2.0"
] | 23 | 2016-02-10T02:24:16.000Z | 2016-04-12T21:51:06.000Z | TutorTrader/app/src/main/java/com/teamname/tutortrader/MyProfileActivity.java | CMPUT301W16T07/TeamName | ab221574e46afc811afdd144a9b2b0ee8d4951e4 | [
"Apache-2.0"
] | null | null | null | 42.25641 | 120 | 0.686286 | 1,000,441 | package com.teamname.tutortrader;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* The activity that allows a user to view their profile.
* It also give the option to edit the profile as well.
*/
public class MyProfileActivity extends MethodsController {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout profileInfo;
setContentView(R.layout.my_profile);
checkConnectivity();
profileInfo = (LinearLayout) findViewById(R.id.profileInfo);
profileInfo.setBackgroundResource(R.drawable.apple_righ);
btn_CurrentBids = (Button) findViewById(R.id.currentBids);
btn_CurrentBids.setOnClickListener(btnClickListener);
btn_myProfile = (Button) findViewById(R.id.myProfile);
btn_myProfile.setOnClickListener(btnClickListener);
btn_mySessions = (Button) findViewById(R.id.mySessions);
btn_mySessions.setOnClickListener(btnClickListener);
btn_availableSession = (Button) findViewById(R.id.availableSessions);
btn_availableSession.setOnClickListener(btnClickListener);
// set activity title
TextView activityTitle = (TextView) findViewById(R.id.activityTitle);
activityTitle.setText(R.string.MyProfileButton);
if (currentProfile.isDefaultUser()){
//create new profile
Intent intent = new Intent(MyProfileActivity.this, CreateProfileActivity.class);
startActivity(intent);
}
if ((Connectivity)&&(getProfile(currentProfile.getProfileID()) != null)) {
setCurrentProfile(getProfile(currentProfile.getProfileID())); // in case ratings changed
}
//get textviews
TextView displayUsername = (TextView) findViewById(R.id.username);
TextView displayEmail = (TextView) findViewById(R.id.email);
TextView displayPhone = (TextView) findViewById(R.id.phone);
TextView displayTutorRating = (TextView) findViewById(R.id.tutorRating);
TextView displayStudentRating = (TextView) findViewById(R.id.studentRating);
//set textviews
displayUsername.setText(Html.fromHtml("Username: <b>" + currentProfile.getName() + "</b>"));
displayEmail.setText(Html.fromHtml("Email: <b>" + currentProfile.getEmail() + "</b>"));
displayPhone.setText(Html.fromHtml("Phone: <b>" + currentProfile.getPhone() + "</b>"));
displayTutorRating.setText(Html.fromHtml("Tutor Rating: <b>" + currentProfile.getTutorRating() + "</b>"));
displayStudentRating.setText(Html.fromHtml("Student Rating: <b>" + currentProfile.getStudentRating() + "</b>"));
//set click listener for edit button
Button editButton = (Button) findViewById(R.id.editProfile);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkConnectivity();
Intent intent = new Intent(MyProfileActivity.this, EditProfileActivity.class );
startActivity(intent);
}
});
}
}
|
923db8a04c39db06eab6528fbd483903a51ebf12 | 4,159 | java | Java | app/src/main/java/com/example/kevpreneur/smartshopper/Cart.java | Apondi/SmartShopper | a25b6a4cbbeae10b9f43a21ad3380eb22e6414b7 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/kevpreneur/smartshopper/Cart.java | Apondi/SmartShopper | a25b6a4cbbeae10b9f43a21ad3380eb22e6414b7 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/kevpreneur/smartshopper/Cart.java | Apondi/SmartShopper | a25b6a4cbbeae10b9f43a21ad3380eb22e6414b7 | [
"MIT"
] | 1 | 2018-04-09T18:12:46.000Z | 2018-04-09T18:12:46.000Z | 34.090164 | 217 | 0.583794 | 1,000,442 | package com.example.kevpreneur.smartshopper;
import android.content.Intent;
import android.net.wifi.hotspot2.pps.Credential;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.android.volley.toolbox.HttpResponse;
import java.io.IOException;
import java.util.ArrayList;
public class Cart extends AppCompatActivity {
String[] productArray = {"Apples (pack of 5) - MUR 80.94",
"Bananas (1kg) - MUR 50.68",
"Oranges (pack of 5) - MUR 11.50",
"Pineapple - MUR 50.69",
"Mango - MUR 70.75",
"Potatoes (2.5kg) - MUR 11.98",
"Tomatoes (1kg) - MUR 21.99",
"Onions (pack of 4) - MUR 51.83",
"Lettuce - MUR 47.49",
"Rice (1kg) - MUR 40.48",
"Pasta (1kg) - MUR 80.00",
"Bread (800g loaf) - MUR 15.00",
"Pizza (350g) - MUR 40.60",
"Beef Mince (500g) - MUR 75.99",
"Chicken Breast (pack of 2) - MUR 78.00",
"Salmon Fillets (pack of 2) - MUR 500.23",
"Pasta Sauce (500g jar) - MUR 41.84",
"Curry Sauce (500g jar) - MUR 20.84",
"Cheese (250g) - MUR 23.74",
"Butter (250g) - MUR 20.92",
"Plain Yoghurt (500g) - MUR 60.94",
"Milk (568ml / 1pint) - MUR 20.58",
"Milk (2.27L / 4pints) - MUR 150.89",
"Fresh Orange Juice (1L) - MUR 20.69",
"Cola (2L) - MUR 25.00",
"Beer (pack of 4 bottles) - MUR 410.00"};
// ArrayList<String> cartItems = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
// cartItems.add("Colgate");
// cartItems.add("Shoe");
// cartItems.add("Laptop");
// cartItems.add("Mouse");
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_listview,productArray);
ListView listView = (ListView) findViewById(R.id.items_List);
listView.setAdapter(adapter);
findViewById(R.id.btn_scan_product).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Cart.this, ScanActivity.class));
}
});
findViewById(R.id.btn_pay).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mcbAPICall();
}
});
}
public void mcbAPICall(){
oAuth();
}
String token;
WebView webview;
public void oAuth() {
webview = new WebView(this);
setContentView(webview);
webview.loadUrl("https://mcboauth3.azurewebsites.net/oauth/authorize?client_id=59b2e360-a0ad-449a-b364-3be2c46b7b3e&response_type=token&redirect_uri=http://smartshopper?&response_mode=query&scope=read,write");
// webview.setWebViewClient(new WebViewClient(){
// @Override
// public void onLoadResource(WebView view, String url) {
// super.onPageFinished(view, url);
// Log.e("test", "------Url:" + url);
// if (url.contains("?#access_token")) {
// token = webview.getUrl().substring(35, -36);
// startActivity(new Intent(getApplicationContext(), ReceiptActivity.class));
// }
// }
// });
}
//
// public void addToCart (ProductDetails.Product product){
//// repository.add(product);
// }
//
// public void removeFromCart (ProductDetails.Product product){
//// repository.remove(product);
// }
//
// private void getRepoItems(){
// for (ProductDetails.Product product : repository ){
// cartItems.add(product.getName());
// }
// }
}
|
923db9c3096d3d55071d8dcf9f338911afb94607 | 2,205 | java | Java | airback-web/src/main/java/com/airback/module/project/view/milestone/MilestoneListPresenter.java | mng335n/airback | 782b1ac49b343d8c497d3dae5be3eb812d151772 | [
"MIT"
] | null | null | null | airback-web/src/main/java/com/airback/module/project/view/milestone/MilestoneListPresenter.java | mng335n/airback | 782b1ac49b343d8c497d3dae5be3eb812d151772 | [
"MIT"
] | null | null | null | airback-web/src/main/java/com/airback/module/project/view/milestone/MilestoneListPresenter.java | mng335n/airback | 782b1ac49b343d8c497d3dae5be3eb812d151772 | [
"MIT"
] | null | null | null | 38.017241 | 98 | 0.74966 | 1,000,443 | /**
* Copyright © airback
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
* <p>
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.airback.module.project.view.milestone;
import com.airback.core.SecureAccessException;
import com.airback.module.project.CurrentProjectVariables;
import com.airback.module.project.ProjectRolePermissionCollections;
import com.airback.module.project.view.ProjectBreadcrumb;
import com.airback.module.project.view.ProjectGenericPresenter;
import com.airback.module.project.view.ProjectView;
import com.airback.vaadin.mvp.LoadPolicy;
import com.airback.vaadin.mvp.ScreenData;
import com.airback.vaadin.mvp.ViewManager;
import com.airback.vaadin.mvp.ViewScope;
import com.vaadin.ui.HasComponents;
/**
* @author airback Ltd.
* @since 1.0
*/
@LoadPolicy(scope = ViewScope.PROTOTYPE)
public class MilestoneListPresenter extends ProjectGenericPresenter<MilestoneListView> {
private static final long serialVersionUID = 1L;
public MilestoneListPresenter() {
super(MilestoneListView.class);
}
@Override
protected void onGo(HasComponents container, ScreenData<?> data) {
if (CurrentProjectVariables.canRead(ProjectRolePermissionCollections.MILESTONES)) {
ProjectView projectView = (ProjectView) container;
projectView.gotoSubView(ProjectView.MILESTONE_ENTRY, view);
view.lazyLoadView();
ProjectBreadcrumb breadcrumb = ViewManager.getCacheComponent(ProjectBreadcrumb.class);
breadcrumb.gotoMilestoneList();
} else {
throw new SecureAccessException();
}
}
}
|
923dba096a9c6e3662b27c87563b8814f297d0ca | 2,008 | java | Java | src/main/java/cn/sevenyuan/demo/aop/BookAspect.java | Vip-Augus/SpringBootLearn | b25913d57939f382bbbca38b9882931352933885 | [
"Apache-2.0"
] | 86 | 2019-11-04T01:19:59.000Z | 2022-03-14T08:02:48.000Z | src/main/java/cn/sevenyuan/demo/aop/BookAspect.java | xiaoxiaoyanz/springboot-note | f55998b645d6d4535904fd3b3cc1802fab419c19 | [
"Apache-2.0"
] | 6 | 2021-01-06T05:16:58.000Z | 2022-02-10T07:42:39.000Z | src/main/java/cn/sevenyuan/demo/aop/BookAspect.java | xiaoxiaoyanz/springboot-note | f55998b645d6d4535904fd3b3cc1802fab419c19 | [
"Apache-2.0"
] | 46 | 2019-08-29T17:18:35.000Z | 2022-03-29T08:27:08.000Z | 28.28169 | 69 | 0.648904 | 1,000,444 | package cn.sevenyuan.demo.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @author JingQ at 2019-08-07
*/
@Aspect
@Component
public class BookAspect {
/**
* pointcut,指明拦截的路径
* 第一个星号表示任意返回值
* 第二个星号表示 aop 路径下任意类
* 第三个星号表示类中的任意方法
* (..) 表示任意参数
*/
@Pointcut("execution(* cn.sevenyuan.demo.aop.BookService.*(..))")
public void pc1() {
}
@Before(value = "pc1()")
public void before(JoinPoint jp) {
String name = jp.getSignature().getName();
System.out.println(name + "方法开始执行");
}
@After(value = "pc1()")
public void after(JoinPoint jp) {
String name = jp.getSignature().getName();
System.out.println(name + "方法结束执行");
}
/**
* 返回值是 Object 类型,表示可以处理任意类型的返回值
* 如果 result 类型是 Long,表示只能处理目标方法返回值是 Long 类型的情况
* @param jp 连接点
* @param result 结果
*/
@AfterReturning(value = "pc1()", returning = "result")
public void afterReturning(JoinPoint jp, Object result) {
String name = jp.getSignature().getName();
System.out.println(name + "方法返回值是 " + result);
}
@AfterThrowing(value = "pc1()", throwing = "e")
public void afterThrowing(JoinPoint jp, Exception e) {
String name = jp.getSignature().getName();
System.out.println(name + "方法抛出异常,ex 是 " + e.getMessage());
}
@Around(value = "pc1()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前置执行");
Object result = pjp.proceed();
System.out.println("环绕后置执行");
return result;
}
}
|
923dba96558ee4855be11ab97a952d010d6f9a2b | 3,361 | java | Java | tencentcloud-sdk-java-gaap/src/main/java/com/tencentcloudapi/gaap/v20180529/models/DescribeProxiesResponse.java | Chronos-Ye/tencentcloud-sdk-java | 07e1d5d59359f81c894070be98262f0a1fbe2ebd | [
"Apache-2.0"
] | 3 | 2020-07-28T07:46:56.000Z | 2021-05-24T12:09:48.000Z | tencentcloud-sdk-java-gaap/src/main/java/com/tencentcloudapi/gaap/v20180529/models/DescribeProxiesResponse.java | Chronos-Ye/tencentcloud-sdk-java | 07e1d5d59359f81c894070be98262f0a1fbe2ebd | [
"Apache-2.0"
] | null | null | null | tencentcloud-sdk-java-gaap/src/main/java/com/tencentcloudapi/gaap/v20180529/models/DescribeProxiesResponse.java | Chronos-Ye/tencentcloud-sdk-java | 07e1d5d59359f81c894070be98262f0a1fbe2ebd | [
"Apache-2.0"
] | 1 | 2021-03-23T03:19:20.000Z | 2021-03-23T03:19:20.000Z | 26.054264 | 83 | 0.648616 | 1,000,445 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.gaap.v20180529.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class DescribeProxiesResponse extends AbstractModel{
/**
* 通道个数。
*/
@SerializedName("TotalCount")
@Expose
private Long TotalCount;
/**
* (旧参数,请切换到ProxySet)通道实例信息列表。
*/
@SerializedName("InstanceSet")
@Expose
private ProxyInfo [] InstanceSet;
/**
* (新参数)通道实例信息列表。
*/
@SerializedName("ProxySet")
@Expose
private ProxyInfo [] ProxySet;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get 通道个数。
* @return TotalCount 通道个数。
*/
public Long getTotalCount() {
return this.TotalCount;
}
/**
* Set 通道个数。
* @param TotalCount 通道个数。
*/
public void setTotalCount(Long TotalCount) {
this.TotalCount = TotalCount;
}
/**
* Get (旧参数,请切换到ProxySet)通道实例信息列表。
* @return InstanceSet (旧参数,请切换到ProxySet)通道实例信息列表。
*/
public ProxyInfo [] getInstanceSet() {
return this.InstanceSet;
}
/**
* Set (旧参数,请切换到ProxySet)通道实例信息列表。
* @param InstanceSet (旧参数,请切换到ProxySet)通道实例信息列表。
*/
public void setInstanceSet(ProxyInfo [] InstanceSet) {
this.InstanceSet = InstanceSet;
}
/**
* Get (新参数)通道实例信息列表。
* @return ProxySet (新参数)通道实例信息列表。
*/
public ProxyInfo [] getProxySet() {
return this.ProxySet;
}
/**
* Set (新参数)通道实例信息列表。
* @param ProxySet (新参数)通道实例信息列表。
*/
public void setProxySet(ProxyInfo [] ProxySet) {
this.ProxySet = ProxySet;
}
/**
* Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.setParamArrayObj(map, prefix + "InstanceSet.", this.InstanceSet);
this.setParamArrayObj(map, prefix + "ProxySet.", this.ProxySet);
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
923dbb7cdd94604f5dadf21c6370c2470ab4300f | 3,155 | java | Java | test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | 38.950617 | 118 | 0.651981 | 1,000,446 | /*
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019 SAP SE. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import jdk.test.lib.*;
import jdk.test.lib.process.*;
import sun.hotspot.WhiteBox;
/*
* @test TestAbortVMOnSafepointTimeout
* @summary Check if VM can kill thread which doesn't reach safepoint.
* @bug 8219584 8227528
* @library /testlibrary /test/lib
* @build TestAbortVMOnSafepointTimeout
* @run driver jdk.test.lib.helpers.ClassFileInstaller sun.hotspot.WhiteBox
* @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI TestAbortVMOnSafepointTimeout
*/
public class TestAbortVMOnSafepointTimeout {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
"-Xbootclasspath/a:.",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+WhiteBoxAPI",
"-XX:+SafepointTimeout",
"-XX:+SafepointALot",
"-XX:+AbortVMOnSafepointTimeout",
"-XX:SafepointTimeoutDelay=50",
"-XX:GuaranteedSafepointInterval=1",
"-XX:-CreateCoredumpOnCrash",
"-Xms64m",
"TestAbortVMOnSafepointTimeout$Test",
"999" /* 999 is max unsafe sleep */
);
OutputAnalyzer output = new OutputAnalyzer(pb.start());
output.shouldMatch("Timed out while spinning to reach a safepoint.");
if (Platform.isWindows()) {
output.shouldMatch("Safepoint sync time longer than");
} else {
output.shouldMatch("SIGILL");
if (Platform.isLinux()) {
output.shouldMatch("(sent by kill)");
}
}
output.shouldNotHaveExitValue(0);
}
public static class Test {
public static void main(String[] args) throws Exception {
Integer waitTime = Integer.parseInt(args[0]);
WhiteBox wb = WhiteBox.getWhiteBox();
// Loop here to cause a safepoint timeout.
while (true) {
wb.waitUnsafe(waitTime);
}
}
}
}
|
923dbbc38cf2e8ac19c078cd4bf4bfccade7e4e2 | 5,293 | java | Java | sem2/homework7/task1/src/main/java/group144/goldov/Trie.java | ivangoldov/spbuHomework | 0e0b4a5d7a107561e489bf9079c58cd459e134d8 | [
"Apache-2.0"
] | null | null | null | sem2/homework7/task1/src/main/java/group144/goldov/Trie.java | ivangoldov/spbuHomework | 0e0b4a5d7a107561e489bf9079c58cd459e134d8 | [
"Apache-2.0"
] | 9 | 2019-04-10T12:57:42.000Z | 2019-06-13T14:11:28.000Z | sem2/homework7/task1/src/main/java/group144/goldov/Trie.java | ivangoldov/spbuHomework | 0e0b4a5d7a107561e489bf9079c58cd459e134d8 | [
"Apache-2.0"
] | null | null | null | 30.953216 | 92 | 0.569431 | 1,000,447 | package group144.goldov;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
/** Implementation of the trie data structure */
public class Trie {
private final int alphabetSize = 26;
private int size;
private TrieNode root = new TrieNode();
private ArrayList<String> serialisator = new ArrayList<>();
/**
* Adds new string to the trie
* @param element string that is added
* @return true if the string is not in the trie, false if string is already in the trie
*/
public boolean add(String element) {
if (contains(element)) {
return false;
}
serialisator.add(element);
size++;
TrieNode current = root;
for (int i = 0; i < element.length(); i++) {
TrieNode node = current.children.get(element.charAt(i));
current.prefixCounter++;
if (node == null) {
node = new TrieNode();
current.children.put(element.charAt(i), node);
}
current = node;
}
current.isEndOfWord = true;
return true;
}
/**
* Checks if the string in the trie
* @param element string that is found
* @return true if the string in the trie, false otherwise
*/
public boolean contains(String element) {
TrieNode current = root;
for (int i = 0; i < element.length(); i++) {
TrieNode node = current.children.get(element.charAt(i));
if (node == null) {
return false;
}
current = node;
}
return current.isEndOfWord;
}
/**
* Removed string from the trie
* @param element string that is removed
* @return true if such string is in the trie, false if not
*/
public boolean remove(String element) {
if (contains(element)) {
size--;
remove(root, element, 0);
return true;
}
return false;
}
/**
* Recursive removing from the trie
* @param current trie node that is checked to be delete
* @param element string that is deleted
* @param index of the string
* @return true if parent should delete the mapping
*/
private boolean remove(TrieNode current, String element, int index) {
if (index == element.length()) {
if (!current.isEndOfWord) {
return false;
}
current.isEndOfWord = false;
return current.children.size() == 0;
}
char character = element.charAt(index);
TrieNode node = current.children.get(character);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = remove(node, element, index + 1);
if (shouldDeleteCurrentNode) {
current.children.remove(character);
return current.children.size() == 0;
}
return false;
}
/**
* Getter for the size field
* @return quantity of strings in the trie
*/
public int getSize() {
return size;
}
/**
* Counts strings that start with the prefix
* @param prefix string with should start strings of trie
* @return quantity of such strings
*/
public int howManyStartWithPrefix(String prefix) {
TrieNode current = root;
int answer = 0;
for (int i = 0; i < prefix.length(); i++) {
if (current.children.containsKey(prefix.charAt(i))) {
current = current.children.get(prefix.charAt(i));
answer += current.children.size();
} else {
return 0;
}
}
if (contains(prefix)) {
return current.prefixCounter + 1;
}
return current.prefixCounter;
}
/**
* Writes trie to the to the output stream
* @param out stream into which trie is written
* @throws IOException is thrown if trie can't be written
*/
public void serialise(OutputStream out) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
for (int i = 0; i < serialisator.size(); i++) {
writer.write(serialisator.get(i));
writer.write("\n");
}
writer.close();
}
/**
* Replaces current trie with the one from the stream
* @param in stream in which new trie is stored
* @throws IOException is thrown if stream can't be read
*/
public void deserialise(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Trie newTrie = new Trie();
while (reader.ready()) {
String element = reader.readLine();
newTrie.add(element);
}
root = newTrie.root;
serialisator = newTrie.serialisator;
size = newTrie.size;
}
private class TrieNode implements Serializable {
private HashMap <Character, TrieNode> children;
private boolean isEndOfWord;
private int prefixCounter;
private TrieNode() {
children = new HashMap<>(alphabetSize);
isEndOfWord = false;
prefixCounter = 0;
}
}
}
|
923dbbc472816e1a54acbb0c8c1ba28fd01c640e | 1,089 | java | Java | src/main/java/io/bloobook/bookmanageapp/entity/bookLocation/BookLocation.java | DevBloo/tu_software_BookManagementApp | cff1f02d151318075dfc64f06b1bcdd24caeebcc | [
"MIT"
] | 1 | 2021-05-14T16:35:25.000Z | 2021-05-14T16:35:25.000Z | src/main/java/io/bloobook/bookmanageapp/entity/bookLocation/BookLocation.java | DevBloo/tu_software_BookManagementApp | cff1f02d151318075dfc64f06b1bcdd24caeebcc | [
"MIT"
] | 18 | 2021-05-14T16:37:57.000Z | 2021-05-31T08:11:38.000Z | src/main/java/io/bloobook/bookmanageapp/entity/bookLocation/BookLocation.java | DevBloo/tu_software_BookManagementApp | cff1f02d151318075dfc64f06b1bcdd24caeebcc | [
"MIT"
] | null | null | null | 23.673913 | 70 | 0.743802 | 1,000,448 | package io.bloobook.bookmanageapp.entity.bookLocation;
import io.bloobook.bookmanageapp.entity.BaseTimeEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @CreateBy: Bloo
* @Date: 2021/05/06
*/
@ToString
@NoArgsConstructor (access = AccessLevel.PROTECTED)
@Getter
@Entity
public class BookLocation extends BaseTimeEntity {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
@Column (nullable = false)
private String categoryName;
@Column (nullable = false)
private String locationCode;
@Builder
public BookLocation ( String categoryName, String locationCode ) {
this.categoryName = categoryName;
this.locationCode = locationCode;
}
public String getLocationInfo () {
return categoryName + " - " + locationCode;
}
}
|
923dbbcf2ae74a3dafd81070e2561872985f834b | 2,192 | java | Java | Coding-Android/app/src/main/java/net/coding/program/maopao/ContentArea.java | zhangqi-ak47/codingnet-android | 1b6c6739957bceecada731b0f758e68840abc908 | [
"MIT"
] | 282 | 2015-09-09T10:39:10.000Z | 2022-02-28T16:25:26.000Z | Coding-Android/app/src/main/java/net/coding/program/maopao/ContentArea.java | zhangqi-ak47/codingnet-android | 1b6c6739957bceecada731b0f758e68840abc908 | [
"MIT"
] | null | null | null | Coding-Android/app/src/main/java/net/coding/program/maopao/ContentArea.java | zhangqi-ak47/codingnet-android | 1b6c6739957bceecada731b0f758e68840abc908 | [
"MIT"
] | 95 | 2015-09-11T04:50:08.000Z | 2021-11-28T18:29:39.000Z | 35.354839 | 195 | 0.685675 | 1,000,449 | package net.coding.program.maopao;
import android.text.Html;
import android.view.View;
import net.coding.program.R;
import net.coding.program.common.ImageLoadTool;
import net.coding.program.common.maopao.ClickImageParam;
import net.coding.program.common.widget.GifMarkImageView;
import net.coding.program.maopao.item.ContentAreaImages;
import java.util.ArrayList;
/**
* Created by chaochen on 14-9-19.
* 添加了当图片只有一张时,显示为一张大图的功能
*/
public class ContentArea extends ContentAreaImages {
private GifMarkImageView imageSingle;
public ContentArea(View convertView, View.OnClickListener onClickContent, View.OnClickListener onclickImage, Html.ImageGetter imageGetterParamer, ImageLoadTool loadParams, int pxImageWidth) {
super(convertView, onClickContent, onclickImage, imageGetterParamer, loadParams, pxImageWidth);
imageSingle = (GifMarkImageView) convertView.findViewById(R.id.imageSingle);
imageSingle.setOnClickListener(onclickImage);
imageSingle.setFocusable(false);
imageSingle.setLongClickable(true);
}
@Override
protected void setImageUrl(ArrayList<String> uris) {
if (uris.size() == 0) {
imageSingle.setVisibility(View.GONE);
imageLayout0.setVisibility(View.GONE);
imageLayout1.setVisibility(View.GONE);
} else if (uris.size() == 1) {
imageSingle.setVisibility(View.VISIBLE);
imageLayout0.setVisibility(View.GONE);
imageLayout1.setVisibility(View.GONE);
} else if (uris.size() < 3) {
imageLayout0.setVisibility(View.VISIBLE);
imageSingle.setVisibility(View.GONE);
imageLayout1.setVisibility(View.GONE);
} else {
imageSingle.setVisibility(View.GONE);
imageLayout0.setVisibility(View.VISIBLE);
imageLayout1.setVisibility(View.VISIBLE);
}
if (uris.size() == 1) {
imageLoad.loadImage(imageSingle, uris.get(0), imageOptions);
imageSingle.showGifFlag(uris.get(0));
imageSingle.setTag(new ClickImageParam(uris, 0, false));
} else {
super.setImageUrl(uris);
}
}
}
|
923dbc2e013367c6c5e9e8cba260e14e97ac6b6c | 35,870 | java | Java | itext/src/main/java/com/itextpdf/text/pdf/DocumentFont.java | luiguik2/itextpdf | 88737e7182ee6829084f53e233145f8616b2e7ee | [
"RSA-MD"
] | 1,459 | 2015-01-10T17:57:47.000Z | 2022-03-27T19:07:45.000Z | itext/src/main/java/com/itextpdf/text/pdf/DocumentFont.java | zwdwww/itextpdf | 43bf5b7cce6a7021ef6b44a992ac94d8df02db64 | [
"RSA-MD"
] | 42 | 2015-04-14T11:50:27.000Z | 2022-01-12T22:17:57.000Z | itext/src/main/java/com/itextpdf/text/pdf/DocumentFont.java | zwdwww/itextpdf | 43bf5b7cce6a7021ef6b44a992ac94d8df02db64 | [
"RSA-MD"
] | 527 | 2015-01-20T14:32:06.000Z | 2022-03-21T06:05:16.000Z | 38.529538 | 154 | 0.518664 | 1,000,450 | /*
*
* This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
* Authors: Bruno Lowagie, Paulo Soares, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://itextpdf.com/terms-of-use/
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* In accordance with Section 7(b) of the GNU Affero General Public License,
* a covered work must retain the producer line in every PDF that is created
* or manipulated using iText.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the iText software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers as an ASP,
* serving PDFs on the fly in a web application, shipping iText with a closed
* source product.
*
* For more information, please contact iText Software Corp. at this
* address: ychag@example.com
*/
package com.itextpdf.text.pdf;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Utilities;
import com.itextpdf.text.io.RandomAccessSourceFactory;
import com.itextpdf.text.pdf.fonts.cmaps.CMapParserEx;
import com.itextpdf.text.pdf.fonts.cmaps.CMapToUnicode;
import com.itextpdf.text.pdf.fonts.cmaps.CidLocationFromByte;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author psoares
*/
public class DocumentFont extends BaseFont {
// code, [glyph, width]
private HashMap<Integer, int[]> metrics = new HashMap<Integer, int[]>();
private String fontName;
private PRIndirectReference refFont;
private PdfDictionary font;
private IntHashtable uni2byte = new IntHashtable();
private IntHashtable byte2uni = new IntHashtable();
private IntHashtable diffmap;
private float ascender = 800;
private float capHeight = 700;
private float descender = -200;
private float italicAngle = 0;
private float fontWeight = 0;
private float llx = -50;
private float lly = -200;
private float urx = 100;
private float ury = 900;
protected boolean isType0 = false;
protected int defaultWidth = 1000;
private IntHashtable hMetrics;
protected String cjkEncoding;
protected String uniMap;
private BaseFont cjkMirror;
private static final int stdEnc[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
32,33,34,35,36,37,38,8217,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
8216,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,161,162,163,8260,165,402,167,164,39,8220,171,8249,8250,64257,64258,
0,8211,8224,8225,183,0,182,8226,8218,8222,8221,187,8230,8240,0,191,
0,96,180,710,732,175,728,729,168,0,730,184,0,733,731,711,
8212,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,198,0,170,0,0,0,0,321,216,338,186,0,0,0,0,
0,230,0,0,0,305,0,0,322,248,339,223,0,0,0,0};
/** Creates a new instance of DocumentFont */
DocumentFont(PdfDictionary font) {
this.refFont = null;
this.font = font;
init();
}
/** Creates a new instance of DocumentFont */
DocumentFont(PRIndirectReference refFont) {
this.refFont = refFont;
font = (PdfDictionary)PdfReader.getPdfObject(refFont);
init();
}
/** Creates a new instance of DocumentFont */
DocumentFont(PRIndirectReference refFont, PdfDictionary drEncoding) {
this.refFont = refFont;
font = (PdfDictionary)PdfReader.getPdfObject(refFont);
if (font.get(PdfName.ENCODING) == null
&& drEncoding != null) {
for (PdfName key : drEncoding.getKeys()) {
font.put(PdfName.ENCODING, drEncoding.get(key));
}
}
init();
}
public PdfDictionary getFontDictionary() {
return font;
}
private void init() {
encoding = "";
fontSpecific = false;
fontType = FONT_TYPE_DOCUMENT;
PdfName baseFont = font.getAsName(PdfName.BASEFONT);
fontName = baseFont != null ? PdfName.decodeName(baseFont.toString()) : "Unspecified Font Name";
PdfName subType = font.getAsName(PdfName.SUBTYPE);
if (PdfName.TYPE1.equals(subType) || PdfName.TRUETYPE.equals(subType))
doType1TT();
else if (PdfName.TYPE3.equals(subType)) {
// In case of a Type3 font, we just show the characters as is.
// Note that this doesn't always make sense:
// Type 3 fonts are user defined fonts where arbitrary characters are mapped to custom glyphs
// For instance: the character a could be mapped to an image of a dog, the character b to an image of a cat
// When parsing a document that shows a cat and a dog, you shouldn't expect seeing a cat and a dog. Instead you'll get b and a.
fillEncoding(null);
fillDiffMap(font.getAsDict(PdfName.ENCODING), null);
fillWidths();
}
else {
PdfName encodingName = font.getAsName(PdfName.ENCODING);
if (encodingName != null){
String enc = PdfName.decodeName(encodingName.toString());
String ffontname = CJKFont.GetCompatibleFont(enc);
if (ffontname != null) {
try {
cjkMirror = BaseFont.createFont(ffontname, enc, false);
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
cjkEncoding = enc;
uniMap = ((CJKFont)cjkMirror).getUniMap();
}
if (PdfName.TYPE0.equals(subType)) {
isType0 = true;
if (!enc.equals("Identity-H") && cjkMirror != null) {
PdfArray df = (PdfArray) PdfReader.getPdfObjectRelease(font.get(PdfName.DESCENDANTFONTS));
PdfDictionary cidft = (PdfDictionary) PdfReader.getPdfObjectRelease(df.getPdfObject(0));
PdfNumber dwo = (PdfNumber) PdfReader.getPdfObjectRelease(cidft.get(PdfName.DW));
if (dwo != null)
defaultWidth = dwo.intValue();
hMetrics = readWidths((PdfArray) PdfReader.getPdfObjectRelease(cidft.get(PdfName.W)));
PdfDictionary fontDesc = (PdfDictionary) PdfReader.getPdfObjectRelease(cidft.get(PdfName.FONTDESCRIPTOR));
fillFontDesc(fontDesc);
} else {
processType0(font);
}
}
}
}
}
private void processType0(PdfDictionary font) {
try {
PdfObject toUniObject = PdfReader.getPdfObjectRelease(font.get(PdfName.TOUNICODE));
PdfArray df = (PdfArray)PdfReader.getPdfObjectRelease(font.get(PdfName.DESCENDANTFONTS));
PdfDictionary cidft = (PdfDictionary)PdfReader.getPdfObjectRelease(df.getPdfObject(0));
PdfNumber dwo = (PdfNumber)PdfReader.getPdfObjectRelease(cidft.get(PdfName.DW));
int dw = 1000;
if (dwo != null)
dw = dwo.intValue();
IntHashtable widths = readWidths((PdfArray)PdfReader.getPdfObjectRelease(cidft.get(PdfName.W)));
PdfDictionary fontDesc = (PdfDictionary)PdfReader.getPdfObjectRelease(cidft.get(PdfName.FONTDESCRIPTOR));
fillFontDesc(fontDesc);
if (toUniObject instanceof PRStream){
fillMetrics(PdfReader.getStreamBytes((PRStream)toUniObject), widths, dw);
} else if (new PdfName("Identity-H").equals(toUniObject)) {
fillMetricsIdentity(widths, dw);
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
private IntHashtable readWidths(PdfArray ws) {
IntHashtable hh = new IntHashtable();
if (ws == null)
return hh;
for (int k = 0; k < ws.size(); ++k) {
int c1 = ((PdfNumber)PdfReader.getPdfObjectRelease(ws.getPdfObject(k))).intValue();
PdfObject obj = PdfReader.getPdfObjectRelease(ws.getPdfObject(++k));
if (obj.isArray()) {
PdfArray a2 = (PdfArray)obj;
for (int j = 0; j < a2.size(); ++j) {
int c2 = ((PdfNumber)PdfReader.getPdfObjectRelease(a2.getPdfObject(j))).intValue();
hh.put(c1++, c2);
}
}
else {
int c2 = ((PdfNumber)obj).intValue();
int w = ((PdfNumber)PdfReader.getPdfObjectRelease(ws.getPdfObject(++k))).intValue();
for (; c1 <= c2; ++c1)
hh.put(c1, w);
}
}
return hh;
}
private String decodeString(PdfString ps) {
if (ps.isHexWriting())
return PdfEncodings.convertToString(ps.getBytes(), "UnicodeBigUnmarked");
else
return ps.toUnicodeString();
}
private void fillMetricsIdentity(IntHashtable widths, int dw) {
for (int i = 0; i < 65536; i++) {
int w = dw;
if (widths.containsKey(i))
w = widths.get(i);
metrics.put(i, new int[] {i, w});
}
}
private void fillMetrics(byte[] touni, IntHashtable widths, int dw) {
try {
PdfContentParser ps = new PdfContentParser(new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(touni))));
PdfObject ob = null;
boolean notFound = true;
int nestLevel = 0;
int maxExc = 50;
while ((notFound || nestLevel > 0)) {
try {
ob = ps.readPRObject();
}
catch (Exception ex) {
if (--maxExc < 0)
break;
continue;
}
if (ob == null)
break;
if (ob.type() == PdfContentParser.COMMAND_TYPE) {
if (ob.toString().equals("begin")) {
notFound = false;
nestLevel++;
}
else if (ob.toString().equals("end")) {
nestLevel--;
}
else if (ob.toString().equals("beginbfchar")) {
while (true) {
PdfObject nx = ps.readPRObject();
if (nx.toString().equals("endbfchar"))
break;
String cid = decodeString((PdfString)nx);
String uni = decodeString((PdfString)ps.readPRObject());
if (uni.length() == 1) {
int cidc = cid.charAt(0);
int unic = uni.charAt(uni.length() - 1);
int w = dw;
if (widths.containsKey(cidc))
w = widths.get(cidc);
metrics.put(Integer.valueOf(unic), new int[]{cidc, w});
}
}
}
else if (ob.toString().equals("beginbfrange")) {
while (true) {
PdfObject nx = ps.readPRObject();
if (nx.toString().equals("endbfrange"))
break;
String cid1 = decodeString((PdfString)nx);
String cid2 = decodeString((PdfString)ps.readPRObject());
int cid1c = cid1.charAt(0);
int cid2c = cid2.charAt(0);
PdfObject ob2 = ps.readPRObject();
if (ob2.isString()) {
String uni = decodeString((PdfString)ob2);
if (uni.length() == 1) {
int unic = uni.charAt(uni.length() - 1);
for (; cid1c <= cid2c; cid1c++, unic++) {
int w = dw;
if (widths.containsKey(cid1c))
w = widths.get(cid1c);
metrics.put(Integer.valueOf(unic), new int[]{cid1c, w});
}
}
}
else {
PdfArray a = (PdfArray)ob2;
for (int j = 0; j < a.size(); ++j, ++cid1c) {
String uni = decodeString(a.getAsString(j));
if (uni.length() == 1) {
int unic = uni.charAt(uni.length() - 1);
int w = dw;
if (widths.containsKey(cid1c))
w = widths.get(cid1c);
metrics.put(Integer.valueOf(unic), new int[]{cid1c, w});
}
}
}
}
}
}
}
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
private void doType1TT() {
CMapToUnicode toUnicode = null;
PdfObject enc = PdfReader.getPdfObject(font.get(PdfName.ENCODING));
if (enc == null) {
PdfName baseFont = font.getAsName(PdfName.BASEFONT);
if (BuiltinFonts14.containsKey(fontName)
&& (PdfName.SYMBOL.equals(baseFont) || PdfName.ZAPFDINGBATS.equals(baseFont))) {
fillEncoding(baseFont);
} else
fillEncoding(null);
try {
toUnicode = processToUnicode();
if (toUnicode != null) {
Map<Integer, Integer> rm = toUnicode.createReverseMapping();
for (Map.Entry<Integer, Integer> kv : rm.entrySet()) {
uni2byte.put(kv.getKey().intValue(), kv.getValue().intValue());
byte2uni.put(kv.getValue().intValue(), kv.getKey().intValue());
}
}
}
catch (Exception ex) {
throw new ExceptionConverter(ex);
}
}
else {
if (enc.isName())
fillEncoding((PdfName)enc);
else if (enc.isDictionary()) {
PdfDictionary encDic = (PdfDictionary)enc;
enc = PdfReader.getPdfObject(encDic.get(PdfName.BASEENCODING));
if (enc == null)
fillEncoding(null);
else
fillEncoding((PdfName)enc);
fillDiffMap(encDic, toUnicode);
}
}
if (BuiltinFonts14.containsKey(fontName)) {
BaseFont bf;
try {
bf = BaseFont.createFont(fontName, WINANSI, false);
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
int e[] = uni2byte.toOrderedKeys();
for (int k = 0; k < e.length; ++k) {
int n = uni2byte.get(e[k]);
widths[n] = bf.getRawWidth(n, GlyphList.unicodeToName(e[k]));
}
if (diffmap != null) { //widths for diffmap must override existing ones
e = diffmap.toOrderedKeys();
for (int k = 0; k < e.length; ++k) {
int n = diffmap.get(e[k]);
widths[n] = bf.getRawWidth(n, GlyphList.unicodeToName(e[k]));
}
diffmap = null;
}
ascender = bf.getFontDescriptor(ASCENT, 1000);
capHeight = bf.getFontDescriptor(CAPHEIGHT, 1000);
descender = bf.getFontDescriptor(DESCENT, 1000);
italicAngle = bf.getFontDescriptor(ITALICANGLE, 1000);
fontWeight = bf.getFontDescriptor(FONT_WEIGHT, 1000);
llx = bf.getFontDescriptor(BBOXLLX, 1000);
lly = bf.getFontDescriptor(BBOXLLY, 1000);
urx = bf.getFontDescriptor(BBOXURX, 1000);
ury = bf.getFontDescriptor(BBOXURY, 1000);
}
fillWidths();
fillFontDesc(font.getAsDict(PdfName.FONTDESCRIPTOR));
}
private void fillWidths() {
PdfArray newWidths = font.getAsArray(PdfName.WIDTHS);
PdfNumber first = font.getAsNumber(PdfName.FIRSTCHAR);
PdfNumber last = font.getAsNumber(PdfName.LASTCHAR);
if (first != null && last != null && newWidths != null) {
int f = first.intValue();
int nSize = f + newWidths.size();
if (widths.length < nSize) {
int[] tmp = new int[nSize];
System.arraycopy(widths, 0, tmp, 0, f);
widths = tmp;
}
for (int k = 0; k < newWidths.size(); ++k) {
widths[f + k] = newWidths.getAsNumber(k).intValue();
}
}
}
private void fillDiffMap(PdfDictionary encDic, CMapToUnicode toUnicode) {
PdfArray diffs = encDic.getAsArray(PdfName.DIFFERENCES);
if (diffs != null) {
diffmap = new IntHashtable();
int currentNumber = 0;
for (int k = 0; k < diffs.size(); ++k) {
PdfObject obj = diffs.getPdfObject(k);
if (obj.isNumber())
currentNumber = ((PdfNumber)obj).intValue();
else {
int c[] = GlyphList.nameToUnicode(PdfName.decodeName(((PdfName)obj).toString()));
if (c != null && c.length > 0) {
uni2byte.put(c[0], currentNumber);
byte2uni.put(currentNumber, c[0]);
diffmap.put(c[0], currentNumber);
}
else {
if (toUnicode == null) {
toUnicode = processToUnicode();
if (toUnicode == null) {
toUnicode = new CMapToUnicode();
}
}
final String unicode = toUnicode.lookup(new byte[]{(byte) currentNumber}, 0, 1);
if ((unicode != null) && (unicode.length() == 1)) {
this.uni2byte.put(unicode.charAt(0), currentNumber);
this.byte2uni.put(currentNumber, unicode.charAt(0));
this.diffmap.put(unicode.charAt(0), currentNumber);
}
}
++currentNumber;
}
}
}
}
private CMapToUnicode processToUnicode() {
CMapToUnicode cmapRet = null;
PdfObject toUni = PdfReader.getPdfObjectRelease(this.font.get(PdfName.TOUNICODE));
if (toUni instanceof PRStream) {
try {
byte[] touni = PdfReader.getStreamBytes((PRStream)toUni);
CidLocationFromByte lb = new CidLocationFromByte(touni);
cmapRet = new CMapToUnicode();
CMapParserEx.parseCid("", cmapRet, lb);
} catch (Exception e) {
cmapRet = null;
}
}
return cmapRet;
}
private void fillFontDesc(PdfDictionary fontDesc) {
if (fontDesc == null)
return;
PdfNumber v = fontDesc.getAsNumber(PdfName.ASCENT);
if (v != null)
ascender = v.floatValue();
v = fontDesc.getAsNumber(PdfName.CAPHEIGHT);
if (v != null)
capHeight = v.floatValue();
v = fontDesc.getAsNumber(PdfName.DESCENT);
if (v != null)
descender = v.floatValue();
v = fontDesc.getAsNumber(PdfName.ITALICANGLE);
if (v != null)
italicAngle = v.floatValue();
v = fontDesc.getAsNumber(PdfName.FONTWEIGHT);
if (v != null) {
fontWeight = v.floatValue();
}
PdfArray bbox = fontDesc.getAsArray(PdfName.FONTBBOX);
if (bbox != null) {
llx = bbox.getAsNumber(0).floatValue();
lly = bbox.getAsNumber(1).floatValue();
urx = bbox.getAsNumber(2).floatValue();
ury = bbox.getAsNumber(3).floatValue();
if (llx > urx) {
float t = llx;
llx = urx;
urx = t;
}
if (lly > ury) {
float t = lly;
lly = ury;
ury = t;
}
}
float maxAscent = Math.max(ury, ascender);
float minDescent = Math.min(lly, descender);
ascender = maxAscent * 1000 / (maxAscent - minDescent);
descender = minDescent * 1000 / (maxAscent - minDescent);
}
private void fillEncoding(PdfName encoding) {
if (encoding == null && isSymbolic()) {
for (int k = 0; k < 256; ++k) {
uni2byte.put(k, k);
byte2uni.put(k, k);
}
} else if (PdfName.MAC_ROMAN_ENCODING.equals(encoding) || PdfName.WIN_ANSI_ENCODING.equals(encoding)
|| PdfName.SYMBOL.equals(encoding) || PdfName.ZAPFDINGBATS.equals(encoding)) {
byte b[] = new byte[256];
for (int k = 0; k < 256; ++k)
b[k] = (byte)k;
String enc = WINANSI;
if (PdfName.MAC_ROMAN_ENCODING.equals(encoding))
enc = MACROMAN;
else if (PdfName.SYMBOL.equals(encoding))
enc = SYMBOL;
else if (PdfName.ZAPFDINGBATS.equals(encoding))
enc = ZAPFDINGBATS;
String cv = PdfEncodings.convertToString(b, enc);
char arr[] = cv.toCharArray();
for (int k = 0; k < 256; ++k) {
uni2byte.put(arr[k], k);
byte2uni.put(k, arr[k]);
}
this.encoding = enc;
}
else {
for (int k = 0; k < 256; ++k) {
uni2byte.put(stdEnc[k], k);
byte2uni.put(k, stdEnc[k]);
}
}
}
/** Gets the family name of the font. If it is a True Type font
* each array element will have {Platform ID, Platform Encoding ID,
* Language ID, font name}. The interpretation of this values can be
* found in the Open Type specification, chapter 2, in the 'name' table.<br>
* For the other fonts the array has a single element with {"", "", "",
* font name}.
* @return the family name of the font
*
*/
@Override
public String[][] getFamilyFontName() {
return getFullFontName();
}
/** Gets the font parameter identified by <CODE>key</CODE>. Valid values
* for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>, <CODE>DESCENT</CODE>,
* <CODE>ITALICANGLE</CODE>, <CODE>BBOXLLX</CODE>, <CODE>BBOXLLY</CODE>, <CODE>BBOXURX</CODE>
* and <CODE>BBOXURY</CODE>.
* @param key the parameter to be extracted
* @param fontSize the font size in points
* @return the parameter in points
*
*/
@Override
public float getFontDescriptor(int key, float fontSize) {
if (cjkMirror != null)
return cjkMirror.getFontDescriptor(key, fontSize);
switch (key) {
case AWT_ASCENT:
case ASCENT:
return ascender * fontSize / 1000;
case CAPHEIGHT:
return capHeight * fontSize / 1000;
case AWT_DESCENT:
case DESCENT:
return descender * fontSize / 1000;
case ITALICANGLE:
return italicAngle;
case BBOXLLX:
return llx * fontSize / 1000;
case BBOXLLY:
return lly * fontSize / 1000;
case BBOXURX:
return urx * fontSize / 1000;
case BBOXURY:
return ury * fontSize / 1000;
case AWT_LEADING:
return 0;
case AWT_MAXADVANCE:
return (urx - llx) * fontSize / 1000;
case FONT_WEIGHT:
return fontWeight * fontSize / 1000;
}
return 0;
}
/** Gets the full name of the font. If it is a True Type font
* each array element will have {Platform ID, Platform Encoding ID,
* Language ID, font name}. The interpretation of this values can be
* found in the Open Type specification, chapter 2, in the 'name' table.<br>
* For the other fonts the array has a single element with {"", "", "",
* font name}.
* @return the full name of the font
*
*/
@Override
public String[][] getFullFontName() {
return new String[][]{{"", "", "", fontName}};
}
/** Gets all the entries of the names-table. If it is a True Type font
* each array element will have {Name ID, Platform ID, Platform Encoding ID,
* Language ID, font name}. The interpretation of this values can be
* found in the Open Type specification, chapter 2, in the 'name' table.<br>
* For the other fonts the array has a single element with {"4", "", "", "",
* font name}.
* @return the full name of the font
* @since 2.0.8
*/
@Override
public String[][] getAllNameEntries() {
return new String[][]{{"4", "", "", "", fontName}};
}
/** Gets the kerning between two Unicode chars.
* @param char1 the first char
* @param char2 the second char
* @return the kerning to be applied
*
*/
@Override
public int getKerning(int char1, int char2) {
return 0;
}
/** Gets the postscript font name.
* @return the postscript font name
*
*/
@Override
public String getPostscriptFontName() {
return fontName;
}
/** Gets the width from the font according to the Unicode char <CODE>c</CODE>
* or the <CODE>name</CODE>. If the <CODE>name</CODE> is null it's a symbolic font.
* @param c the unicode char
* @param name the glyph name
* @return the width of the char
*
*/
@Override
int getRawWidth(int c, String name) {
return 0;
}
/** Checks if the font has any kerning pairs.
* @return <CODE>true</CODE> if the font has any kerning pairs
*
*/
@Override
public boolean hasKernPairs() {
return false;
}
/** Outputs to the writer the font dictionaries and streams.
* @param writer the writer for this document
* @param ref the font indirect reference
* @param params several parameters that depend on the font type
* @throws IOException on error
* @throws DocumentException error in generating the object
*
*/
@Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object[] params) throws DocumentException, IOException {
}
/**
* Always returns null.
* @return null
* @since 2.1.3
*/
@Override
public PdfStream getFullFontStream() {
return null;
}
/**
* Gets the width of a <CODE>char</CODE> in normalized 1000 units.
* @param char1 the unicode <CODE>char</CODE> to get the width of
* @return the width in normalized 1000 units
*/
@Override
public int getWidth(int char1) {
if (isType0) {
if(hMetrics != null && cjkMirror != null && !cjkMirror.isVertical()) {
int c = cjkMirror.getCidCode(char1);
int v = hMetrics.get(c);
if (v > 0)
return v;
else
return defaultWidth;
} else {
int[] ws = metrics.get(Integer.valueOf(char1));
if (ws != null)
return ws[1];
else
return 0;
}
}
if (cjkMirror != null)
return cjkMirror.getWidth(char1);
return super.getWidth(char1);
}
@Override
public int getWidth(String text) {
if (isType0) {
int total = 0;
if(hMetrics != null && cjkMirror != null && !cjkMirror.isVertical()) {
if (((CJKFont)cjkMirror).isIdentity()) {
for (int k = 0; k < text.length(); ++k) {
total += getWidth(text.charAt(k));
}
}
else {
for (int k = 0; k < text.length(); ++k) {
int val;
if (Utilities.isSurrogatePair(text, k)) {
val = Utilities.convertToUtf32(text, k);
k++;
}
else {
val = text.charAt(k);
}
total += getWidth(val);
}
}
} else {
char[] chars = text.toCharArray();
int len = chars.length;
for (int k = 0; k < len; ++k) {
int[] ws = metrics.get(Integer.valueOf(chars[k]));
if (ws != null)
total += ws[1];
}
}
return total;
}
if (cjkMirror != null)
return cjkMirror.getWidth(text);
return super.getWidth(text);
}
@Override
public byte[] convertToBytes(String text) {
if (cjkMirror != null)
return cjkMirror.convertToBytes(text);
else if (isType0) {
char[] chars = text.toCharArray();
int len = chars.length;
byte[] b = new byte[len * 2];
int bptr = 0;
for (int k = 0; k < len; ++k) {
int[] ws = metrics.get(Integer.valueOf(chars[k]));
if (ws != null) {
int g = ws[0];
b[bptr++] = (byte)(g / 256);
b[bptr++] = (byte)g;
}
}
if (bptr == b.length)
return b;
else {
byte[] nb = new byte[bptr];
System.arraycopy(b, 0, nb, 0, bptr);
return nb;
}
}
else {
char cc[] = text.toCharArray();
byte b[] = new byte[cc.length];
int ptr = 0;
for (int k = 0; k < cc.length; ++k) {
if (uni2byte.containsKey(cc[k]))
b[ptr++] = (byte)uni2byte.get(cc[k]);
}
if (ptr == b.length)
return b;
else {
byte[] b2 = new byte[ptr];
System.arraycopy(b, 0, b2, 0, ptr);
return b2;
}
}
}
@Override
byte[] convertToBytes(int char1) {
if (cjkMirror != null)
return cjkMirror.convertToBytes(char1);
else if (isType0) {
int[] ws = metrics.get(Integer.valueOf(char1));
if (ws != null) {
int g = ws[0];
return new byte[]{(byte)(g / 256), (byte)g};
}
else
return new byte[0];
}
else {
if (uni2byte.containsKey(char1))
return new byte[]{(byte)uni2byte.get(char1)};
else
return new byte[0];
}
}
PdfIndirectReference getIndirectReference() {
if (refFont == null)
throw new IllegalArgumentException("Font reuse not allowed with direct font objects.");
return refFont;
}
@Override
public boolean charExists(int c) {
if (cjkMirror != null)
return cjkMirror.charExists(c);
else if (isType0) {
return metrics.containsKey(Integer.valueOf(c));
}
else
return super.charExists(c);
}
@Override
public double[] getFontMatrix() {
if (font.getAsArray(PdfName.FONTMATRIX) != null)
return font.getAsArray(PdfName.FONTMATRIX).asDoubleArray();
else
return DEFAULT_FONT_MATRIX;
}
/**
* Sets the font name that will appear in the pdf font dictionary.
* It does nothing in this case as the font is already in the document.
* @param name the new font name
*/
@Override
public void setPostscriptFontName(String name) {
}
@Override
public boolean setKerning(int char1, int char2, int kern) {
return false;
}
@Override
public int[] getCharBBox(int c) {
return null;
}
@Override
protected int[] getRawCharBBox(int c, String name) {
return null;
}
@Override
public boolean isVertical() {
if (cjkMirror != null)
return cjkMirror.isVertical();
else
return super.isVertical();
}
/**
* Exposes the unicode - > CID map that is constructed from the font's encoding
* @return the unicode to CID map
* @since 2.1.7
*/
IntHashtable getUni2Byte(){
return uni2byte;
}
/**
* Exposes the CID - > unicode map that is constructed from the font's encoding
* @return the CID to unicode map
* @since 5.4.0
*/
IntHashtable getByte2Uni(){
return byte2uni;
}
/**
* Gets the difference map
* @return the difference map
* @since 5.0.5
*/
IntHashtable getDiffmap() {
return diffmap;
}
boolean isSymbolic() {
PdfDictionary fontDescriptor = font.getAsDict(PdfName.FONTDESCRIPTOR);
if (fontDescriptor == null)
return false;
PdfNumber flags = fontDescriptor.getAsNumber(PdfName.FLAGS);
if (flags == null)
return false;
return (flags.intValue() & 0x04) != 0;
}
}
|
923dbce81025d5d1e1528736ffe98907d45b8335 | 2,688 | java | Java | flowgrid-android-legacy/src/main/java/org/flowgrid/android/operation/OperationHelpDialog.java | stefanhaustein/flowgrid | 66e02b2b50c0fe4d5b05cd2459ea4b765d30b008 | [
"Apache-2.0"
] | 16 | 2017-06-04T23:39:19.000Z | 2020-02-12T01:05:47.000Z | flowgrid-android-legacy/src/main/java/org/flowgrid/android/operation/OperationHelpDialog.java | stefanhaustein/flowgrid | 66e02b2b50c0fe4d5b05cd2459ea4b765d30b008 | [
"Apache-2.0"
] | 1 | 2019-07-07T03:58:04.000Z | 2019-07-08T03:40:15.000Z | flowgrid-android-legacy/src/main/java/org/flowgrid/android/operation/OperationHelpDialog.java | stefanhaustein/flowgrid | 66e02b2b50c0fe4d5b05cd2459ea4b765d30b008 | [
"Apache-2.0"
] | 1 | 2018-05-20T13:26:03.000Z | 2018-05-20T13:26:03.000Z | 35.84 | 87 | 0.69308 | 1,000,451 | package org.flowgrid.android.operation;
import org.flowgrid.android.Dialogs;
import org.flowgrid.android.Views;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputType;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
public class OperationHelpDialog {
public static void show(final EditOperationFragment fragment) {
Context context = fragment.platform();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
TextView editorHelp = new TextView(context);
editorHelp.setText(fragment.platform().documentation("Operation Editor"));
String documentationText = fragment.operation.documentation();
final EditText documentation = new EditText(context);
documentation.setText(documentationText);
documentation.setInputType(
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
documentation.setGravity(Gravity.TOP);
documentation.setMinLines(5);
if (fragment.tutorialMode &&
(fragment.landscapeMode || !fragment.operation.hasDocumentation())) {
int px = Views.px(context, 4);
editorHelp.setPadding(px, 4*px, px, px);
alert.setView(editorHelp);
alert.setTitle("Editor Help");
} else {
TabHost tabHost = Views.createTabHost(context);
if (fragment.operation.isTutorial()) {
int index = 1;
for(String paragraph : documentationText.split("\n\n")) {
TextView textView = new TextView(context);
textView.setText(paragraph);
// textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);
TextView parView = textView;
Views.addTab(tabHost, "Hint " + (index++), parView);
}
}
Views.addTab(tabHost, "Editor Help", editorHelp);
if (!fragment.tutorialMode) {
Views.addTab(tabHost, "Operation Documentation", documentation);
if (documentationText != null && !documentationText.trim().isEmpty()) {
tabHost.setCurrentTab(1);
}
alert.setNegativeButton("Cancel", null);
}
alert.setView(tabHost);
}
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
fragment.beforeChange();
fragment.operation.setDocumentation(documentation.getText().toString());
fragment.tutorialHelpView.setText(fragment.operation.documentation());
fragment.afterChange();
}
});
Dialogs.showWithoutKeyboard(alert);
}
}
|
923dbd4a154e2c22c9d30e6b8d97bd51c2a43895 | 1,101 | java | Java | api/src/main/java/com/meli/social/api/service/RecentPostService.java | danilopeixoto/social-meli | 14bf88faf5fe7d0736c58be7724625a7ec8a0680 | [
"BSD-3-Clause"
] | null | null | null | api/src/main/java/com/meli/social/api/service/RecentPostService.java | danilopeixoto/social-meli | 14bf88faf5fe7d0736c58be7724625a7ec8a0680 | [
"BSD-3-Clause"
] | null | null | null | api/src/main/java/com/meli/social/api/service/RecentPostService.java | danilopeixoto/social-meli | 14bf88faf5fe7d0736c58be7724625a7ec8a0680 | [
"BSD-3-Clause"
] | null | null | null | 33.363636 | 109 | 0.783833 | 1,000,452 | package com.meli.social.api.service;
import com.meli.social.api.model.PostResponseModel;
import com.meli.social.api.repository.RecentPostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.r2dbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import java.time.Instant;
@Service
public class RecentPostService {
@Autowired
private RecentPostRepository recentPostRepository;
@Autowired
private PostService postService;
public Flux<PostResponseModel> listRecentFollowed(Integer accountId, Instant fromDate, Pageable pageable) {
return this.recentPostRepository
.findByFollowerId(accountId, fromDate, pageable.getSort())
.onErrorMap(
BadSqlGrammarException.class,
(exception) -> new IllegalArgumentException("Invalid sort parameter."))
.skip(pageable.getOffset())
.take(pageable.getPageSize())
.flatMap(this.postService::packProduct)
.map(this.postService::toResponse);
}
}
|
923dbd7853c14458e1fa16e6097e17a23361190f | 13,024 | java | Java | src/layout/StudentW.java | heitor57/school-management | 6910a36a57f359757ecf3e559dc63f9f8d0a1b1b | [
"MIT"
] | 2 | 2019-12-03T12:53:46.000Z | 2019-12-04T16:13:33.000Z | src/layout/StudentW.java | heitor57/school-management | 6910a36a57f359757ecf3e559dc63f9f8d0a1b1b | [
"MIT"
] | null | null | null | src/layout/StudentW.java | heitor57/school-management | 6910a36a57f359757ecf3e559dc63f9f8d0a1b1b | [
"MIT"
] | null | null | null | 43.851852 | 164 | 0.626689 | 1,000,453 | /*
* 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 layout;
import classtables.Student;
import com.sun.org.apache.xerces.internal.xs.StringList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import query.StudentQ;
/**
*
* @author heitor
*/
public class StudentW extends javax.swing.JDialog {
/**
* Creates new form NewJDialog
*/
public StudentW(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bt_delete = new javax.swing.JButton();
bt_name = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
student_table = new javax.swing.JTable();
bt_id = new javax.swing.JTextField();
bt_save = new javax.swing.JButton();
bt_update = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Student");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
bt_delete.setText("Delete");
bt_delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_deleteActionPerformed(evt);
}
});
bt_name.setBorder(javax.swing.BorderFactory.createTitledBorder("Name"));
bt_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_nameActionPerformed(evt);
}
});
student_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Name"
}
));
student_table.addContainerListener(new java.awt.event.ContainerAdapter() {
public void componentAdded(java.awt.event.ContainerEvent evt) {
student_tableComponentAdded(evt);
}
});
student_table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
student_tableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(student_table);
bt_id.setEditable(false);
bt_id.setBorder(javax.swing.BorderFactory.createTitledBorder("ID"));
bt_id.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_idActionPerformed(evt);
}
});
bt_save.setText("Save");
bt_save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_saveActionPerformed(evt);
}
});
bt_update.setText("Update");
bt_update.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_updateActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(bt_name, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(150, 150, 150)
.addComponent(bt_update, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(bt_id, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(73, 73, 73)
.addComponent(bt_delete, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bt_save, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(bt_save)
.addComponent(bt_delete)))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(bt_id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bt_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bt_update))
.addGap(39, 39, 39)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(35, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bt_deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_deleteActionPerformed
Remove();
// TODO add your handling code here:
}//GEN-LAST:event_bt_deleteActionPerformed
private void bt_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_bt_nameActionPerformed
private void student_tableComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_student_tableComponentAdded
}//GEN-LAST:event_student_tableComponentAdded
private void bt_idActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_idActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_bt_idActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
List();
}//GEN-LAST:event_formWindowOpened
private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_saveActionPerformed
Save();
}//GEN-LAST:event_bt_saveActionPerformed
private void student_tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_student_tableMouseClicked
bt_id.setText(String.valueOf(student_table.getValueAt(student_table.getSelectedRow(), 0)));
bt_name.setText(String.valueOf(student_table.getValueAt(student_table.getSelectedRow(), 1)));
}//GEN-LAST:event_student_tableMouseClicked
private void bt_updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_updateActionPerformed
Update();
}//GEN-LAST:event_bt_updateActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StudentW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StudentW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StudentW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StudentW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
StudentW dialog = new StudentW(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bt_delete;
private javax.swing.JTextField bt_id;
private javax.swing.JTextField bt_name;
private javax.swing.JButton bt_save;
private javax.swing.JButton bt_update;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable student_table;
// End of variables declaration//GEN-END:variables
void Save(){
try{
Student student = new Student();
student.setS_name(bt_name.getText());
StudentQ q = new StudentQ();
q.AddStudent(student);
List();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
void List(){
try{
Student student = new Student();
student.setS_name(bt_name.getText());
StudentQ q = new StudentQ();
List<Student> list= q.ListStudents();
DefaultTableModel model = (DefaultTableModel)student_table.getModel();
model.setRowCount(0);
for(Student s : list){
model.addRow(new Object[]{s.getS_id(),s.getS_name()});
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
void Remove(){
try{
Student student = new Student();
student.setS_id(Integer.parseInt(bt_id.getText()));
StudentQ q = new StudentQ();
q.RemoveStudent(student);
List();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
void Update(){
try{
Student student = new Student();
student.setS_id(Integer.parseInt(bt_id.getText()));
student.setS_name(bt_name.getText());
StudentQ s = new StudentQ();
s.UpdateStudent(student);
List();
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
}
|
923dbdc3bb577a5981b7421fd80a7816cd82f802 | 598 | java | Java | src/ru/fizteh/fivt/students/kalandarovshakarim/shell/PwdCommand.java | ElinRin/fizteh-java-2014 | abdf7a7223aff607d3c9eff60c3e74cf8d5f3225 | [
"BSD-2-Clause"
] | 1 | 2019-05-20T12:54:04.000Z | 2019-05-20T12:54:04.000Z | src/ru/fizteh/fivt/students/kalandarovshakarim/shell/PwdCommand.java | Soshikan/fizteh-java-2014 | bcc825bb82f6b2844dae7d011431861623fdfeaa | [
"BSD-2-Clause"
] | null | null | null | src/ru/fizteh/fivt/students/kalandarovshakarim/shell/PwdCommand.java | Soshikan/fizteh-java-2014 | bcc825bb82f6b2844dae7d011431861623fdfeaa | [
"BSD-2-Clause"
] | null | null | null | 21.357143 | 68 | 0.617057 | 1,000,454 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ru.fizteh.fivt.students.kalandarovshakarim.shell;
/**
*
* @author shakarim
*/
public class PwdCommand {
public static void run(String[] args) throws Exception {
if (args.length > 1) {
throw new Exception(getName() + ": too much arguments");
}
System.out.println(getCurPath());
}
public static String getCurPath() {
return System.getProperty("user.dir");
}
public static String getName() {
return "pwd";
}
}
|
923dbe30160f8795b13fd175682930924347d015 | 870 | java | Java | gruul/gruul-shops-open/gruul-shops-open-service/src/main/java/com/medusa/gruul/shops/properties/ShopsRenovationRedisTools.java | zengjixiang2eziw/NozaM8b | 80d49eacc655a906b06f8c8e253340db9de5cd00 | [
"Apache-2.0"
] | null | null | null | gruul/gruul-shops-open/gruul-shops-open-service/src/main/java/com/medusa/gruul/shops/properties/ShopsRenovationRedisTools.java | zengjixiang2eziw/NozaM8b | 80d49eacc655a906b06f8c8e253340db9de5cd00 | [
"Apache-2.0"
] | null | null | null | gruul/gruul-shops-open/gruul-shops-open-service/src/main/java/com/medusa/gruul/shops/properties/ShopsRenovationRedisTools.java | zengjixiang2eziw/NozaM8b | 80d49eacc655a906b06f8c8e253340db9de5cd00 | [
"Apache-2.0"
] | null | null | null | 24.857143 | 124 | 0.733333 | 1,000,455 | package com.medusa.gruul.shops.properties;
import com.medusa.gruul.common.redis.RedisVisitorBaseFacade;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @author create by zq
* @date created in 2019/11/06
*/
public class ShopsRenovationRedisTools extends RedisVisitorBaseFacade {
public static final String KEY_BASE = "shops_renovation";
public ShopsRenovationRedisTools() {
this(KEY_BASE);
}
public ShopsRenovationRedisTools(String baseKey) {
super(baseKey);
}
public void innerRemoveCache(String name) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (null != requestAttributes) {
this.del(name);
}
}
}
|
923dbe7fa7204132a8ae0a57f9cb51da0a7e1b1f | 1,662 | java | Java | src/main/java/com/rki/essenAufRaedern/ui/components/person/AddressEditorComponent.java | miich43l/dibse4-rki-EAR | 4ad208d3f331679b112130c5291e8fe95951cf98 | [
"Unlicense"
] | null | null | null | src/main/java/com/rki/essenAufRaedern/ui/components/person/AddressEditorComponent.java | miich43l/dibse4-rki-EAR | 4ad208d3f331679b112130c5291e8fe95951cf98 | [
"Unlicense"
] | null | null | null | src/main/java/com/rki/essenAufRaedern/ui/components/person/AddressEditorComponent.java | miich43l/dibse4-rki-EAR | 4ad208d3f331679b112130c5291e8fe95951cf98 | [
"Unlicense"
] | null | null | null | 29.678571 | 92 | 0.679302 | 1,000,456 | package com.rki.essenAufRaedern.ui.components.person;
import com.rki.essenAufRaedern.backend.entity.Address;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.ValidationException;
public class AddressEditorComponent extends FormLayout {
private final TextField street = new TextField("Strasse");
private final TextField houseNumber = new TextField("Hausnummer");
private final TextField floor = new TextField("Stock");
private final TextField zipCode = new TextField("PLZ");
private final TextField city = new TextField("Stadt");
private final TextField country = new TextField("Land");
private final Binder<Address> addressBinder = new BeanValidationBinder<>(Address.class);
private Address address = new Address();
public AddressEditorComponent() {
addClassName("address-editor");
setWidthFull();
addressBinder.bindInstanceFields(this);
add(
street,
houseNumber,
floor,
zipCode,
city,
country
);
}
public boolean isValid() {
return addressBinder.isValid();
}
public void setAddress(Address address) {
this.address = address;
addressBinder.readBean(address);
}
public Address getAddress() {
return address;
}
public void validateAndSave() throws ValidationException {
addressBinder.writeBean(address);
}
}
|
923dbf3b9f0bb0ff1203fc6f5a560edc39e804f5 | 884 | java | Java | cute/src/test/java/io/toolisticon/cute/TestUtilities.java | AlexRogalskiy/cute | 8a7f57a4e205cabdd29c5e9f16be16572eee7d74 | [
"MIT"
] | 3 | 2021-03-02T16:57:48.000Z | 2021-05-13T16:48:14.000Z | cute/src/test/java/io/toolisticon/cute/TestUtilities.java | toolisticon/cute | 8a7f57a4e205cabdd29c5e9f16be16572eee7d74 | [
"MIT"
] | 35 | 2020-09-30T00:06:44.000Z | 2022-02-25T12:24:43.000Z | cute/src/test/java/io/toolisticon/cute/TestUtilities.java | AlexRogalskiy/cute | 8a7f57a4e205cabdd29c5e9f16be16572eee7d74 | [
"MIT"
] | 1 | 2018-11-20T03:09:56.000Z | 2018-11-20T03:09:56.000Z | 26 | 221 | 0.697964 | 1,000,457 | package io.toolisticon.cute;
import org.hamcrest.MatcherAssert;
public final class TestUtilities {
private TestUtilities() {
}
public static void assertAssertionMessageContainsMessageTokensAssertion(AssertionError assertionError, String message) {
MatcherAssert.assertThat("AssertionError message '" + assertionError.getMessage() + "' should have matched message string: '" + message + "'", assertAssertionMessageContainsMessageTokens(assertionError, message));
}
public static boolean assertAssertionMessageContainsMessageTokens(AssertionError assertionError, String message) {
String[] messageTokens = message.split("[%]s");
for (String messageToken : messageTokens) {
if (!assertionError.getMessage().contains(messageToken)) {
return false;
}
}
return true;
}
}
|
923dbf62b81b5bed0f9b9b03583c5dec1022cb4f | 832 | java | Java | teamcity-iq-plugin-server/src/main/java/org/sonatype/teamcity/results/ConstraintFact.java | ctownshend/teamcity-echo-plugin | ec0d9287a11576379dc5c3188fa853d08d92cf22 | [
"Apache-2.0"
] | 1 | 2021-12-04T01:19:25.000Z | 2021-12-04T01:19:25.000Z | teamcity-iq-plugin-server/src/main/java/org/sonatype/teamcity/results/ConstraintFact.java | sonatype-nexus-community/teamcity-nexusiq-plugin | ec0d9287a11576379dc5c3188fa853d08d92cf22 | [
"Apache-2.0"
] | 9 | 2021-06-29T06:58:16.000Z | 2021-10-14T13:40:43.000Z | teamcity-iq-plugin-server/src/main/java/org/sonatype/teamcity/results/ConstraintFact.java | sonatype-nexus-community/teamcity-nexusiq-plugin | ec0d9287a11576379dc5c3188fa853d08d92cf22 | [
"Apache-2.0"
] | 1 | 2021-12-04T01:19:15.000Z | 2021-12-04T01:19:15.000Z | 34.666667 | 89 | 0.751202 | 1,000,458 |
// ConstraintFact.java
package org.sonatype.teamcity.results;
public class ConstraintFact {
private String constraintID;
private String constraintName;
private String operatorName;
private ConditionFact[] conditionFacts;
public String getConstraintID() { return constraintID; }
public void setConstraintID(String value) { this.constraintID = value; }
public String getConstraintName() { return constraintName; }
public void setConstraintName(String value) { this.constraintName = value; }
public String getOperatorName() { return operatorName; }
public void setOperatorName(String value) { this.operatorName = value; }
public ConditionFact[] getConditionFacts() { return conditionFacts; }
public void setConditionFacts(ConditionFact[] value) { this.conditionFacts = value; }
}
|
923dc12cc131ab33cded0e14b93f736c45bfc5a2 | 14,226 | java | Java | src/module5/EarthquakeCityMap.java | jure-koren/UCSDUnfoldingMaps | 373ab104e57cd463e83a718eb0b4f70c47ec70fe | [
"MIT"
] | null | null | null | src/module5/EarthquakeCityMap.java | jure-koren/UCSDUnfoldingMaps | 373ab104e57cd463e83a718eb0b4f70c47ec70fe | [
"MIT"
] | null | null | null | src/module5/EarthquakeCityMap.java | jure-koren/UCSDUnfoldingMaps | 373ab104e57cd463e83a718eb0b4f70c47ec70fe | [
"MIT"
] | null | null | null | 31.265934 | 107 | 0.702727 | 1,000,459 | package module5;
import java.util.ArrayList;
import java.util.List;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.GeoJSONReader;
import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractShapeMarker;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MultiMarker;
import de.fhpotsdam.unfolding.marker.SimplePointMarker;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.utils.GeoUtils;
import de.fhpotsdam.unfolding.utils.MapUtils;
import parsing.ParseFeed;
import processing.core.PApplet;
/** EarthquakeCityMap
* An application with an interactive map displaying earthquake data.
* Author: UC San Diego Intermediate Software Development MOOC team
* @author Your name here
* Date: July 17, 2015
* */
public class EarthquakeCityMap extends PApplet {
// We will use member variables, instead of local variables, to store the data
// that the setup and draw methods will need to access (as well as other methods)
// You will use many of these variables, but the only one you should need to add
// code to modify is countryQuakes, where you will store the number of earthquakes
// per country.
// You can ignore this. It's to get rid of eclipse warnings
private static final long serialVersionUID = 1L;
// IF YOU ARE WORKING OFFILINE, change the value of this variable to true
private static final boolean offline = false;
/** This is where to find the local tiles, for working without an Internet connection */
public static String mbTilesString = "blankLight-1-3.mbtiles";
//feed with magnitude 2.5+ Earthquakes
private String earthquakesURL = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom";
// The files containing city names and info and country names and info
private String cityFile = "city-data.json";
private String countryFile = "countries.geo.json";
// The map
private UnfoldingMap map;
// Markers for each city
private List<Marker> cityMarkers;
// Markers for each earthquake
private List<Marker> quakeMarkers;
// A List of country markers
private List<Marker> countryMarkers;
// NEW IN MODULE 5
private CommonMarker lastSelected;
private CommonMarker lastClicked;
public void setup() {
// (1) Initializing canvas and map tiles
size(900, 700, OPENGL);
if (offline) {
map = new UnfoldingMap(this, 200, 50, 650, 600, new MBTilesMapProvider(mbTilesString));
earthquakesURL = "2.5_week.atom"; // The same feed, but saved August 7, 2015
}
else {
//map = new UnfoldingMap(this, 200, 50, 650, 600, new Google.GoogleMapProvider());
map = new UnfoldingMap(this, 200, 50, 650, 600, new MBTilesMapProvider(mbTilesString));
// IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line
//earthquakesURL = "2.5_week.atom";
}
MapUtils.createDefaultEventDispatcher(this, map);
// (2) Reading in earthquake data and geometric properties
// STEP 1: load country features and markers
List<Feature> countries = GeoJSONReader.loadData(this, countryFile);
countryMarkers = MapUtils.createSimpleMarkers(countries);
// STEP 2: read in city data
List<Feature> cities = GeoJSONReader.loadData(this, cityFile);
cityMarkers = new ArrayList<Marker>();
for(Feature city : cities) {
cityMarkers.add(new CityMarker(city));
}
// STEP 3: read in earthquake RSS feed
List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL);
quakeMarkers = new ArrayList<Marker>();
for(PointFeature feature : earthquakes) {
//check if LandQuake
if(isLand(feature)) {
quakeMarkers.add(new LandQuakeMarker(feature));
}
// OceanQuakes
else {
quakeMarkers.add(new OceanQuakeMarker(feature));
}
}
// could be used for debugging
printQuakes();
// (3) Add markers to map
// NOTE: Country markers are not added to the map. They are used
// for their geometric properties
map.addMarkers(quakeMarkers);
map.addMarkers(cityMarkers);
} // End setup
public void draw() {
background(0);
map.draw();
addKey();
}
/** Event handler that gets called automatically when the
* mouse moves.
*/
@Override
public void mouseMoved()
{
// clear the last selection
if (lastSelected != null) {
lastSelected.setSelected(false);
lastSelected = null;
}
selectMarkerIfHover(quakeMarkers);
selectMarkerIfHover(cityMarkers);
}
// If there is a marker under the cursor, and lastSelected is null
// set the lastSelected to be the first marker found under the cursor
// Make sure you do not select two markers.
//
private void selectMarkerIfHover(List<Marker> markers)
{
// loop through markers
for(Marker marker : markers) {
// check if location is under the mouse
if (marker.isInside(map, mouseX, mouseY) ) {
// ok, mouse is inside/over marker
marker.setSelected(true);
lastSelected = (CommonMarker) marker;
//System.out.println("Selected marker: " + marker.toString() );
break;
}
}
}
/** The event handler for mouse clicks
* It will display an earthquake and its threat circle of cities
* Or if a city is clicked, it will display all the earthquakes
* where the city is in the threat circle
*/
@Override
public void mouseClicked()
{
// TODO: Implement this method
// Hint: You probably want a helper method or two to keep this code
// from getting too long/disorganized
// if user clicked and some marker was/is selected, we de-select it
if (lastClicked != null) {
System.out.println("LastClicked != null");
// this “de-selects” whichever marker was clicked on last and so all markers should be displayed.
lastClicked.setClicked(false);
setAllMarkers(false);
lastClicked = null;
System.out.println("Deselect currently selected marker and show all others");
} else {
System.out.println("LastClicked == null");
checkAndSelectMarkersUnderMouse();
}
}
// find marker under crusor and select it
private void checkAndSelectMarkersUnderMouse() {
// determine which marker is being selected (if any) and hide / display other markers so that:
/*
When an earthquake’s marker is selected, all cities within the threat circle of
this earthquake are displayed on the map and all other cities and earthquakes are hidden.
You are given an implementation of the threatCircle() method in the EarthquakeMarker class.
When a city’s marker is selected, all earthquakes which contain that city in their threat
circle are displayed on the map and all other cities and earthquakes are hidden. You are
given an implementation of the threatCircle() method in the EarthquakeMarker class.
*/
boolean found = false;
for(Marker marker : quakeMarkers) {
if (marker.isInside(map, mouseX, mouseY) ) {
// set clicked
System.out.println("Select clicked quake marker");
found = true;
((CommonMarker) marker).setClicked(true);
// hide all other cities and earthquakes
setAllOtherMarkers(true, marker, quakeMarkers);
setAllOtherMarkers(true, marker, cityMarkers);
// display cities in threat circle
displayCitiesNearMarker((EarthquakeMarker) marker);
}
}
for(Marker marker : cityMarkers) {
if (marker.isInside(map, mouseX, mouseY) ) {
// set clicked
found = true;
System.out.println("Select clicked city marker");
((CommonMarker) marker).setClicked(true);
// hide all other cities and earthquakes
setAllOtherMarkers(true, marker, quakeMarkers);
setAllOtherMarkers(true, marker, cityMarkers);
// display earthquakes that have this city in their threat circle
displayQuakesNearCity((CityMarker) marker);
}
}
if (!found) {
setAllMarkers(false);
}
}
private void displayCitiesNearMarker(EarthquakeMarker quakeMarker) {
// find threat circle in km
double maxDistance = quakeMarker.threatCircle();
System.out.println("displayCitiesNearMarker: threat circle = " + maxDistance);
// find cities nearby
for(Marker marker : cityMarkers) {
double distance;
distance = Math.abs(GeoUtils.getDistance(marker.getLocation(), quakeMarker.getLocation() ));
if (distance < maxDistance) {
// yaay - set visible (hidden = false)
marker.setHidden(false);
System.out.println("displayCitiesNearMarker: nearby city = " + marker.toString() );
}
}
// other cities were hidden before
}
// find cities near quake
private void displayQuakesNearCity(CityMarker myCity) {
// find cities nearby
for(Marker marker : quakeMarkers) {
double distance, maxDistance;
// get quake threat circle
maxDistance = ((EarthquakeMarker)marker).threatCircle();
// get distance from city
distance = Math.abs(GeoUtils.getDistance(marker.getLocation(), myCity.getLocation() ));
if (distance < maxDistance) {
// yaay - set visible (hidden = false)
marker.setHidden(false);
System.out.println("displayQuakesNearCity: nearby quake = " + marker.toString() );
}
}
}
// loop over and unhide all markers
private void unhideMarkers() {
setAllMarkers(false);
}
// loop over and hide/unhide all markers
private void setAllMarkers(boolean setHidden) {
System.out.println("Set hidden for all markers" + setHidden );
for(Marker marker : quakeMarkers) {
marker.setHidden(setHidden);
}
for(Marker marker : cityMarkers) {
marker.setHidden(setHidden);
}
}
// loop over and hide/unhide all markers
private void setAllOtherMarkers(boolean setHiddenForOthers, Marker myMarker, List<Marker> markers) {
for(Marker marker : markers) {
if (!marker.equals(myMarker)) {
marker.setHidden(setHiddenForOthers);
} else {
marker.setHidden(!setHiddenForOthers);
}
}
}
// helper method to draw key in GUI
private void addKey() {
// Remember you can use Processing's graphics methods here
fill(255, 250, 240);
int xbase = 25;
int ybase = 50;
rect(xbase, ybase, 150, 250);
fill(0);
textAlign(LEFT, CENTER);
textSize(12);
text("Earthquake Key", xbase+25, ybase+25);
fill(150, 30, 30);
int tri_xbase = xbase + 35;
int tri_ybase = ybase + 50;
triangle(tri_xbase, tri_ybase-CityMarker.TRI_SIZE, tri_xbase-CityMarker.TRI_SIZE,
tri_ybase+CityMarker.TRI_SIZE, tri_xbase+CityMarker.TRI_SIZE,
tri_ybase+CityMarker.TRI_SIZE);
fill(0, 0, 0);
textAlign(LEFT, CENTER);
text("City Marker", tri_xbase + 15, tri_ybase);
text("Land Quake", xbase+50, ybase+70);
text("Ocean Quake", xbase+50, ybase+90);
text("Size ~ Magnitude", xbase+25, ybase+110);
fill(255, 255, 255);
ellipse(xbase+35,
ybase+70,
10,
10);
rect(xbase+35-5, ybase+90-5, 10, 10);
fill(color(255, 255, 0));
ellipse(xbase+35, ybase+140, 12, 12);
fill(color(0, 0, 255));
ellipse(xbase+35, ybase+160, 12, 12);
fill(color(255, 0, 0));
ellipse(xbase+35, ybase+180, 12, 12);
textAlign(LEFT, CENTER);
fill(0, 0, 0);
text("Shallow", xbase+50, ybase+140);
text("Intermediate", xbase+50, ybase+160);
text("Deep", xbase+50, ybase+180);
text("Past hour", xbase+50, ybase+200);
fill(255, 255, 255);
int centerx = xbase+35;
int centery = ybase+200;
ellipse(centerx, centery, 12, 12);
strokeWeight(2);
line(centerx-8, centery-8, centerx+8, centery+8);
line(centerx-8, centery+8, centerx+8, centery-8);
}
// Checks whether this quake occurred on land. If it did, it sets the
// "country" property of its PointFeature to the country where it occurred
// and returns true. Notice that the helper method isInCountry will
// set this "country" property already. Otherwise it returns false.
private boolean isLand(PointFeature earthquake) {
// IMPLEMENT THIS: loop over all countries to check if location is in any of them
// If it is, add 1 to the entry in countryQuakes corresponding to this country.
for (Marker country : countryMarkers) {
if (isInCountry(earthquake, country)) {
return true;
}
}
// not inside any country
return false;
}
// prints countries with number of earthquakes
private void printQuakes() {
int totalWaterQuakes = quakeMarkers.size();
for (Marker country : countryMarkers) {
String countryName = country.getStringProperty("name");
int numQuakes = 0;
for (Marker marker : quakeMarkers)
{
EarthquakeMarker eqMarker = (EarthquakeMarker)marker;
if (eqMarker.isOnLand()) {
if (countryName.equals(eqMarker.getStringProperty("country"))) {
numQuakes++;
}
}
}
if (numQuakes > 0) {
totalWaterQuakes -= numQuakes;
System.out.println(countryName + ": " + numQuakes);
}
}
System.out.println("OCEAN QUAKES: " + totalWaterQuakes);
}
// helper method to test whether a given earthquake is in a given country
// This will also add the country property to the properties of the earthquake feature if
// it's in one of the countries.
// You should not have to modify this code
private boolean isInCountry(PointFeature earthquake, Marker country) {
// getting location of feature
Location checkLoc = earthquake.getLocation();
// some countries represented it as MultiMarker
// looping over SimplePolygonMarkers which make them up to use isInsideByLoc
if(country.getClass() == MultiMarker.class) {
// looping over markers making up MultiMarker
for(Marker marker : ((MultiMarker)country).getMarkers()) {
// checking if inside
if(((AbstractShapeMarker)marker).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
// return if is inside one
return true;
}
}
}
// check if inside country represented by SimplePolygonMarker
else if(((AbstractShapeMarker)country).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
return true;
}
return false;
}
}
|
923dc1441592f87eeb4804aab6abd34322b122df | 3,890 | java | Java | src/edu/mit/jwi/morph/WordnetStemmer.java | jlarteaga/jwi | 80596d85c1638c729abef0fd5f07853165328ef1 | [
"CC-BY-4.0"
] | 1 | 2022-01-18T21:08:16.000Z | 2022-01-18T21:08:16.000Z | src/edu/mit/jwi/morph/WordnetStemmer.java | jlarteaga/jwi | 80596d85c1638c729abef0fd5f07853165328ef1 | [
"CC-BY-4.0"
] | 3 | 2017-07-17T15:13:39.000Z | 2018-03-22T15:11:00.000Z | src/edu/mit/jwi/morph/WordnetStemmer.java | jlarteaga/jwi | 80596d85c1638c729abef0fd5f07853165328ef1 | [
"CC-BY-4.0"
] | 4 | 2018-03-21T17:12:18.000Z | 2022-01-21T05:16:40.000Z | 33.826087 | 94 | 0.595887 | 1,000,460 | /********************************************************************************
* Java Wordnet Interface Library (JWI) v2.4.0
* Copyright (c) 2007-2015 Mark A. Finlayson
*
* JWI is distributed under the terms of the Creative Commons Attribution 4.0
* International Public License, which means it may be freely used for all
* purposes, as long as proper acknowledgment is made. See the license file
* included with this distribution for more details.
*******************************************************************************/
package edu.mit.jwi.morph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import edu.mit.jwi.IDictionary;
import edu.mit.jwi.item.IExceptionEntry;
import edu.mit.jwi.item.POS;
/**
* This stemmer adds functionality to the simple pattern-based stemmer
* {@code SimpleStemmer} by checking to see if possible stems are actually
* contained in Wordnet. If any stems are found, only these stems are returned.
* If no prospective stems are found, the word is considered unknown, and the
* result returned is the same as that of the {@code SimpleStemmer} class.
*
* @author Mark A. Finlayson
* @version 2.4.0
* @since JWI 1.0
*/
public class WordnetStemmer extends SimpleStemmer {
private final IDictionary dict;
/**
* Constructs a WordnetStemmer that, naturally, requires a Wordnet
* dictionary.
*
* @param dict
* the dictionary to use; may not be <code>null</code>
* @throws NullPointerException
* if the specified dictionary is <code>null</code>
* @since JWI 1.0
*/
public WordnetStemmer(IDictionary dict) {
if(dict == null)
throw new NullPointerException();
this.dict = dict;
}
/**
* Returns the dictionary in use by the stemmer; will not return <code>null</code>
*
* @return the dictionary in use by this stemmer
* @since JWI 2.2.0
*/
public IDictionary getDictionary(){
return dict;
}
/*
* (non-Javadoc)
*
* @see edu.mit.jwi.morph.SimpleStemmer#findStems(java.lang.String, edu.mit.jwi.item.POS)
*/
public List<String> findStems(String word, POS pos) {
word = normalize(word);
if(pos == null)
return super.findStems(word, null);
Set<String> result = new LinkedHashSet<String>();
// first look for the word in the exception lists
IExceptionEntry excEntry = dict.getExceptionEntry(word, pos);
if (excEntry != null)
result.addAll(excEntry.getRootForms());
// then look and see if it's in Wordnet; if so, the form itself is a stem
if (dict.getIndexWord(word, pos) != null)
result.add(word);
if(excEntry != null)
return new ArrayList<String>(result);
// go to the simple stemmer and check and see if any of those stems are in WordNet
List<String> possibles = super.findStems(word, pos);
// Fix for Bug015: don't allow empty strings to go to the dictionary
for(Iterator<String> i = possibles.iterator(); i.hasNext(); )
if(i.next().trim().length() == 0)
i.remove();
// check each algorithmically obtained root to see if it's in WordNet
for (String possible : possibles) {
if(dict.getIndexWord(possible, pos) != null)
result.add(possible);
}
if(result.isEmpty())
if(possibles.isEmpty()){
return Collections.<String>emptyList();
} else{
return new ArrayList<String>(possibles);
}
return new ArrayList<String>(result);
}
}
|
923dc1c1ec9f7ba4c552da41dace744219de11b5 | 2,834 | java | Java | domain/src/main/java/nl/roka/mozaa/card/CardFactory.java | robinvandenbogaard/mozaa | 4de73f86315230878f5798eeacd647b55307d43d | [
"MIT"
] | null | null | null | domain/src/main/java/nl/roka/mozaa/card/CardFactory.java | robinvandenbogaard/mozaa | 4de73f86315230878f5798eeacd647b55307d43d | [
"MIT"
] | null | null | null | domain/src/main/java/nl/roka/mozaa/card/CardFactory.java | robinvandenbogaard/mozaa | 4de73f86315230878f5798eeacd647b55307d43d | [
"MIT"
] | null | null | null | 19.957746 | 74 | 0.65561 | 1,000,461 | package nl.roka.mozaa.card;
import nl.roka.mozaa.api.Color;
import nl.roka.mozaa.api.Direction;
import nl.roka.mozaa.util.Rotation;
import java.util.Objects;
import static nl.roka.mozaa.api.Color.BLUE;
import static nl.roka.mozaa.api.Color.RED;
public class CardFactory {
public static Card of(Color bottom, Color right, Color top, Color left) {
return CardBuilder.instance()
.bottom(bottom)
.right(right)
.top(top)
.left(left)
.build();
}
public static Card createInitialCard() {
return of("rgbz");
}
public static Card of(String data) {
return of(data, 0);
}
public static Card of(String data, Integer rotation) {
return CardBuilder.instance()
.bottom(toColor(data.charAt(0)))
.right(toColor(data.charAt(1)))
.top(toColor(data.charAt(2)))
.left(toColor(data.charAt(3)))
.rotation(rotation)
.build();
}
private static Color toColor(char c) {
return Color.from(c);
}
public static Card allRed() {
return of("rrrr");
}
public static Card allBlue() {
return of("bbbb");
}
public static Card oneRedAt(Direction direction) {
CardBuilder builder = CardBuilder.instance();
switch (direction) {
case DOWN:
builder.bottom(RED)
.right(BLUE)
.top(BLUE)
.left(BLUE);
break;
case RIGHT:
builder.bottom(BLUE)
.right(RED)
.top(BLUE)
.left(BLUE);
break;
case UP:
builder.bottom(BLUE)
.right(BLUE)
.top(RED)
.left(BLUE);
break;
case LEFT:
builder.bottom(BLUE)
.right(BLUE)
.top(BLUE)
.left(RED);
break;
default:
throw new IllegalArgumentException("Unknown direction");
}
return builder.build();
}
public static Card empty() {
return of("----");
}
private static class CardBuilder {
private Color bottom;
private Color right;
private Color top;
private Color left;
private Integer rotation;
static CardBuilder instance() {
return new CardBuilder();
}
CardBuilder bottom(Color color) {
bottom = color;
return this;
}
CardBuilder right(Color color) {
right = color;
return this;
}
CardBuilder top(Color color) {
top = color;
return this;
}
CardBuilder left(Color color) {
left = color;
return this;
}
CardBuilder rotation(Integer rotation) {
this.rotation = rotation;
return this;
}
Card build() {
Objects.requireNonNull(bottom, "Bottom color must be supplied.");
Objects.requireNonNull(right, "Right color must be supplied.");
Objects.requireNonNull(top, "Top color must be supplied.");
Objects.requireNonNull(left, "Left color must be supplied.");
Rotation rotation = Rotation.none();
if (this.rotation != null) {
rotation = Rotation.of(this.rotation);
}
return Card.of(Faces.of(bottom,right,top,left), rotation);
}
}
}
|
923dc251e7428c976c57c9d276713a225b0245a9 | 14,171 | java | Java | src/main/java/yang/base/nsd/descriptor/common/scaling/group/descriptor/scaling/policy/ScalingCriteriaBuilder.java | 5GinFIRE/-eu.5ginfire.nbi.osm4java | 2482514814828bf54d82ef1fe19e4b72a9e9096b | [
"Apache-2.0"
] | 1 | 2019-05-22T08:57:17.000Z | 2019-05-22T08:57:17.000Z | src/main/java/yang/base/nsd/descriptor/common/scaling/group/descriptor/scaling/policy/ScalingCriteriaBuilder.java | 5GinFIRE/-eu.5ginfire.nbi.osm4java | 2482514814828bf54d82ef1fe19e4b72a9e9096b | [
"Apache-2.0"
] | 1 | 2019-03-20T09:09:17.000Z | 2019-03-20T10:18:31.000Z | src/main/java/yang/base/nsd/descriptor/common/scaling/group/descriptor/scaling/policy/ScalingCriteriaBuilder.java | 5GinFIRE/-eu.5ginfire.nbi.osm4java | 2482514814828bf54d82ef1fe19e4b72a9e9096b | [
"Apache-2.0"
] | 1 | 2019-06-07T17:15:56.000Z | 2019-06-07T17:15:56.000Z | 37.588859 | 165 | 0.640675 | 1,000,462 | package yang.base.nsd.descriptor.common.scaling.group.descriptor.scaling.policy;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Range;
import ns.yang.nfvo.mano.types.rev170208.RelationalOperationType;
import yang.base.$YangModuleInfoImpl;
import java.lang.Class;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.opendaylight.yangtools.concepts.Builder;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
import org.opendaylight.yangtools.yang.binding.CodeHelpers;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.common.QName;
/**
* Class that builds {@link ScalingCriteria} instances.
*
* @see ScalingCriteria
*
*/
public class ScalingCriteriaBuilder implements Builder<ScalingCriteria> {
private String _name;
private String _nsMonitoringParamRef;
private RelationalOperationType _scaleInRelationalOperation;
private BigInteger _scaleInThreshold;
private RelationalOperationType _scaleOutRelationalOperation;
private BigInteger _scaleOutThreshold;
private ScalingCriteriaKey key;
public static final QName QNAME = $YangModuleInfoImpl.qnameOf("scaling-criteria");
Map<Class<? extends Augmentation<ScalingCriteria>>, Augmentation<ScalingCriteria>> augmentation = Collections.emptyMap();
public ScalingCriteriaBuilder() {
}
public ScalingCriteriaBuilder(ScalingCriteria base) {
if (base.key() == null) {
this.key = new ScalingCriteriaKey(
base.getName()
);
this._name = base.getName();
} else {
this.key = base.key();
this._name = key.getName();
}
this._nsMonitoringParamRef = base.getNsMonitoringParamRef();
this._scaleInRelationalOperation = base.getScaleInRelationalOperation();
this._scaleInThreshold = base.getScaleInThreshold();
this._scaleOutRelationalOperation = base.getScaleOutRelationalOperation();
this._scaleOutThreshold = base.getScaleOutThreshold();
if (base instanceof ScalingCriteriaImpl) {
ScalingCriteriaImpl impl = (ScalingCriteriaImpl) base;
if (!impl.augmentation.isEmpty()) {
this.augmentation = new HashMap<>(impl.augmentation);
}
} else if (base instanceof AugmentationHolder) {
@SuppressWarnings("unchecked")
AugmentationHolder<ScalingCriteria> casted =(AugmentationHolder<ScalingCriteria>) base;
if (!casted.augmentations().isEmpty()) {
this.augmentation = new HashMap<>(casted.augmentations());
}
}
}
public ScalingCriteriaKey key() {
return key;
}
public String getName() {
return _name;
}
public String getNsMonitoringParamRef() {
return _nsMonitoringParamRef;
}
public RelationalOperationType getScaleInRelationalOperation() {
return _scaleInRelationalOperation;
}
public BigInteger getScaleInThreshold() {
return _scaleInThreshold;
}
public RelationalOperationType getScaleOutRelationalOperation() {
return _scaleOutRelationalOperation;
}
public BigInteger getScaleOutThreshold() {
return _scaleOutThreshold;
}
@SuppressWarnings("unchecked")
public <E extends Augmentation<ScalingCriteria>> E augmentation(Class<E> augmentationType) {
return (E) augmentation.get(CodeHelpers.nonNullValue(augmentationType, "augmentationType"));
}
public ScalingCriteriaBuilder withKey(final ScalingCriteriaKey key) {
this.key = key;
return this;
}
public ScalingCriteriaBuilder setName(final String value) {
this._name = value;
return this;
}
public ScalingCriteriaBuilder setNsMonitoringParamRef(final String value) {
this._nsMonitoringParamRef = value;
return this;
}
public ScalingCriteriaBuilder setScaleInRelationalOperation(final RelationalOperationType value) {
this._scaleInRelationalOperation = value;
return this;
}
private static final Range<java.math.BigInteger>[] CHECKSCALEINTHRESHOLDRANGE_RANGES;
static {
@SuppressWarnings("unchecked")
final Range<java.math.BigInteger>[] a = (Range<java.math.BigInteger>[]) Array.newInstance(Range.class, 1);
a[0] = Range.closed(java.math.BigInteger.ZERO, new java.math.BigInteger("18446744073709551615"));
CHECKSCALEINTHRESHOLDRANGE_RANGES = a;
}
private static void checkScaleInThresholdRange(final java.math.BigInteger value) {
for (Range<java.math.BigInteger> r : CHECKSCALEINTHRESHOLDRANGE_RANGES) {
if (r.contains(value)) {
return;
}
}
CodeHelpers.throwInvalidRange(CHECKSCALEINTHRESHOLDRANGE_RANGES, value);
}
public ScalingCriteriaBuilder setScaleInThreshold(final BigInteger value) {
if (value != null) {
checkScaleInThresholdRange(value);
}
this._scaleInThreshold = value;
return this;
}
public ScalingCriteriaBuilder setScaleOutRelationalOperation(final RelationalOperationType value) {
this._scaleOutRelationalOperation = value;
return this;
}
private static final Range<java.math.BigInteger>[] CHECKSCALEOUTTHRESHOLDRANGE_RANGES;
static {
@SuppressWarnings("unchecked")
final Range<java.math.BigInteger>[] a = (Range<java.math.BigInteger>[]) Array.newInstance(Range.class, 1);
a[0] = Range.closed(java.math.BigInteger.ZERO, new java.math.BigInteger("18446744073709551615"));
CHECKSCALEOUTTHRESHOLDRANGE_RANGES = a;
}
private static void checkScaleOutThresholdRange(final java.math.BigInteger value) {
for (Range<java.math.BigInteger> r : CHECKSCALEOUTTHRESHOLDRANGE_RANGES) {
if (r.contains(value)) {
return;
}
}
CodeHelpers.throwInvalidRange(CHECKSCALEOUTTHRESHOLDRANGE_RANGES, value);
}
public ScalingCriteriaBuilder setScaleOutThreshold(final BigInteger value) {
if (value != null) {
checkScaleOutThresholdRange(value);
}
this._scaleOutThreshold = value;
return this;
}
public ScalingCriteriaBuilder addAugmentation(Class<? extends Augmentation<ScalingCriteria>> augmentationType, Augmentation<ScalingCriteria> augmentationValue) {
if (augmentationValue == null) {
return removeAugmentation(augmentationType);
}
if (!(this.augmentation instanceof HashMap)) {
this.augmentation = new HashMap<>();
}
this.augmentation.put(augmentationType, augmentationValue);
return this;
}
public ScalingCriteriaBuilder removeAugmentation(Class<? extends Augmentation<ScalingCriteria>> augmentationType) {
if (this.augmentation instanceof HashMap) {
this.augmentation.remove(augmentationType);
}
return this;
}
@Override
public ScalingCriteria build() {
return new ScalingCriteriaImpl(this);
}
private static final class ScalingCriteriaImpl implements ScalingCriteria {
@Override
public Class<ScalingCriteria> getImplementedInterface() {
return ScalingCriteria.class;
}
private final String _name;
private final String _nsMonitoringParamRef;
private final RelationalOperationType _scaleInRelationalOperation;
private final BigInteger _scaleInThreshold;
private final RelationalOperationType _scaleOutRelationalOperation;
private final BigInteger _scaleOutThreshold;
private final ScalingCriteriaKey key;
private Map<Class<? extends Augmentation<ScalingCriteria>>, Augmentation<ScalingCriteria>> augmentation = Collections.emptyMap();
private ScalingCriteriaImpl(ScalingCriteriaBuilder base) {
if (base.key() == null) {
this.key = new ScalingCriteriaKey(
base.getName()
);
this._name = base.getName();
} else {
this.key = base.key();
this._name = key.getName();
}
this._nsMonitoringParamRef = base.getNsMonitoringParamRef();
this._scaleInRelationalOperation = base.getScaleInRelationalOperation();
this._scaleInThreshold = base.getScaleInThreshold();
this._scaleOutRelationalOperation = base.getScaleOutRelationalOperation();
this._scaleOutThreshold = base.getScaleOutThreshold();
this.augmentation = ImmutableMap.copyOf(base.augmentation);
}
@Override
public ScalingCriteriaKey key() {
return key;
}
@Override
public String getName() {
return _name;
}
@Override
public String getNsMonitoringParamRef() {
return _nsMonitoringParamRef;
}
@Override
public RelationalOperationType getScaleInRelationalOperation() {
return _scaleInRelationalOperation;
}
@Override
public BigInteger getScaleInThreshold() {
return _scaleInThreshold;
}
@Override
public RelationalOperationType getScaleOutRelationalOperation() {
return _scaleOutRelationalOperation;
}
@Override
public BigInteger getScaleOutThreshold() {
return _scaleOutThreshold;
}
@SuppressWarnings("unchecked")
@Override
public <E extends Augmentation<ScalingCriteria>> E augmentation(Class<E> augmentationType) {
return (E) augmentation.get(CodeHelpers.nonNullValue(augmentationType, "augmentationType"));
}
private int hash = 0;
private volatile boolean hashValid = false;
@Override
public int hashCode() {
if (hashValid) {
return hash;
}
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(_name);
result = prime * result + Objects.hashCode(_nsMonitoringParamRef);
result = prime * result + Objects.hashCode(_scaleInRelationalOperation);
result = prime * result + Objects.hashCode(_scaleInThreshold);
result = prime * result + Objects.hashCode(_scaleOutRelationalOperation);
result = prime * result + Objects.hashCode(_scaleOutThreshold);
result = prime * result + Objects.hashCode(augmentation);
hash = result;
hashValid = true;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DataObject)) {
return false;
}
if (!ScalingCriteria.class.equals(((DataObject)obj).getImplementedInterface())) {
return false;
}
ScalingCriteria other = (ScalingCriteria)obj;
if (!Objects.equals(_name, other.getName())) {
return false;
}
if (!Objects.equals(_nsMonitoringParamRef, other.getNsMonitoringParamRef())) {
return false;
}
if (!Objects.equals(_scaleInRelationalOperation, other.getScaleInRelationalOperation())) {
return false;
}
if (!Objects.equals(_scaleInThreshold, other.getScaleInThreshold())) {
return false;
}
if (!Objects.equals(_scaleOutRelationalOperation, other.getScaleOutRelationalOperation())) {
return false;
}
if (!Objects.equals(_scaleOutThreshold, other.getScaleOutThreshold())) {
return false;
}
if (getClass() == obj.getClass()) {
// Simple case: we are comparing against self
ScalingCriteriaImpl otherImpl = (ScalingCriteriaImpl) obj;
if (!Objects.equals(augmentation, otherImpl.augmentation)) {
return false;
}
} else {
// Hard case: compare our augments with presence there...
for (Map.Entry<Class<? extends Augmentation<ScalingCriteria>>, Augmentation<ScalingCriteria>> e : augmentation.entrySet()) {
if (!e.getValue().equals(other.augmentation(e.getKey()))) {
return false;
}
}
// .. and give the other one the chance to do the same
if (!obj.equals(this)) {
return false;
}
}
return true;
}
@Override
public String toString() {
final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper("ScalingCriteria");
CodeHelpers.appendValue(helper, "_name", _name);
CodeHelpers.appendValue(helper, "_nsMonitoringParamRef", _nsMonitoringParamRef);
CodeHelpers.appendValue(helper, "_scaleInRelationalOperation", _scaleInRelationalOperation);
CodeHelpers.appendValue(helper, "_scaleInThreshold", _scaleInThreshold);
CodeHelpers.appendValue(helper, "_scaleOutRelationalOperation", _scaleOutRelationalOperation);
CodeHelpers.appendValue(helper, "_scaleOutThreshold", _scaleOutThreshold);
CodeHelpers.appendValue(helper, "augmentation", augmentation.values());
return helper.toString();
}
}
}
|
923dc39a25593b6a67ddf2c023211a1a1b383e85 | 3,538 | java | Java | cluster/src/test/java/com/hartwig/pipeline/calling/sage/SageSomaticCallerTest.java | hartwigmedical/pipeline2 | 70237f3b895b41c9c45d892692f1f36572bda189 | [
"MIT"
] | null | null | null | cluster/src/test/java/com/hartwig/pipeline/calling/sage/SageSomaticCallerTest.java | hartwigmedical/pipeline2 | 70237f3b895b41c9c45d892692f1f36572bda189 | [
"MIT"
] | null | null | null | cluster/src/test/java/com/hartwig/pipeline/calling/sage/SageSomaticCallerTest.java | hartwigmedical/pipeline2 | 70237f3b895b41c9c45d892692f1f36572bda189 | [
"MIT"
] | 1 | 2018-06-26T13:12:38.000Z | 2018-06-26T13:12:38.000Z | 43.679012 | 176 | 0.686829 | 1,000,463 | package com.hartwig.pipeline.calling.sage;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.hartwig.pipeline.Arguments;
import com.hartwig.pipeline.metadata.SomaticRunMetadata;
import com.hartwig.pipeline.reruns.NoopPersistedDataset;
import com.hartwig.pipeline.stages.Stage;
import com.hartwig.pipeline.storage.GoogleStorageLocation;
import com.hartwig.pipeline.tertiary.TertiaryStageTest;
import com.hartwig.pipeline.testsupport.TestInputs;
import org.junit.Before;
import org.junit.Test;
public class SageSomaticCallerTest extends TertiaryStageTest<SageOutput> {
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void shallowModeUsesHotspotQualOverride() {
SageSomaticCaller victim = new SageSomaticCaller(TestInputs.defaultPair(),
new NoopPersistedDataset(),
TestInputs.REF_GENOME_37_RESOURCE_FILES, Arguments.testDefaultsBuilder().shallow(true).build());
assertThat(victim.tumorReferenceCommands(input()).get(0).asBash()).contains("-hotspot_min_tumor_qual 40");
}
@Override
protected Stage<SageOutput, SomaticRunMetadata> createVictim() {
return new SageSomaticCaller(TestInputs.defaultPair(),
new NoopPersistedDataset(),
TestInputs.REF_GENOME_37_RESOURCE_FILES, Arguments.testDefaults());
}
@Override
protected List<String> expectedCommands() {
return ImmutableList.of("java -Xmx60G -jar /opt/tools/sage/3.0/sage.jar " + "-tumor tumor -tumor_bam /data/input/tumor.bam "
+ "-reference reference -reference_bam /data/input/reference.bam "
+ "-hotspots /opt/resources/sage/37/KnownHotspots.somatic.37.vcf.gz "
+ "-panel_bed /opt/resources/sage/37/ActionableCodingPanel.somatic.37.bed.gz "
+ "-coverage_bed /opt/resources/sage/37/ActionableCodingPanel.somatic.37.bed.gz "
+ "-high_confidence_bed /opt/resources/giab_high_conf/37/NA12878_GIAB_highconf_IllFB-IllGATKHC-CG-Ion-Solid_ALLCHROM_v3.2.2_highconf.bed.gz "
+ "-ref_genome /opt/resources/reference_genome/37/Homo_sapiens.GRCh37.GATK.illumina.fasta " + "-ref_genome_version V37 "
+ "-ensembl_data_dir /opt/resources/ensembl_data_cache/37/ " + "-write_bqr_data -write_bqr_plot "
+ "-out /data/output/tumor.sage.somatic.vcf.gz -threads $(grep -c '^processor' /proc/cpuinfo)",
"(/opt/tools/bcftools/1.9/bcftools filter -i 'FILTER=\"PASS\"' /data/output/tumor.sage.somatic.vcf.gz -O z -o /data/output/tumor.sage.somatic.filtered.vcf.gz)",
"/opt/tools/tabix/0.2.6/tabix /data/output/tumor.sage.somatic.filtered.vcf.gz -p vcf");
}
@Override
public void returnsExpectedOutput() {
// not supported currently
}
@Override
protected void validateOutput(final SageOutput output) {
// not supported currently
}
@Override
public void addsLogs() {
// not supported currently
}
@Override
protected void validatePersistedOutput(final SageOutput output) {
assertThat(output.variants()).isEqualTo(GoogleStorageLocation.of(OUTPUT_BUCKET,
"set/sage_somatic/tumor.sage.somatic.filtered.vcf.gz"));
}
@Override
public void returnsExpectedFurtherOperations() {
// ignore for now
}
} |
923dc39fc2a1c7fc7fdabc51703cddb0a6da80bf | 3,036 | java | Java | src/main/java/gamess/InputFileHandlers/InputFileReader.java | eroma2014/seagrid-rich-client | a432af6aa97d6c1d5855dffa4c85cb9c14718af9 | [
"Apache-2.0"
] | 1 | 2017-02-22T08:41:20.000Z | 2017-02-22T08:41:20.000Z | src/main/java/gamess/InputFileHandlers/InputFileReader.java | eroma2014/seagrid-rich-client | a432af6aa97d6c1d5855dffa4c85cb9c14718af9 | [
"Apache-2.0"
] | 39 | 2018-09-06T10:47:02.000Z | 2018-12-11T14:16:35.000Z | src/main/java/gamess/InputFileHandlers/InputFileReader.java | airavata-courses/airavata-nextcoud | b8d89c60363167b16b27dd42ff4f46beca815d66 | [
"Apache-2.0"
] | 8 | 2016-03-08T17:15:49.000Z | 2019-07-28T11:35:39.000Z | 25.948718 | 167 | 0.716403 | 1,000,464 | package gamess.InputFileHandlers;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import gamess.GamessGUI;
public class InputFileReader {
private static InputFileReader instance = new InputFileReader();
private JTextPane inputFilePane = null;
private StyledDocument inputFile = null;
private InputFileReader()
{
if(GamessGUI.inputFilePane != null)
{
inputFilePane = GamessGUI.inputFilePane;
inputFile = GamessGUI.inputFilePane.getStyledDocument();
}
}
public static InputFileReader getInstance()
{
return instance;
}
public String Read(String Group)
{
//Read the full Group
int groupStartPosition = -1;
if((groupStartPosition = getGroupStartPosition(Group)) == -1)
{
return null;
}
groupStartPosition += Group.length() + 1;
int groupEndPosition = getFullInputText().indexOf("$END", groupStartPosition);
groupEndPosition--;
KeywordRW KeywordReader = RWGetter.getReadWriteHandle(Group, inputFilePane);
return KeywordReader.read(Group, groupStartPosition, groupEndPosition);
}
public String Read(String Group, String Keyword)
{
//Read the value of the keyword
int groupStartPosition = -1;
if((groupStartPosition = getGroupStartPosition(Group)) == -1)
{
return null;
}
groupStartPosition += Group.length() + 1;
int groupEndPosition = getFullInputText().indexOf("$END", groupStartPosition);
groupEndPosition--;
KeywordRW KeywordReader = RWGetter.getReadWriteHandle(Group, inputFilePane);
return KeywordReader.read(Group, Keyword, groupStartPosition, groupEndPosition);
}
public boolean isAvailable(String Group)
{
if(Read(Group) == null)
return false;
return true;
}
public boolean isAvailable(String Group, String Keyword)
{
int valueIndex = -1;
if( (valueIndex = Keyword.indexOf("=")) == -1)
{
if(Read(Group,Keyword) == null)
return false;
}
else
{
String value = Read(Group,Keyword.substring(0, valueIndex));
if(value == null || !value.equalsIgnoreCase(Keyword.substring(valueIndex + 1)))
return false;
}
return true;
}
private int getGroupStartPosition(String Group)
{
String fullText = getFullInputText();
//Get the start index
for(int startIndex, possibleStartIndex = fullText.indexOf("$" + Group); possibleStartIndex != -1 ; possibleStartIndex = fullText.indexOf("$" + Group,startIndex + 1))
{
startIndex = possibleStartIndex;
//Try to hit the line starting backwards with empty spaces
while(--possibleStartIndex >= 0 && fullText.charAt(possibleStartIndex) == ' ');
//Check if it is the starting of the text
if(possibleStartIndex == -1)
return startIndex;
//Check if there are some other characters in between
if(fullText.charAt(possibleStartIndex) != '\n')
continue;
return startIndex;
}
return -1;
}
private String getFullInputText()
{
try {
return inputFile.getText(0, inputFile.getLength());
} catch (BadLocationException e) {}
return "";
}
}
|
923dc420b022606849e8f6eb171146e9a69b5a76 | 569 | java | Java | src/com/java/string/SwitchCaseUsingString.java | Franklin-QA/Java-Programs | 96bccdf51e0229d34d2cbcd2d50ab01c7867d6b5 | [
"MIT"
] | 1 | 2021-07-25T09:29:46.000Z | 2021-07-25T09:29:46.000Z | src/com/java/string/SwitchCaseUsingString.java | Franklin-QA/Java-Programs | 96bccdf51e0229d34d2cbcd2d50ab01c7867d6b5 | [
"MIT"
] | null | null | null | src/com/java/string/SwitchCaseUsingString.java | Franklin-QA/Java-Programs | 96bccdf51e0229d34d2cbcd2d50ab01c7867d6b5 | [
"MIT"
] | null | null | null | 19.62069 | 53 | 0.659051 | 1,000,465 | package com.java.string;
import java.util.Scanner;
public class SwitchCaseUsingString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String");
String sString = sc.nextLine();
System.out.println(getCorrespondentName(sString));
sc.close();
}
static String getCorrespondentName(String sString) {
String s = "";
switch (sString) {
case "frank":
s="franklin "+ "8072333636";
break;
case "ash":
s="abi "+ "807233366";
default:
s=null;
break;
}
return s;
}
}
|
923dc483d229e9127652de82b2af11ca0b1fe907 | 2,797 | java | Java | Mage.Sets/src/mage/cards/a/AsajjVentress.java | zeffirojoe/mage | 71260c382a4e3afef5cdf79adaa00855b963c166 | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/a/AsajjVentress.java | zeffirojoe/mage | 71260c382a4e3afef5cdf79adaa00855b963c166 | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/a/AsajjVentress.java | zeffirojoe/mage | 71260c382a4e3afef5cdf79adaa00855b963c166 | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 43.030769 | 188 | 0.749732 | 1,000,466 |
package mage.cards.a;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.common.BecomesBlockedSourceTriggeredAbility;
import mage.abilities.condition.common.HateCondition;
import mage.abilities.decorator.ConditionalInterveningIfTriggeredAbility;
import mage.abilities.dynamicvalue.common.BlockedCreatureCount;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.combat.BlocksIfAbleTargetEffect;
import mage.abilities.effects.common.continuous.BoostSourceEffect;
import mage.abilities.keyword.DoubleStrikeAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.target.common.TargetCreaturePermanent;
import mage.watchers.common.LifeLossOtherFromCombatWatcher;
/**
* @author Styxo
*/
public final class AsajjVentress extends CardImpl {
public AsajjVentress(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{U}{B}{R}");
this.addSuperType(SuperType.LEGENDARY);
this.subtype.add(SubType.DATHOMIRIAN);
this.subtype.add(SubType.SITH);
this.power = new MageInt(3);
this.toughness = new MageInt(2);
// Double Strike
this.addAbility(DoubleStrikeAbility.getInstance());
// When Asajj Ventress becomes blocked, she gets +1/+1 for each creature blocking her until end of turn.
BlockedCreatureCount value = BlockedCreatureCount.ALL;
Effect effect = new BoostSourceEffect(value, value, Duration.EndOfTurn, true);
effect.setText("she gets +1/+1 for each creature blocking her until end of turn");
this.addAbility(new BecomesBlockedSourceTriggeredAbility(effect, false));
// <i>Hate</i> — Whenever Asajj Ventress attacks, if an opponent lost life from a source other than combat damage this turn, target creature blocks this turn if able.
Ability ability = new ConditionalInterveningIfTriggeredAbility(
new AttacksTriggeredAbility(new BlocksIfAbleTargetEffect(Duration.EndOfTurn), false),
HateCondition.instance,
"<i>Hate</i> — Whenever Asajj Ventress attacks, if an opponent lost life from a source other than combat damage this turn, target creature blocks this turn if able");
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability, new LifeLossOtherFromCombatWatcher());
}
private AsajjVentress(final AsajjVentress card) {
super(card);
}
@Override
public AsajjVentress copy() {
return new AsajjVentress(this);
}
}
|
923dc4ef47c9eac5e99e5f15637af191017ee36b | 2,894 | java | Java | state-engine/src/main/java/storage/datatype/LongDataBox.java | zhonghao-yang/MorphStream | 693d92f6d80a20e35071fb36601690bf6adb4537 | [
"Apache-2.0"
] | 27 | 2022-01-09T04:36:07.000Z | 2022-03-18T07:52:19.000Z | state-engine/src/main/java/storage/datatype/LongDataBox.java | zhonghao-yang/MorphStream | 693d92f6d80a20e35071fb36601690bf6adb4537 | [
"Apache-2.0"
] | 40 | 2021-12-14T07:35:59.000Z | 2022-03-29T08:34:55.000Z | state-engine/src/main/java/storage/datatype/LongDataBox.java | zhonghao-yang/MorphStream | 693d92f6d80a20e35071fb36601690bf6adb4537 | [
"Apache-2.0"
] | 4 | 2022-03-03T02:13:56.000Z | 2022-03-13T03:20:55.000Z | 21.597015 | 69 | 0.561161 | 1,000,467 | package storage.datatype;
import storage.SchemaRecord;
import java.nio.ByteBuffer;
/**
* Long data type which serializes to 8 bytes
*/
public class LongDataBox extends DataBox {
private long i;
/**
* Construct an empty LongDataBox with value_list 0.
*/
public LongDataBox() {
this.i = 0;
}
/**
* Constructs an LongDataBox with value_list i.
*
* @param i the value_list of the LongDataBox
*/
public LongDataBox(long i) {
this.i = i;
}
/**
* Construct an LongDataBox from the bytes in buf.
*
* @param buf the byte buffer source
*/
public LongDataBox(byte[] buf) {
if (buf.length != this.getSize()) {
throw new DataBoxException("Wrong size buffer for long");
}
this.i = ByteBuffer.wrap(buf).getLong();
}
@Override
public LongDataBox clone() {
return new LongDataBox(i);
}
@Override
public long getLong() {
return this.i;
}
@Override
public void setLong(long i) {
this.i = i;
}
/**
* MVCC to make sure it's reading the correct version..
*
* @param s_record
* @param delta
*/
@Override
public void incLong(SchemaRecord s_record, long delta) {
this.i = s_record.getValues().get(1).getLong() + delta;
}
@Override
public void incLong(long current_value, long delta) {
this.i = current_value + delta;
}
@Override
public void incLong(long delta) {
this.i = i + delta;
}
@Override
public void decLong(SchemaRecord s_record, long delta) {
this.i = s_record.getValues().get(1).getLong() + delta;
}
public void decLong(long current_value, long delta) {
this.i = current_value - delta;
}
@Override
public Types type() {
return Types.LONG;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
LongDataBox other = (LongDataBox) obj;
return this.getLong() == other.getLong();
}
@Override
public int hashCode() {
return (int) Math.abs(this.getLong());
}
public int compareTo(Object obj) {
if (this.getClass() != obj.getClass()) {
throw new DataBoxException("Invalid Comparsion");
}
LongDataBox other = (LongDataBox) obj;
return Long.compare(this.getLong(), other.getLong());
}
@Override
public byte[] getBytes() {
return ByteBuffer.allocate(8).putLong(this.i).array();
}
@Override
public int getSize() {
return 8;
}
@Override
public String toString() {
return "" + this.i;
}
}
|
923dc5f5d7a6df9470e7d061b4d981f0da051af9 | 357 | java | Java | src/test/java/uo/asw/junitTest/AllTests.java | Arquisoft/InciManagement_e3a | 150f8a3d7ac87514c359f1da470abfc3301cfe01 | [
"Unlicense"
] | null | null | null | src/test/java/uo/asw/junitTest/AllTests.java | Arquisoft/InciManagement_e3a | 150f8a3d7ac87514c359f1da470abfc3301cfe01 | [
"Unlicense"
] | 32 | 2018-03-09T23:52:27.000Z | 2018-05-08T18:56:29.000Z | src/test/java/uo/asw/junitTest/AllTests.java | Arquisoft/InciManagement_e3a | 150f8a3d7ac87514c359f1da470abfc3301cfe01 | [
"Unlicense"
] | 3 | 2018-04-17T15:41:23.000Z | 2018-05-10T10:03:02.000Z | 19.833333 | 44 | 0.795518 | 1,000,468 | package uo.asw.junitTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
CategoriaTest.class,
ChatTest.class,
IncidenciaBDTest.class,
MensajeTest.class,
PropiedadTest.class,
UsuarioBDTest.class,
ValorLimiteTest.class
})
public class AllTests { } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.