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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92323e8f4bd2fb24a8d1a0aa81c324bd43dd4abf | 2,891 | java | Java | java/epi/bst/OrderedNodes.java | crazy-baddy/Problem-Solving | be9e3b8a630e4126f150b9e7f03c2f3290ba3255 | [
"MIT"
] | null | null | null | java/epi/bst/OrderedNodes.java | crazy-baddy/Problem-Solving | be9e3b8a630e4126f150b9e7f03c2f3290ba3255 | [
"MIT"
] | null | null | null | java/epi/bst/OrderedNodes.java | crazy-baddy/Problem-Solving | be9e3b8a630e4126f150b9e7f03c2f3290ba3255 | [
"MIT"
] | null | null | null | 25.8125 | 158 | 0.49706 | 996,152 | package epi.bst;
//Given three nodes, ancestor, middle and descendant check if ancestor is middle's ancestor and descendant is middle descendant in O(log n) time and space
public class OrderedNodes {
static class BNode {
BNode left, right, parent;
int value;
BNode(int value) {
this.value = value;
}
}
public static void main(String[] args) {
/*
20
/ \
8 22
/ \
4 12
/ \
10 14
/ \
13 19
*/
BNode root = insert(null, 20);
root = insert(root, 8);
root = insert(root, 22);
root = insert(root, 4);
root = insert(root, 12);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 13);
root = insert(root, 19);
BNode eight = root.left;
BNode four = eight.left;
BNode fourteen = eight.right.right;
BNode nineteen = fourteen.right;
BNode thirteen = fourteen.left;
System.out.println(isOrdered(root, eight, fourteen, thirteen));
System.out.println(isOrdered(root, eight, fourteen, nineteen));
System.out.println(isOrdered(root, eight, four, fourteen));
/*
Output:
true
true
false
*/
}
static boolean isOrdered(BNode root, BNode ancestor, BNode middle, BNode descendant){
//search ancestor first, then start from ancestor and find middle, then start from middle and find descendant . If all found then elements are ordered
boolean foundAnc = bSearch(root, ancestor);
if(!foundAnc){
return false;
}
boolean foundMid = bSearch(ancestor, middle);
if(!foundMid){
return false;
}
return bSearch(middle, descendant);
}
static boolean bSearch(BNode cur, BNode elem){
if (cur == null){
return false;
}
if (cur.value == elem.value){//found the element
return true;
}
if (cur.value > elem.value){//go left
return bSearch(cur.left, elem);
}else {
return bSearch(cur.right, elem);
}
}
static BNode insert(BNode root, int value){
if(root == null){
return new BNode(value);
}
if(value < root.value){//go left
BNode templ = insert(root.left, value);
root.left = templ;
templ.parent = root;
}else{//go right
BNode tempr = insert(root.right, value);
root.right = tempr;
tempr.parent = root;
}
return root;
}
}
|
92323fd82ee9357241d98fede2e907b3a597863b | 345 | java | Java | integrating/spring/src/main/java/org/agoncal/fascicle/jpa/integrating/spring/JPASpringApplication.java | agoncal/agoncal-fascicle-jpa | 24db21af1b4ddb80259d4113f36f3043aac647e5 | [
"MIT"
] | 22 | 2019-05-20T13:05:51.000Z | 2022-02-04T06:25:47.000Z | integrating/spring/src/main/java/org/agoncal/fascicle/jpa/integrating/spring/JPASpringApplication.java | SepehrRad/agoncal-fascicle-jpa | 33d45d1eba225beef6389047240d6a13fe7f024f | [
"MIT"
] | 5 | 2019-07-11T20:55:14.000Z | 2022-01-21T23:10:11.000Z | integrating/spring/src/main/java/org/agoncal/fascicle/jpa/integrating/spring/JPASpringApplication.java | SepehrRad/agoncal-fascicle-jpa | 33d45d1eba225beef6389047240d6a13fe7f024f | [
"MIT"
] | 8 | 2019-12-21T07:10:56.000Z | 2022-03-24T08:24:21.000Z | 26.538462 | 68 | 0.82029 | 996,153 | package org.agoncal.fascicle.jpa.integrating.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JPASpringApplication {
public static void main(String[] args) {
SpringApplication.run(JPASpringApplication.class, args);
}
}
|
92323ff4b53009a9a77a0fdb0fce9753f2a058f4 | 6,117 | java | Java | KeyboardHero/src/keyboardhero/GameplayPanel.java | dankearney/KeyboardHero | ed2444923a4cbaee06d234b36a6c7e3116cfc6f5 | [
"MIT"
] | null | null | null | KeyboardHero/src/keyboardhero/GameplayPanel.java | dankearney/KeyboardHero | ed2444923a4cbaee06d234b36a6c7e3116cfc6f5 | [
"MIT"
] | null | null | null | KeyboardHero/src/keyboardhero/GameplayPanel.java | dankearney/KeyboardHero | ed2444923a4cbaee06d234b36a6c7e3116cfc6f5 | [
"MIT"
] | null | null | null | 36.628743 | 103 | 0.536211 | 996,154 | /*
* 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 keyboardhero;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
/**
*
* @author Dank
* Main visualization of game.
* This game draws the game based on its state (for example, notes that have
* been hit or not hit) based on the game state and the current timestamp.
*/
public class GameplayPanel extends JPanel {
// The relevant game object
private final KeyboardHeroGame game;
// Constructor for the gameplay panel
public GameplayPanel(KeyboardHeroGame game) {
super();
// Attach the game
this.game = game;
// Set panel to be 3/4 the size of the window
Dimension gpDimension = new Dimension(
Constants.WINDOW_WIDTH * 3 / 4, Constants.WINDOW_HEIGHT
);
this.setPreferredSize(gpDimension);
// Attach click logic
this.setKeyBindings();
}
private void setKeyBindings() {
// Set up key bindings to handle button presses
InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actMap = getActionMap();
// Iterate over the frets and add a key binding for each key value
// Help for implementing this found on Stack Overflow:
// https://stackoverflow.com/questions/7940173/how-do-i-use-keyeventdispatcher/7940227#7940227
for (Fret fret : this.game.getFrets()) {
// Pull the name of the fret from the string the fret is on
String fretStr = fret.getKeyboardString().toString();
// Create a unique action string for the fret
String pressActionStr = "pressed" + fretStr;
String unpressActionStr = "unpressed" + fretStr;
// Determine correct keyboard letter to map to the key events
int k = -1;
switch (fret.getKeyboardString()) {
case A:
k = KeyEvent.VK_A;
break;
case S:
k = KeyEvent.VK_S;
break;
case D:
k = KeyEvent.VK_D;
break;
case F:
k = KeyEvent.VK_F;
break;
case G:
k = KeyEvent.VK_G;
break;
}
// Assign key stroke actions to the fret button for pressing
KeyStroke pressed = KeyStroke.getKeyStroke(k, 0, false);
inMap.put(pressed, pressActionStr);
actMap.put(pressActionStr, new FretKeyboardAction(fret, true));
// Assign key stroke actions to the fret button for un-pressing
KeyStroke unpressed = KeyStroke.getKeyStroke(k, 0, true);
inMap.put(unpressed, unpressActionStr);
actMap.put(unpressActionStr, new FretKeyboardAction(fret, false));
}
// Create a unique action string for the fret
String strikeActionStr = "struck";
KeyStroke struck = KeyStroke.getKeyStroke(KeyEvent.VK_L, 0, false);
inMap.put(struck, strikeActionStr);
actMap.put(strikeActionStr, new StrikeKeyboardAction(game));
}
@Override
public void paintComponent(Graphics g) {
// If the game is dormant, just draw something simple.
if (this.game.isDormant()) {
// Draw score on top left
g.setFont(new Font("Arial", Font.BOLD, 40));
String text = "Select a song to begin.";
g.drawString(text, 250, 450);
}
// Draw the game in gameplay mode.
else if (this.game.isPlaying())
{
// Draw the fret line
g.setColor(Color.black);
int height = 2;
int width = Constants.FRET_SPACING * (this.game.getFrets().size());
int x = 100;
int y = Constants.FRET_OFFSET_HEIGHT + Constants.BASE_FRET_HEIGHT / 2 - height / 2;
g.fillRect(x, y, width, height);
// Draw helper text for fret line
g.setFont(new Font("Arial", Font.BOLD, 30));
g.drawString("L", x - 30, y + 10);
// Draw the frets
for ( Fret fret : this.game.getFrets() ) {
fret.draw(g, game);
}
// Draw each note
for ( Note note : this.game.getSong().getNotes() ) {
note.draw(g, this.game);
}
// Draw score on top left with time remaining
int timeRemaining = (int) (Constants.SONG_LENGTH - game.getCurrentTimestamp()) / 1000;
String labelText = String.format(
"Time remaining: %d Score: %d",
timeRemaining,
this.game.getScore()
);
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.BOLD, 40));
g.drawString(labelText, 50, 50);
// Iterate the game state forward one step
this.game.step();
}
// Draw the game completed UI
else if (this.game.isComplete())
{
// Draw score on top left in large font
g.setFont(new Font("Arial", Font.BOLD, 40));
String text = "Song complete! Your score: " + Integer.toString(this.game.getScore());
g.drawString(text, 150, 400);
}
}
}
|
9232414e60d6182b85ee497a0840b131ee7fac86 | 11,063 | java | Java | com.io7m.r2.tests/src/test/java/com/io7m/r2/tests/shaders/lights/api/R2ShaderLightVolumeSingleContract.java | io7m/r2 | 4bc17f03d5447bf9e37a138f668c0aeb88b2ec5c | [
"ISC"
] | 4 | 2016-06-20T18:30:24.000Z | 2020-09-24T03:29:03.000Z | com.io7m.r2.tests/src/test/java/com/io7m/r2/tests/shaders/lights/api/R2ShaderLightVolumeSingleContract.java | io7m/r2 | 4bc17f03d5447bf9e37a138f668c0aeb88b2ec5c | [
"ISC"
] | 99 | 2016-01-05T17:04:41.000Z | 2017-06-29T17:03:15.000Z | com.io7m.r2.tests/src/test/java/com/io7m/r2/tests/shaders/lights/api/R2ShaderLightVolumeSingleContract.java | io7m/r2 | 4bc17f03d5447bf9e37a138f668c0aeb88b2ec5c | [
"ISC"
] | 1 | 2020-11-14T07:52:19.000Z | 2020-11-14T07:52:19.000Z | 35.219745 | 83 | 0.73777 | 996,155 | /*
* Copyright © 2016 <ychag@example.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.r2.tests.shaders.lights.api;
import com.io7m.jcanephora.core.JCGLTextureUnitType;
import com.io7m.jcanephora.core.api.JCGLContextType;
import com.io7m.jcanephora.core.api.JCGLFramebuffersType;
import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type;
import com.io7m.jcanephora.core.api.JCGLShadersType;
import com.io7m.jcanephora.core.api.JCGLTexturesType;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitAllocator;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitAllocatorType;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitContextParentType;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitContextType;
import com.io7m.jfsm.core.FSMTransitionException;
import com.io7m.jfunctional.Unit;
import com.io7m.jregions.core.unparameterized.sizes.AreaSizeL;
import com.io7m.jregions.core.unparameterized.sizes.AreaSizesL;
import com.io7m.jtensors.core.parameterized.matrices.PMatrices4x4D;
import com.io7m.jtensors.core.parameterized.matrices.PMatrix4x4D;
import com.io7m.r2.core.api.ids.R2IDPool;
import com.io7m.r2.core.api.ids.R2IDPoolType;
import com.io7m.r2.lights.R2LightVolumeSingleReadableType;
import com.io7m.r2.matrices.R2Matrices;
import com.io7m.r2.matrices.R2MatricesType;
import com.io7m.r2.projections.R2ProjectionOrthographic;
import com.io7m.r2.projections.R2ProjectionReadableType;
import com.io7m.r2.rendering.geometry.R2GeometryBuffer;
import com.io7m.r2.rendering.geometry.api.R2GeometryBufferComponents;
import com.io7m.r2.rendering.geometry.api.R2GeometryBufferDescription;
import com.io7m.r2.rendering.geometry.api.R2GeometryBufferType;
import com.io7m.r2.shaders.api.R2ShaderPreprocessingEnvironmentReadableType;
import com.io7m.r2.shaders.api.R2ShaderPreprocessingEnvironmentType;
import com.io7m.r2.shaders.light.api.R2LightShaderDefines;
import com.io7m.r2.shaders.light.api.R2ShaderLightVolumeSingleType;
import com.io7m.r2.shaders.light.api.R2ShaderParametersLight;
import com.io7m.r2.spaces.R2SpaceEyeType;
import com.io7m.r2.spaces.R2SpaceWorldType;
import com.io7m.r2.tests.R2JCGLContract;
import com.io7m.r2.tests.ShaderPreprocessing;
import com.io7m.r2.textures.R2TextureDefaults;
import com.io7m.r2.textures.R2TextureDefaultsType;
import com.io7m.r2.transforms.R2TransformT;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public abstract class R2ShaderLightVolumeSingleContract<
T extends R2LightVolumeSingleReadableType>
extends R2JCGLContract
{
@Rule public ExpectedException expected = ExpectedException.none();
private static R2GeometryBufferType newGeometryBuffer(
final JCGLFramebuffersType g_fb,
final JCGLTexturesType g_tex,
final JCGLTextureUnitContextParentType tr)
{
final JCGLTextureUnitContextType tc =
tr.unitContextNew();
try {
final R2GeometryBufferDescription gbuffer_desc =
R2GeometryBufferDescription.of(
AreaSizeL.of(4L, 4L),
R2GeometryBufferComponents.R2_GEOMETRY_BUFFER_FULL);
final R2GeometryBufferType gb = R2GeometryBuffer.create(
g_fb, g_tex, tc, gbuffer_desc);
g_fb.framebufferDrawUnbind();
return gb;
} finally {
tc.unitContextFinish(g_tex);
}
}
protected abstract R2ShaderLightVolumeSingleType<T> newShaderWithVerifier(
JCGLInterfaceGL33Type g,
R2ShaderPreprocessingEnvironmentReadableType sources,
R2IDPoolType pool);
protected abstract T newLight(
JCGLInterfaceGL33Type g,
R2IDPoolType pool);
@Test
public final void testCorrect()
throws Exception
{
final JCGLContextType c =
this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g =
c.contextGetGL33();
final R2ShaderPreprocessingEnvironmentType sources =
ShaderPreprocessing.preprocessor();
final R2IDPoolType pool =
R2IDPool.newPool();
final JCGLFramebuffersType g_fb =
g.framebuffers();
final JCGLTexturesType g_tex =
g.textures();
final JCGLShadersType g_sh =
g.shaders();
final JCGLTextureUnitAllocatorType ta =
JCGLTextureUnitAllocator.newAllocatorWithStack(
32,
g_tex.textureGetUnits());
final JCGLTextureUnitContextParentType tr =
ta.rootContext();
final R2TextureDefaultsType td =
R2TextureDefaults.create(g_tex, tr);
final R2GeometryBufferType gbuffer =
newGeometryBuffer(g_fb, g_tex, tr);
final JCGLTextureUnitContextType tc = tr.unitContextNew();
final JCGLTextureUnitType ua =
tc.unitContextBindTexture2D(
g_tex, gbuffer.albedoEmissiveTexture().texture());
final JCGLTextureUnitType un =
tc.unitContextBindTexture2D(
g_tex, gbuffer.normalTexture().texture());
final JCGLTextureUnitType us =
tc.unitContextBindTexture2D(
g_tex, gbuffer.specularTextureOrDefault(td).texture());
final JCGLTextureUnitType ud =
tc.unitContextBindTexture2D(
g_tex, gbuffer.depthTexture().texture());
final R2ShaderLightVolumeSingleType<T> f =
this.newShaderWithVerifier(g, sources, pool);
final T params =
this.newLight(g, pool);
final R2ProjectionReadableType proj =
R2ProjectionOrthographic.create();
final R2MatricesType mat =
R2Matrices.create();
final PMatrix4x4D<R2SpaceWorldType, R2SpaceEyeType> view =
PMatrices4x4D.identity();
final R2TransformT trans =
R2TransformT.create();
mat.withObserver(view, proj, this, (mo, x) -> {
f.onActivate(g);
f.onReceiveBoundGeometryBufferTextures(g, gbuffer, ua, us, ud, un);
f.onReceiveValues(
g,
R2ShaderParametersLight.of(
tc,
params,
mo,
AreaSizesL.area(gbuffer.size())));
return mo.withVolumeLight(trans, this, (mv, y) -> {
f.onReceiveVolumeLightTransform(g, mv);
f.onValidate();
f.onDeactivate(g);
return Unit.unit();
});
});
}
@Test
public final void testMissedGeometryBuffer()
throws Exception
{
final JCGLContextType c =
this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g =
c.contextGetGL33();
final R2ShaderPreprocessingEnvironmentType sources =
ShaderPreprocessing.preprocessor();
final R2IDPoolType pool =
R2IDPool.newPool();
final JCGLFramebuffersType g_fb =
g.framebuffers();
final JCGLTexturesType g_tex =
g.textures();
final JCGLShadersType g_sh =
g.shaders();
final JCGLTextureUnitAllocatorType ta =
JCGLTextureUnitAllocator.newAllocatorWithStack(
32,
g_tex.textureGetUnits());
final JCGLTextureUnitContextParentType tr =
ta.rootContext();
final R2GeometryBufferType gbuffer =
newGeometryBuffer(g_fb, g_tex, tr);
final JCGLTextureUnitContextType tc = tr.unitContextNew();
final R2ShaderLightVolumeSingleType<T> f =
this.newShaderWithVerifier(g, sources, pool);
final T params =
this.newLight(g, pool);
final R2ProjectionReadableType proj =
R2ProjectionOrthographic.create();
final R2MatricesType mat =
R2Matrices.create();
final PMatrix4x4D<R2SpaceWorldType, R2SpaceEyeType> view =
PMatrices4x4D.identity();
f.onActivate(g);
this.expected.expect(FSMTransitionException.class);
mat.withObserver(view, proj, this, (mo, x) -> {
f.onReceiveValues(
g,
R2ShaderParametersLight.of(
tc, params, mo, AreaSizesL.area(gbuffer.size())));
return Unit.unit();
});
}
@Test
public final void testNewDefault()
{
final JCGLContextType c = this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g = c.contextGetGL33();
final R2ShaderPreprocessingEnvironmentType sources =
ShaderPreprocessing.preprocessor();
final R2IDPoolType pool = R2IDPool.newPool();
final R2ShaderLightVolumeSingleType<T> s =
this.newShaderWithVerifier(g, sources, pool);
final T light =
this.newLight(g, pool);
final Class<?> s_class = s.shaderParametersType();
final Class<?> l_class = light.getClass();
Assert.assertTrue(s_class.isAssignableFrom(l_class));
Assert.assertTrue(light.lightID() >= 0L);
Assert.assertFalse(s.isDeleted());
s.delete(g);
Assert.assertTrue(s.isDeleted());
}
@Test
public final void testNewLightBuffer()
{
final JCGLContextType c = this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g = c.contextGetGL33();
final R2ShaderPreprocessingEnvironmentType sources =
ShaderPreprocessing.preprocessor();
sources.preprocessorDefineSet(
R2LightShaderDefines.R2_LIGHT_SHADER_OUTPUT_TARGET_DEFINE,
R2LightShaderDefines.R2_LIGHT_SHADER_OUTPUT_TARGET_LBUFFER);
final R2IDPoolType pool = R2IDPool.newPool();
final R2ShaderLightVolumeSingleType<T> s =
this.newShaderWithVerifier(g, sources, pool);
final T light =
this.newLight(g, pool);
final Class<?> s_class = s.shaderParametersType();
final Class<?> l_class = light.getClass();
Assert.assertTrue(s_class.isAssignableFrom(l_class));
Assert.assertTrue(light.lightID() >= 0L);
Assert.assertFalse(s.isDeleted());
s.delete(g);
Assert.assertTrue(s.isDeleted());
}
@Test
public final void testNewImageBuffer()
{
final JCGLContextType c = this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g = c.contextGetGL33();
final R2ShaderPreprocessingEnvironmentType sources =
ShaderPreprocessing.preprocessor();
sources.preprocessorDefineSet(
R2LightShaderDefines.R2_LIGHT_SHADER_OUTPUT_TARGET_DEFINE,
R2LightShaderDefines.R2_LIGHT_SHADER_OUTPUT_TARGET_IBUFFER);
final R2IDPoolType pool = R2IDPool.newPool();
final R2ShaderLightVolumeSingleType<T> s =
this.newShaderWithVerifier(g, sources, pool);
final T light =
this.newLight(g, pool);
final Class<?> s_class = s.shaderParametersType();
final Class<?> l_class = light.getClass();
Assert.assertTrue(s_class.isAssignableFrom(l_class));
Assert.assertTrue(light.lightID() >= 0L);
Assert.assertFalse(s.isDeleted());
s.delete(g);
Assert.assertTrue(s.isDeleted());
}
}
|
923242254e041b85ffe0aedfb159d557bb396faf | 2,096 | java | Java | plume-admin-api-log/src/main/java/com/coreoz/plume/admin/db/generated/LogHeader.java | lucas-amiaud/Plume-admin | 1add6d47db214487b1885b4c48b926b98e297271 | [
"Apache-2.0"
] | 2 | 2016-11-10T20:42:59.000Z | 2020-06-09T14:58:39.000Z | plume-admin-api-log/src/main/java/com/coreoz/plume/admin/db/generated/LogHeader.java | lucas-amiaud/Plume-admin | 1add6d47db214487b1885b4c48b926b98e297271 | [
"Apache-2.0"
] | 3 | 2020-09-11T12:13:43.000Z | 2021-08-02T16:56:38.000Z | plume-admin-api-log/src/main/java/com/coreoz/plume/admin/db/generated/LogHeader.java | lucas-amiaud/Plume-admin | 1add6d47db214487b1885b4c48b926b98e297271 | [
"Apache-2.0"
] | 6 | 2016-09-08T15:44:48.000Z | 2021-05-06T14:43:18.000Z | 20.349515 | 89 | 0.599714 | 996,156 | package com.coreoz.plume.admin.db.generated;
import javax.annotation.Generated;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.querydsl.sql.Column;
/**
* LogHeader is a Querydsl bean type
*/
@Generated("com.coreoz.plume.db.querydsl.generation.IdBeanSerializer")
public class LogHeader extends com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl {
@JsonSerialize(using=com.fasterxml.jackson.databind.ser.std.ToStringSerializer.class)
@Column("id")
private Long id;
@JsonSerialize(using=com.fasterxml.jackson.databind.ser.std.ToStringSerializer.class)
@Column("id_log_api")
private Long idLogApi;
@Column("name")
private String name;
@Column("type")
private String type;
@Column("value")
private String value;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public Long getIdLogApi() {
return idLogApi;
}
public void setIdLogApi(Long idLogApi) {
this.idLogApi = idLogApi;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (id == null) {
return super.equals(o);
}
if (!(o instanceof LogHeader)) {
return false;
}
LogHeader obj = (LogHeader) o;
return id.equals(obj.id);
}
@Override
public int hashCode() {
if (id == null) {
return super.hashCode();
}
final int prime = 31;
int result = 1;
result = prime * result + id.hashCode();
return result;
}
@Override
public String toString() {
return "LogHeader#" + id;
}
}
|
923243dcefaea8dc42d7991568e905661f67f4ef | 15,129 | java | Java | hadoop-tools/hadoop-openstack/src/test/java/org/apache/hadoop/fs/swift/TestSwiftObjectPath.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-tools/hadoop-openstack/src/test/java/org/apache/hadoop/fs/swift/TestSwiftObjectPath.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-tools/hadoop-openstack/src/test/java/org/apache/hadoop/fs/swift/TestSwiftObjectPath.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | 15.469325 | 813 | 0.813471 | 996,157 | 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.hadoop.fs.swift
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|swift
package|;
end_package
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|swift
operator|.
name|http
operator|.
name|RestClientBindings
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|swift
operator|.
name|http
operator|.
name|SwiftRestClient
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|swift
operator|.
name|util
operator|.
name|SwiftObjectPath
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|swift
operator|.
name|util
operator|.
name|SwiftUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URI
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertFalse
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertTrue
import|;
end_import
begin_comment
comment|/** * Unit tests for SwiftObjectPath class. */
end_comment
begin_class
DECL|class|TestSwiftObjectPath
specifier|public
class|class
name|TestSwiftObjectPath
implements|implements
name|SwiftTestConstants
block|{
DECL|field|LOG
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|TestSwiftObjectPath
operator|.
name|class
argument_list|)
decl_stmt|;
comment|/** * What an endpoint looks like. This is derived from a (valid) * rackspace endpoint address */
DECL|field|ENDPOINT
specifier|private
specifier|static
specifier|final
name|String
name|ENDPOINT
init|=
literal|"https://storage101.region1.example.org/v1/MossoCloudFS_9fb40cc0-1234-5678-9abc-def000c9a66"
decl_stmt|;
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testParsePath ()
specifier|public
name|void
name|testParsePath
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|String
name|pathString
init|=
literal|"/home/user/files/file1"
decl_stmt|;
specifier|final
name|Path
name|path
init|=
operator|new
name|Path
argument_list|(
name|pathString
argument_list|)
decl_stmt|;
specifier|final
name|URI
name|uri
init|=
operator|new
name|URI
argument_list|(
literal|"http://container.localhost"
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|expected
init|=
name|SwiftObjectPath
operator|.
name|fromPath
argument_list|(
name|uri
argument_list|,
name|path
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|actual
init|=
operator|new
name|SwiftObjectPath
argument_list|(
name|RestClientBindings
operator|.
name|extractContainerName
argument_list|(
name|uri
argument_list|)
argument_list|,
name|pathString
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testParseUrlPath ()
specifier|public
name|void
name|testParseUrlPath
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|String
name|pathString
init|=
literal|"swift://container.service1/home/user/files/file1"
decl_stmt|;
specifier|final
name|URI
name|uri
init|=
operator|new
name|URI
argument_list|(
name|pathString
argument_list|)
decl_stmt|;
specifier|final
name|Path
name|path
init|=
operator|new
name|Path
argument_list|(
name|pathString
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|expected
init|=
name|SwiftObjectPath
operator|.
name|fromPath
argument_list|(
name|uri
argument_list|,
name|path
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|actual
init|=
operator|new
name|SwiftObjectPath
argument_list|(
name|RestClientBindings
operator|.
name|extractContainerName
argument_list|(
name|uri
argument_list|)
argument_list|,
literal|"/home/user/files/file1"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testHandleUrlAsPath ()
specifier|public
name|void
name|testHandleUrlAsPath
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|String
name|hostPart
init|=
literal|"swift://container.service1"
decl_stmt|;
specifier|final
name|String
name|pathPart
init|=
literal|"/home/user/files/file1"
decl_stmt|;
specifier|final
name|String
name|uriString
init|=
name|hostPart
operator|+
name|pathPart
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|expected
init|=
operator|new
name|SwiftObjectPath
argument_list|(
name|uriString
argument_list|,
name|pathPart
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|actual
init|=
operator|new
name|SwiftObjectPath
argument_list|(
name|uriString
argument_list|,
name|uriString
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testParseAuthenticatedUrl ()
specifier|public
name|void
name|testParseAuthenticatedUrl
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|String
name|pathString
init|=
literal|"swift://container.service1/v2/AUTH_00345h34l93459y4/home/tom/documents/finance.docx"
decl_stmt|;
specifier|final
name|URI
name|uri
init|=
operator|new
name|URI
argument_list|(
name|pathString
argument_list|)
decl_stmt|;
specifier|final
name|Path
name|path
init|=
operator|new
name|Path
argument_list|(
name|pathString
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|expected
init|=
name|SwiftObjectPath
operator|.
name|fromPath
argument_list|(
name|uri
argument_list|,
name|path
argument_list|)
decl_stmt|;
specifier|final
name|SwiftObjectPath
name|actual
init|=
operator|new
name|SwiftObjectPath
argument_list|(
name|RestClientBindings
operator|.
name|extractContainerName
argument_list|(
name|uri
argument_list|)
argument_list|,
literal|"/home/tom/documents/finance.docx"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testConvertToPath ()
specifier|public
name|void
name|testConvertToPath
parameter_list|()
throws|throws
name|Throwable
block|{
name|String
name|initialpath
init|=
literal|"/dir/file1"
decl_stmt|;
name|Path
name|ipath
init|=
operator|new
name|Path
argument_list|(
name|initialpath
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|objectPath
init|=
name|SwiftObjectPath
operator|.
name|fromPath
argument_list|(
operator|new
name|URI
argument_list|(
name|initialpath
argument_list|)
argument_list|,
name|ipath
argument_list|)
decl_stmt|;
name|URI
name|endpoint
init|=
operator|new
name|URI
argument_list|(
name|ENDPOINT
argument_list|)
decl_stmt|;
name|URI
name|uri
init|=
name|SwiftRestClient
operator|.
name|pathToURI
argument_list|(
name|objectPath
argument_list|,
name|endpoint
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Inital Hadoop Path ="
operator|+
name|initialpath
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Merged URI="
operator|+
name|uri
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testRootDirProbeEmptyPath ()
specifier|public
name|void
name|testRootDirProbeEmptyPath
parameter_list|()
throws|throws
name|Throwable
block|{
name|SwiftObjectPath
name|object
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|""
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|SwiftUtils
operator|.
name|isRootDir
argument_list|(
name|object
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testRootDirProbeRootPath ()
specifier|public
name|void
name|testRootDirProbeRootPath
parameter_list|()
throws|throws
name|Throwable
block|{
name|SwiftObjectPath
name|object
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|SwiftUtils
operator|.
name|isRootDir
argument_list|(
name|object
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|assertParentOf (SwiftObjectPath p1, SwiftObjectPath p2)
specifier|private
name|void
name|assertParentOf
parameter_list|(
name|SwiftObjectPath
name|p1
parameter_list|,
name|SwiftObjectPath
name|p2
parameter_list|)
block|{
name|assertTrue
argument_list|(
name|p1
operator|.
name|toString
argument_list|()
operator|+
literal|" is not a parent of "
operator|+
name|p2
argument_list|,
name|p1
operator|.
name|isEqualToOrParentOf
argument_list|(
name|p2
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|assertNotParentOf (SwiftObjectPath p1, SwiftObjectPath p2)
specifier|private
name|void
name|assertNotParentOf
parameter_list|(
name|SwiftObjectPath
name|p1
parameter_list|,
name|SwiftObjectPath
name|p2
parameter_list|)
block|{
name|assertFalse
argument_list|(
name|p1
operator|.
name|toString
argument_list|()
operator|+
literal|" is a parent of "
operator|+
name|p2
argument_list|,
name|p1
operator|.
name|isEqualToOrParentOf
argument_list|(
name|p2
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testChildOfProbe ()
specifier|public
name|void
name|testChildOfProbe
parameter_list|()
throws|throws
name|Throwable
block|{
name|SwiftObjectPath
name|parent
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/parent"
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|parent2
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/parent2"
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|child
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/parent/child"
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|sibling
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/parent/sibling"
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|grandchild
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/parent/child/grandchild"
argument_list|)
decl_stmt|;
name|assertParentOf
argument_list|(
name|parent
argument_list|,
name|child
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|parent
argument_list|,
name|grandchild
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|child
argument_list|,
name|grandchild
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|parent
argument_list|,
name|parent
argument_list|)
expr_stmt|;
name|assertNotParentOf
argument_list|(
name|child
argument_list|,
name|parent
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|child
argument_list|,
name|child
argument_list|)
expr_stmt|;
name|assertNotParentOf
argument_list|(
name|parent
argument_list|,
name|parent2
argument_list|)
expr_stmt|;
name|assertNotParentOf
argument_list|(
name|grandchild
argument_list|,
name|parent
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
name|SWIFT_TEST_TIMEOUT
argument_list|)
DECL|method|testChildOfRoot ()
specifier|public
name|void
name|testChildOfRoot
parameter_list|()
throws|throws
name|Throwable
block|{
name|SwiftObjectPath
name|root
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/"
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|child
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"child"
argument_list|)
decl_stmt|;
name|SwiftObjectPath
name|grandchild
init|=
operator|new
name|SwiftObjectPath
argument_list|(
literal|"container"
argument_list|,
literal|"/child/grandchild"
argument_list|)
decl_stmt|;
name|assertParentOf
argument_list|(
name|root
argument_list|,
name|child
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|root
argument_list|,
name|grandchild
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|child
argument_list|,
name|grandchild
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|root
argument_list|,
name|root
argument_list|)
expr_stmt|;
name|assertNotParentOf
argument_list|(
name|child
argument_list|,
name|root
argument_list|)
expr_stmt|;
name|assertParentOf
argument_list|(
name|child
argument_list|,
name|child
argument_list|)
expr_stmt|;
name|assertNotParentOf
argument_list|(
name|grandchild
argument_list|,
name|root
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
92324468420cafba15179df0e89012df0d034f07 | 157 | java | Java | src/main/java/org/web3j/mavenplugin/ballot.java | jensenyang2004/blockchain-voting-system | 44580e421825cda09f26e06c69f009b4c7226e50 | [
"Apache-2.0"
] | 1 | 2022-01-29T13:44:40.000Z | 2022-01-29T13:44:40.000Z | src/main/java/org/web3j/mavenplugin/ballot.java | jensenyang2004/blockchain-voting-system | 44580e421825cda09f26e06c69f009b4c7226e50 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/web3j/mavenplugin/ballot.java | jensenyang2004/blockchain-voting-system | 44580e421825cda09f26e06c69f009b4c7226e50 | [
"Apache-2.0"
] | 1 | 2021-06-27T16:57:04.000Z | 2021-06-27T16:57:04.000Z | 17.444444 | 57 | 0.700637 | 996,158 | package org.web3j.mavenplugin;
public class ballot01 {
public static void main(String[] args) throws Exception{
Main1 a = new Main1();
a.start();
}
}
|
923244c70d875979f60f4f42a944a55d28dbe33d | 2,356 | java | Java | sdk/edgeorder/azure-resourcemanager-edgeorder/src/main/java/com/azure/resourcemanager/edgeorder/models/BillingMeterDetails.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/edgeorder/azure-resourcemanager-edgeorder/src/main/java/com/azure/resourcemanager/edgeorder/models/BillingMeterDetails.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/edgeorder/azure-resourcemanager-edgeorder/src/main/java/com/azure/resourcemanager/edgeorder/models/BillingMeterDetails.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 26.772727 | 96 | 0.66129 | 996,159 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.edgeorder.models;
import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Holds billing meter details for each type of billing. */
@Immutable
public final class BillingMeterDetails {
@JsonIgnore private final ClientLogger logger = new ClientLogger(BillingMeterDetails.class);
/*
* Represents Billing type name
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private String name;
/*
* Represents MeterDetails
*/
@JsonProperty(value = "meterDetails", access = JsonProperty.Access.WRITE_ONLY)
private MeterDetails meterDetails;
/*
* Represents Metering type (eg one-time or recurrent)
*/
@JsonProperty(value = "meteringType", access = JsonProperty.Access.WRITE_ONLY)
private MeteringType meteringType;
/*
* Frequency of recurrence
*/
@JsonProperty(value = "frequency", access = JsonProperty.Access.WRITE_ONLY)
private String frequency;
/**
* Get the name property: Represents Billing type name.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Get the meterDetails property: Represents MeterDetails.
*
* @return the meterDetails value.
*/
public MeterDetails meterDetails() {
return this.meterDetails;
}
/**
* Get the meteringType property: Represents Metering type (eg one-time or recurrent).
*
* @return the meteringType value.
*/
public MeteringType meteringType() {
return this.meteringType;
}
/**
* Get the frequency property: Frequency of recurrence.
*
* @return the frequency value.
*/
public String frequency() {
return this.frequency;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (meterDetails() != null) {
meterDetails().validate();
}
}
}
|
92324504258482ef30c8daeaf240f9ad9722bbd4 | 1,059 | java | Java | test-web/src/main/java/net/hserver/auth/TestPermission.java | heixiaoma/HServer-For-Java | ebb45c72d0a47dd0ce0ce33b6ab9d561b33a6b0c | [
"Apache-2.0"
] | 5 | 2020-03-16T15:07:16.000Z | 2021-01-18T13:45:21.000Z | test-web/src/main/java/net/hserver/auth/TestPermission.java | heixiaoma/HServer-For-Java | ebb45c72d0a47dd0ce0ce33b6ab9d561b33a6b0c | [
"Apache-2.0"
] | null | null | null | test-web/src/main/java/net/hserver/auth/TestPermission.java | heixiaoma/HServer-For-Java | ebb45c72d0a47dd0ce0ce33b6ab9d561b33a6b0c | [
"Apache-2.0"
] | 1 | 2020-12-13T17:51:07.000Z | 2020-12-13T17:51:07.000Z | 31.147059 | 110 | 0.741265 | 996,160 | package net.hserver.auth;
import top.hserver.core.interfaces.PermissionAdapter;
import top.hserver.core.ioc.annotation.Bean;
import top.hserver.core.ioc.annotation.RequiresPermissions;
import top.hserver.core.ioc.annotation.RequiresRoles;
import top.hserver.core.ioc.annotation.Sign;
import top.hserver.core.server.context.Webkit;
import top.hserver.core.server.util.JsonResult;
/**
* 验证逻辑请自己实现哦
*/
@Bean
public class TestPermission implements PermissionAdapter {
@Override
public void requiresPermissions(RequiresPermissions requiresPermissions, Webkit webkit) throws Exception {
System.out.println(1/0);
webkit.httpResponse.sendJson(JsonResult.ok());
System.out.println(requiresPermissions.value()[0]);
}
@Override
public void requiresRoles(RequiresRoles requiresRoles, Webkit webkit) throws Exception {
System.out.println(requiresRoles.value()[0]);
}
@Override
public void sign(Sign sign, Webkit webkit) throws Exception {
System.out.println(sign.value());
}
}
|
9232457b26e6bf2e0ccd02ea8063b1944e18d086 | 1,652 | java | Java | laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/PhpParser/namespaces/Node/classes/FunctionLike.java | RuntimeConverter/RuntimeConverterLarvelJava | 7ae848744fbcd993122347ffac853925ea4ea3b9 | [
"MIT"
] | null | null | null | laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/PhpParser/namespaces/Node/classes/FunctionLike.java | RuntimeConverter/RuntimeConverterLarvelJava | 7ae848744fbcd993122347ffac853925ea4ea3b9 | [
"MIT"
] | null | null | null | laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/PhpParser/namespaces/Node/classes/FunctionLike.java | RuntimeConverter/RuntimeConverterLarvelJava | 7ae848744fbcd993122347ffac853925ea4ea3b9 | [
"MIT"
] | null | null | null | 36.711111 | 95 | 0.743947 | 996,161 | package com.project.convertedCode.globalNamespace.namespaces.PhpParser.namespaces.Node.classes;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.project.convertedCode.globalNamespace.namespaces.PhpParser.classes.Node;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.arrays.ZPair;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php
*/
public interface FunctionLike extends Node {
public static final Object CONST_class = "PhpParser\\Node\\FunctionLike";
@ConvertedMethod
public Object returnsByRef(RuntimeEnv env, Object... args);
@ConvertedMethod
public Object getParams(RuntimeEnv env, Object... args);
@ConvertedMethod
public Object getReturnType(RuntimeEnv env, Object... args);
@ConvertedMethod
public Object getStmts(RuntimeEnv env, Object... args);
static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("PhpParser\\Node\\FunctionLike")
.setLookup(FunctionLike.class, MethodHandles.lookup())
.setLocalProperties()
.setFilename("vendor/nikic/php-parser/lib/PhpParser/Node/FunctionLike.php")
.addInterface("PhpParser\\Node")
.get();
}
|
92324596e9aaa3a42a47e5c32cee04f5bace7fb7 | 2,439 | java | Java | sts-3-eclipse-jee-2018-12-R/SpringAlternativeAnnotations/src/main/java/com/pbasu/simple/car/InjectAnnotation/WeekendCar.java | pradiptabasu/pbasu-SpringBasics | 706f157db7cebf4588ef53764a9a561adc788286 | [
"Apache-2.0"
] | null | null | null | sts-3-eclipse-jee-2018-12-R/SpringAlternativeAnnotations/src/main/java/com/pbasu/simple/car/InjectAnnotation/WeekendCar.java | pradiptabasu/pbasu-SpringBasics | 706f157db7cebf4588ef53764a9a561adc788286 | [
"Apache-2.0"
] | null | null | null | sts-3-eclipse-jee-2018-12-R/SpringAlternativeAnnotations/src/main/java/com/pbasu/simple/car/InjectAnnotation/WeekendCar.java | pradiptabasu/pbasu-SpringBasics | 706f157db7cebf4588ef53764a9a561adc788286 | [
"Apache-2.0"
] | null | null | null | 19.204724 | 103 | 0.697417 | 996,162 | package com.pbasu.simple.car.InjectAnnotation;
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.pbasu.simple.car.Engine;
import com.pbasu.simple.car.Tire;
public class WeekendCar {
//@Autowired
//@Qualifier("sTire")
@Inject
@Named("smallTire")
private Tire frontLeft;
//@Autowired
//@Qualifier("sTire")
@Inject
@Named("smallTire")
private Tire frontRight;
//@Autowired
//@Qualifier("bTire")
@Inject
@Named("bigTire")
private Tire rearLeft;
//@Autowired
//@Qualifier("bTire")
@Inject
@Named("bigTire")
private Tire rearRight;
//@Autowired
//@Qualifier("sixCylinider")
@Inject
@Named("sixCyl")
private Engine engineType;
public WeekendCar()
{
}
public WeekendCar(Tire frontLeft, Tire frontRight, Tire rearLeft, Tire rearRight, Engine engineType) {
this.frontLeft = frontLeft;
this.frontRight = frontRight;
this.rearLeft = rearLeft;
this.rearRight = rearRight;
this.engineType = engineType;
}
public Tire getFrontLeft() {
return frontLeft;
}
public void setFrontLeft(Tire frontLeft) {
this.frontLeft = frontLeft;
}
public Tire getFrontRight() {
return frontRight;
}
public void setFrontRight(Tire frontRight) {
this.frontRight = frontRight;
}
public Tire getRearLeft() {
return rearLeft;
}
public void setRearLeft(Tire rearLeft) {
this.rearLeft = rearLeft;
}
public Tire getRearRight() {
return rearRight;
}
public void setRearRight(Tire rearRight) {
this.rearRight = rearRight;
}
public Engine getEngineType() {
return engineType;
}
public void setEngineType(Engine engineType) {
this.engineType = engineType;
}
public String getCarDescription()
{
String description="";
if(frontLeft != null)
{
description += "\n\tFront Left Tire: " + frontLeft.getTireDiameter();
}
if(frontRight != null)
{
description += "\n\tFront Right Tire: " + frontRight.getTireDiameter();
}
if(rearLeft != null)
{
description += "\n\tRear Left Tire: " + rearLeft.getTireDiameter();
}
if(rearRight != null)
{
description += "\n\tRear Right Tire: " + rearRight.getTireDiameter();
}
if(engineType != null)
{
description += "\n\tEngine: " + engineType.drive();
}
if(description.equalsIgnoreCase(""))
{
description = "Not Set";
}
return description;
}
}
|
923246b260a33f777454b5764983a3023ad5da68 | 3,537 | java | Java | src/main/java/org/restheart/security/handlers/AuthenticatorMechanismWrapper.java | anniyanvr/restheart-security | c88820799f89c63f56e560155861df246f908490 | [
"Apache-2.0"
] | 7 | 2018-10-18T15:10:56.000Z | 2019-05-08T01:57:38.000Z | src/main/java/org/restheart/security/handlers/AuthenticatorMechanismWrapper.java | anniyanvr/restheart-security | c88820799f89c63f56e560155861df246f908490 | [
"Apache-2.0"
] | 4 | 2019-09-05T13:41:00.000Z | 2020-02-04T16:52:23.000Z | src/main/java/org/restheart/security/handlers/AuthenticatorMechanismWrapper.java | anniyanvr/restheart-security | c88820799f89c63f56e560155861df246f908490 | [
"Apache-2.0"
] | 1 | 2019-09-09T06:02:11.000Z | 2019-09-09T06:02:11.000Z | 36.916667 | 112 | 0.740971 | 996,163 | /*
* RESTHeart Security
*
* Copyright (C) SoftInstigate Srl
*
* 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.restheart.security.handlers;
import io.undertow.security.api.AuthenticationMechanism.AuthenticationMechanismOutcome;
import static io.undertow.security.api.AuthenticationMechanism.AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
import io.undertow.security.api.AuthenticationMechanism.ChallengeResult;
import io.undertow.security.api.SecurityContext;
import io.undertow.server.HttpServerExchange;
import org.restheart.plugins.security.AuthMechanism;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* log the wapped AuthenticatorMechanism outcomes and makes sure that it can't
* fail the whole authetication process if it doesn't authenticate the request.
*
* when multiple AuthenticatorMechanism are defined, the standard undertow
* authentication process is:
*
* As an in-bound request is received the authenticate method is called on each
* mechanism in turn until one of the following occurs: <br>
* - A mechanism successfully authenticates the incoming request. <br>
* - A mechanism attempts but fails to authenticate the request. <br>
* - The list of mechanisms is exhausted.
*
* * @see
* http://undertow.io/javadoc/2.0.x/io/undertow/security/api/AuthenticationMechanism.html
*
* The restheart-security process is:
*
* As an in-bound request is received the authenticate method is called on each
* mechanism in turn until one of the following occurs: <br>
* - A mechanism successfully authenticates the incoming request. <br>
* - The list of mechanisms is exhausted. <br>
*
* this is achieved avoiding the wrapper AuthenticationMechanism to return
* NOT_AUTHENTICATED replacing the return value with NOT_ATTEMPTED
*
*
* @author Andrea Di Cesare <dycjh@example.com>
*/
public class AuthenticatorMechanismWrapper implements AuthMechanism {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthMechanism.class);
private final AuthMechanism wrapped;
public AuthenticatorMechanismWrapper(AuthMechanism wrapped) {
this.wrapped = wrapped;
}
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange,
SecurityContext securityContext) {
AuthenticationMechanismOutcome outcome = wrapped.authenticate(exchange,
securityContext);
LOGGER.debug(wrapped.getMechanismName()
+ " -> "
+ outcome.name());
switch (outcome) {
case NOT_AUTHENTICATED:
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
default:
return outcome;
}
}
@Override
public ChallengeResult sendChallenge(HttpServerExchange exchange,
SecurityContext securityContext) {
return wrapped.sendChallenge(exchange, securityContext);
}
@Override
public String getMechanismName() {
return wrapped.getMechanismName();
}
}
|
92324840483278d11269e0728f61bfeb4c5b46c2 | 3,007 | java | Java | conductor-client/src/main/java/com/openlattice/postgres/mapstores/AppMapstore.java | openlattice/openlattice | c570a08a9d9ce7fb5aaed89b8c23ba8d73e8ad27 | [
"Apache-2.0"
] | 3 | 2021-06-02T13:14:12.000Z | 2021-09-09T19:36:55.000Z | conductor-client/src/main/java/com/openlattice/postgres/mapstores/AppMapstore.java | openlattice/openlattice | c570a08a9d9ce7fb5aaed89b8c23ba8d73e8ad27 | [
"Apache-2.0"
] | 48 | 2018-09-14T07:05:29.000Z | 2022-03-22T08:42:24.000Z | conductor-client/src/main/java/com/openlattice/postgres/mapstores/AppMapstore.java | openlattice/openlattice | c570a08a9d9ce7fb5aaed89b8c23ba8d73e8ad27 | [
"Apache-2.0"
] | 1 | 2017-07-27T15:10:06.000Z | 2017-07-27T15:10:06.000Z | 36.228916 | 108 | 0.671101 | 996,164 | package com.openlattice.postgres.mapstores;
import com.dataloom.mappers.ObjectMappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openlattice.apps.App;
import com.openlattice.hazelcast.HazelcastMap;
import com.openlattice.mapstores.TestDataFactory;
import com.openlattice.postgres.PostgresTable;
import com.openlattice.postgres.ResultSetAdapters;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
public class AppMapstore extends AbstractBasePostgresMapstore<UUID, App> {
private static final ObjectMapper mapper = ObjectMappers.getJsonMapper();
public AppMapstore( HikariDataSource hds ) {
super( HazelcastMap.APPS, PostgresTable.APPS, hds );
}
@Override protected void bind( PreparedStatement ps, UUID key, App value ) throws SQLException {
String rolesAsString = "[]";
String settingsAsString = "{}";
try {
rolesAsString = mapper.writeValueAsString( value.getAppRoles() );
settingsAsString = mapper.writeValueAsString( value.getDefaultSettings() );
} catch ( JsonProcessingException e ) {
logger.error( "Unable to write AppRoles as string for app {}: {}", key, value, e );
}
int index = bind( ps, key, 1 );
ps.setString( index++, value.getName() );
ps.setString( index++, value.getTitle() );
ps.setString( index++, value.getDescription() );
ps.setObject( index++, value.getEntityTypeCollectionId() );
ps.setString( index++, value.getUrl() );
ps.setString( index++, rolesAsString );
ps.setString( index++, settingsAsString );
// UPDATE
ps.setString( index++, value.getName() );
ps.setString( index++, value.getTitle() );
ps.setString( index++, value.getDescription() );
ps.setObject( index++, value.getEntityTypeCollectionId() );
ps.setString( index++, value.getUrl() );
ps.setString( index++, rolesAsString );
ps.setString( index++, settingsAsString );
}
@Override protected int bind( PreparedStatement ps, UUID key, int parameterIndex ) throws SQLException {
ps.setObject( parameterIndex++, key );
return parameterIndex;
}
@Override protected App mapToValue( ResultSet rs ) throws SQLException {
try {
return ResultSetAdapters.app( rs );
} catch ( IOException e ) {
logger.error( "Could not deserialize app from ResultSet", e );
return null;
}
}
@Override protected UUID mapToKey( ResultSet rs ) throws SQLException {
return ResultSetAdapters.id( rs );
}
@Override public UUID generateTestKey() {
return UUID.randomUUID();
}
@Override public App generateTestValue() {
return TestDataFactory.app();
}
}
|
923249dce32a9f59652437b5ef310ceb26b5d274 | 1,405 | java | Java | platform/main/armedbear-j-src/gnu/regexp/CharIndexedCharArray.java | TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | 31ce724b21468bee0693dfc1d0ca4bc861c58e2b | [
"Apache-2.0"
] | 10 | 2016-09-03T18:41:14.000Z | 2020-01-17T16:29:19.000Z | platform/main/armedbear-j-src/gnu/regexp/CharIndexedCharArray.java | TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | 31ce724b21468bee0693dfc1d0ca4bc861c58e2b | [
"Apache-2.0"
] | 3 | 2016-09-01T19:15:27.000Z | 2016-10-12T16:28:48.000Z | platform/main/armedbear-j-src/gnu/regexp/CharIndexedCharArray.java | TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | 31ce724b21468bee0693dfc1d0ca4bc861c58e2b | [
"Apache-2.0"
] | 1 | 2017-11-21T13:29:31.000Z | 2017-11-21T13:29:31.000Z | 29.893617 | 76 | 0.690391 | 996,165 | /*
* gnu/regexp/CharIndexedCharArray.java
* Copyright (C) 1998-2001 Wes Biggs
*
* This library 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 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package gnu.regexp;
import java.io.Serializable;
class CharIndexedCharArray implements CharIndexed, Serializable {
private char[] s;
private int anchor;
CharIndexedCharArray(char[] str, int index) {
s = str;
anchor = index;
}
@Override
public char charAt(int index) {
int pos = anchor + index;
return ((pos < s.length) && (pos >= 0)) ? s[pos] : OUT_OF_BOUNDS;
}
@Override
public boolean isValid() {
return (anchor < s.length);
}
@Override
public boolean move(int index) {
return ((anchor += index) < s.length);
}
}
|
92324a2e2436c8309550cee3a741a966417b3695 | 933 | java | Java | src/main/java/io/frjufvjn/lab/vertx_mybatis/factory/MyBatisConnectionFactory.java | frjufvjn/vertx-mybatis | 6e49036142f9285542554b4ec7541e73f7537e02 | [
"MIT"
] | 25 | 2018-10-18T22:17:03.000Z | 2022-03-02T14:18:23.000Z | src/main/java/io/frjufvjn/lab/vertx_mybatis/factory/MyBatisConnectionFactory.java | frjufvjn/vertx-mybatis | 6e49036142f9285542554b4ec7541e73f7537e02 | [
"MIT"
] | 6 | 2018-09-22T05:15:46.000Z | 2020-11-10T01:23:28.000Z | src/main/java/io/frjufvjn/lab/vertx_mybatis/factory/MyBatisConnectionFactory.java | frjufvjn/vertx-mybatis | 6e49036142f9285542554b4ec7541e73f7537e02 | [
"MIT"
] | 6 | 2019-01-18T04:18:34.000Z | 2020-11-12T01:36:18.000Z | 25.216216 | 70 | 0.749196 | 996,166 | package io.frjufvjn.lab.vertx_mybatis.factory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisConnectionFactory {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "config/db-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
}
catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
catch (IOException iOException) {
iOException.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
|
92324a6c77870a1f0a599d506425368dfc1d3510 | 196 | java | Java | output/rec1.java | sgolitsynskiy/playerc | 5ca0a71503389fb5562153feee69f34e8de14b2c | [
"Unlicense"
] | null | null | null | output/rec1.java | sgolitsynskiy/playerc | 5ca0a71503389fb5562153feee69f34e8de14b2c | [
"Unlicense"
] | null | null | null | output/rec1.java | sgolitsynskiy/playerc | 5ca0a71503389fb5562153feee69f34e8de14b2c | [
"Unlicense"
] | null | null | null | 14 | 48 | 0.668367 | 996,167 | public class rec1
{
public String name;
public int age;
public boolean cool;
public rec1(String name, int age, boolean cool)
{
this.name = name;
this.age = age;
this.cool = cool;
}
}
|
92324abd01be28ac8dc7db5cba9c59aded97315e | 1,040 | java | Java | src/main/java/com/github/quiram/course/collectors/e/errors/vehicles/Vehicle.java | quiram/course-stream-collectors | 236577de7cbc4a57be85f5099bbe61d84871cf0c | [
"MIT"
] | 7 | 2020-09-28T14:50:00.000Z | 2022-02-06T09:57:58.000Z | src/main/java/com/github/quiram/course/collectors/e/errors/vehicles/Vehicle.java | quiram/course-stream-collectors | 236577de7cbc4a57be85f5099bbe61d84871cf0c | [
"MIT"
] | null | null | null | src/main/java/com/github/quiram/course/collectors/e/errors/vehicles/Vehicle.java | quiram/course-stream-collectors | 236577de7cbc4a57be85f5099bbe61d84871cf0c | [
"MIT"
] | 16 | 2020-09-28T14:15:02.000Z | 2022-02-03T11:49:16.000Z | 28.108108 | 83 | 0.657692 | 996,168 | package com.github.quiram.course.collectors.e.errors.vehicles;
import java.util.Random;
import java.util.stream.IntStream;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
public abstract class Vehicle {
private final String registration;
public static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
protected Vehicle() {
registration = generateRegistrationNumber();
}
private String generateRegistrationNumber() {
final Random random = new Random();
return IntStream.range(0, 7)
.map(i -> random.nextInt(CHARACTERS.length()))
.mapToObj(CHARACTERS::charAt)
.map(c -> Character.toString(c))
.collect(joining());
}
public abstract int numberOfWheels();
private String type() {
return this.getClass().getSimpleName().toLowerCase();
}
@Override
public String toString() {
return format("%s (%s)", registration, type());
}
}
|
92324b5802172ac8675dc31a9088d7be9a7b0d62 | 457 | java | Java | Aula-Java-Loiane/pooLoianeG/src/ExercicioZoologico/Mamifero.java | MarceloJbCosta/Curso-Java-Loiane | edaee5159ab1f6eab9093340565ba6eedb547749 | [
"MIT"
] | null | null | null | Aula-Java-Loiane/pooLoianeG/src/ExercicioZoologico/Mamifero.java | MarceloJbCosta/Curso-Java-Loiane | edaee5159ab1f6eab9093340565ba6eedb547749 | [
"MIT"
] | null | null | null | Aula-Java-Loiane/pooLoianeG/src/ExercicioZoologico/Mamifero.java | MarceloJbCosta/Curso-Java-Loiane | edaee5159ab1f6eab9093340565ba6eedb547749 | [
"MIT"
] | null | null | null | 16.925926 | 55 | 0.669584 | 996,169 | package ExercicioZoologico;
public class Mamifero extends Animal{
@Override
public String toString() {
return super.toString() + "\nAlimento: " + alimento ;
}
private String alimento;
public Mamifero() {
super();
this.setAmbiente("Terra");
this.setCor("Castanho");
this.alimento = "mel";
}
public String getAlimento() {
return alimento;
}
public void setAlimento(String alimento) {
this.alimento = alimento;
}
}
|
92324bdcb59baa1e543fa4182d037196c646f9f9 | 936 | java | Java | new-api-gateway/src/main/java/com/open/capacity/client/task/ScheduledTask.java | zhjamie/opc | 4f1cd63618ab075792e017426698464af6055d2a | [
"Apache-2.0"
] | 1 | 2020-02-08T04:46:45.000Z | 2020-02-08T04:46:45.000Z | new-api-gateway/src/main/java/com/open/capacity/client/task/ScheduledTask.java | zhjamie/opc | 4f1cd63618ab075792e017426698464af6055d2a | [
"Apache-2.0"
] | null | null | null | new-api-gateway/src/main/java/com/open/capacity/client/task/ScheduledTask.java | zhjamie/opc | 4f1cd63618ab075792e017426698464af6055d2a | [
"Apache-2.0"
] | null | null | null | 31.2 | 82 | 0.75641 | 996,170 | package com.open.capacity.client.task;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.open.capacity.client.service.impl.SysClientServiceImpl;
@Component
@Order(1)
public class ScheduledTask implements CommandLineRunner {
private static Logger log = LoggerFactory.getLogger(ScheduledTask.class);
@Resource
SysClientServiceImpl sysClientServiceImpl;
//启动全部加载一次同步
public void run(String... args) throws Exception {
log.info("同步数据库信息开始:");
long startTimeLog = System.currentTimeMillis();
sysClientServiceImpl.loadAllClientToCache();
long endTimeLog = System.currentTimeMillis();
log.info("同步数据库里的信息结束耗时(ms):{}", Long.valueOf(endTimeLog - startTimeLog));
}
} |
92324d9f7ba5aad5639399246803aac3d08d9e2f | 613 | java | Java | Mobile App/Code/sources/com/google/android/gms/internal/C1500es.java | shivi98g/EpilNet-EpilepsyPredictor | 15a98fb9ac7ee535005fb2aebb36548f28c7f6d1 | [
"MIT"
] | null | null | null | Mobile App/Code/sources/com/google/android/gms/internal/C1500es.java | shivi98g/EpilNet-EpilepsyPredictor | 15a98fb9ac7ee535005fb2aebb36548f28c7f6d1 | [
"MIT"
] | null | null | null | Mobile App/Code/sources/com/google/android/gms/internal/C1500es.java | shivi98g/EpilNet-EpilepsyPredictor | 15a98fb9ac7ee535005fb2aebb36548f28c7f6d1 | [
"MIT"
] | null | null | null | 27.863636 | 66 | 0.738989 | 996,171 | package com.google.android.gms.internal;
import com.google.android.gms.ads.purchase.InAppPurchaseListener;
import com.google.android.gms.internal.C1485en;
@C1507ey
/* renamed from: com.google.android.gms.internal.es */
public final class C1500es extends C1485en.C1486a {
/* renamed from: oM */
private final InAppPurchaseListener f3039oM;
public C1500es(InAppPurchaseListener inAppPurchaseListener) {
this.f3039oM = inAppPurchaseListener;
}
/* renamed from: a */
public void mo15234a(C1482em emVar) {
this.f3039oM.onInAppPurchaseRequested(new C1504ev(emVar));
}
}
|
92324f11a662e2883e544e6fd6dfbd1e10169ea7 | 2,893 | java | Java | oasys-service/oasys-user/src/main/java/cn/linter/oasys/user/entity/User.java | wuchunfu/OASys | e601b8397f5fcb1542406f51d36f18b4bddb26a7 | [
"Apache-2.0"
] | 2 | 2019-12-25T08:04:22.000Z | 2019-12-25T08:24:25.000Z | oasys-service/oasys-user/src/main/java/cn/linter/oasys/user/entity/User.java | citrucn/OaSys | e601b8397f5fcb1542406f51d36f18b4bddb26a7 | [
"Apache-2.0"
] | null | null | null | oasys-service/oasys-user/src/main/java/cn/linter/oasys/user/entity/User.java | citrucn/OaSys | e601b8397f5fcb1542406f51d36f18b4bddb26a7 | [
"Apache-2.0"
] | null | null | null | 28.087379 | 121 | 0.624265 | 996,172 | package cn.linter.oasys.user.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;
import javax.validation.Valid;
import javax.validation.constraints.*;
import javax.validation.groups.ConvertGroup;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户实体类
*
* @author wangxiaoyang
* @since 2020/11/01
*/
@Data
@ToString
@EqualsAndHashCode
public class User {
/**
* 用户ID
*/
@NotNull(message = "用户ID不能为空", groups = {Update.class})
private Long id;
/**
* 用户名
*/
@NotBlank(message = "用户名不能为空", groups = {Create.class})
@Length(min = 2, max = 20, message = "用户名长度为 2 到 20 之间", groups = {Create.class, Update.class})
private String username;
/**
* 密码
*/
@NotBlank(message = "密码不能为空", groups = {Create.class})
@Length(min = 6, max = 20, message = "密码长度为 6 到 20 之间", groups = {Create.class, Update.class})
private String password;
/**
* 姓名
*/
@NotBlank(message = "姓名不能为空", groups = {Create.class})
@Length(min = 2, max = 10, message = "姓名长度为 2 到 10 之间", groups = {Create.class, Update.class})
private String fullName;
/**
* 性别
*/
@NotBlank(message = "性别不能为空", groups = {Create.class})
@Pattern(regexp = "^([男女])$", message = "性别只能为男或女", groups = {Create.class, Update.class})
private String gender;
/**
* 部门
*/
@NotNull(message = "部门不能为空", groups = {Create.class})
@Valid
@ConvertGroup.List({@ConvertGroup(from = Create.class, to = Dept.UserNested.class)})
private Dept dept;
/**
* 角色
*/
@NotEmpty(message = "角色不能为空", groups = {Create.class})
private List<@Valid @ConvertGroup.List({@ConvertGroup(from = Create.class, to = Role.UserNested.class)}) Role> roles;
/**
* 邮箱地址
*/
@NotBlank(message = "邮箱地址不能为空", groups = {Create.class})
@Email(message = "邮箱地址格式不正确", groups = {Create.class, Update.class})
private String emailAddress;
/**
* 手机号码
*/
@NotBlank(message = "手机号码不能为空", groups = {Create.class})
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号码格式不正确", groups = {Create.class, Update.class})
private String phoneNumber;
/**
* 头像链接
*/
@NotBlank(message = "头像链接不能为空", groups = {Create.class})
@URL(message = "头像链接必须是一个URL", groups = {Create.class, Update.class})
private String profilePicture;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
/**
* 修改时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime updateTime;
public interface Create {
}
public interface Update {
}
} |
92324f1919bf86372705d3bb39187169b1637dfc | 12,628 | java | Java | app/src/main/java/org/dbhatt/d_deleted_contact/Deleted_contact.java | devdattbhatt/DDeletedContact | 7b11651d038369bafbd7e910c2420a9ade281044 | [
"Apache-2.0"
] | 3 | 2017-12-05T13:55:28.000Z | 2021-08-06T07:10:52.000Z | app/src/main/java/org/dbhatt/d_deleted_contact/Deleted_contact.java | devdattbhatt/DDeletedContact | 7b11651d038369bafbd7e910c2420a9ade281044 | [
"Apache-2.0"
] | 1 | 2018-06-21T15:47:28.000Z | 2018-06-21T15:47:28.000Z | app/src/main/java/org/dbhatt/d_deleted_contact/Deleted_contact.java | devdattbhatt/DDeletedContact | 7b11651d038369bafbd7e910c2420a9ade281044 | [
"Apache-2.0"
] | null | null | null | 46.597786 | 182 | 0.555908 | 996,173 | /*
* Copyright (c) 2016. Devdatt s bhatt
*
* 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.dbhatt.d_deleted_contact;
import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by devsb on 18-09-2016.
*/
public class Deleted_contact extends RecyclerView.Adapter<Deleted_contact.Contact> {
private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1433;
private MainActivity mainActivity;
private Context context;
private boolean rtl = false;
private Random rnd;
private Paint paint;
private ArrayList<org.dbhatt.d_deleted_contact.data.Contact> deleted_contact;
Deleted_contact(ArrayList<org.dbhatt.d_deleted_contact.data.Contact> all_contact, Context context, MainActivity mainActivity) {
try {
this.deleted_contact = all_contact;
rnd = new Random();
paint = new Paint();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
rtl = context.getResources().getConfiguration().getLayoutDirection() != View.LAYOUT_DIRECTION_LTR;
this.context = context;
this.mainActivity = mainActivity;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Contact onCreateViewHolder(ViewGroup parent, int viewType) {
return new Contact(LayoutInflater.from(parent.getContext()).inflate(R.layout.deleted_contact, parent, false));
}
@Override
public void onBindViewHolder(Contact holder, int position) {
try {
org.dbhatt.d_deleted_contact.data.Contact contact = deleted_contact.get(position);
holder.contact_name.setText(contact.getName());
holder.account_type.setText(contact.getAccount_type());
new Load_Contact_Photo(holder.contact_photo, contact.getName()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_SHORT).show();
}
}
@Override
public int getItemCount() {
return deleted_contact.size();
}
class Contact extends RecyclerView.ViewHolder {
CardView contact_raw;
TextView contact_name, account_type;
ImageView contact_photo;
Contact(View itemView) {
super(itemView);
try {
contact_raw = (CardView) itemView.findViewById(R.id.contact_raw);
contact_name = (TextView) itemView.findViewById(R.id.contact_name);
account_type = (TextView) itemView.findViewById(R.id.contact_account_type);
contact_photo = (ImageView) itemView.findViewById(R.id.contact_photo);
contact_raw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(deleted_contact.get(getAdapterPosition()).getName());
builder.setNegativeButton(R.string.restore, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
if (Build.VERSION.SDK_INT > 22) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
restore_one_contact();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(mainActivity, Manifest.permission.WRITE_CONTACTS)) {
new AlertDialog.Builder(context)
.setTitle(R.string.permission)
.setMessage(R.string.permission_message_write_external_storage)
.setPositiveButton(R.string.permission_grant, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(mainActivity,
new String[]{Manifest.permission.WRITE_CONTACTS},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
}).create().show();
} else {
ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
} else {
restore_one_contact();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_SHORT).show();
}
}
});
builder.create().show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_LONG).show();
}
}
private void restore_one_contact() {
/* this function
recovers one selected contact
*/
try {
ArrayList<ContentProviderOperation> ops = new ArrayList();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter("caller_is_syncadapter", "true").build())
.withSelection(ContactsContract.RawContacts._ID + "=?", new String[]{String.valueOf(deleted_contact.get(getAdapterPosition()).getId())})
.withValue(ContactsContract.RawContacts.DELETED, 0)
.withYieldAllowed(true)
.build());
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_SHORT).show();
}
try {
mainActivity.add_to_all_contact(deleted_contact.get(getAdapterPosition()));
deleted_contact.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
} catch (Exception e) {
e.printStackTrace();
}
try {
if (deleted_contact.size() == 0)
mainActivity.update_delete();
} catch (Exception e) {
e.printStackTrace();
}
try {
mainActivity.ask_for_ratings();
} catch (Exception e) {
e.printStackTrace();
}
}
private void delete_one_contact() {
try {
ArrayList<ContentProviderOperation> ops = new ArrayList();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter("caller_is_syncadapter", "true").build())
.withSelection(ContactsContract.RawContacts._ID + "=?", new String[]{String.valueOf(deleted_contact.get(getAdapterPosition()).getId())})
.withValue(ContactsContract.RawContacts.DELETED, 1)
.withYieldAllowed(true)
.build());
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_SHORT).show();
}
}
}
private class Load_Contact_Photo extends AsyncTask<Void, Void, Bitmap> {
String contact_name;
private final WeakReference<ImageView> imageViewReference;
Load_Contact_Photo(ImageView imageView, String contact_name) {
this.imageViewReference = new WeakReference<>(imageView);
this.contact_name = contact_name;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
Bitmap bitmap_photo = null;
Canvas canvas = null;
bitmap_photo = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap_photo);
if (rtl)
contact_name = contact_name.substring(contact_name.length() - 1);
else
contact_name = contact_name.substring(0, 1);
paint.setStyle(Paint.Style.FILL);
paint.setARGB(255, rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255));
canvas.drawPaint(paint);
paint.setColor(Color.WHITE);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(30);
paint.setTypeface(Typeface.create("Arial", Typeface.BOLD));
canvas.drawText(contact_name, 25, 35, paint);
return bitmap_photo;
} catch (Exception e) {
e.printStackTrace();
return BitmapFactory.decodeResource(context.getResources(), R.drawable.developer);
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
try {
if (bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, R.string.contact_developer, Toast.LENGTH_LONG).show();
}
}
}
} |
92324fe13f0ef7d6f8ba0e83ad276872247fa0f7 | 2,487 | java | Java | src/main/java/de/thinkbaer/aios/server/TransportChannelInboundHandlerImpl.java | thinkbaer/aios | fd15b5013a6baf500e407c0a77cfd9a2814202d5 | [
"MIT"
] | 2 | 2015-07-10T17:26:09.000Z | 2016-06-20T13:21:18.000Z | src/main/java/de/thinkbaer/aios/server/TransportChannelInboundHandlerImpl.java | thinkbaer/aios | fd15b5013a6baf500e407c0a77cfd9a2814202d5 | [
"MIT"
] | 9 | 2015-07-13T09:50:52.000Z | 2021-12-18T18:17:31.000Z | src/main/java/de/thinkbaer/aios/server/TransportChannelInboundHandlerImpl.java | thinkbaer/aios | fd15b5013a6baf500e407c0a77cfd9a2814202d5 | [
"MIT"
] | null | null | null | 28.261364 | 120 | 0.703257 | 996,174 | package de.thinkbaer.aios.server;
import de.thinkbaer.aios.api.exception.AiosException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import javax.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import de.thinkbaer.aios.api.action.support.OperationRequest;
import de.thinkbaer.aios.api.transport.Transport;
import de.thinkbaer.aios.server.action.OperationResponseHandler;
public class TransportChannelInboundHandlerImpl extends SimpleChannelInboundHandler<Transport> implements
TransportChannelInboundHandler {
// private static final Logger L = LogManager.getLogger(
// ExchangeChannelInboundHandlerImpl.class );
private Logger L;
@Inject
private ResponseHandlerDispatcher dispatcher;
public TransportChannelInboundHandlerImpl() {
super(true);
L = LogManager.getLogger("channel.inbound.server");
}
protected void channelRead0(ChannelHandlerContext ctx, Transport exchange_2) throws Exception {
if (exchange_2 instanceof OperationRequest) {
OperationResponseHandler<?, ?, ?> oph = dispatcher.inject(ctx.channel(), (OperationRequest) exchange_2);
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
oph.execute();
} catch (Exception e) {
L.error("processing error: " + e.getMessage());
L.throwing(e);
Transport response = oph.createResponse();
response.addError(new AiosException(e).asErrorMessage());
ctx.channel().writeAndFlush(response);
}
}
});
}
}
private void handleResponse(ChannelHandlerContext ctx, Transport response, boolean sync) throws InterruptedException {
try {
ChannelFuture writeFuture = ctx.write(response);
if (sync) {
writeFuture.sync();
}
} catch (Exception e) {
L.throwing(e);
}
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
L.throwing(cause);
L.debug("Channel closed");
ctx.close();
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
// Once session is secured, send a greeting and register the channel to
// the global channel
// list so the channel received the messages from others.
L.debug("Channel active");
}
}
|
92325020692bb6bd58b365910329c8ee2316e450 | 1,198 | java | Java | sensingservices/src/main/java/com/navatar/sensing/NavatarSensor.java | Hariprasath88/Navatar | d3af91db956d0a94cd5437905ef30a4f2e628015 | [
"MIT"
] | 5 | 2016-09-20T17:30:58.000Z | 2018-10-02T14:44:17.000Z | sensingservices/src/main/java/com/navatar/sensing/NavatarSensor.java | Hariprasath88/Navatar | d3af91db956d0a94cd5437905ef30a4f2e628015 | [
"MIT"
] | 4 | 2016-09-09T23:24:08.000Z | 2020-03-30T17:06:39.000Z | sensingservices/src/main/java/com/navatar/sensing/NavatarSensor.java | Hariprasath88/Navatar | d3af91db956d0a94cd5437905ef30a4f2e628015 | [
"MIT"
] | 8 | 2016-09-20T17:31:01.000Z | 2019-01-25T05:00:57.000Z | 28.52381 | 75 | 0.72788 | 996,175 | package com.navatar.sensing;
import java.util.LinkedList;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public abstract class NavatarSensor implements SensorEventListener
{
public static final int ACCELEROMETER = 0;
public static final int GYROSCOPE = 1;
public static final int COMPASS = 2;
public static final int PEDOMETER = 3;
public static final int GYRO_COMPASS = 4;
protected int[] types, delays;
protected SensorManager mgr;
protected LinkedList<NavatarSensorListener> listeners;
protected NavatarSensor(SensorManager mgr) {
listeners = new LinkedList<NavatarSensorListener>();
this.mgr = mgr;
}
public void registerSensorListener(NavatarSensorListener listener) {
if(listeners.size() == 0) {
for(int i=0; i<types.length; ++i)
mgr.registerListener(this, mgr.getDefaultSensor(types[i]), delays[i]);
}
listeners.add(listener);
}
public void unregisterSensorListener(NavatarSensorListener listener) {
listeners.remove(listener);
if(listeners.size() == 0) {
for(int i=0; i<types.length; ++i)
mgr.unregisterListener(this, mgr.getDefaultSensor(types[i]));
}
}
} |
9232507e9f059ee99e52962fe8fbc1af21e028cd | 1,000 | java | Java | src/test/java/com/sample/tests/pages/banking/CustomersPage.java | movilidadagil/JavaUIAutomationFramework | 9a0acfca140a946c6cfccce8107f63921025cc12 | [
"Apache-2.0"
] | 1 | 2017-11-26T00:54:01.000Z | 2017-11-26T00:54:01.000Z | src/test/java/com/sample/tests/pages/banking/CustomersPage.java | movilidadagil/JavaUIAutomationFramework | 9a0acfca140a946c6cfccce8107f63921025cc12 | [
"Apache-2.0"
] | 2 | 2017-07-30T02:46:34.000Z | 2017-09-10T10:15:51.000Z | src/test/java/com/sample/tests/pages/banking/CustomersPage.java | movilidadagil/JavaUIAutomationFramework | 9a0acfca140a946c6cfccce8107f63921025cc12 | [
"Apache-2.0"
] | 1 | 2020-11-07T21:55:55.000Z | 2020-11-07T21:55:55.000Z | 31.25 | 69 | 0.694 | 996,176 | package com.sample.tests.pages.banking;
import org.openqa.selenium.WebDriver;
import com.sample.framework.kdt.Alias;
import com.sample.framework.ui.FindBy;
import com.sample.framework.ui.Page;
import com.sample.framework.ui.SubItem;
import com.sample.framework.ui.controls.TableView;
@Alias("Customers")
public class CustomersPage extends BankManagerCommonPage {
public CustomersPage(WebDriver driverValue) {
super(driverValue);
}
@Alias("Customer List")
@FindBy(locator = "//table", itemLocator = "/tbody/tr")
@SubItem(name = "First Name", locator = "/td[1]")
@SubItem(name = "Last Name", locator = "/td[2]")
@SubItem(name = "Post Code", locator = "/td[3]")
@SubItem(name = "Account Number", locator = "/td[4]")
@SubItem(name = "Delete Customer", locator = "/td[5]/button")
public TableView tableCustomers;
@Override
public Page navigate() throws Exception {
return this.buttonCustomers.clickAndWaitFor(this.getClass());
}
}
|
92325080e0c0b38582f55019b5f7bc82eebdf2c7 | 11,377 | java | Java | dropwizard-service-discovery-bundle/src/main/java/io/appform/dropwizard/discovery/bundle/ServiceDiscoveryBundle.java | pradurg/dropwizard-service-discovery | 7a1c819c3cdbba685399e278c909c972e312a90b | [
"Apache-2.0"
] | 14 | 2016-03-13T15:50:03.000Z | 2021-08-22T02:55:21.000Z | dropwizard-service-discovery-bundle/src/main/java/io/appform/dropwizard/discovery/bundle/ServiceDiscoveryBundle.java | pradurg/dropwizard-service-discovery | 7a1c819c3cdbba685399e278c909c972e312a90b | [
"Apache-2.0"
] | 4 | 2018-09-26T04:57:04.000Z | 2021-12-16T09:57:01.000Z | dropwizard-service-discovery-bundle/src/main/java/io/appform/dropwizard/discovery/bundle/ServiceDiscoveryBundle.java | pradurg/dropwizard-service-discovery | 7a1c819c3cdbba685399e278c909c972e312a90b | [
"Apache-2.0"
] | 23 | 2016-03-13T15:35:11.000Z | 2021-06-27T19:19:41.000Z | 42.159259 | 135 | 0.694984 | 996,177 | /*
* Copyright (c) 2019 Santanu Sinha <ychag@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 io.appform.dropwizard.discovery.bundle;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.ranger.ServiceProviderBuilders;
import com.flipkart.ranger.healthcheck.Healthcheck;
import com.flipkart.ranger.healthservice.TimeEntity;
import com.flipkart.ranger.healthservice.monitor.IsolatedHealthMonitor;
import com.flipkart.ranger.serviceprovider.ServiceProvider;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.appform.dropwizard.discovery.bundle.healthchecks.InitialDelayChecker;
import io.appform.dropwizard.discovery.bundle.healthchecks.InternalHealthChecker;
import io.appform.dropwizard.discovery.bundle.healthchecks.RotationCheck;
import io.appform.dropwizard.discovery.bundle.id.IdGenerator;
import io.appform.dropwizard.discovery.bundle.id.NodeIdManager;
import io.appform.dropwizard.discovery.bundle.id.constraints.IdValidationConstraint;
import io.appform.dropwizard.discovery.bundle.monitors.DropwizardHealthMonitor;
import io.appform.dropwizard.discovery.bundle.monitors.DropwizardServerStartupCheck;
import io.appform.dropwizard.discovery.bundle.rotationstatus.BIRTask;
import io.appform.dropwizard.discovery.bundle.rotationstatus.DropwizardServerStatus;
import io.appform.dropwizard.discovery.bundle.rotationstatus.OORTask;
import io.appform.dropwizard.discovery.bundle.rotationstatus.RotationStatus;
import io.appform.dropwizard.discovery.client.ServiceDiscoveryClient;
import io.appform.dropwizard.discovery.common.ShardInfo;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.lifecycle.Managed;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryForever;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* A dropwizard bundle for service discovery.
*/
@Slf4j
public abstract class ServiceDiscoveryBundle<T extends Configuration> implements ConfiguredBundle<T> {
private ServiceDiscoveryConfiguration serviceDiscoveryConfiguration;
private List<Healthcheck> healthchecks = Lists.newArrayList();
private ServiceProvider<ShardInfo> serviceProvider;
private final List<IdValidationConstraint> globalIdConstraints;
@Getter
private CuratorFramework curator;
@Getter
private ServiceDiscoveryClient serviceDiscoveryClient;
@Getter
@VisibleForTesting
private RotationStatus rotationStatus;
@Getter
@VisibleForTesting
private DropwizardServerStatus serverStatus;
protected ServiceDiscoveryBundle() {
globalIdConstraints = Collections.emptyList();
}
protected ServiceDiscoveryBundle(List<IdValidationConstraint> globalIdConstraints) {
this.globalIdConstraints = globalIdConstraints != null
? globalIdConstraints
: Collections.emptyList();
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
}
@Override
public void run(T configuration, Environment environment) throws Exception {
serviceDiscoveryConfiguration = getRangerConfiguration(configuration);
val objectMapper = environment.getObjectMapper();
final String namespace = serviceDiscoveryConfiguration.getNamespace();
final String serviceName = getServiceName(configuration);
final String hostname = getHost();
final int port = getPort(configuration);
rotationStatus = new RotationStatus(serviceDiscoveryConfiguration.isInitialRotationStatus());
serverStatus = new DropwizardServerStatus(false);
curator = CuratorFrameworkFactory.builder()
.connectString(serviceDiscoveryConfiguration.getZookeeper())
.namespace(namespace)
.retryPolicy(new RetryForever(serviceDiscoveryConfiguration.getConnectionRetryIntervalMillis()))
.build();
serviceProvider = buildServiceProvider(
environment,
objectMapper,
namespace,
serviceName,
hostname,
port
);
serviceDiscoveryClient = buildDiscoveryClient(
environment,
namespace,
serviceName);
environment.lifecycle()
.manage(new ServiceDiscoveryManager(serviceName));
environment.jersey()
.register(new InfoResource(serviceDiscoveryClient));
environment.admin()
.addTask(new OORTask(rotationStatus));
environment.admin()
.addTask(new BIRTask(rotationStatus));
}
protected abstract ServiceDiscoveryConfiguration getRangerConfiguration(T configuration);
protected abstract String getServiceName(T configuration);
protected List<IsolatedHealthMonitor> getHealthMonitors() {
return Lists.newArrayList();
}
protected int getPort(T configuration) {
Preconditions.checkArgument(
Constants.DEFAULT_PORT != serviceDiscoveryConfiguration.getPublishedPort()
&& 0 != serviceDiscoveryConfiguration.getPublishedPort(),
"Looks like publishedPost has not been set and getPort() has not been overridden. This is wrong. \n" +
"Either set publishedPort in config or override getPort() to return the port on which the service is running");
return serviceDiscoveryConfiguration.getPublishedPort();
}
protected String getHost() throws UnknownHostException {
final String host = serviceDiscoveryConfiguration.getPublishedHost();
if (Strings.isNullOrEmpty(host) || host.equals(Constants.DEFAULT_HOST)) {
return InetAddress.getLocalHost()
.getCanonicalHostName();
}
return host;
}
public void registerHealthcheck(Healthcheck healthcheck) {
this.healthchecks.add(healthcheck);
}
public void registerHealthchecks(List<Healthcheck> healthchecks) {
this.healthchecks.addAll(healthchecks);
}
private ServiceDiscoveryClient buildDiscoveryClient(
Environment environment,
String namespace,
String serviceName) {
return ServiceDiscoveryClient.fromCurator()
.curator(curator)
.namespace(namespace)
.serviceName(serviceName)
.environment(serviceDiscoveryConfiguration.getEnvironment())
.objectMapper(environment.getObjectMapper())
.refreshTimeMs(serviceDiscoveryConfiguration.getRefreshTimeMs())
.disableWatchers(serviceDiscoveryConfiguration.isDisableWatchers())
.build();
}
private ServiceProvider<ShardInfo> buildServiceProvider(
Environment environment,
ObjectMapper objectMapper,
String namespace,
String serviceName,
String hostname,
int port) {
val nodeInfo = ShardInfo.builder()
.environment(serviceDiscoveryConfiguration.getEnvironment())
.build();
val initialDelayForMonitor = serviceDiscoveryConfiguration.getInitialDelaySeconds() > 1
? serviceDiscoveryConfiguration.getInitialDelaySeconds() - 1
: 0;
val dwMonitoringInterval = serviceDiscoveryConfiguration.getDropwizardCheckInterval() == 0
? Constants.DEFAULT_DW_CHECK_INTERVAl
: serviceDiscoveryConfiguration.getDropwizardCheckInterval();
val dwMonitoringStaleness = serviceDiscoveryConfiguration.getDropwizardCheckStaleness() < dwMonitoringInterval + 1
? dwMonitoringInterval + 1
: serviceDiscoveryConfiguration.getDropwizardCheckStaleness();
val serviceProviderBuilder = ServiceProviderBuilders.<ShardInfo>shardedServiceProviderBuilder()
.withCuratorFramework(curator)
.withNamespace(namespace)
.withServiceName(serviceName)
.withSerializer(data -> {
try {
return objectMapper.writeValueAsBytes(data);
}
catch (Exception e) {
log.warn("Could not parse node data", e);
}
return null;
})
.withHostname(hostname)
.withPort(port)
.withNodeData(nodeInfo)
.withHealthcheck(new InternalHealthChecker(healthchecks))
.withHealthcheck(new RotationCheck(rotationStatus))
.withHealthcheck(new InitialDelayChecker(serviceDiscoveryConfiguration.getInitialDelaySeconds()))
.withHealthcheck(new DropwizardServerStartupCheck(environment, serverStatus))
.withIsolatedHealthMonitor(
new DropwizardHealthMonitor(
new TimeEntity(initialDelayForMonitor, dwMonitoringInterval, TimeUnit.SECONDS),
dwMonitoringStaleness * 1_000, environment))
.withHealthUpdateIntervalMs(serviceDiscoveryConfiguration.getRefreshTimeMs())
.withStaleUpdateThresholdMs(10000);
val healthMonitors = getHealthMonitors();
if (healthMonitors != null && !healthMonitors.isEmpty()) {
healthMonitors.forEach(serviceProviderBuilder::withIsolatedHealthMonitor);
}
return serviceProviderBuilder.buildServiceDiscovery();
}
private class ServiceDiscoveryManager implements Managed {
private final String serviceName;
public ServiceDiscoveryManager(String serviceName) {
this.serviceName = serviceName;
}
@Override
public void start() throws Exception {
curator.start();
serviceProvider.start();
serviceDiscoveryClient.start();
NodeIdManager nodeIdManager = new NodeIdManager(curator, serviceName);
IdGenerator.initialize(nodeIdManager.fixNodeId(), globalIdConstraints, Collections.emptyMap());
}
@Override
public void stop() throws Exception {
serviceDiscoveryClient.stop();
serviceProvider.stop();
curator.close();
IdGenerator.cleanUp();
}
}
}
|
923250fb181e47ebb70c1cf0f31d7a13119701c0 | 2,340 | java | Java | CS-1501/Network-Analysis/DijkstraNode.java | zmattis/University_of_Pittsburgh | 29ba0f4686f34d633b474bb792cf0e6cee8b0f1c | [
"MIT"
] | 6 | 2017-07-21T17:56:15.000Z | 2021-07-05T09:25:12.000Z | CS-1501/Network-Analysis/DijkstraNode.java | zmattis/University_of_Pittsburgh | 29ba0f4686f34d633b474bb792cf0e6cee8b0f1c | [
"MIT"
] | null | null | null | CS-1501/Network-Analysis/DijkstraNode.java | zmattis/University_of_Pittsburgh | 29ba0f4686f34d633b474bb792cf0e6cee8b0f1c | [
"MIT"
] | 4 | 2018-10-14T03:28:19.000Z | 2021-03-04T07:41:07.000Z | 21.081081 | 98 | 0.654701 | 996,178 | /**
* @author Brandon S. Hang
* @version 1.100
* CS 1501
* Assignment 4
* April 7, 2016
*
* This class functions as a simple data structure to use for Dijkstra's
* algorithm of finding the shortest weighted path in a graph. It holds
* indices representing the node's place in a tentative latency array
* and where the node was traversed from previously. It also holds the
* tentative latency calculated thus far in the algorithm.
*
*/
public class DijkstraNode {
private int index, previous; // Indices used in the tentative latency array
private double latency, bandwidth; // The tentative latency
/**
* Creates a new node with the tentative latency set to the maximum value of a int
* @param idx The node's index in the tentative latency array
*/
public DijkstraNode(int idx) {
setIndex(idx);
setLatency(Double.POSITIVE_INFINITY);
setMinBandwidth(Double.POSITIVE_INFINITY);
setPrevious(-1); // Initializes the previous value to -1 (I.e., not having a previous index)
}
/**
* Sets the tentative latency of the node
* @param lt The tentative latency
*/
public void setLatency(double lt) {
latency = lt;
}
/**
* Sets the minimum bandwidth of the node
* @param bw The minimum bandwidth
*/
public void setMinBandwidth(double bw) {
bandwidth = bw;
}
/**
* Sets where the node was previously linked to as a path
* @param prev The previous index
*/
public void setPrevious(int prev) {
previous = prev;
}
/**
* Sets the index of the node in the tentative latency array
* @param idx The array index
*/
private void setIndex(int idx) {
index = idx;
}
/**
* Gets the tentative latency of the node
* @return The tentative latency
*/
public double getLatency() {
return latency;
}
/**
* Gets the minimum bandwidth of the node
* @return The miimum bandwidth
*/
public double getMinBandwidth() {
return bandwidth;
}
/**
* Gets the previous index where the node was linked to
* @return The previous index
*/
public int getPrevious() {
return previous;
}
/**
* Gets the index of the node in the tentative latency array
* @return The array index
*/
public int getIndex() {
return index;
}
}
|
92325230143fef59c21080ed686ceabb1e315a1c | 1,193 | java | Java | retrofit-converters/guava/src/test/java/retrofit/converter/guava/AlwaysNullConverterFactory.java | JasonFengHot/Ismartv-Retrofit | b1660ec79e69c106bb8dec4d3dec52fb00dc6642 | [
"Apache-2.0"
] | 16 | 2016-01-18T10:41:14.000Z | 2021-11-01T09:44:30.000Z | retrofit-converters/guava/src/test/java/retrofit/converter/guava/AlwaysNullConverterFactory.java | JasonFengHot/Ismartv-Retrofit | b1660ec79e69c106bb8dec4d3dec52fb00dc6642 | [
"Apache-2.0"
] | 2 | 2021-01-21T01:25:08.000Z | 2021-12-09T22:30:45.000Z | retrofit-converters/guava/src/test/java/retrofit/converter/guava/AlwaysNullConverterFactory.java | JasonFengHot/Ismartv-Retrofit | b1660ec79e69c106bb8dec4d3dec52fb00dc6642 | [
"Apache-2.0"
] | 10 | 2018-04-20T08:43:59.000Z | 2022-03-16T02:52:53.000Z | 33.138889 | 94 | 0.74518 | 996,179 | /*
* Copyright (C) 2017 Square, 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 retrofit.converter.guava;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
final class AlwaysNullConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return new Converter<ResponseBody, Object>() {
@Override public Object convert(ResponseBody value) throws IOException {
return null;
}
};
}
}
|
923253964123200130a53b8ff1033a510aced564 | 18,738 | java | Java | src/br/com/sisclod/view/JdialogTerminarAtendimento.java | slivadrip/sisclod | c96b04da6b1fb2071c3379e8e7ea91afc12d6757 | [
"Apache-2.0"
] | null | null | null | src/br/com/sisclod/view/JdialogTerminarAtendimento.java | slivadrip/sisclod | c96b04da6b1fb2071c3379e8e7ea91afc12d6757 | [
"Apache-2.0"
] | null | null | null | src/br/com/sisclod/view/JdialogTerminarAtendimento.java | slivadrip/sisclod | c96b04da6b1fb2071c3379e8e7ea91afc12d6757 | [
"Apache-2.0"
] | null | null | null | 48.046154 | 185 | 0.633846 | 996,180 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.sisclod.view;
import br.com.sisclod.dao.AtendimentoDAO;
import br.com.sisclod.model.Atendimento;
import br.com.sisclod.model.ModeloTabela;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
/**
*
* @author Dih
*/
public class JdialogTerminarAtendimento extends javax.swing.JDialog {
/**
* Creates new form JdialogTerminarAtendimento
*/
public JdialogTerminarAtendimento(java.awt.Frame parent, boolean modal) throws SQLException {
super(parent, modal);
initComponents();
setLocationRelativeTo(null);
setResizable(false);
// popularTabela();
}
private void popularTabela() throws SQLException {
String[] coluna = new String[]{"ID", "NOME", "DATA","HORA","STATUS"};
ArrayList dados = new ArrayList();
AtendimentoDAO dao = new AtendimentoDAO();
ArrayList<Atendimento> listagem;
String nome = jTextFieldNomePaciente.getText().toUpperCase();
listagem = (ArrayList<Atendimento>) dao.getListaDialogTerminar(nome);
for (Atendimento atendimento : listagem) {
dados.add(new Object[]{atendimento.getId(), atendimento.getNomePaciente(), atendimento.getData(),atendimento.getHora(),atendimento.getStatus()});
}
ModeloTabela modelo = new ModeloTabela(dados, coluna);
try {
jTableAtendimento.setModel(modelo);
jTableAtendimento.getColumnModel().getColumn(0).setPreferredWidth(50);
jTableAtendimento.getColumnModel().getColumn(0).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(1).setPreferredWidth(380);
jTableAtendimento.getColumnModel().getColumn(1).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(2).setPreferredWidth(100);
jTableAtendimento.getColumnModel().getColumn(2).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(3).setPreferredWidth(100);
jTableAtendimento.getColumnModel().getColumn(3).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(4).setPreferredWidth(100);
jTableAtendimento.getColumnModel().getColumn(4).setResizable(false);
jTableAtendimento.getTableHeader().setReorderingAllowed(false);
jTableAtendimento.setAutoResizeMode(jTableAtendimento.AUTO_RESIZE_OFF);
jTableAtendimento.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Não foi possivel listar os dados\ndetalhes: " + ex, "Aviso!", 1);
}
}
private void popularTabelaData(String data) throws SQLException {
String[] coluna = new String[]{"ID", "NOME", "DATA","HORA","STATUS"};
ArrayList dados = new ArrayList();
AtendimentoDAO dao = new AtendimentoDAO();
ArrayList<Atendimento> listagem;
listagem = (ArrayList<Atendimento>) dao.getListaDialogTerminarData(data);
for (Atendimento atendimento : listagem) {
dados.add(new Object[]{atendimento.getId(), atendimento.getNomePaciente(), atendimento.getData(),atendimento.getHora(),atendimento.getStatus()});
}
ModeloTabela modelo = new ModeloTabela(dados, coluna);
try {
jTableAtendimento.setModel(modelo);
jTableAtendimento.getColumnModel().getColumn(0).setPreferredWidth(50);
jTableAtendimento.getColumnModel().getColumn(0).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(1).setPreferredWidth(380);
jTableAtendimento.getColumnModel().getColumn(1).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(2).setPreferredWidth(100);
jTableAtendimento.getColumnModel().getColumn(2).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(3).setPreferredWidth(100);
jTableAtendimento.getColumnModel().getColumn(3).setResizable(false);
jTableAtendimento.getColumnModel().getColumn(4).setPreferredWidth(100);
jTableAtendimento.getColumnModel().getColumn(4).setResizable(false);
jTableAtendimento.getTableHeader().setReorderingAllowed(false);
jTableAtendimento.setAutoResizeMode(jTableAtendimento.AUTO_RESIZE_OFF);
jTableAtendimento.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Não foi possivel listar os dados\ndetalhes: " + ex, "Aviso!", 1);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextFieldNomePaciente = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTableAtendimento = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jDateChooserDataPesquisa = new com.toedter.calendar.JDateChooser();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("Finalizar Atendimento");
jLabel2.setText("Paciente..:");
jTextFieldNomePaciente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldNomePacienteActionPerformed(evt);
}
});
jTextFieldNomePaciente.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldNomePacienteKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldNomePacienteKeyTyped(evt);
}
});
jTableAtendimento.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane1.setViewportView(jTableAtendimento);
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("CONCLUIDA");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("OK");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jDateChooserDataPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jDateChooserDataPesquisaKeyPressed(evt);
}
});
jLabel3.setText("Data..:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(33, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 738, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(33, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldNomePaciente, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jDateChooserDataPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)))
.addGap(26, 26, 26)
.addComponent(jButton1)
.addGap(191, 191, 191))
.addGroup(layout.createSequentialGroup()
.addGap(341, 341, 341)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(266, 266, 266)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextFieldNomePaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDateChooserDataPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jButton3))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jButton1)))
.addGap(49, 49, 49)
.addComponent(jButton2)
.addContainerGap(167, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
int resposta = JOptionPane.showConfirmDialog(null, "FINALIZAR ESSE ATEDIMENTO?", "Confirmar a Exclusão", JOptionPane.YES_NO_OPTION);
if (resposta == JOptionPane.YES_OPTION) {
try { Atendimento atendimento = new Atendimento();
AtendimentoDAO dao = new AtendimentoDAO();
atendimento.setStatus("CONCLUIDA");
atendimento.setId((int)jTableAtendimento.getValueAt(jTableAtendimento.getSelectedRow(), 0));
dao.alterarStatus((int) jTableAtendimento.getValueAt(jTableAtendimento.getSelectedRow(), 0));
popularTabela();
} catch (SQLException ex) {
Logger.getLogger(FrmCadPacientes.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (resposta == JOptionPane.NO_OPTION) {
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jTextFieldNomePacienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNomePacienteActionPerformed
}//GEN-LAST:event_jTextFieldNomePacienteActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
SimpleDateFormat simpleDate = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(jDateChooserDataPesquisa.getDate());
String data = simpleDate.format(jDateChooserDataPesquisa.getDate());
try {
popularTabelaData(data);
} catch (SQLException ex) {
Logger.getLogger(FrmVisulizarAgenda.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
popularTabela();
} catch (SQLException ex) {
Logger.getLogger(JdialogTerminarAtendimento.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextFieldNomePacienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldNomePacienteKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER){
jButton1ActionPerformed(null);
} }//GEN-LAST:event_jTextFieldNomePacienteKeyPressed
private void jDateChooserDataPesquisaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jDateChooserDataPesquisaKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER){
jButton3ActionPerformed(null);
} }//GEN-LAST:event_jDateChooserDataPesquisaKeyPressed
private void jTextFieldNomePacienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldNomePacienteKeyTyped
String min = "qwertyuiopasdfghjklçzxcvbnm";
if (min.contains(evt.getKeyChar() + "")) {
evt.setKeyChar(Character.toUpperCase(evt.getKeyChar()));
}
int limite = 50;
if ( jTextFieldNomePaciente.getText().length() >= limite) {
evt.consume();
}
}//GEN-LAST:event_jTextFieldNomePacienteKeyTyped
/**
* @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(JdialogTerminarAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JdialogTerminarAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JdialogTerminarAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JdialogTerminarAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JdialogTerminarAtendimento dialog = null;
try {
dialog = new JdialogTerminarAtendimento(new javax.swing.JFrame(), true);
} catch (SQLException ex) {
Logger.getLogger(JdialogTerminarAtendimento.class.getName()).log(Level.SEVERE, null, ex);
}
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 jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private com.toedter.calendar.JDateChooser jDateChooserDataPesquisa;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTableAtendimento;
private javax.swing.JTextField jTextFieldNomePaciente;
// End of variables declaration//GEN-END:variables
}
|
923254495c5207f0074e581584c6adaabed3dca4 | 1,970 | java | Java | hatunatu/src/test/java/jp/fieldnotes/hatunatu/dao/id/SequenceIdentifierGeneratorTest.java | azusa/hatunatu | f31a8a8e6fa819cf89d41d2fec44c5958326454c | [
"Apache-2.0"
] | null | null | null | hatunatu/src/test/java/jp/fieldnotes/hatunatu/dao/id/SequenceIdentifierGeneratorTest.java | azusa/hatunatu | f31a8a8e6fa819cf89d41d2fec44c5958326454c | [
"Apache-2.0"
] | null | null | null | hatunatu/src/test/java/jp/fieldnotes/hatunatu/dao/id/SequenceIdentifierGeneratorTest.java | azusa/hatunatu | f31a8a8e6fa819cf89d41d2fec44c5958326454c | [
"Apache-2.0"
] | null | null | null | 37.169811 | 80 | 0.739594 | 996,181 | /*
* Copyright 2015 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 jp.fieldnotes.hatunatu.dao.id;
import jp.fieldnotes.hatunatu.api.PropertyType;
import jp.fieldnotes.hatunatu.api.beans.BeanDesc;
import jp.fieldnotes.hatunatu.api.beans.PropertyDesc;
import jp.fieldnotes.hatunatu.dao.dbms.HSQL;
import jp.fieldnotes.hatunatu.dao.impl.PropertyTypeImpl;
import jp.fieldnotes.hatunatu.dao.types.ValueTypes;
import jp.fieldnotes.hatunatu.dao.unit.HatunatuTest;
import jp.fieldnotes.hatunatu.util.beans.factory.BeanDescFactory;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class SequenceIdentifierGeneratorTest {
@Rule
public HatunatuTest test = new HatunatuTest(getClass());
@Test
public void testGenerateTx() throws Exception {
BeanDesc beanDesc = BeanDescFactory.getBeanDesc(Hoge.class);
PropertyDesc propertyDesc = beanDesc.getPropertyDesc("id");
PropertyType propertyType = new PropertyTypeImpl(propertyDesc,
ValueTypes.getValueType(int.class));
SequenceIdentifierGenerator generator = new SequenceIdentifierGenerator(
propertyType, new HSQL());
generator.setSequenceName("myseq");
Hoge hoge = new Hoge();
generator.setIdentifier(hoge, test.getDataSource());
System.out.println(hoge.getId());
assertTrue("1", hoge.getId() > 0);
}
} |
923254f7fc96ead32424642bca9c89c941d1ab2b | 720 | java | Java | repasse-analise/src/main/java/io/sjcdigital/repasse/model/ideb/Rede.java | sjcdigital/repasse-analises | e4413d881259929a0d9ce8ec11887e4b072123bd | [
"Apache-2.0"
] | null | null | null | repasse-analise/src/main/java/io/sjcdigital/repasse/model/ideb/Rede.java | sjcdigital/repasse-analises | e4413d881259929a0d9ce8ec11887e4b072123bd | [
"Apache-2.0"
] | null | null | null | repasse-analise/src/main/java/io/sjcdigital/repasse/model/ideb/Rede.java | sjcdigital/repasse-analises | e4413d881259929a0d9ce8ec11887e4b072123bd | [
"Apache-2.0"
] | null | null | null | 16.454545 | 102 | 0.671271 | 996,182 | package io.sjcdigital.repasse.model.ideb;
/**
* @author Pedro Hos <nnheo@example.com>
*
*/
public enum Rede {
MUNICIPAL("Municipal"), ESTADUAL("Estadual"), FEDERAL("Federal"), PUBLICA("Pública"), OUTRA("Outra");
private String redeTexto;
Rede(String texto) {
this.redeTexto = texto;
}
public static Rede converteRedeStringParaRede(String rede) {
rede = rede.toLowerCase();
switch (rede) {
case "municipal":
return Rede.MUNICIPAL;
case "federal":
return Rede.FEDERAL;
case "estadual":
return Rede.ESTADUAL;
case "pública":
return Rede.PUBLICA;
default:
return Rede.OUTRA;
}
}
/**
* @return the redeTexto
*/
public String getRedeTexto() {
return redeTexto;
}
}
|
9232563311f2efe64877adbce69ac8cc0f7bf173 | 920 | java | Java | iam-login-service/src/main/java/it/infn/mw/iam/api/scim/provisioning/ScimQuery.java | uhonliu/iam | e401a46c0c4c335ddffbefb0fd6a5a9c1bc79da8 | [
"Apache-2.0"
] | 74 | 2016-07-05T15:03:04.000Z | 2022-03-13T01:44:59.000Z | iam-login-service/src/main/java/it/infn/mw/iam/api/scim/provisioning/ScimQuery.java | uhonliu/iam | e401a46c0c4c335ddffbefb0fd6a5a9c1bc79da8 | [
"Apache-2.0"
] | 333 | 2016-08-01T07:09:09.000Z | 2022-03-31T09:25:14.000Z | iam-login-service/src/main/java/it/infn/mw/iam/api/scim/provisioning/ScimQuery.java | uhonliu/iam | e401a46c0c4c335ddffbefb0fd6a5a9c1bc79da8 | [
"Apache-2.0"
] | 36 | 2016-06-16T08:24:21.000Z | 2022-03-13T01:44:54.000Z | 29.677419 | 75 | 0.743478 | 996,183 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2016-2019
*
* 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 it.infn.mw.iam.api.scim.provisioning;
import it.infn.mw.iam.api.scim.provisioning.paging.ScimPageRequest;
public interface ScimQuery extends ScimPageRequest {
public enum SortOrder {
ascending, descending;
}
String getFilter();
SortOrder getSortOder();
}
|
923257c9eea91d08c84b1fc7c2a3d80ded940d2e | 320 | java | Java | amico_im_service/amico_im_service_entity/src/main/java/com/amico/service/im/entity/model/TokenUserToken.java | 13802410684/IM_AMICO_SERVICE | 8abe99b5d17727565dad5b4fa687f6f38a651fb5 | [
"Apache-2.0"
] | null | null | null | amico_im_service/amico_im_service_entity/src/main/java/com/amico/service/im/entity/model/TokenUserToken.java | 13802410684/IM_AMICO_SERVICE | 8abe99b5d17727565dad5b4fa687f6f38a651fb5 | [
"Apache-2.0"
] | null | null | null | amico_im_service/amico_im_service_entity/src/main/java/com/amico/service/im/entity/model/TokenUserToken.java | 13802410684/IM_AMICO_SERVICE | 8abe99b5d17727565dad5b4fa687f6f38a651fb5 | [
"Apache-2.0"
] | null | null | null | 24.615385 | 72 | 0.778125 | 996,184 | package com.amico.service.im.entity.model;
import io.jboot.db.annotation.Table;
import com.amico.service.im.entity.model.base.BaseTokenUserToken;
/**
* Generated by Jboot.
*/
@Table(tableName = "token_user_token", primaryKey = "user_uid")
public class TokenUserToken extends BaseTokenUserToken<TokenUserToken> {
}
|
92325807af3593fab514105c058e4657848ebd2a | 925 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/old/FirstAutonomousTest.java | abhardwaj09/ftc-19539 | 94a471f4dbbeb61b033111224ed96f0b708fea9b | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/old/FirstAutonomousTest.java | abhardwaj09/ftc-19539 | 94a471f4dbbeb61b033111224ed96f0b708fea9b | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/old/FirstAutonomousTest.java | abhardwaj09/ftc-19539 | 94a471f4dbbeb61b033111224ed96f0b708fea9b | [
"MIT"
] | null | null | null | 28.90625 | 66 | 0.732973 | 996,185 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
@Autonomous(name = "FirstAutonomousTest", group = "Linear OpMode")
public class FirstAutonomousTest extends LinearOpMode {
DcMotor left = hardwareMap.dcMotor.get("left");
DcMotor right = hardwareMap.dcMotor.get("right");
double power = 1.0;
@Override
public void runOpMode() {
right.setDirection(DcMotorSimple.Direction.REVERSE);
left.setDirection(DcMotorSimple.Direction.REVERSE);
right.setDirection(DcMotorSimple.Direction.REVERSE);
left.setDirection(DcMotorSimple.Direction.REVERSE);
waitForStart();
left.setPower(power);
right.setPower(power);
sleep(10000);
}
} |
9232587f4acf127f16d21edd2805d7c8b6a5b498 | 6,809 | java | Java | qwandaq/src/main/java/life/genny/qwandautils/QwandaUtils.java | genny-project/gennyq | 61f42fb0e6655aef1a4e111e6ac57125b619d46a | [
"Apache-2.0"
] | null | null | null | qwandaq/src/main/java/life/genny/qwandautils/QwandaUtils.java | genny-project/gennyq | 61f42fb0e6655aef1a4e111e6ac57125b619d46a | [
"Apache-2.0"
] | null | null | null | qwandaq/src/main/java/life/genny/qwandautils/QwandaUtils.java | genny-project/gennyq | 61f42fb0e6655aef1a4e111e6ac57125b619d46a | [
"Apache-2.0"
] | null | null | null | 32.89372 | 232 | 0.723161 | 996,186 | package life.genny.qwandautils;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jboss.logging.Logger;
public class QwandaUtils {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static final String ANSI_BOLD = "\u001b[1m";
private static final Logger log = Logger.getLogger(QwandaUtils.class);
public static String apiGet(String getUrl, final String authToken, final int timeout) throws ClientProtocolException, IOException {
// log.debug("GET:" + getUrl + ":");
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).build();
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpGet request = new HttpGet(getUrl);
if (authToken != null) {
request.addHeader("Authorization", "Bearer " + authToken); // Authorization": `Bearer
}
CloseableHttpResponse response =null;
try {
response = httpclient.execute(request);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network
// socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
HttpEntity entity1 = response.getEntity();
if (entity1 == null) {
return "";
}
String responseString = EntityUtils.toString(entity1);
if (StringUtils.isBlank(responseString)) {
return "";
}
EntityUtils.consume(entity1);
return responseString;
}
catch (java.net.SocketTimeoutException e) {
log.error("API Get call timeout - "+timeout+" secs to "+getUrl);
return null;
}
catch (Exception e) {
log.error("API Get exception -for "+getUrl+" :");
return "";
}
finally {
if (response != null) {
response.close();
}
httpclient.close();
//IOUtils.closeQuietly(response); removed commons-io
//IOUtils.closeQuietly(httpclient);
}
}
public static String apiGet(String getUrl, final String authToken) throws ClientProtocolException, IOException {
return apiGet(getUrl, authToken, 200);
}
public static String apiPostEntity(final String postUrl, final String entityString, final String authToken, final Consumer<String> callback)
throws IOException {
String responseString = null;
if (StringUtils.isBlank(postUrl)) {
log.error("Blank url in apiPostEntity");
}
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(postUrl);
StringEntity postEntity = new StringEntity(entityString, "UTF-8");
post.setEntity(postEntity);
post.setHeader("Content-Type", "application/json; charset=UTF-8");
if (authToken != null) {
post.addHeader("Authorization", "Bearer " + authToken); // Authorization": `Bearer
}
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
if(callback != null) {
callback.accept(responseString);
}
return responseString;
} catch (Exception e) {
log.error(e.getMessage());
}
finally {
if (response != null) {
response.close();
} else {
log.error("postApi response was null");
}
httpclient.close();
// IOUtils.closeQuietly(response);
// IOUtils.closeQuietly(httpclient);
}
return responseString;
}
public static String apiPostNote(final String postUrl, final String sourceCode, final String tag, final String targetCode, final String content, final String authToken, final Consumer<String> callback)
throws IOException {
String responseString = null;
if (StringUtils.isBlank(postUrl)) {
log.error("Blank url in apiPostNote");
}
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(postUrl);
String jsonString = String.format("{\"id\":0,\"content\":\""+content+"\",\"sourceCode\":\""+sourceCode+"\",\"tags\":[{\"name\":\""+sourceCode+"\",\"value\":0}, {\"name\":\"sys\",\"value\":0}],\"targetCode\":\""+targetCode+"\"}");
StringEntity noteContent = new StringEntity(jsonString, "UTF-8");
post.setEntity(noteContent);
post.setHeader("Content-Type", "application/json; charset=UTF-8");
if (authToken != null) {
post.addHeader("Authorization", "Bearer " + authToken); // Authorization": `Bearer
}
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
if(callback != null) {
callback.accept(responseString);
}
return responseString;
} catch (Exception e) {
log.error(e.getMessage());
}
finally {
if (response != null) {
response.close();
} else {
log.error("postApi response was null");
}
httpclient.close();
// IOUtils.closeQuietly(response);
// IOUtils.closeQuietly(httpclient);
}
return responseString;
}
public static String apiPostEntity(final String postUrl, final String entityString, final String authToken) throws IOException {
return apiPostEntity(postUrl, entityString, authToken, null);
}
public static String apiPost(final String postUrl, final List<BasicNameValuePair> nameValuePairs, final String authToken) throws IOException {
return apiPostEntity(postUrl, new UrlEncodedFormEntity(nameValuePairs).toString(), authToken, null);
}
}
|
923258baabfd654e9ea3bd5a93e9c96e7aafc86e | 1,176 | java | Java | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryUnavailableException.java | shangcg/spring-boot-2.2 | 0ab7b1b8998a4d17e7dbc91f574c0396cd17bf77 | [
"Apache-2.0"
] | 66,985 | 2015-01-01T14:37:10.000Z | 2022-03-31T21:00:10.000Z | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryUnavailableException.java | pavelgordon/spring-boot | 17d5e170698044336f86969fbad457e0c93b5c3a | [
"Apache-2.0"
] | 27,513 | 2015-01-01T03:27:09.000Z | 2022-03-31T19:03:12.000Z | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryUnavailableException.java | pavelgordon/spring-boot | 17d5e170698044336f86969fbad457e0c93b5c3a | [
"Apache-2.0"
] | 42,709 | 2015-01-02T01:08:50.000Z | 2022-03-31T20:26:44.000Z | 28.682927 | 84 | 0.759354 | 996,187 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.session;
import org.springframework.session.SessionRepository;
/**
* Exception thrown when no {@link SessionRepository} is available.
*
* @author Stephane Nicoll
* @since 2.0.0
*/
public class SessionRepositoryUnavailableException extends RuntimeException {
private final StoreType storeType;
public SessionRepositoryUnavailableException(String message, StoreType storeType) {
super(message);
this.storeType = storeType;
}
public StoreType getStoreType() {
return this.storeType;
}
}
|
923258da2469e9034eeb86dcfe52d1ce3e906c02 | 2,739 | java | Java | src/main/java/com/hillert/calculator/antlr/ExprListener.java | ghillert/antlr-demo | aadf92471e12c05ed1de971189697d6c371b317a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hillert/calculator/antlr/ExprListener.java | ghillert/antlr-demo | aadf92471e12c05ed1de971189697d6c371b317a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hillert/calculator/antlr/ExprListener.java | ghillert/antlr-demo | aadf92471e12c05ed1de971189697d6c371b317a | [
"Apache-2.0"
] | null | null | null | 32.607143 | 74 | 0.719241 | 996,188 | // Generated from Expr.g4 by ANTLR 4.9.3
package com.hillert.calculator.antlr;
import org.antlr.v4.runtime.tree.ParseTreeListener;
/**
* This interface defines a complete listener for a parse tree produced by
* {@link ExprParser}.
*/
public interface ExprListener extends ParseTreeListener {
/**
* Enter a parse tree produced by the {@code Program}
* labeled alternative in {@link ExprParser#prog}.
* @param ctx the parse tree
*/
void enterProgram(ExprParser.ProgramContext ctx);
/**
* Exit a parse tree produced by the {@code Program}
* labeled alternative in {@link ExprParser#prog}.
* @param ctx the parse tree
*/
void exitProgram(ExprParser.ProgramContext ctx);
/**
* Enter a parse tree produced by the {@code Declaration}
* labeled alternative in {@link ExprParser#decl}.
* @param ctx the parse tree
*/
void enterDeclaration(ExprParser.DeclarationContext ctx);
/**
* Exit a parse tree produced by the {@code Declaration}
* labeled alternative in {@link ExprParser#decl}.
* @param ctx the parse tree
*/
void exitDeclaration(ExprParser.DeclarationContext ctx);
/**
* Enter a parse tree produced by the {@code Multiplication}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void enterMultiplication(ExprParser.MultiplicationContext ctx);
/**
* Exit a parse tree produced by the {@code Multiplication}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void exitMultiplication(ExprParser.MultiplicationContext ctx);
/**
* Enter a parse tree produced by the {@code Addition}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void enterAddition(ExprParser.AdditionContext ctx);
/**
* Exit a parse tree produced by the {@code Addition}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void exitAddition(ExprParser.AdditionContext ctx);
/**
* Enter a parse tree produced by the {@code Variable}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void enterVariable(ExprParser.VariableContext ctx);
/**
* Exit a parse tree produced by the {@code Variable}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void exitVariable(ExprParser.VariableContext ctx);
/**
* Enter a parse tree produced by the {@code Number}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void enterNumber(ExprParser.NumberContext ctx);
/**
* Exit a parse tree produced by the {@code Number}
* labeled alternative in {@link ExprParser#expr}.
* @param ctx the parse tree
*/
void exitNumber(ExprParser.NumberContext ctx);
} |
9232596d6a52840c0ddb5a030efef4fdcd3278ac | 2,411 | java | Java | src/main/java/com/mayreh/intellij/plugin/tlaplus/psi/ext/TLAplusLetExprImplMixin.java | okue/tlaplus-intellij-plugin | 2c4d4b2de7066d9053c5474fa4382ab271c29465 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mayreh/intellij/plugin/tlaplus/psi/ext/TLAplusLetExprImplMixin.java | okue/tlaplus-intellij-plugin | 2c4d4b2de7066d9053c5474fa4382ab271c29465 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mayreh/intellij/plugin/tlaplus/psi/ext/TLAplusLetExprImplMixin.java | okue/tlaplus-intellij-plugin | 2c4d4b2de7066d9053c5474fa4382ab271c29465 | [
"Apache-2.0"
] | null | null | null | 43.836364 | 115 | 0.536707 | 996,189 | package com.mayreh.intellij.plugin.tlaplus.psi.ext;
import static com.mayreh.intellij.plugin.tlaplus.psi.TLAplusPsiUtils.isForwardReference;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;
import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;
import com.mayreh.intellij.plugin.tlaplus.psi.TLAplusFuncDefinition;
import com.mayreh.intellij.plugin.tlaplus.psi.TLAplusLetExpr;
import com.mayreh.intellij.plugin.tlaplus.psi.TLAplusNamedElement;
public abstract class TLAplusLetExprImplMixin extends TLAplusElementImpl implements TLAplusLetExpr {
protected TLAplusLetExprImplMixin(@NotNull ASTNode node) {
super(node);
}
@Override
public @NotNull Stream<TLAplusNamedElement> localDefinitions(
@NotNull TLAplusElement placement) {
Stream.Builder<Stream<TLAplusNamedElement>> streams = Stream.builder();
streams.add(
getOpDefinitionList()
.stream()
.flatMap(def -> Stream.of(def.getNonfixLhs(),
def.getPrefixOpLhs(),
def.getDashdotOpLhs(),
def.getInfixOpLhs(),
def.getPostfixOpLhs())
.filter(Objects::nonNull)
.findFirst()
.map(TLAplusNamedLhs::getNamedElement)
.filter(namedElement -> !isForwardReference(placement, namedElement))
.stream()));
streams.add(getFuncDefinitionList()
.stream()
.map(TLAplusFuncDefinition::getFuncName)
.filter(e -> !isForwardReference(placement, e))
.map(Function.identity()));
streams.add(getModuleDefinitionList()
.stream()
.map(e -> e.getNonfixLhs().getNonfixLhsName())
.filter(name -> !isForwardReference(placement, name))
.map(Function.identity()));
return streams.build().flatMap(Function.identity());
}
}
|
92325a884c3a30673141861cb6ddf2d7ba8c34be | 830 | java | Java | web.registry/src/test/java/collabware/registry/internal/EditorReferenceTest.java | HotblackDesiato/collabware | 3fc4d6d9214d63cb6a9273720124e1fa0379601f | [
"MIT"
] | 2 | 2015-03-30T18:59:18.000Z | 2021-04-13T03:43:38.000Z | web.registry/src/test/java/collabware/registry/internal/EditorReferenceTest.java | HotblackDesiato/collabware | 3fc4d6d9214d63cb6a9273720124e1fa0379601f | [
"MIT"
] | null | null | null | web.registry/src/test/java/collabware/registry/internal/EditorReferenceTest.java | HotblackDesiato/collabware | 3fc4d6d9214d63cb6a9273720124e1fa0379601f | [
"MIT"
] | null | null | null | 29.642857 | 132 | 0.762651 | 996,190 | package collabware.registry.internal;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import collabware.registry.EditorReference;
public class EditorReferenceTest {
@Test
public void editorIdMustOnlyContainLettersNumbers() throws Exception {
EditorReference reference = new EditorReference("Some-id.12_3", "The Name", "Some description", this.getClass().getClassLoader());
assertThat(reference.getContentType(), is("Some-id.12_3"));
assertThat(reference.getName(), is("The Name"));
assertThat(reference.getDescription(), is("Some description"));
}
@Test(expected=IllegalArgumentException.class)
public void illegalId() throws Exception {
new EditorReference("/illegal&$", "The Name", "Some description", this.getClass().getClassLoader());
}
}
|
92325b8ef285f83c36ae312a8ed5604236087225 | 1,379 | java | Java | COMP 1210 - Java I/Nick's/JAVA1/Dudes/Source Code/Chap10/DisplayColor.java | Skyfox64/auburn-csse | 7343c7cc4567c751f3c7d298c78b8cc85d25d6dd | [
"MIT"
] | 1 | 2020-12-10T00:50:08.000Z | 2020-12-10T00:50:08.000Z | COMP 1210 - Java I/Nick's/JAVA1/Dudes/Source Code/Chap10/DisplayColor.java | Skyfox64/auburn-csse | 7343c7cc4567c751f3c7d298c78b8cc85d25d6dd | [
"MIT"
] | null | null | null | COMP 1210 - Java I/Nick's/JAVA1/Dudes/Source Code/Chap10/DisplayColor.java | Skyfox64/auburn-csse | 7343c7cc4567c751f3c7d298c78b8cc85d25d6dd | [
"MIT"
] | null | null | null | 30.644444 | 70 | 0.491661 | 996,191 | //********************************************************************
// DisplayColor.java Author: Lewis/Loftus
//
// Demonstrates the use of a color chooser.
//********************************************************************
import javax.swing.*;
import java.awt.*;
public class DisplayColor
{
//-----------------------------------------------------------------
// Presents a frame with a colored panel, then allows the user
// to change the color multiple times using a color chooser.
//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("Display Color");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel colorPanel = new JPanel();
colorPanel.setBackground (Color.white);
colorPanel.setPreferredSize (new Dimension (300, 100));
frame.getContentPane().add (colorPanel);
frame.pack();
frame.setVisible(true);
Color shade = Color.white;
int again;
do
{
shade = JColorChooser.showDialog (frame, "Pick a Color!",
shade);
colorPanel.setBackground (shade);
again = JOptionPane.showConfirmDialog (null,
"Display another color?");
}
while (again == JOptionPane.YES_OPTION);
}
}
|
92325bf52e69d6485e8700898c63fa50bc0f80b4 | 1,236 | java | Java | gemma-core/src/main/java/ubic/gemma/persistence/service/AbstractVoEnabledDao.java | PavlidisLab/Gemma | ec019d89f89e889fcb64cb957928d01dc36e44fd | [
"Apache-2.0"
] | 8 | 2019-04-30T09:00:41.000Z | 2021-06-20T18:34:48.000Z | gemma-core/src/main/java/ubic/gemma/persistence/service/AbstractVoEnabledDao.java | PavlidisLab/Gemma | ec019d89f89e889fcb64cb957928d01dc36e44fd | [
"Apache-2.0"
] | 252 | 2018-01-08T19:13:36.000Z | 2022-03-31T17:15:10.000Z | gemma-core/src/main/java/ubic/gemma/persistence/service/AbstractVoEnabledDao.java | PavlidisLab/Gemma | ec019d89f89e889fcb64cb957928d01dc36e44fd | [
"Apache-2.0"
] | 4 | 2020-08-09T09:55:17.000Z | 2021-11-09T13:07:32.000Z | 30.9 | 105 | 0.72411 | 996,192 | package ubic.gemma.persistence.service;
import org.hibernate.SessionFactory;
import ubic.gemma.model.IdentifiableValueObject;
import ubic.gemma.model.common.Identifiable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by tesarst on 01/06/17.
* Base DAO providing value object functionality.
*/
public abstract class AbstractVoEnabledDao<O extends Identifiable, VO extends IdentifiableValueObject<O>>
extends AbstractDao<O> implements BaseVoEnabledDao<O, VO> {
protected AbstractVoEnabledDao( Class<O> elementClass, SessionFactory sessionFactory ) {
super( elementClass, sessionFactory );
}
@Override
public abstract VO loadValueObject( O entity );
@Override
public List<VO> loadValueObjects( Collection<O> entities ) {
return entities.stream().map( this::loadValueObject ).collect( Collectors.toList() );
}
/**
* Should be overridden for any entity that requires special handling of larger amounts of VOs.
*
* @return VOs of all instances of the class this DAO manages.
*/
@Override
public List<VO> loadAllValueObjects() {
return this.loadValueObjects( this.loadAll() );
}
}
|
92325da139a62f0d410bfd7d1a71e648e3a89434 | 25,559 | java | Java | core/src/com/cherokeelessons/util/StringUtils.java | CherokeeLanguage/Animals | 9191869e50dc23ed03a8707bd5be44ecfd84641e | [
"MIT"
] | 1 | 2022-01-12T17:55:36.000Z | 2022-01-12T17:55:36.000Z | core/src/com/cherokeelessons/util/StringUtils.java | CherokeeLanguage/Animals | 9191869e50dc23ed03a8707bd5be44ecfd84641e | [
"MIT"
] | null | null | null | core/src/com/cherokeelessons/util/StringUtils.java | CherokeeLanguage/Animals | 9191869e50dc23ed03a8707bd5be44ecfd84641e | [
"MIT"
] | null | null | null | 30.719952 | 120 | 0.592824 | 996,193 | package com.cherokeelessons.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class StringUtils {
public static final String EMPTY = "";
/**
* Represents a failed index search.
*
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* A regex pattern for recognizing blocks of whitespace characters.
*/
private static final Pattern WHITESPACE_BLOCK = Pattern.compile("\\s+");
// Defaults
// -----------------------------------------------------------------------
/**
* <p>
* Returns either the passed in String, or if the String is {@code null} , an
* empty String ("").
* </p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it was {@code null}
*/
public static String defaultString(final String str) {
return str == null ? EMPTY : str;
}
/**
* <p>
* Checks if a CharSequence is whitespace, empty ("") or null.
* </p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
// Empty checks
// -----------------------------------------------------------------------
/**
* <p>
* Checks if a CharSequence is empty ("") or null.
* </p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>
* NOTE: This method changed in Lang version 2.0. It no longer trims the
* CharSequence. That functionality is available in isBlank().
* </p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
// Left/Right/Mid
// -----------------------------------------------------------------------
/**
* <p>
* Gets the leftmost {@code len} characters of a String.
* </p>
*
* <p>
* If {@code len} characters are not available, or the String is {@code null},
* the String will be returned without an exception. An empty String is returned
* if len is negative.
* </p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String
* @return the leftmost characters, {@code null} if null String input
*/
public static String left(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* <p>
* Gets {@code len} characters from the middle of a String.
* </p>
*
* <p>
* If {@code len} characters are not available, the remainder of the String will
* be returned without an exception. If the String is {@code null}, {@code null}
* will be returned. An empty String is returned if len is negative or exceeds
* the length of {@code str}.
* </p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String
* @return the middle characters, {@code null} if null String input
*/
public static String mid(final String str, int pos, final int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= pos + len) {
return str.substring(pos);
}
return str.substring(pos, pos + len);
}
/**
* <p>
* Similar to <a href=
* "http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize
* -space</a>
* </p>
* <p>
* The function returns the argument string with whitespace normalized by using
* <code>{@link #trim(String)}</code> to remove leading and trailing whitespace
* and then replacing sequences of whitespace characters by a single space.
* </p>
* In XML Whitespace characters are the same as those allowed by the
* <a href="http://www.w3.org/TR/REC-xml/#NT-S">S</a> production, which is S ::=
* (#x20 | #x9 | #xD | #xA)+
* <p>
* Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r]
* <p>
* For reference:
* <ul>
* <li>\x0B = vertical tab</li>
* <li>\f = #xC = form feed</li>
* <li>#x20 = space</li>
* <li>#x9 = \t</li>
* <li>#xA = \n</li>
* <li>#xD = \r</li>
* </ul>
* </p>
* <p>
* The difference is that Java's whitespace includes vertical tab and form feed,
* which this functional will also normalize. Additionally
* <code>{@link #trim(String)}</code> removes control characters (char <= 32)
* from both ends of this String.
* </p>
*
* @see Pattern
* @see #trim(String)
* @see <a href=
* "http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize-space</a>
* @param str the source String to normalize whitespaces from, may be null
* @return the modified string with whitespace normalized, {@code null} if null
* String input
*
* @since 3.0
*/
public static String normalizeSpace(final String str) {
if (str == null) {
return null;
}
return WHITESPACE_BLOCK.matcher(trim(str)).replaceAll(" ");
}
// Reversing
// -----------------------------------------------------------------------
/**
* <p>
* Reverses a String as per {@link StringBuilder#reverse()}.
* </p>
*
* <p>
* A {@code null} String returns {@code null}.
* </p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, {@code null} if null String input
*/
public static String reverse(final String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* <p>
* Gets the rightmost {@code len} characters of a String.
* </p>
*
* <p>
* If {@code len} characters are not available, or the String is {@code null},
* the String will be returned without an an exception. An empty String is
* returned if len is negative.
* </p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String
* @return the rightmost characters, {@code null} if null String input
*/
public static String right(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
// Stripping
// -----------------------------------------------------------------------
/**
* <p>
* Strips whitespace from the start and end of a String.
* </p>
*
* <p>
* This is similar to {@link #trim(String)} but removes whitespace. Whitespace
* is defined by {@link Character#isWhitespace(char)}.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}.
* </p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, {@code null} if null String input
*/
public static String strip(final String str) {
return strip(str, null);
}
/**
* <p>
* Strips any of a set of characters from the start and end of a String. This is
* similar to {@link String#trim()} but allows the characters to be stripped to
* be controlled.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}. An empty string ("") input
* returns the empty string.
* </p>
*
* <p>
* If the stripChars String is {@code null}, whitespace is stripped as defined
* by {@link Character#isWhitespace(char)}. Alternatively use
* {@link #strip(String)}.
* </p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String strip(String str, final String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>
* Strips any of a set of characters from the end of a String.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}. An empty string ("") input
* returns the empty string.
* </p>
*
* <p>
* If the stripChars String is {@code null}, whitespace is stripped as defined
* by {@link Character#isWhitespace(char)}.
* </p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the set of characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripEnd(final String str, final String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
}
/**
* <p>
* Strips any of a set of characters from the start of a String.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}. An empty string ("") input
* returns the empty string.
* </p>
*
* <p>
* If the stripChars String is {@code null}, whitespace is stripped as defined
* by {@link Character#isWhitespace(char)}.
* </p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripStart(final String str, final String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while (start != strLen && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) {
start++;
}
}
return str.substring(start);
}
/**
* <p>
* Gets the substring after the first occurrence of a separator. The separator
* is not returned.
* </p>
*
* <p>
* A {@code null} string input will return {@code null}. An empty ("") string
* input will return the empty string. A {@code null} separator will return the
* empty string if the input string is not {@code null}.
* </p>
*
* <p>
* If nothing is found, the empty string is returned.
* </p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
/**
* <p>
* Gets the substring after the last occurrence of a separator. The separator is
* not returned.
* </p>
*
* <p>
* A {@code null} string input will return {@code null}. An empty ("") string
* input will return the empty string. An empty or {@code null} separator will
* return the empty string if the input string is not {@code null}.
* </p>
*
* <p>
* If nothing is found, the empty string is returned.
* </p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfterLast(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// SubStringAfter/SubStringBefore
// -----------------------------------------------------------------------
/**
* <p>
* Gets the substring before the first occurrence of a separator. The separator
* is not returned.
* </p>
*
* <p>
* A {@code null} string input will return {@code null}. An empty ("") string
* input will return the empty string. A {@code null} separator will return the
* input string.
* </p>
*
* <p>
* If nothing is found, the string input is returned.
* </p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBefore(final String str, final String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.length() == 0) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>
* Gets the substring before the last occurrence of a separator. The separator
* is not returned.
* </p>
*
* <p>
* A {@code null} string input will return {@code null}. An empty ("") string
* input will return the empty string. An empty or {@code null} separator will
* return the input string.
* </p>
*
* <p>
* If nothing is found, the string input is returned.
* </p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBeforeLast(final String str, final String separator) {
if (isEmpty(str) || isEmpty(separator)) {
return str;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
// Substring between
// -----------------------------------------------------------------------
/**
* <p>
* Gets the String that is nested in between two instances of the same String.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}. A {@code null} tag returns
* {@code null}.
* </p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String tag) {
return substringBetween(str, tag, tag);
}
/**
* <p>
* Gets the String that is nested in between two Strings. Only the first match
* is returned.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}. A {@code null} open/close
* returns {@code null} (no match). An empty ("") open and close returns an
* empty string.
* </p>
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String open, final String close) {
if (str == null || open == null || close == null) {
return null;
}
final int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
final int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* <p>
* Searches a String for substrings delimited by a start and end tag, returning
* all matching substrings in an array.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}. A {@code null} open/close
* returns {@code null} (no match). An empty ("") open/close returns
* {@code null} (no match).
* </p>
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str the String containing the substrings, null returns null, empty
* returns empty
* @param open the String identifying the start of the substring, empty returns
* null
* @param close the String identifying the end of the substring, empty returns
* null
* @return a String Array of substrings, or {@code null} if no match
* @since 2.3
*/
public static String[] substringsBetween(final String str, final String open, final String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
final int strLen = str.length();
if (strLen == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final int closeLen = close.length();
final int openLen = open.length();
final List<String> list = new ArrayList<>();
int pos = 0;
while (pos < strLen - closeLen) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
final int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(new String[list.size()]);
}
// Trim
// -----------------------------------------------------------------------
/**
* <p>
* Removes control characters (char <= 32) from both ends of this String,
* handling {@code null} by returning {@code null}.
* </p>
*
* <p>
* The String is trimmed using {@link String#trim()}. Trim removes start and end
* characters <= 32. To strip whitespace use {@link #strip(String)}.
* </p>
*
* <p>
* To trim your choice of characters, use the {@link #strip(String, String)}
* methods.
* </p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, {@code null} if null String input
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}
} |
92325fe24ac6c1051e7c5918276d13a70236027e | 635 | java | Java | library/src/main/java/com/github/kr328/magic/util/ClassLoaderUtils.java | Kr328/MagicLibrary | 721ab5e203ed9aa889154778f84cc27c9de73aa8 | [
"MIT"
] | 1 | 2022-03-13T17:22:22.000Z | 2022-03-13T17:22:22.000Z | library/src/main/java/com/github/kr328/magic/util/ClassLoaderUtils.java | Kr328/MagicLibrary | 721ab5e203ed9aa889154778f84cc27c9de73aa8 | [
"MIT"
] | null | null | null | library/src/main/java/com/github/kr328/magic/util/ClassLoaderUtils.java | Kr328/MagicLibrary | 721ab5e203ed9aa889154778f84cc27c9de73aa8 | [
"MIT"
] | 1 | 2022-01-12T17:47:03.000Z | 2022-01-12T17:47:03.000Z | 31.75 | 135 | 0.754331 | 996,194 | package com.github.kr328.magic.util;
import android.annotation.SuppressLint;
import java.lang.reflect.Field;
public final class ClassLoaderUtils {
@SuppressWarnings("JavaReflectionMemberAccess")
@SuppressLint("DiscouragedPrivateApi")
public static ClassLoader replaceParentClassLoader(ClassLoader target, ClassLoader newParent) throws ReflectiveOperationException {
final Field field = ClassLoader.class.getDeclaredField("parent");
field.setAccessible(true);
final ClassLoader oldParent = (ClassLoader) field.get(target);
field.set(target, newParent);
return oldParent;
}
}
|
923262519b4059b09828c190d22f0a07b7600a90 | 5,251 | java | Java | org/apache/poi/ss/formula/ParseNode.java | kelu124/pyS3 | 86eb139d971921418d6a62af79f2868f9c7704d5 | [
"MIT"
] | 1 | 2021-04-09T06:03:36.000Z | 2021-04-09T06:03:36.000Z | org/apache/poi/ss/formula/ParseNode.java | kelu124/pyS3 | 86eb139d971921418d6a62af79f2868f9c7704d5 | [
"MIT"
] | null | null | null | org/apache/poi/ss/formula/ParseNode.java | kelu124/pyS3 | 86eb139d971921418d6a62af79f2868f9c7704d5 | [
"MIT"
] | null | null | null | 32.614907 | 142 | 0.600647 | 996,195 | package org.apache.poi.ss.formula;
import org.apache.poi.ss.formula.ptg.ArrayPtg;
import org.apache.poi.ss.formula.ptg.AttrPtg;
import org.apache.poi.ss.formula.ptg.FuncVarPtg;
import org.apache.poi.ss.formula.ptg.MemAreaPtg;
import org.apache.poi.ss.formula.ptg.MemFuncPtg;
import org.apache.poi.ss.formula.ptg.Ptg;
final class ParseNode {
public static final ParseNode[] EMPTY_ARRAY = new ParseNode[0];
private final ParseNode[] _children;
private boolean _isIf;
private final Ptg _token;
private final int _tokenCount;
private static final class TokenCollector {
private int _offset = 0;
private final Ptg[] _ptgs;
public TokenCollector(int tokenCount) {
this._ptgs = new Ptg[tokenCount];
}
public int sumTokenSizes(int fromIx, int toIx) {
int result = 0;
for (int i = fromIx; i < toIx; i++) {
result += this._ptgs[i].getSize();
}
return result;
}
public int createPlaceholder() {
int i = this._offset;
this._offset = i + 1;
return i;
}
public void add(Ptg token) {
if (token == null) {
throw new IllegalArgumentException("token must not be null");
}
this._ptgs[this._offset] = token;
this._offset++;
}
public void setPlaceholder(int index, Ptg token) {
if (this._ptgs[index] != null) {
throw new IllegalStateException("Invalid placeholder index (" + index + ")");
}
this._ptgs[index] = token;
}
public Ptg[] getResult() {
return this._ptgs;
}
}
public ParseNode(Ptg token, ParseNode[] children) {
if (token == null) {
throw new IllegalArgumentException("token must not be null");
}
this._token = token;
this._children = (ParseNode[]) children.clone();
this._isIf = isIf(token);
int tokenCount = 1;
for (ParseNode tokenCount2 : children) {
tokenCount += tokenCount2.getTokenCount();
}
if (this._isIf) {
tokenCount += children.length;
}
this._tokenCount = tokenCount;
}
public ParseNode(Ptg token) {
this(token, EMPTY_ARRAY);
}
public ParseNode(Ptg token, ParseNode child0) {
this(token, new ParseNode[]{child0});
}
public ParseNode(Ptg token, ParseNode child0, ParseNode child1) {
this(token, new ParseNode[]{child0, child1});
}
private int getTokenCount() {
return this._tokenCount;
}
public int getEncodedSize() {
int result = this._token instanceof ArrayPtg ? 8 : this._token.getSize();
for (ParseNode encodedSize : this._children) {
result += encodedSize.getEncodedSize();
}
return result;
}
public static Ptg[] toTokenArray(ParseNode rootNode) {
TokenCollector temp = new TokenCollector(rootNode.getTokenCount());
rootNode.collectPtgs(temp);
return temp.getResult();
}
private void collectPtgs(TokenCollector temp) {
if (isIf(this._token)) {
collectIfPtgs(temp);
return;
}
boolean isPreFixOperator = (this._token instanceof MemFuncPtg) || (this._token instanceof MemAreaPtg);
if (isPreFixOperator) {
temp.add(this._token);
}
for (ParseNode collectPtgs : getChildren()) {
collectPtgs.collectPtgs(temp);
}
if (!isPreFixOperator) {
temp.add(this._token);
}
}
private void collectIfPtgs(TokenCollector temp) {
getChildren()[0].collectPtgs(temp);
int ifAttrIndex = temp.createPlaceholder();
getChildren()[1].collectPtgs(temp);
int skipAfterTrueParamIndex = temp.createPlaceholder();
AttrPtg attrIf = AttrPtg.createIf(temp.sumTokenSizes(ifAttrIndex + 1, skipAfterTrueParamIndex) + 4);
AttrPtg attrSkipAfterTrue;
if (getChildren().length > 2) {
getChildren()[2].collectPtgs(temp);
int skipAfterFalseParamIndex = temp.createPlaceholder();
attrSkipAfterTrue = AttrPtg.createSkip(((temp.sumTokenSizes(skipAfterTrueParamIndex + 1, skipAfterFalseParamIndex) + 4) + 4) - 1);
AttrPtg attrSkipAfterFalse = AttrPtg.createSkip(3);
temp.setPlaceholder(ifAttrIndex, attrIf);
temp.setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue);
temp.setPlaceholder(skipAfterFalseParamIndex, attrSkipAfterFalse);
} else {
attrSkipAfterTrue = AttrPtg.createSkip(3);
temp.setPlaceholder(ifAttrIndex, attrIf);
temp.setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue);
}
temp.add(this._token);
}
private static boolean isIf(Ptg token) {
if ((token instanceof FuncVarPtg) && "IF".equals(((FuncVarPtg) token).getName())) {
return true;
}
return false;
}
public Ptg getToken() {
return this._token;
}
public ParseNode[] getChildren() {
return this._children;
}
}
|
9232630141dee9dc90e66c78618418926e1ed0c3 | 558 | java | Java | bpel-nobj/src/main/java/org/apache/ode/bpel/obj/serde/SmileOmSerializer.java | apache/ode | a0c2d1a3c24268523c81b4ddc125eb05d758c6f5 | [
"Apache-2.0"
] | 20 | 2015-06-03T05:42:40.000Z | 2022-02-15T05:22:13.000Z | bpel-nobj/src/main/java/org/apache/ode/bpel/obj/serde/SmileOmSerializer.java | apache/attic-ode | a0c2d1a3c24268523c81b4ddc125eb05d758c6f5 | [
"Apache-2.0"
] | 1 | 2016-03-10T22:34:09.000Z | 2016-03-10T22:34:09.000Z | bpel-nobj/src/main/java/org/apache/ode/bpel/obj/serde/SmileOmSerializer.java | apache/ode | a0c2d1a3c24268523c81b4ddc125eb05d758c6f5 | [
"Apache-2.0"
] | 57 | 2015-03-12T12:45:09.000Z | 2021-11-10T19:09:27.000Z | 25.363636 | 105 | 0.781362 | 996,196 | package org.apache.ode.bpel.obj.serde;
import java.io.OutputStream;
import org.apache.ode.bpel.obj.OProcess;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
/**
* OModel Serializer that corresponding to {@link OmSerdeFactory.SerializeFormat#FORMAT_SERIALIZED_SMILE}
* @see JsonOmDeserializer
*/
public class SmileOmSerializer extends JsonOmSerializer{
public SmileOmSerializer(){
super();
factory = new SmileFactory();
}
public SmileOmSerializer(OutputStream out, OProcess process) {
super(out, process, new SmileFactory());
}
}
|
92326339e9ae9accfb2292d26af43a02915602d8 | 9,432 | java | Java | test/StableTopoSort.java | slonopotamus/stable-topo-sort | 2e99a9fe0a836bad6f27e93c1762e1bb707c997b | [
"Unlicense"
] | null | null | null | test/StableTopoSort.java | slonopotamus/stable-topo-sort | 2e99a9fe0a836bad6f27e93c1762e1bb707c997b | [
"Unlicense"
] | 1 | 2021-09-30T08:57:55.000Z | 2021-10-01T14:29:24.000Z | test/StableTopoSort.java | slonopotamus/stable-topo-sort | 2e99a9fe0a836bad6f27e93c1762e1bb707c997b | [
"Unlicense"
] | null | null | null | 24.435233 | 127 | 0.470314 | 996,197 | import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.*;
/**
* http://www.timl.id.au/SCC/
* https://doi.org/10.1016/j.ipl.2015.08.010
* https://github.com/DavePearce/StronglyConnectedComponents/blob/master/src/PeaFindScc2.java
* https://github.com/gonum/gonum/blob/master/graph/topo/tarjan.go
* http://homepages.ecs.vuw.ac.nz/~djp/files/IPL15-preprint.pdf
* https://habr.com/ru/post/451208/
*/
public final class StableTopoSort {
/**
* Performs stable "topological" sort of directed graphs (including graphs with cycles).
* Possible optimization: instead of counting sort just put vertices on rindex[v] positions if there were no SCCs detected.
*/
static void stableTopoSort(Node[] nodes) {
// 0. Remember where each node was
for (int i = 0; i < nodes.length; ++i) {
nodes[i].index = i;
}
// 1. Sort edges according to node indices
for (int i = 0; i < nodes.length; ++i) {
nodes[i].edges.sort(Comparator.comparingInt(o -> o.index));
}
// 2. Perform Tarjan SCC
final PeaSCC scc = new PeaSCC(nodes);
scc.visit();
// 3. Perform *reverse* counting sort
reverseCountingSort(nodes, scc.rindex);
}
static final class PeaSCC {
final Node[] graph;
final int[] rindex;
DoubleStack vS;
DoubleStack iS;
boolean[] root;
int index;
int c;
PeaSCC(Node[] g) {
this.graph = g;
this.rindex = new int[g.length];
this.index = 1;
this.c = g.length - 1;
vS = new DoubleStack(graph.length);
iS = new DoubleStack(graph.length);
root = new boolean[graph.length];
}
void visit() {
// Attn! We're walking nodes in reverse
for (int i = graph.length - 1; i >= 0; --i) {
if (rindex[i] == 0) {
visit(i);
}
}
}
void visit(int v) {
beginVisiting(v);
while (!vS.isEmptyFront()) {
visitLoop();
}
}
void visitLoop() {
int v = vS.topFront();
int i = iS.topFront();
int numEdges = graph[v].edges.size();
// Continue traversing out-edges until none left.
while (i <= numEdges) {
// Continuation
if (i > 0) {
// Update status for previously traversed out-edge
finishEdge(v, i - 1);
}
if (i < numEdges && beginEdge(v, i)) {
return;
}
i = i + 1;
}
// Finished traversing out edges, update component info
finishVisiting(v);
}
void beginVisiting(int v) {
// First time this node encountered
vS.pushFront(v);
iS.pushFront(0);
root[v] = true;
rindex[v] = index;
++index;
}
void finishVisiting(int v) {
// Take this vertex off the call stack
vS.popFront();
iS.popFront();
// Update component information
if (root[v]) {
--index;
while (!vS.isEmptyBack() && rindex[v] <= rindex[vS.topBack()]) {
int w = vS.popBack();
rindex[w] = c;
--index;
}
rindex[v] = c;
--c;
} else {
vS.pushBack(v);
}
}
boolean beginEdge(int v, int k) {
int w = graph[v].edges.get(k).index;
if (rindex[w] == 0) {
iS.popFront();
iS.pushFront(k + 1);
beginVisiting(w);
return true;
} else {
return false;
}
}
void finishEdge(int v, int k) {
int w = graph[v].edges.get(k).index;
if (rindex[w] < rindex[v]) {
rindex[v] = rindex[w];
root[v] = false;
}
}
}
static void reverseCountingSort(Node[] nodes, int[] rindex) {
final int[] count = new int[nodes.length];
for (int i = 0; i < rindex.length; ++i) {
final int cindex = nodes.length - 1 - rindex[i];
++count[cindex];
}
for (int i = 1; i < count.length; ++i) {
count[i] += count[i - 1];
}
final Node[] output = new Node[nodes.length];
for (int i = 0; i < output.length; ++i) {
final int cindex = nodes.length - 1 - rindex[i];
// Attn! We're sorting in reverse
final int outputIndex = output.length - count[cindex];
output[outputIndex] = nodes[i];
--count[cindex];
}
System.arraycopy(output, 0, nodes, 0, nodes.length);
}
public static class DoubleStack {
final int[] items;
int fp; // front pointer
int bp; // back pointer
DoubleStack(int capacity) {
this.fp = 0;
this.bp = capacity;
this.items = new int[capacity];
}
boolean isEmptyFront() {
return fp == 0;
}
int topFront() {
return items[fp - 1];
}
int popFront() {
return items[--fp];
}
void pushFront(int item) {
items[fp++] = item;
}
boolean isEmptyBack() {
return bp == items.length;
}
int topBack() {
return items[bp];
}
int popBack() {
return items[bp++];
}
void pushBack(int item) {
items[--bp] = item;
}
}
static final Node[] emptyNodes = {};
@Test
public void testLoop3() {
node("D");
node("E");
node("C");
node("B");
node("A");
edge("A", "B");
edge("B", "C");
edge("C", "A");
assertSort("D", "E", "C", "B", "A");
}
@Test
public void testReverseLoop() {
node("B");
node("A");
edge("A", "B");
edge("B", "A");
assertSort("B", "A");
}
List<Node> graph = new ArrayList<>();
Map<String, Node> nodes = new HashMap<>();
@AfterMethod
void afterMethod() {
nodes.clear();
graph.clear();
}
void node(String name) {
Node node = new Node(name);
Assert.assertNull(nodes.put(name, node));
graph.add(node);
}
void edge(String from, String... tos) {
Node fromNode = nodes.get(from);
Assert.assertNotNull(fromNode);
for (String to : tos) {
Node toNode = nodes.get(to);
Assert.assertNotNull(toNode);
fromNode.addEdgeTo(toNode);
}
}
@Test
public void testSingle() {
node("A");
assertSort("A");
}
@Test
public void testEmpty() {
assertSort();
}
@Test
public void testUnconnected() {
node("A");
node("B");
node("C");
assertSort("A", "B", "C");
}
@Test
public void testTrivial() {
node("A");
node("B");
edge("A", "B");
assertSort("A", "B");
}
void assertSort(String... expected) {
Node[] graphArr = graph.toArray(emptyNodes);
doAssertSort(graphArr, expected);
// Since our algorithm is stable, subsequent sorts must not change order
doAssertSort(graphArr, expected);
}
private void doAssertSort(Node[] graphArr, String[] expected) {
stableTopoSort(graphArr);
Assert.assertEquals(graphArr.length, expected.length);
final String[] actualNames = Arrays.stream(graphArr).map(node -> node.name).toArray(String[]::new);
Assert.assertEquals(Arrays.toString(actualNames), Arrays.toString(expected));
}
@Test
public void testReverse() {
node("A");
node("B");
edge("B", "A");
assertSort("B", "A");
}
@Test
public void testTransitive() {
node("A");
node("B");
node("C");
edge("B", "A");
edge("C", "B");
assertSort("C", "B", "A");
}
/**
* https://sourceware.org/bugzilla/show_bug.cgi?id=17645#c8
*/
@Test
public void testInitorder() {
node("main");
node("a2");
node("a1");
node("b2");
node("b1");
node("a3");
node("a4");
edge("a2", "a1");
edge("b2", "b1", "a2");
edge("a3", "b2", "b1");
edge("a4", "a3");
edge("main", "a4", "a1", "b2");
assertSort("main", "a4", "a3", "b2", "b1", "a2", "a1");
}
static final class Node {
String name;
List<Node> edges = new ArrayList<>();
Set<Node> uniqueEdges = new HashSet<>();
int index;
Node(String name) {
this.name = name;
}
void addEdgeTo(Node node) {
Assert.assertTrue(uniqueEdges.add(node));
edges.add(node);
}
@Override
public String toString() {
return name;
}
}
}
|
9232650e5d06a2042398c84d7309630c32d897dc | 3,028 | java | Java | external/storm-hdfs/src/test/java/org/apache/storm/hdfs/trident/TridentSequenceTopology.java | ADSC-Cloud/storm | 720b6527449d80e0d822cf91bdbca9cf402f1c22 | [
"Apache-2.0"
] | 47 | 2015-01-23T01:32:09.000Z | 2019-01-14T08:40:00.000Z | external/storm-hdfs/src/test/java/org/apache/storm/hdfs/trident/TridentSequenceTopology.java | ADSC-Cloud/storm | 720b6527449d80e0d822cf91bdbca9cf402f1c22 | [
"Apache-2.0"
] | 11 | 2015-01-09T05:23:43.000Z | 2018-05-10T08:18:08.000Z | external/storm-hdfs/src/test/java/org/apache/storm/hdfs/trident/TridentSequenceTopology.java | ADSC-Cloud/storm | 720b6527449d80e0d822cf91bdbca9cf402f1c22 | [
"Apache-2.0"
] | 35 | 2015-01-14T18:27:33.000Z | 2020-06-02T08:59:50.000Z | 42.055556 | 136 | 0.685271 | 996,198 | package org.apache.storm.hdfs.trident;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import org.apache.storm.hdfs.common.rotation.MoveFileAction;
import org.apache.storm.hdfs.trident.format.*;
import org.apache.storm.hdfs.trident.rotation.FileRotationPolicy;
import org.apache.storm.hdfs.trident.rotation.FileSizeRotationPolicy;
import storm.trident.Stream;
import storm.trident.TridentState;
import storm.trident.TridentTopology;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.state.StateFactory;
import storm.trident.tuple.TridentTuple;
public class TridentSequenceTopology {
public static StormTopology buildTopology(String hdfsUrl){
FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence", "key"), 1000, new Values("the cow jumped over the moon", 1l),
new Values("the man went to the store and bought some candy", 2l), new Values("four score and seven years ago", 3l),
new Values("how many apples can you eat", 4l), new Values("to be or not to be the person", 5l));
spout.setCycle(true);
TridentTopology topology = new TridentTopology();
Stream stream = topology.newStream("spout1", spout);
Fields hdfsFields = new Fields("sentence", "key");
FileNameFormat fileNameFormat = new DefaultFileNameFormat()
.withPath("/trident")
.withPrefix("trident")
.withExtension(".seq");
FileRotationPolicy rotationPolicy = new FileSizeRotationPolicy(5.0f, FileSizeRotationPolicy.Units.MB);
HdfsState.Options seqOpts = new HdfsState.SequenceFileOptions()
.withFileNameFormat(fileNameFormat)
.withSequenceFormat(new DefaultSequenceFormat("key", "sentence"))
.withRotationPolicy(rotationPolicy)
.withFsUrl(hdfsUrl)
.addRotationAction(new MoveFileAction().toDestination("/dest2/"));
StateFactory factory = new HdfsStateFactory().withOptions(seqOpts);
TridentState state = stream
.partitionPersist(factory, hdfsFields, new HdfsUpdater(), new Fields());
return topology.build();
}
public static void main(String[] args) throws Exception {
Config conf = new Config();
conf.setMaxSpoutPending(5);
if (args.length == 1) {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("wordCounter", conf, buildTopology(args[0]));
Thread.sleep(120 * 1000);
}
else if(args.length == 2) {
conf.setNumWorkers(3);
StormSubmitter.submitTopology(args[1], conf, buildTopology(args[0]));
} else{
System.out.println("Usage: TridentFileTopology <hdfs url> [topology name]");
}
}
}
|
9232653e716119d0ca7b83d81c99a455ab90b66f | 132 | java | Java | src/SpaceShip.java | PromiNent-Jin/RocketSimulation | eafa5cd8272039a3a36e8f14b9a239b07484251a | [
"MIT"
] | null | null | null | src/SpaceShip.java | PromiNent-Jin/RocketSimulation | eafa5cd8272039a3a36e8f14b9a239b07484251a | [
"MIT"
] | null | null | null | src/SpaceShip.java | PromiNent-Jin/RocketSimulation | eafa5cd8272039a3a36e8f14b9a239b07484251a | [
"MIT"
] | null | null | null | 18.857143 | 32 | 0.659091 | 996,199 | public interface SpaceShip {
boolean launch();
boolean land();
boolean canCarry(Item item);
int carry(Item item);
}
|
923266f11ad9a03fe1b545880211a158226b01b3 | 1,824 | java | Java | taotao-cloud-microservice/taotao-cloud-store/taotao-cloud-store-biz/src/main/java/com/taotao/cloud/store/biz/service/impl/FreightTemplateServiceChildImpl.java | shuigedeng/taotao-cloud-paren | 3d281b919490f7cbee4520211e2eee5da7387564 | [
"Apache-2.0"
] | 47 | 2021-04-13T10:32:13.000Z | 2022-03-31T10:30:30.000Z | taotao-cloud-microservice/taotao-cloud-store/taotao-cloud-store-biz/src/main/java/com/taotao/cloud/store/biz/service/impl/FreightTemplateServiceChildImpl.java | shuigedeng/taotao-cloud-paren | 3d281b919490f7cbee4520211e2eee5da7387564 | [
"Apache-2.0"
] | 1 | 2021-11-01T07:41:04.000Z | 2021-11-01T07:41:10.000Z | taotao-cloud-microservice/taotao-cloud-store/taotao-cloud-store-biz/src/main/java/com/taotao/cloud/store/biz/service/impl/FreightTemplateServiceChildImpl.java | shuigedeng/taotao-cloud-paren | 3d281b919490f7cbee4520211e2eee5da7387564 | [
"Apache-2.0"
] | 21 | 2021-04-13T10:32:17.000Z | 2022-03-26T07:43:22.000Z | 38 | 125 | 0.80318 | 996,200 | package com.taotao.cloud.store.biz.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taotao.cloud.store.biz.entity.FreightTemplateChild;
import com.taotao.cloud.store.biz.mapper.FreightTemplateChildMapper;
import com.taotao.cloud.store.biz.service.FreightTemplateChildService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 配送子模板业务层实现
*
*
* @since 2020-03-07 09:24:33
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class FreightTemplateServiceChildImpl extends ServiceImpl<FreightTemplateChildMapper, FreightTemplateChild> implements
FreightTemplateChildService {
@Override
public List<FreightTemplateChild> getFreightTemplateChild(String freightTemplateId) {
LambdaQueryWrapper<FreightTemplateChild> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper.eq(FreightTemplateChild::getFreightTemplateId, freightTemplateId);
return this.baseMapper.selectList(lambdaQueryWrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean addFreightTemplateChild(List<FreightTemplateChild> freightTemplateChildren) {
return this.saveBatch(freightTemplateChildren);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean removeFreightTemplate(String freightTemplateId) {
LambdaQueryWrapper<FreightTemplateChild> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper.eq(FreightTemplateChild::getFreightTemplateId, freightTemplateId);
return this.remove(lambdaQueryWrapper);
}
}
|
9232671b5b71101a5863887e922ceb41a8268388 | 7,169 | java | Java | sparkzxl-log-starter/src/main/java/com/github/sparkzxl/log/netty/LogWebSocketHandler.java | zhouxinlei298/sparksys-component | 62cd12d432d61e10748c13179891fa37f0f604e6 | [
"Apache-2.0"
] | 13 | 2020-09-12T10:37:27.000Z | 2021-07-09T09:32:11.000Z | sparkzxl-log-starter/src/main/java/com/github/sparkzxl/log/netty/LogWebSocketHandler.java | zhouxinlei298/sparksys-component | 62cd12d432d61e10748c13179891fa37f0f604e6 | [
"Apache-2.0"
] | 8 | 2020-12-09T07:27:31.000Z | 2021-10-30T06:02:19.000Z | sparkzxl-log-starter/src/main/java/com/github/sparkzxl/log/netty/LogWebSocketHandler.java | zhouxinlei298/sparksys-component | 62cd12d432d61e10748c13179891fa37f0f604e6 | [
"Apache-2.0"
] | 5 | 2020-09-16T01:04:22.000Z | 2021-06-02T06:20:47.000Z | 42.928144 | 134 | 0.567722 | 996,201 | package com.github.sparkzxl.log.netty;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HtmlUtil;
import com.alibaba.fastjson.JSON;
import com.github.sparkzxl.core.util.StrPool;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* description: WebSocket处理器,处理websocket连接相关
*
* @author zhouxinlei
*/
@Slf4j
@ChannelHandler.Sharable
public class LogWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static final Map<String, Integer> LENGTH_MAP = Maps.newConcurrentMap();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,
3,
0,
NANOSECONDS,
new LinkedBlockingDeque<>(1000),
new CustomizableThreadFactory());
private String logPath;
private static Map<String, String> getUrlParams(String url) {
Map<String, String> map = Maps.newHashMap();
url = url.replace(StrPool.QUESTION_MARK, StrPool.SEMICOLON);
if (!url.contains(StrPool.SEMICOLON)) {
return map;
}
if (url.split(StrPool.SEMICOLON).length > 0) {
String[] arr = url.split(StrPool.SEMICOLON)[1].split(StrPool.AMPERSAND);
for (String s : arr) {
String key = s.split(StrPool.EQUALS)[0];
String value = s.split(StrPool.EQUALS)[1];
map.put(key, value);
}
}
return map;
}
public void setLogPath(String logPath) {
this.logPath = logPath;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
log.info("与客户端建立连接,通道开启!channelId:{}", ctx.channel().id().toString());
//添加到channelGroup通道组
ChannelHandlerPool.channelGroup.add(ctx.channel());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.info("与客户端断开连接,通道关闭!channelId:{}", ctx.channel().id().toString());
//添加到channelGroup 通道组
ChannelHandlerPool.channelGroup.remove(ctx.channel());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
String uri = request.uri();
Map<String, String> paramMap = getUrlParams(uri);
log.info("接收到的参数是:{}", JSON.toJSONString(paramMap));
//如果url包含参数,需要处理
if (uri.contains(StrPool.QUESTION_MARK)) {
String newUri = uri.substring(0, uri.indexOf(StrPool.QUESTION_MARK));
System.out.println(newUri);
request.setUri(newUri);
}
} else if (msg instanceof TextWebSocketFrame) {
//正常的TEXT消息类型
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
String text = frame.text();
log.info("客户端收到服务器数据:{}", text);
if (StringUtils.equals(text, "log")) {
LENGTH_MAP.put(ctx.channel().id().toString(), 1);
threadPoolExecutor.execute(() -> {
boolean first = true;
while (ctx.channel().isActive()) {
//日志文件路径,获取最新的
try {
File logFile = ResourceUtils.getFile(logPath);
RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
randomFile.seek(LENGTH_MAP.get(ctx.channel().id().toString()));
String tmp;
List<String> resourceList = Lists.newArrayList();
while ((tmp = randomFile.readLine()) != null) {
String log = new String(tmp.getBytes("ISO8859-1"));
String escapeLog = HtmlUtil.escape(log);
escapeLog = escapeLog.replaceAll("\"", """)
.replaceAll("\\s", StrPool.HTML_NBSP);
//处理等级
escapeLog = escapeLog.replace("DEBUG", "<span style='color: black;'>DEBUG</span>");
escapeLog = escapeLog.replace("INFO", "<span style='color: #3FB1F5;'>INFO</span>");
escapeLog = escapeLog.replace("WARN", "<span style='color: #F16372;'>WARN</span>");
escapeLog = escapeLog.replace("ERROR", "<span style='color: red;'>ERROR</span>");
escapeLog = escapeLog.replace("application", "<span style='color: #3FB1F5;'>application</span>");
//处理类名
String regex = "\\[(.*?)]";
String result = ReUtil.get(regex, escapeLog, 1);
if (StringUtils.isNotBlank(result)) {
escapeLog = escapeLog.replace(result, "<span style='color: #298a8a;'>" + result + "</span>");
}
resourceList.add(escapeLog);
}
LENGTH_MAP.put(ctx.channel().id().toString(), (int) randomFile.length());
//第一次如果太大,截取最新的1000行就够了,避免传输的数据太大
if (first && resourceList.size() > 1000) {
resourceList = ListUtil.sub(resourceList, resourceList.size() - 1000, resourceList.size());
first = false;
}
sendAllMessage(StringUtils.join(resourceList, "<br/>"));
//休眠半秒
Thread.sleep(500);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
super.channelRead(ctx, msg);
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
}
private void sendAllMessage(String message) {
//收到信息后,群发给所有channel
ChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));
}
}
|
923267d27ecf23018920c633994d489ee5a258e3 | 552 | java | Java | cvdnn-lang/src/main/java/android/io/IParcelable.java | cvdnn/ZtoneLang | efc422738e2b463ab1d3990ef6ee64b71e7ea5a6 | [
"MulanPSL-1.0"
] | null | null | null | cvdnn-lang/src/main/java/android/io/IParcelable.java | cvdnn/ZtoneLang | efc422738e2b463ab1d3990ef6ee64b71e7ea5a6 | [
"MulanPSL-1.0"
] | null | null | null | cvdnn-lang/src/main/java/android/io/IParcelable.java | cvdnn/ZtoneLang | efc422738e2b463ab1d3990ef6ee64b71e7ea5a6 | [
"MulanPSL-1.0"
] | null | null | null | 21.230769 | 63 | 0.672101 | 996,202 | package android.io;
import android.assist.Assert;
import android.os.Parcel;
import android.os.Parcelable;
public abstract class IParcelable implements Parcelable {
public abstract IParcelable readFromParcel(Parcel in);
@Override
public abstract void writeToParcel(Parcel dest, int flags);
@Override
public int describeContents() {
return 0;
}
public final void writeString(Parcel dest, String val) {
if (dest != null) {
dest.writeString(Assert.notEmpty(val) ? val : "");
}
}
}
|
923268281aa70dcca5f0d84981dd238c966b8142 | 1,615 | java | Java | editor/src/main/java/io/github/rosemoe/editor/widget/KeyMetaStates.java | RandunuK/CodeEditor | fc2e5c8b497ffb6dda83807bc47f937babc00dfd | [
"Apache-2.0"
] | null | null | null | editor/src/main/java/io/github/rosemoe/editor/widget/KeyMetaStates.java | RandunuK/CodeEditor | fc2e5c8b497ffb6dda83807bc47f937babc00dfd | [
"Apache-2.0"
] | null | null | null | editor/src/main/java/io/github/rosemoe/editor/widget/KeyMetaStates.java | RandunuK/CodeEditor | fc2e5c8b497ffb6dda83807bc47f937babc00dfd | [
"Apache-2.0"
] | null | null | null | 27.844828 | 77 | 0.689783 | 996,203 | /*
* Copyright 2020-2021 Rosemoe
*
* 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 io.github.rosemoe.editor.widget;
import android.text.Editable;
import android.view.KeyEvent;
/**
* Handles key events such SHIFT
* @author Rosemoe
*/
public class KeyMetaStates extends android.text.method.MetaKeyKeyListener {
private CodeEditor editor;
/**
* Dummy text used for Android original APIs
*/
private Editable dest = Editable.Factory.getInstance().newEditable("");
public KeyMetaStates(CodeEditor editor) {
this.editor = editor;
}
public void onKeyDown(KeyEvent event) {
super.onKeyDown(editor, dest, event.getKeyCode(), event);
}
public void onKeyUp(KeyEvent event) {
super.onKeyUp(editor, dest, event.getKeyCode(), event);
}
public boolean isShiftPressed() {
return getMetaState(dest, META_SHIFT_ON) != 0;
}
public void adjust() {
adjustMetaAfterKeypress(dest);
}
public void clearMetaStates(int states) {
clearMetaKeyState(editor, dest, states);
}
}
|
9232685f3474ad4e43eb01767568951f9297b38d | 1,927 | java | Java | talk-db-proxy/src/main/java/com/blt/talk/service/jpa/entity/IMRelationShip.java | xrogzu/sctalk | 9eab7c5b02b78212899e824d3419b245884628ca | [
"Apache-2.0"
] | 168 | 2017-05-20T15:33:27.000Z | 2022-03-03T04:03:59.000Z | server/talk-db-proxy/src/main/java/com/blt/talk/service/jpa/entity/IMRelationShip.java | tanbinh123/sctalk | aa5b8d185d180b841c17d452a75d16821d96a3bc | [
"Apache-2.0"
] | 9 | 2017-07-05T09:48:36.000Z | 2021-08-06T06:55:09.000Z | server/talk-db-proxy/src/main/java/com/blt/talk/service/jpa/entity/IMRelationShip.java | tanbinh123/sctalk | aa5b8d185d180b841c17d452a75d16821d96a3bc | [
"Apache-2.0"
] | 94 | 2017-05-20T15:50:15.000Z | 2022-03-25T03:45:15.000Z | 20.5 | 86 | 0.653866 | 996,204 | package com.blt.talk.service.jpa.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the im_relation_ship database table.
*
*/
@Entity
@Table(name = "im_relation_ship")
@NamedQuery(name = "IMRelationShip.findAll", query = "SELECT i FROM IMRelationShip i")
public class IMRelationShip implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "big_id", nullable = false)
private Long bigId;
@Column(nullable = false)
private int created;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private Long id;
@Column(name = "small_id", nullable = false)
private Long smallId;
private byte status;
@Column(nullable = false)
private int updated;
public IMRelationShip() {}
public Long getBigId() {
return this.bigId;
}
public int getCreated() {
return this.created;
}
public Long getId() {
return this.id;
}
public Long getSmallId() {
return this.smallId;
}
public byte getStatus() {
return this.status;
}
public int getUpdated() {
return this.updated;
}
public void setBigId(Long bigId) {
this.bigId = bigId;
}
public void setCreated(int created) {
this.created = created;
}
public void setId(Long id) {
this.id = id;
}
public void setSmallId(Long smallId) {
this.smallId = smallId;
}
public void setStatus(byte status) {
this.status = status;
}
public void setUpdated(int updated) {
this.updated = updated;
}
}
|
92326906c61838d649ce7fbfecd5f59b86c34b4d | 3,571 | java | Java | SpringCloud-Custom-ConfigCenter/custom-config-service/src/main/java/com/xiao/custom/config/service/service/impl/ServerHostConfigServiceImpl.java | ghl1024/SpringCloud-Demo | 6580ad6af9e918a407ecfde3f6ff61e203ff1148 | [
"MIT"
] | 198 | 2018-12-24T10:06:37.000Z | 2022-03-11T01:45:06.000Z | SpringCloud-Custom-ConfigCenter/custom-config-service/src/main/java/com/xiao/custom/config/service/service/impl/ServerHostConfigServiceImpl.java | ghl1024/SpringCloud-Demo | 6580ad6af9e918a407ecfde3f6ff61e203ff1148 | [
"MIT"
] | 6 | 2019-11-13T08:39:41.000Z | 2022-01-04T16:33:16.000Z | SpringCloud-Custom-ConfigCenter/custom-config-service/src/main/java/com/xiao/custom/config/service/service/impl/ServerHostConfigServiceImpl.java | ghl1024/SpringCloud-Demo | 6580ad6af9e918a407ecfde3f6ff61e203ff1148 | [
"MIT"
] | 113 | 2018-12-06T13:10:47.000Z | 2022-03-14T07:02:36.000Z | 33.373832 | 111 | 0.731448 | 996,205 | package com.xiao.custom.config.service.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiao.custom.config.pojo.dto.ServerHostConfigDto;
import com.xiao.custom.config.pojo.entity.ServerHostConfig;
import com.xiao.custom.config.pojo.mapper.ApplicationMapper;
import com.xiao.custom.config.pojo.mapper.ServerHostConfigMapper;
import com.xiao.custom.config.pojo.query.ServerHostConfigQuery;
import com.xiao.custom.config.service.service.ServerHostConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
* [简要描述]:
* [详细描述]:
*
* @author jun.liu
* @version 1.0, 2018/11/27 09:48
* @since JDK 1.8
*/
@Service
public class ServerHostConfigServiceImpl implements ServerHostConfigService
{
@Resource
private ServerHostConfigMapper serverHostConfigMapper;
@Autowired
private ApplicationMapper applicationConfigMapper;
@Override
@Transactional
public int save(ServerHostConfigDto serverHostConfigDto)
{
serverHostConfigDto.setCreateTime(new Date());
ServerHostConfig serverHostConfig = serverHostConfigDtoconvertserverHostConfig(serverHostConfigDto);
return serverHostConfigMapper.insert(serverHostConfig);
}
@Override
@Transactional
public int update(ServerHostConfigDto serverHostConfigDto)
{
ServerHostConfig serverHostConfig = serverHostConfigDtoconvertserverHostConfig(serverHostConfigDto);
return serverHostConfigMapper.updateByPrimaryKey(serverHostConfig);
}
/**
* [简要描述]: -1 标识删除失败,已关联应用不能删除该区域,必须先删除应用<br/>
* [详细描述]:<br/>
*
* @param id :
* @return int
* llxiao 2019/1/2 - 17:54
**/
@Override
@Transactional
public int delete(Long id)
{
// if (applicationConfigMapper.countByRegionId(id) > 0)
// {
// return -1;
// }
return serverHostConfigMapper.deleteByPrimaryKey(id);
}
@Override
public PageInfo<ServerHostConfigDto> pageServerHostConfig(ServerHostConfigQuery serverHostConfigQuery,
Integer pageNum, Integer pageSize)
{
PageHelper.startPage(pageNum, pageSize);
List<ServerHostConfigDto> list = serverHostConfigMapper.pageServerHostConfig(serverHostConfigQuery);
return new PageInfo<>(list);
}
/**
* [简要描述]:serverHostConfigDto转ServerHostConfig<br/>
* [详细描述]:serverHostConfigDto转ServerHostConfig<br/>
*
* @return ServerHostConfig
**/
public ServerHostConfig serverHostConfigDtoconvertserverHostConfig(ServerHostConfigDto serverHostConfigDto)
{
ServerHostConfig serverHostConfig = new ServerHostConfig();
serverHostConfig.setId(serverHostConfigDto.getId());
serverHostConfig.setRegionId(serverHostConfigDto.getRegionId());
serverHostConfig.setServerDesc(serverHostConfigDto.getServerDesc());
serverHostConfig.setServerHost(serverHostConfigDto.getServerHost());
serverHostConfig.setCreateTime(serverHostConfigDto.getCreateTime());
serverHostConfig.setUpdateTime(new Date());
return serverHostConfig;
}
@Override
public ServerHostConfig selectServerHostConfigById(Long id)
{
// TODO Auto-generated method stub
return serverHostConfigMapper.selectByPrimaryKey(id);
}
}
|
923269606049c49ba1537422e2855918e31346e9 | 2,062 | java | Java | src/test/java/com/restfb/types/ConversationTest.java | ViktorSukhonin/restfb | ceea0eccd654898fabbba7341ee8583a8ffe9339 | [
"MIT"
] | 572 | 2015-02-18T16:32:44.000Z | 2022-03-25T17:25:34.000Z | src/test/java/com/restfb/types/ConversationTest.java | ViktorSukhonin/restfb | ceea0eccd654898fabbba7341ee8583a8ffe9339 | [
"MIT"
] | 984 | 2015-02-18T13:39:46.000Z | 2022-02-18T10:05:42.000Z | src/test/java/com/restfb/types/ConversationTest.java | ViktorSukhonin/restfb | ceea0eccd654898fabbba7341ee8583a8ffe9339 | [
"MIT"
] | 409 | 2015-02-18T12:18:33.000Z | 2022-03-22T02:32:19.000Z | 44.826087 | 140 | 0.760912 | 996,206 | /*
* Copyright (c) 2010-2021 Mark Allen, Norbert Bartels.
*
* 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 com.restfb.types;
import static com.restfb.testutils.RestfbAssertions.assertThat;
import org.junit.jupiter.api.Test;
import com.restfb.AbstractJsonMapperTests;
public class ConversationTest extends AbstractJsonMapperTests {
@Test
void checkV10_instagram() {
Conversation instaConversation = createJsonMapper().toJavaObject(jsonFromClasspath("v10_0/instagram-conversation"), Conversation.class);
assertThat(instaConversation).isNotNull();
assertThat(instaConversation.getParticipants()).isNotNull();
assertThat(instaConversation.getParticipants()).isNotEmpty();
for (ExtendedReferenceType refType : instaConversation.getParticipants()) {
assertThat(refType.getUserId()).isEqualTo("<IGID>");
assertThat(refType.getUsername()).isEqualTo("<IG_USER_NAME>");
assertThat(refType.getId()).isIn("<IGID>","<IGSID>");
assertThat(refType.isInstagram()).isTrue();
}
}
}
|
9232696ee7b1dee22aa46e0336516413a5a63c04 | 627 | java | Java | Service/src/main/java/com/zhzteam/zhz233/mapper/zlb/GoodsRentMapper.java | Archer-Wen/ZHZ-project | cfaf47b58317beb4d48e8d0806029fe54ab95d0f | [
"MIT"
] | 2 | 2021-01-01T15:22:36.000Z | 2021-03-08T13:25:30.000Z | Service/src/main/java/com/zhzteam/zhz233/mapper/zlb/GoodsRentMapper.java | Archer-Wen/ZHZ-project | cfaf47b58317beb4d48e8d0806029fe54ab95d0f | [
"MIT"
] | 3 | 2020-10-23T02:37:58.000Z | 2022-03-15T06:15:57.000Z | Service/src/main/java/com/zhzteam/zhz233/mapper/zlb/GoodsRentMapper.java | Archer-Wen/ZHZ-project | cfaf47b58317beb4d48e8d0806029fe54ab95d0f | [
"MIT"
] | 5 | 2018-10-23T07:06:31.000Z | 2022-03-10T02:31:44.000Z | 27.26087 | 54 | 0.665072 | 996,207 | package com.zhzteam.zhz233.mapper.zlb;
import com.zhzteam.zhz233.model.zlb.GoodsRentResult;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface GoodsRentMapper {
/**
* 返回 List<GoodsRentResult> Limit N
* @param goodstype
* @param goodsrecomm
* @param goodsstatus
* @param pagesize
* @return
*/
public List<GoodsRentResult> selectTByKey(
@Param("goodstype") Integer goodstype,
@Param("goodsrecomm") Integer goodsrecomm,
@Param("goodsstatus") Integer goodsstatus,
@Param("pagesize") Integer pagesize);
}
|
92326a25ca15aa4f562dcdcbac36367f1796581f | 214 | java | Java | src/main/java/data/QuestionSubject.java | VennMaker/vennmaker-source | 5bb5a446ab00555800da211a2f6c29ab50a5aa59 | [
"Apache-2.0"
] | 2 | 2019-07-05T14:18:31.000Z | 2020-09-01T08:06:04.000Z | src/main/java/data/QuestionSubject.java | VennMaker/vennmaker-source | 5bb5a446ab00555800da211a2f6c29ab50a5aa59 | [
"Apache-2.0"
] | 16 | 2017-04-17T16:42:29.000Z | 2021-08-25T15:11:17.000Z | src/main/java/data/QuestionSubject.java | VennMaker/vennmaker-source | 5bb5a446ab00555800da211a2f6c29ab50a5aa59 | [
"Apache-2.0"
] | 4 | 2017-01-14T20:03:32.000Z | 2019-05-27T14:02:27.000Z | 13.375 | 58 | 0.649533 | 996,208 | /**
*
*/
package data;
/**
*
*
*/
public interface QuestionSubject extends AttributeSubject
{
public String getAnswer(String label);
public void saveAnswer(String label, String answer);
}
|
92326c113ab58978062c8d0b3b5ec77553e4eb5d | 165 | java | Java | volleynet/src/main/java/com/volleynet/network/RequestComplete.java | GAURAV-POSWAL/volleynet-android | 247a910268c9bd1b19d1255153b9491cb36546fb | [
"MIT"
] | 1 | 2019-12-13T07:28:55.000Z | 2019-12-13T07:28:55.000Z | volleynet/src/main/java/com/volleynet/network/RequestComplete.java | GAURAV-POSWAL/volleynet-android | 247a910268c9bd1b19d1255153b9491cb36546fb | [
"MIT"
] | null | null | null | volleynet/src/main/java/com/volleynet/network/RequestComplete.java | GAURAV-POSWAL/volleynet-android | 247a910268c9bd1b19d1255153b9491cb36546fb | [
"MIT"
] | null | null | null | 20.625 | 47 | 0.793939 | 996,209 | package com.volleynet.network;
public interface RequestComplete {
void requestSuccess(ResponseObject object);
void requestFailed(ResponseObject object);
}
|
92326d55cda20021e8c956e22de996f0643e2e31 | 5,188 | java | Java | src/java/com/echothree/control/user/item/server/command/GetItemImageTypeDescriptionCommand.java | echothreellc/echothree | 1744df7654097cc000e5eca32de127b5dc745302 | [
"Apache-2.0"
] | 1 | 2020-09-01T08:39:01.000Z | 2020-09-01T08:39:01.000Z | src/java/com/echothree/control/user/item/server/command/GetItemImageTypeDescriptionCommand.java | echothreellc/echothree | 1744df7654097cc000e5eca32de127b5dc745302 | [
"Apache-2.0"
] | null | null | null | src/java/com/echothree/control/user/item/server/command/GetItemImageTypeDescriptionCommand.java | echothreellc/echothree | 1744df7654097cc000e5eca32de127b5dc745302 | [
"Apache-2.0"
] | 1 | 2020-05-31T08:34:46.000Z | 2020-05-31T08:34:46.000Z | 51.88 | 146 | 0.720316 | 996,210 | // --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, LLC
//
// 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.echothree.control.user.item.server.command;
import com.echothree.control.user.item.common.form.GetItemImageTypeDescriptionForm;
import com.echothree.control.user.item.common.result.GetItemImageTypeDescriptionResult;
import com.echothree.control.user.item.common.result.ItemResultFactory;
import com.echothree.model.control.item.server.control.ItemControl;
import com.echothree.model.control.party.common.PartyTypes;
import com.echothree.model.control.party.server.control.PartyControl;
import com.echothree.model.control.security.common.SecurityRoleGroups;
import com.echothree.model.control.security.common.SecurityRoles;
import com.echothree.model.data.item.server.entity.ItemImageType;
import com.echothree.model.data.item.server.entity.ItemImageTypeDescription;
import com.echothree.model.data.party.server.entity.Language;
import com.echothree.model.data.user.common.pk.UserVisitPK;
import com.echothree.util.common.message.ExecutionErrors;
import com.echothree.util.common.validation.FieldDefinition;
import com.echothree.util.common.validation.FieldType;
import com.echothree.util.common.command.BaseResult;
import com.echothree.util.server.control.BaseSimpleCommand;
import com.echothree.util.server.control.CommandSecurityDefinition;
import com.echothree.util.server.control.PartyTypeDefinition;
import com.echothree.util.server.control.SecurityRoleDefinition;
import com.echothree.util.server.persistence.Session;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class GetItemImageTypeDescriptionCommand
extends BaseSimpleCommand<GetItemImageTypeDescriptionForm> {
private final static CommandSecurityDefinition COMMAND_SECURITY_DEFINITION;
private final static List<FieldDefinition> FORM_FIELD_DEFINITIONS;
static {
COMMAND_SECURITY_DEFINITION = new CommandSecurityDefinition(Collections.unmodifiableList(Arrays.asList(
new PartyTypeDefinition(PartyTypes.UTILITY.name(), null),
new PartyTypeDefinition(PartyTypes.EMPLOYEE.name(), Collections.unmodifiableList(Arrays.asList(
new SecurityRoleDefinition(SecurityRoleGroups.ItemImageType.name(), SecurityRoles.Description.name())
)))
)));
FORM_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList(
new FieldDefinition("ItemImageTypeName", FieldType.ENTITY_NAME, true, null, null),
new FieldDefinition("LanguageIsoName", FieldType.ENTITY_NAME, true, null, null)
));
}
/** Creates a new instance of GetItemImageTypeDescriptionCommand */
public GetItemImageTypeDescriptionCommand(UserVisitPK userVisitPK, GetItemImageTypeDescriptionForm form) {
super(userVisitPK, form, COMMAND_SECURITY_DEFINITION, FORM_FIELD_DEFINITIONS, false);
}
@Override
protected BaseResult execute() {
var itemControl = Session.getModelController(ItemControl.class);
GetItemImageTypeDescriptionResult result = ItemResultFactory.getGetItemImageTypeDescriptionResult();
String itemImageTypeName = form.getItemImageTypeName();
ItemImageType itemImageType = itemControl.getItemImageTypeByName(itemImageTypeName);
if(itemImageType != null) {
var partyControl = Session.getModelController(PartyControl.class);
String languageIsoName = form.getLanguageIsoName();
Language language = partyControl.getLanguageByIsoName(languageIsoName);
if(language != null) {
ItemImageTypeDescription itemImageTypeDescription = itemControl.getItemImageTypeDescription(itemImageType, language);
if(itemImageTypeDescription != null) {
result.setItemImageTypeDescription(itemControl.getItemImageTypeDescriptionTransfer(getUserVisit(), itemImageTypeDescription));
} else {
addExecutionError(ExecutionErrors.UnknownItemImageTypeDescription.name(), itemImageTypeName, languageIsoName);
}
} else {
addExecutionError(ExecutionErrors.UnknownLanguageIsoName.name(), languageIsoName);
}
} else {
addExecutionError(ExecutionErrors.UnknownItemImageTypeName.name(), itemImageTypeName);
}
return result;
}
}
|
92326dee7096ae49ba16f70a8789ad14c331305a | 7,017 | java | Java | src/main/java/com/google/cloud/compute/v1/NetworkEndpointGroupCloudFunction.java | twinkle-kadia/java-compute | 81455209a42016a2d09f67d4b7c09157db11d828 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/google/cloud/compute/v1/NetworkEndpointGroupCloudFunction.java | twinkle-kadia/java-compute | 81455209a42016a2d09f67d4b7c09157db11d828 | [
"Apache-2.0"
] | 2 | 2020-10-01T06:51:52.000Z | 2020-10-07T10:10:46.000Z | src/main/java/com/google/cloud/compute/v1/NetworkEndpointGroupCloudFunction.java | suraj-qlogic/java-compute | 81455209a42016a2d09f67d4b7c09157db11d828 | [
"Apache-2.0"
] | null | null | null | 29.733051 | 100 | 0.68334 | 996,211 | /*
* Copyright 2020 Google LLC
*
* 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 com.google.cloud.compute.v1;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;
@Generated("by GAPIC")
@BetaApi
/**
* Configuration for a Cloud Function network endpoint group (NEG). The function must be provided
* explicitly or in the URL mask.
*
* <p>Note: Cloud Function must be in the same project and located in the same region as the
* Serverless NEG.
*/
public final class NetworkEndpointGroupCloudFunction implements ApiMessage {
private final String function;
private final String urlMask;
private NetworkEndpointGroupCloudFunction() {
this.function = null;
this.urlMask = null;
}
private NetworkEndpointGroupCloudFunction(String function, String urlMask) {
this.function = function;
this.urlMask = urlMask;
}
@Override
public Object getFieldValue(String fieldName) {
if ("function".equals(fieldName)) {
return function;
}
if ("urlMask".equals(fieldName)) {
return urlMask;
}
return null;
}
@Nullable
@Override
public ApiMessage getApiMessageRequestBody() {
return null;
}
@Nullable
@Override
/**
* The fields that should be serialized (even if they have empty values). If the containing
* message object has a non-null fieldmask, then all the fields in the field mask (and only those
* fields in the field mask) will be serialized. If the containing object does not have a
* fieldmask, then only non-empty fields will be serialized.
*/
public List<String> getFieldMask() {
return null;
}
/**
* A user-defined name of the Cloud Function.
*
* <p>The function name is case-sensitive and must be 1-63 characters long.
*
* <p>Example value: "func1".
*/
public String getFunction() {
return function;
}
/**
* A template to parse function field from a request URL. URL mask allows for routing to multiple
* Cloud Functions without having to create multiple Network Endpoint Groups and backend services.
*
* <p>For example, request URLs "mydomain.com/function1" and "mydomain.com/function2" can be
* backed by the same Serverless NEG with URL mask "/". The URL mask will parse them to { function
* = "function1" } and { function = "function2" } respectively.
*/
public String getUrlMask() {
return urlMask;
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(NetworkEndpointGroupCloudFunction prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
public static NetworkEndpointGroupCloudFunction getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final NetworkEndpointGroupCloudFunction DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new NetworkEndpointGroupCloudFunction();
}
public static class Builder {
private String function;
private String urlMask;
Builder() {}
public Builder mergeFrom(NetworkEndpointGroupCloudFunction other) {
if (other == NetworkEndpointGroupCloudFunction.getDefaultInstance()) return this;
if (other.getFunction() != null) {
this.function = other.function;
}
if (other.getUrlMask() != null) {
this.urlMask = other.urlMask;
}
return this;
}
Builder(NetworkEndpointGroupCloudFunction source) {
this.function = source.function;
this.urlMask = source.urlMask;
}
/**
* A user-defined name of the Cloud Function.
*
* <p>The function name is case-sensitive and must be 1-63 characters long.
*
* <p>Example value: "func1".
*/
public String getFunction() {
return function;
}
/**
* A user-defined name of the Cloud Function.
*
* <p>The function name is case-sensitive and must be 1-63 characters long.
*
* <p>Example value: "func1".
*/
public Builder setFunction(String function) {
this.function = function;
return this;
}
/**
* A template to parse function field from a request URL. URL mask allows for routing to
* multiple Cloud Functions without having to create multiple Network Endpoint Groups and
* backend services.
*
* <p>For example, request URLs "mydomain.com/function1" and "mydomain.com/function2" can be
* backed by the same Serverless NEG with URL mask "/". The URL mask will parse them to {
* function = "function1" } and { function = "function2" } respectively.
*/
public String getUrlMask() {
return urlMask;
}
/**
* A template to parse function field from a request URL. URL mask allows for routing to
* multiple Cloud Functions without having to create multiple Network Endpoint Groups and
* backend services.
*
* <p>For example, request URLs "mydomain.com/function1" and "mydomain.com/function2" can be
* backed by the same Serverless NEG with URL mask "/". The URL mask will parse them to {
* function = "function1" } and { function = "function2" } respectively.
*/
public Builder setUrlMask(String urlMask) {
this.urlMask = urlMask;
return this;
}
public NetworkEndpointGroupCloudFunction build() {
return new NetworkEndpointGroupCloudFunction(function, urlMask);
}
public Builder clone() {
Builder newBuilder = new Builder();
newBuilder.setFunction(this.function);
newBuilder.setUrlMask(this.urlMask);
return newBuilder;
}
}
@Override
public String toString() {
return "NetworkEndpointGroupCloudFunction{"
+ "function="
+ function
+ ", "
+ "urlMask="
+ urlMask
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof NetworkEndpointGroupCloudFunction) {
NetworkEndpointGroupCloudFunction that = (NetworkEndpointGroupCloudFunction) o;
return Objects.equals(this.function, that.getFunction())
&& Objects.equals(this.urlMask, that.getUrlMask());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(function, urlMask);
}
}
|
92326e2be1c3ce4b9c743fd56c73dfb5f4a53518 | 1,543 | java | Java | soraka-admin/src/test/java/com/soraka/admin/service/UserServiceTest.java | huangkangyuan/soraka | 8e3eb8c253bd7af333dd815fa97f3c5112c068a2 | [
"Apache-2.0"
] | null | null | null | soraka-admin/src/test/java/com/soraka/admin/service/UserServiceTest.java | huangkangyuan/soraka | 8e3eb8c253bd7af333dd815fa97f3c5112c068a2 | [
"Apache-2.0"
] | null | null | null | soraka-admin/src/test/java/com/soraka/admin/service/UserServiceTest.java | huangkangyuan/soraka | 8e3eb8c253bd7af333dd815fa97f3c5112c068a2 | [
"Apache-2.0"
] | null | null | null | 29.711538 | 78 | 0.719094 | 996,212 | /*
* Apache License
* Version 2.0, January 2004
*
* Copyright 2018 北有风雪 (nnheo@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.soraka.admin.service;
import com.soraka.common.model.domain.UserDO;
import com.soraka.common.model.dto.Page;
import com.soraka.admin.model.dto.QueryParam;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Autowired
UserService userService;
@Test
public void get() {
UserDO user = userService.get(1L);
Assert.assertNotNull(user);
}
@Test
public void findPage() {
QueryParam param = new QueryParam();
param.setQueryText("soraka");
Page page = userService.findPage(param);
}
}
|
92326e800ba4d92504da005e40702bdc3ef5800f | 796 | java | Java | Willie/src/willie/core/WillieDataException.java | aaronpowers10/Willie | a6594738af5ff972d14a3916b6d7bcf9d41ef39e | [
"Apache-2.0"
] | null | null | null | Willie/src/willie/core/WillieDataException.java | aaronpowers10/Willie | a6594738af5ff972d14a3916b6d7bcf9d41ef39e | [
"Apache-2.0"
] | null | null | null | Willie/src/willie/core/WillieDataException.java | aaronpowers10/Willie | a6594738af5ff972d14a3916b6d7bcf9d41ef39e | [
"Apache-2.0"
] | null | null | null | 29.481481 | 77 | 0.704774 | 996,213 | /*
*
* Copyright (C) 2017 Aaron Powers
*
* 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 willie.core;
public class WillieDataException extends RuntimeException{
public WillieDataException(String message) {
super(message);
}
}
|
92326ed4e140c14e18234d2b43076f2ae440c591 | 9,884 | java | Java | hoot-runtime/src/main/java/Hoot/Runtime/Maps/ClassPath.java | nikboyd/hoot-smalltalk | 08f20a84ba63a5ec54bf972d7665c5ac97616a6e | [
"MIT"
] | 3 | 2022-01-20T22:44:45.000Z | 2022-03-07T15:00:42.000Z | hoot-runtime/src/main/java/Hoot/Runtime/Maps/ClassPath.java | nikboyd/hoot-smalltalk | 08f20a84ba63a5ec54bf972d7665c5ac97616a6e | [
"MIT"
] | null | null | null | hoot-runtime/src/main/java/Hoot/Runtime/Maps/ClassPath.java | nikboyd/hoot-smalltalk | 08f20a84ba63a5ec54bf972d7665c5ac97616a6e | [
"MIT"
] | 1 | 2022-01-20T22:44:50.000Z | 2022-01-20T22:44:50.000Z | 46.843602 | 123 | 0.656819 | 996,214 | package Hoot.Runtime.Maps;
import java.io.*;
import java.util.*;
import static java.util.Collections.*;
import org.eclipse.aether.resolution.ArtifactResult;
import Hoot.Runtime.Names.Name;
import Hoot.Runtime.Faces.Logging;
import static Hoot.Runtime.Functions.Utils.*;
import static Hoot.Runtime.Maps.Discovery.*;
import static Hoot.Runtime.Maps.Library.*;
import static Hoot.Runtime.Names.Operator.Dot;
import static Hoot.Runtime.Names.Primitive.*;
/**
* Provides a directory of the classes located by the Java class path.
* Locates packages by their directory names and provides a list of the classes contained in a package.
*
* @author nik <kenaa@example.com>
* @see "Copyright 1999,2021 Nikolas S Boyd."
* @see "Permission is granted to copy this work provided this copyright statement is retained in all copies."
*/
public class ClassPath implements Logging {
protected ClassPath() { }
public static final ClassPath CurrentPath = new ClassPath();
static String normalPath(String p) { return Package.normalPath(p); }
static final String WorkPath = "user.dir";
public static String workPath() { return systemValue(WorkPath); }
static File CachedBase = new File(workPath());
public static File cachedBase() { return CachedBase; }
public static final String Workspace = "workspace";
public static final String HootSmalltalk = "hoot-smalltalk";
static { discoverBase(Workspace, HootSmalltalk); }
static final String BaseReport = "using default base folder: %s";
static void reportDefaultBase(File baseCache) {
cachedDiscovery().report(String.format(BaseReport, baseCache.getAbsolutePath())); }
static boolean found(File f) { return cachedDiscovery().found(f); }
static File find(String name, File f) { return hasSome(f) && !found(name, f) ? find(name, f.getParentFile()) : f; }
static boolean found(String baseName, File f) { return f.getAbsolutePath().endsWith(baseName); }
static boolean foundAny(File f, String... baseNames) { return matchAny(wrap(baseNames), (n) -> found(n, f)); }
public static File discoverBase(String... baseNames) {
File workFolder = new File(workPath());
File baseFolder = find(baseNames[0], workFolder);
int index = 0;
while (!found(baseFolder) && (++index) < baseNames.length)
{ baseFolder = find(baseNames[index], workFolder); }
File baseCache = baseFolder;
setSafely(() -> baseCache, (f) -> {
if (!CachedBase.getAbsolutePath().equals(f.getAbsolutePath()) && !foundAny(f, baseNames)) {
reportDefaultBase(f); // found a different default
}
CachedBase = f;
});
return cachedBase();
}
List<PathMap> contents = emptyList(PathMap.class);
public void clear() { contents.clear(); }
public List<PathMap> contents() { return this.contents; }
private List<PathMap> reversedPath() { List<PathMap> results = copyList(contents); reverse(results); return results; }
public List<String> listFaces() { return collectList(fs -> collectFaces(fs)); }
void collectFaces(Collection<String> fs) { contents().forEach(pathMap -> fs.addAll(pathMap.listFaces())); }
public void mapLibs(String... libNames) { mapLibs(wrap(libNames)); }
public void mapLibs(List<String> libNames) { libNames.forEach(libName -> mapLibrary(libName)); }
public void mapLibWhen(String codePath, String libName) { if (whenSource(codePath)) mapLibrary(libName); }
public void mapLibWhenNot(String... codePaths) { mapLibWhenNot(wrap(codePaths)); }
public void mapLibWhenNot(List<String> codePaths) { // when lib not the source
if (!matchAny(codePaths, s -> whenSource(s))) mapLibrary(codePaths.get(0));
}
public boolean whenSource(String libName) { return CurrentLib.sourcePath().contains(libName); }
public boolean whenTarget(String libName) { return CurrentLib.targetPath().contains(libName); }
static final String Colon = ":";
static final String LATEST = Colon + "LATEST";
static String artifactNamed(String libName) { // default to Hoot if no group provided
return libName.contains(Colon) ? libName : HootSmalltalk + Colon + libName + LATEST; }
static final String TargetClasses = "target/classes";
public void mapLibrary(String libName) {
String artifactName = artifactNamed(libName);
ArtifactResult result = Discovery.lookup(artifactName);
if (hasSome(result)) { // try maven resolution first
if (Package.ReportLoads) reportMapping(result, artifactName);
File file = result.getArtifact().getFile();
if (file.exists()) {
PathMap m = mapPath(file);
if (Package.ReportLoads) printLine();
m.getPackages().forEach(p -> p.loadFaces());
return; // done with found library
}
}
// try local library class resolution
File libFolder = new File(cachedBase(), libName);
if (libFolder.exists()) {
File classFolder = new File(libFolder, normalPath(TargetClasses));
if (classFolder.exists()) {
if (Package.ReportLoads) reportMapping(libName, classFolder);
PathMap m = mapPath(classFolder);
if (Package.ReportLoads) printLine();
m.getPackages().forEach(p -> p.loadFaces());
}
}
}
public PathMap mapPath(File folder) { boolean appended = true; return addMapped(folder, appended); }
public PathMap addMapped(File folder, boolean appended) {
if (hasNo(folder) || !folder.exists()) {
if (hasSome(folder)) report(folder.getName() + " not loaded");
return null; // bail out, can't load from non-existent folder
}
PathMap map = buildMap(folder);
if (appended) contents.add(map);
else contents.add(0, map);
map.load();
reportMapped(); // while mapping
if (Package.ReportLoads) reportCount(map.listFaces().size());
return map;
}
private PathMap buildMap(File folder) {
// NOTE: folder may actually locate
// a ZIP or JAR file that contains a class library!
return ZipMap.supports(folder.getAbsolutePath()) ?
new ZipMap(folder.getAbsolutePath()) :
new PathMap(folder.getAbsolutePath()) ; }
boolean classPathMapping = false;
public boolean showDots() { return this.classPathMapping; }
public boolean showOnlyDots(boolean value) { this.classPathMapping = value; return value; }
private boolean locatesFace(String faceName, String packageName) {
return matchAny(classesInPackage(packageName), faceNames ->
hasSome(faceNames) && faceNames.contains(faceName)); }
private boolean anyPackageHasFaceNamed(String faceName) {
return matchAny(reversedPath(), pathMap ->
hasSome(pathMap.packageContaining(faceName)));
}
public boolean canLocateFaceNamed(String fullName) {
String faceName = Name.typeName(fullName);
String packageName = Name.packageName(fullName);
return locatesFace(faceName, packageName) || anyPackageHasFaceNamed(faceName); }
public boolean canLocatePackage(Package aPackage) { return classesExistInFolder(aPackage.pathname()); }
private boolean classesExistInFolder(String packagePath) {
return matchAny(reversedPath(), pathMap ->
hasSome(pathMap.classesInFolder(packagePath))); }
public Set<String> classesInPackage(Package aPackage) { return classesInPackage(aPackage.pathname()); }
private Set<String> classesInPackage(String packageName) {
return collectSet(results ->
reversedPath().forEach(pathMap ->
results.addAll(pathMap.classesInFolder(packageName)))); }
public java.io.File locate(String folder) {
for (PathMap map : reversedPath()) {
File result = map.locate(folder);
if (hasSome(result)) return result;
}
return null;
}
static final String StandardPath = "java.class.path";
String[] standardPaths() { return systemValue(StandardPath).split(Separator); }
public static String buildPath(String... basePaths) { return joinWith(Separator, wrap(basePaths)); }
public void mapStandardPaths() {
reportMapping("CLASSPATH", null); wrap(standardPaths()).forEach(p -> mapPath(new File(p))); }
static final String ArtReport = "mapping %s = %s ";
private void reportMapping(ArtifactResult r, String name) {
printLine(); print(format(ArtReport, name, r.getArtifact().getVersion())); }
static final String CountReport = " mapped %d faces";
private void reportCount(int count) { if (!showDots()) print(format(CountReport, count)); }
static final String MappingReport = "mapping %s ";
public void reportMapping(String name, File folder) { printLine();
print(hasNo(folder) ? format(MappingReport, name) : format(ArtReport, name, folder.getAbsolutePath())); }
public void reportMapped() { if (showDots()) print(Dot); }
public void println(int count) { while(count-- > 0) printLine(); }
public void println() { System.out.println(); }
public static final String PathSeparator = "path.separator";
public static final String Separator = systemValue(PathSeparator);
static final String[] Hoots = { "Hoot", "Smalltalk", };
static final List<String> HootBases = wrap(Hoots);
public static boolean matchHoots(String faceName) { return matchAny(HootBases, (h) -> faceName.startsWith(h)); }
} // ClassPath
|
923271934ef9174c1e2c1f28077d131f5d0d865b | 1,469 | java | Java | src/main/java/io/github/qtrouper/core/rabbit/RabbitConfiguration.java | Chaitanyachavali/qtrouper | bee42f2f8c96f0c729e4f24c023cda67b9c6ad89 | [
"Apache-2.0"
] | 4 | 2018-09-30T07:48:59.000Z | 2021-07-14T12:03:24.000Z | src/main/java/io/github/qtrouper/core/rabbit/RabbitConfiguration.java | Chaitanyachavali/qtrouper | bee42f2f8c96f0c729e4f24c023cda67b9c6ad89 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/qtrouper/core/rabbit/RabbitConfiguration.java | Chaitanyachavali/qtrouper | bee42f2f8c96f0c729e4f24c023cda67b9c6ad89 | [
"Apache-2.0"
] | 9 | 2018-04-08T06:52:12.000Z | 2021-06-15T07:56:39.000Z | 28.882353 | 75 | 0.754922 | 996,215 | /*
* Copyright 2019 Koushik R <efpyi@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 io.github.qtrouper.core.rabbit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.NotEmpty;
/**
* @author koushik
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class RabbitConfiguration {
@NotNull
@NotEmpty
private List<RabbitBroker> brokers;
@Builder.Default
private int threadPoolSize = 128;
@NotNull
@Builder.Default
private String userName = "";
@NotNull
@Builder.Default
private String password = "";
private String virtualHost;
private boolean sslEnabled;
private boolean metricsEnabled;
}
|
923271dcac03f736c952d64599fadbf2be1f3cb0 | 793 | java | Java | tl/src/main/java/com/github/badoualy/telegram/tl/api/messages/TLAbsDhConfig.java | FullStackD3vs/kotlogram | e3c26c69c2896b6bf3fce539ba0c46debc884e0f | [
"MIT"
] | 240 | 2016-01-04T11:23:29.000Z | 2022-03-04T20:22:30.000Z | tl/src/main/java/com/github/badoualy/telegram/tl/api/messages/TLAbsDhConfig.java | FullStackD3vs/kotlogram | e3c26c69c2896b6bf3fce539ba0c46debc884e0f | [
"MIT"
] | 57 | 2016-01-28T10:57:25.000Z | 2021-03-02T21:32:57.000Z | tl/src/main/java/com/github/badoualy/telegram/tl/api/messages/TLAbsDhConfig.java | FullStackD3vs/kotlogram | e3c26c69c2896b6bf3fce539ba0c46debc884e0f | [
"MIT"
] | 103 | 2016-01-29T20:20:17.000Z | 2022-03-28T18:48:51.000Z | 25.741935 | 95 | 0.70802 | 996,216 | package com.github.badoualy.telegram.tl.api.messages;
import com.github.badoualy.telegram.tl.core.TLBytes;
import com.github.badoualy.telegram.tl.core.TLObject;
/**
* Abstraction level for the following constructors:
* <ul>
* <li>{@link TLDhConfig}: messages.dhConfig#2c221edd</li>
* <li>{@link TLDhConfigNotModified}: messages.dhConfigNotModified#c0e24635</li>
* </ul>
*
* @author Yannick Badoual efpyi@example.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public abstract class TLAbsDhConfig extends TLObject {
protected TLBytes random;
public TLAbsDhConfig() {
}
public TLBytes getRandom() {
return random;
}
public void setRandom(TLBytes random) {
this.random = random;
}
}
|
923272a4b8263b7bb8f080dff63b15a1955b4fe5 | 521 | java | Java | j2ee-ref-libros-negocio/src/main/java/br/org/libros/negocio/cliente/model/business/ClienteBusiness.java | alissonwilker/br.org.j2ee-ref | ab622e8d7690ddc1069c6ece4217bc5426ae378a | [
"MIT"
] | null | null | null | j2ee-ref-libros-negocio/src/main/java/br/org/libros/negocio/cliente/model/business/ClienteBusiness.java | alissonwilker/br.org.j2ee-ref | ab622e8d7690ddc1069c6ece4217bc5426ae378a | [
"MIT"
] | null | null | null | j2ee-ref-libros-negocio/src/main/java/br/org/libros/negocio/cliente/model/business/ClienteBusiness.java | alissonwilker/br.org.j2ee-ref | ab622e8d7690ddc1069c6ece4217bc5426ae378a | [
"MIT"
] | null | null | null | 26.05 | 73 | 0.798464 | 996,217 | package br.org.libros.negocio.cliente.model.business;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import br.org.arquitetura.model.business.AbstractBusiness;
import br.org.libros.negocio.cliente.model.persistence.entity.Cliente;
/**
* Componente de negócio de Cliente.
*
* @see br.org.arquitetura.model.business.AbstractBusiness
*/
@Named
@RequestScoped
public class ClienteBusiness extends AbstractBusiness<Cliente, Integer> {
private static final long serialVersionUID = 1L;
}
|
9232741520891f231dc63401f124ccc2c6d462fa | 1,243 | java | Java | threathunter_common_java/1.0.1/src/test/java/com/threathunter/metricsagent/Car.java | threathunterX/java_lib | e4d32a6552942aafcb859b81e49f298a9ff5bb3a | [
"Apache-2.0"
] | 2 | 2019-05-01T09:42:26.000Z | 2020-02-11T09:10:39.000Z | threathunter_common_java/1.0.2/src/test/java/com/threathunter/metricsagent/Car.java | threathunterX/java_lib | e4d32a6552942aafcb859b81e49f298a9ff5bb3a | [
"Apache-2.0"
] | null | null | null | threathunter_common_java/1.0.2/src/test/java/com/threathunter/metricsagent/Car.java | threathunterX/java_lib | e4d32a6552942aafcb859b81e49f298a9ff5bb3a | [
"Apache-2.0"
] | 5 | 2019-06-24T05:48:33.000Z | 2021-08-10T14:35:22.000Z | 30.317073 | 124 | 0.604183 | 996,218 | package com.threathunter.metricsagent;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* created by www.threathunter.cn
*/
public class Car {
private static Random random = new Random();
private static String[] countries = new String[] {"China", "Germany", "America"};
private static String[] types = new String[] {"SUV", "MPV", "MINI"};
private static String[] levels = new String[] {"first-class", "second-class", "third-class"};
private static Double[][] leveledPrices = new Double[][] {{10.0, 15.0, 18.0}, {20.0, 30.0, 50.0}, {80.0, 100.0, 200.0}};
String country;
String type;
String level;
Double price;
Map<String, Object> tags;
Map<String, Object> getTags() {
return tags;
}
Double getPrice() {
return price;
}
void fillSelf() {
country = countries[random.nextInt(10) % 3];
type = types[random.nextInt(10) % 3];
int levelIndex = random.nextInt(10) % 3;
level = levels[levelIndex];
price = leveledPrices[levelIndex][random.nextInt(10) % 3];
tags = new HashMap<>();
tags.put("country", country);
tags.put("level", level);
tags.put("type", type);
}
}
|
923274b907539b487dbbb2e4b08c35885c5f4de5 | 4,807 | java | Java | app/src/main/java/no/rustelefonen/hap/intro/PrivacyActivity.java | rustelefonen/hap-android | 54b2c0db5e4591161d6a25ba580eca4665a8a7bd | [
"Apache-2.0"
] | 1 | 2016-09-09T10:41:52.000Z | 2016-09-09T10:41:52.000Z | app/src/main/java/no/rustelefonen/hap/intro/PrivacyActivity.java | rustelefonen/hap-android | 54b2c0db5e4591161d6a25ba580eca4665a8a7bd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/no/rustelefonen/hap/intro/PrivacyActivity.java | rustelefonen/hap-android | 54b2c0db5e4591161d6a25ba580eca4665a8a7bd | [
"Apache-2.0"
] | null | null | null | 34.335714 | 149 | 0.665072 | 996,219 | package no.rustelefonen.hap.intro;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.util.Calendar;
import java.util.Date;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import no.rustelefonen.hap.R;
import no.rustelefonen.hap.entities.User;
import no.rustelefonen.hap.main.tabs.activity.MainActivity;
import no.rustelefonen.hap.notifications.AchievementScheduler;
import no.rustelefonen.hap.persistence.OrmLiteActivity;
import no.rustelefonen.hap.persistence.dao.UserDao;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.primitives.Ints.tryParse;
/**
* Created by simenfonnes on 14.06.2017.
*/
public class PrivacyActivity extends OrmLiteActivity {
private static final String SERVER_URL = "http://app.rustelefonen.no/";
public static final String ID = "PrivacyActivity";
private Unbinder unbinder;
private PrivacyPojo privacyPojo;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.privacy_activity);
super.onCreate(savedInstanceState);
unbinder = ButterKnife.bind(this);
privacyPojo = (PrivacyPojo) getIntent().getSerializableExtra(ID);
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
public void accept(View view) {
if (privacyPojo != null) {
saveDetailsAndStartProgram(privacyPojo);
}
}
public void saveDetailsAndStartProgram(PrivacyPojo privacyPojo) {
User user = new User();
if(privacyPojo.isAgreedToParticipate()){
user.setAge(privacyPojo.getAge());
user.setCounty(privacyPojo.getCounty());
user.setGender(privacyPojo.getGender());
user.setUserType(privacyPojo.getUserType());
submitResearchData(user);
}
user.setAppRegistered(new Date());
user.setStartDate(getStartDateWithTimeAdjusted(privacyPojo.getStartDate()).getTime());
new UserDao(this).persist(user);
AchievementScheduler achievementScheduler = new AchievementScheduler(this);
achievementScheduler.reScheduleNext();
startActivity(new Intent(this, MainActivity.class));
finish();
}
public Calendar getStartDateWithTimeAdjusted(Calendar startDate) {
Calendar startTime = Calendar.getInstance();
//if start time is in future, set time to start of day
if(startDate.getTime().after(startTime.getTime())){
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.SECOND, 0);
}
startTime.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DAY_OF_MONTH));
return startTime;
}
private void submitResearchData(User user){
IntroActivity.ResearchRemote researchRemote = new Retrofit.Builder()
.baseUrl(SERVER_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(IntroActivity.ResearchRemote.class);
Call<ResponseBody> call = researchRemote.postResearchData(""+ user.getAge(), user.getGenderAsString(), user.getCounty(), user.getUserType());
call.enqueue(new Callback<ResponseBody>() {
@Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
getSharedPreferences(UserDetailsTab.INTRO_RESEARCH_SENT, MODE_PRIVATE)
.edit()
.putBoolean(UserDetailsTab.INTRO_RESEARCH_SENT, true)
.apply();
Log.e("Submitted", " research data Success");
}
@Override public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Submitted", " research data Failed");
}
});
}
public interface ResearchRemote {
@FormUrlEncoded
@Headers("Content-Type: application/x-www-form-urlencoded;charset=UTF-8")
@POST("/api/research")
Call<ResponseBody> postResearchData(@Field("age") String age,
@Field("gender") String gender,
@Field("county") String county,
@Field("userType") String userType);
}
}
|
9232752c184af84f34e1f827bdd00aa75aa421b0 | 398 | java | Java | src/main/java/org/hbrs/se2/project/coll/repository/SettingsRepository.java | Mastercheef/SE2 | 70d456f8d62551831284ace6969fb8ebd81360d3 | [
"MIT"
] | null | null | null | src/main/java/org/hbrs/se2/project/coll/repository/SettingsRepository.java | Mastercheef/SE2 | 70d456f8d62551831284ace6969fb8ebd81360d3 | [
"MIT"
] | null | null | null | src/main/java/org/hbrs/se2/project/coll/repository/SettingsRepository.java | Mastercheef/SE2 | 70d456f8d62551831284ace6969fb8ebd81360d3 | [
"MIT"
] | null | null | null | 28.428571 | 78 | 0.826633 | 996,220 | package org.hbrs.se2.project.coll.repository;
import org.hbrs.se2.project.coll.dtos.SettingsDTO;
import org.hbrs.se2.project.coll.entities.Settings;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
@Component
public interface SettingsRepository extends JpaRepository<Settings, Integer> {
SettingsDTO findSettingsById(int id);
}
|
92327575b7f2ee81b8532eccea0df2a0e19385b8 | 2,234 | java | Java | src/org/apache/commons/math3/stat/clustering/Cluster.java | weltam/idylfin | b55cbab20a931f7d11f863c90201d4bfac13eb43 | [
"ECL-2.0",
"Apache-2.0"
] | 28 | 2015-01-19T07:12:09.000Z | 2021-12-31T14:50:55.000Z | src/org/apache/commons/math3/stat/clustering/Cluster.java | weltam/idylfin | b55cbab20a931f7d11f863c90201d4bfac13eb43 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/org/apache/commons/math3/stat/clustering/Cluster.java | weltam/idylfin | b55cbab20a931f7d11f863c90201d4bfac13eb43 | [
"ECL-2.0",
"Apache-2.0"
] | 25 | 2015-03-11T18:38:45.000Z | 2022-03-19T09:20:56.000Z | 29.786667 | 75 | 0.676813 | 996,221 | /*
* 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.commons.math3.stat.clustering;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Cluster holding a set of {@link Clusterable} points.
* @param <T> the type of points that can be clustered
* @version $Id: Cluster.java 1416643 2012-12-03 19:37:14Z tn $
* @since 2.0
*/
public class Cluster<T extends Clusterable<T>> implements Serializable {
/** Serializable version identifier. */
private static final long serialVersionUID = -3442297081515880464L;
/** The points contained in this cluster. */
private final List<T> points;
/** Center of the cluster. */
private final T center;
/**
* Build a cluster centered at a specified point.
* @param center the point which is to be the center of this cluster
*/
public Cluster(final T center) {
this.center = center;
points = new ArrayList<T>();
}
/**
* Add a point to this cluster.
* @param point point to add
*/
public void addPoint(final T point) {
points.add(point);
}
/**
* Get the points contained in the cluster.
* @return points contained in the cluster
*/
public List<T> getPoints() {
return points;
}
/**
* Get the point chosen to be the center of this cluster.
* @return chosen cluster center
*/
public T getCenter() {
return center;
}
}
|
9232758184ad1c6ba0cfef462fda12275709fb56 | 1,701 | java | Java | spring-cloud-zuul-ratelimit-core/src/test/java/com/marcosbarbero/cloud/autoconfigure/zuul/ratelimit/config/repository/BaseRateLimiterTest.java | abujagonda/spring-cloud-zuul-ratelimit | ba6d2057331f1fcb059874a17ab627792e0d24f2 | [
"Apache-2.0"
] | 2 | 2020-02-26T04:21:30.000Z | 2020-02-26T04:24:43.000Z | spring-cloud-zuul-ratelimit-core/src/test/java/com/marcosbarbero/cloud/autoconfigure/zuul/ratelimit/config/repository/BaseRateLimiterTest.java | abujagonda/spring-cloud-zuul-ratelimit | ba6d2057331f1fcb059874a17ab627792e0d24f2 | [
"Apache-2.0"
] | null | null | null | spring-cloud-zuul-ratelimit-core/src/test/java/com/marcosbarbero/cloud/autoconfigure/zuul/ratelimit/config/repository/BaseRateLimiterTest.java | abujagonda/spring-cloud-zuul-ratelimit | ba6d2057331f1fcb059874a17ab627792e0d24f2 | [
"Apache-2.0"
] | 3 | 2019-10-15T01:46:52.000Z | 2021-12-22T02:29:00.000Z | 33.352941 | 105 | 0.689594 | 996,222 | package com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.repository;
import static org.assertj.core.api.Assertions.assertThat;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.Rate;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.RateLimiter;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.properties.RateLimitProperties.Policy;
import org.junit.Test;
public abstract class BaseRateLimiterTest {
protected RateLimiter target;
@Test
public void testConsumeOnlyLimit() {
Policy policy = new Policy();
policy.setLimit(10L);
policy.setRefreshInterval(2L);
Rate rate = target.consume(policy, "key", null);
assertThat(rate.getRemaining()).isEqualTo(9L);
assertThat(rate.getRemainingQuota()).isNull();
}
@Test
public void testConsumeOnlyQuota() {
Policy policy = new Policy();
policy.setQuota(1L);
policy.setRefreshInterval(2L);
Rate rate = target.consume(policy, "key", 800L);
assertThat(rate.getRemainingQuota()).isEqualTo(200L);
assertThat(rate.getRemaining()).isNull();
}
@Test
public void testConsume() {
Policy policy = new Policy();
policy.setLimit(10L);
policy.setQuota(1L);
policy.setRefreshInterval(2L);
Rate rate = target.consume(policy, "key", null);
assertThat(rate.getRemaining()).isEqualTo(9L);
assertThat(rate.getRemainingQuota()).isEqualTo(1000L);
rate = target.consume(policy, "key", 800L);
assertThat(rate.getRemaining()).isEqualTo(9L);
assertThat(rate.getRemainingQuota()).isEqualTo(200L);
}
} |
923275a6fc3acd766097fd7eb5a9e3b742542381 | 11,842 | java | Java | src/main/java/com/notes/java8/stream/StreamDemo.java | fujiangwei/java-review | 1b34139922d70b6c7913c8ad12f71704f0f39af2 | [
"MIT"
] | 24 | 2019-07-10T01:06:51.000Z | 2021-12-08T06:51:55.000Z | src/main/java/com/notes/java8/stream/StreamDemo.java | fujiangwei/java-review | 1b34139922d70b6c7913c8ad12f71704f0f39af2 | [
"MIT"
] | 1 | 2020-12-17T02:59:11.000Z | 2020-12-17T02:59:11.000Z | src/main/java/com/notes/java8/stream/StreamDemo.java | fujiangwei/java-review | 1b34139922d70b6c7913c8ad12f71704f0f39af2 | [
"MIT"
] | 37 | 2019-11-01T01:28:30.000Z | 2022-03-14T09:01:56.000Z | 42.905797 | 144 | 0.554552 | 996,223 | package com.notes.java8.stream;
import com.google.common.collect.Lists;
import com.notes.domain.User;
import com.notes.utils.UserUtil;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 文件描述 Stream 流使用demo
**/
public class StreamDemo {
public static void main(String[] args) {
// /*************流的来源*************/
// 1、of方法
// of(T... values):返回含有多个T元素的Stream
// of(T t):返回含有一个T元素的Stream
Stream<String> single = Stream.of("a");
Stream<String> multiple = Stream.of("a", "b", "c");
// 2、generator方法,返回一个无限长度的Stream,其元素由Supplier接口的提供。
Stream<String> generate = Stream.generate(() -> "a");
Stream<Double> generateA = Stream.generate(new Supplier<Double>() {
@Override
public Double get() {
return java.lang.Math.random();
}
});
// lambda写法
Stream<Double> generateB = Stream.generate(() -> java.lang.Math.random());
Stream<Double> generateC = Stream.generate(java.lang.Math::random);
// 3、iterate方法,返回的也是一个无限长度的Stream,与generate方法不同的是,其是通过函数f迭代对给指定的元素种子而产生无限连续有序Stream,其中包含的元素可以认为是:seed,f(seed),f(f(seed))无限循环
Stream<Integer> iterate = Stream.iterate(1, item -> item + 2);
// 无限流处理
iterate.limit(10).forEach(System.out::println);
// 4、empty方法返回一个空的顺序Stream,该Stream里面不包含元素项。
Stream<Object> empty = Stream.empty();
// 5、Collection接口和数组的默认方法
String[] chars = new String[]{"a", "b", "c"};
Arrays.stream(chars).forEach(System.out::println);
List list = Arrays.asList(chars);
list.stream().forEach(System.out::println);
/*************流的操作*************/
//concat 将两个Stream连接在一起,合成一个Stream。若两个输入的Stream都时排序的,则新Stream也是排序的;若输入的Stream中任何一个是并行的,则新的Stream也是并行的;若关闭新的Stream时,原两个输入的Stream都将执行关闭处理。
Stream.concat(Stream.of(1, 2, 3), Stream.of(4, 5))
.forEach(integer -> System.out.print(integer + " "));
//distinct 去除掉原Stream中重复的元素,生成的新Stream中没有没有重复的元素。
Stream.of(1, 1, 3, 4, 3).distinct().forEach(System.out::println);
//filter 对原Stream按照指定条件过滤,过滤出满足条件的元素。
Stream.of(1, 1, 3, 4, 3).filter(x -> x > 2).forEach(System.out::println);
//map方法将对于Stream中包含的元素使用给定的转换函数进行转换操作,新生成的Stream只包含转换生成的元素。
//为了提高处理效率,官方已封装好了,三种变形:mapToDouble,mapToInt,mapToLong,将原Stream中的数据类型,转换为double,int或者long类型。
Stream.of("a", "b", "c")
.map(item -> item.toUpperCase()) // .map(String::toUpperCase)
.forEach(System.out::println);
// flatMap方法与map方法类似,都是将原Stream中的每一个元素通过转换函数转换,
// 不同的是,该换转函数的对象是一个Stream,也不会再创建一个新的Stream,而是将原Stream的元素取代为转换的Stream。
List<User> users = UserUtil.getUsers(6);
users.stream()
.flatMap(s -> s.getInterests().stream())
.forEach(System.out::println);
Stream.of("a", "b", "c").flatMap(s -> Stream.of(s.toUpperCase()));
//peek 生成一个包含原Stream的所有元素的新Stream,同时会提供一个消费函数(Consumer实例)
Stream.of("a", "b", "c")
//优先执行
.peek(s -> System.out.println("peek:" + s))
.forEach(System.out::println);
//skip 将过滤掉原Stream中的前N个元素,返回剩下的元素所组成的新Stream。
// 如果原Stream的元素个数大于N,将返回原Stream的后的元素所组成的新Stream;
// 如果原Stream的元素个数小于或等于N,将返回一个空Stream。
Stream.of("a", "b", "c").skip(2)
.forEach(System.out::println);
// sorted方法将对原Stream进行排序,返回一个有序列的新Stream。sorterd有两种变体sorted(),sorted(Comparator),
// 前者将默认使用Object.equals(Object)进行排序,而后者接受一个自定义排序规则函数(Comparator),可自定义进行排序。
Stream.of(5, 6, 3, 9, 1)
.sorted()
.forEach(System.out::println);
System.out.println("+++++++++++++++++++++++++++++++");
Stream.of(5, 6, 3, 9, 1)
.sorted(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
//asc
return o1 - o2;
}
})
.forEach(System.out::println);
Stream.of(5, 6, 3, 9, 1)
//desc
.sorted(((o1, o2) -> o2 - o1))
.forEach(System.out::println);
System.out.println("+++++++++++++++++++++++++++++++");
// count 将返回Stream中元素的个数。
long count = Stream.of(1, 2, 3, 4, 5).count();
System.out.println("count:" + count);
// forEach 用于遍历Stream中的所元素,避免了使用for循环,让代码更简洁,逻辑更清晰。
Stream.of("a", "b", "c").forEach(System.out::println);
// forEachOrdered 与forEach类似,都是遍历Stream中的所有元素,
// 不同的是,如果该Stream预先设定了顺序,会按照预先设定的顺序执行(Stream是无序的),默认为元素插入的顺序。
Stream.of(5, 2, 1, 4, 3)
.forEachOrdered(integer ->
System.out.println("integer:" + integer)
);
// max 根据指定的Comparator,返回一个Optional,该Optional中的value值就是Stream中最大的元素。
Optional<Integer> max = Stream.of(5, 2, 2, 3, 4, 8)
.max((o1, o2) -> o2 - o1);
// Optional<Integer> max3 = Stream.of(1, 2, 3, 4, 5)
// .max(Comparator.comparingInt(x -> x));
Optional<Integer> max3 = Stream.of(1, 2, 3, 4, 5)
.max((o1, o2) -> o1 - o2);
int max2 = Stream.of(1, 2, 3, 4, 5)
.mapToInt(x -> x).max().getAsInt();
System.out.println("max = " + max.get() + " max2 = " + max2 + " max3 = " + max3.orElse(-1));
UserUtil.getUsers(6).stream()
.sorted(Comparator.comparing(User::getName).thenComparing(User::getId))
.forEach(u -> System.out.println(u.getName()));
// min 根据指定的Comparator,返回一个Optional,该Optional中的value值就是Stream中最小的元素。
Optional<Integer> min = Stream.of(1, 2, 3, 4, 5)
.min((o1, o2) -> o1 - o2);
System.out.println("min:" + min.get());
System.out.println("*********************reduce********************");
// reduce
// 1、reduce((sum, item) -> { ... }); //返回Optional,因为可能存在为空的情况,
// 2、reduce(0, (sum, item) -> { ... }); /返回对应类型,不存在为空的情况
//无初始值,第一个参数为stream的第一个元素,第二个参数为stream的第二个元素,计算的结果赋值给下一轮计算的sum
Optional<Integer> optional = Stream.of(1, 2, 3, 4, 5).reduce((sum, item) -> {
System.out.println("sum before:" + sum);
System.out.println("item:" + item);
sum = sum + item;
System.out.println("sum after:" + sum);
return sum;
// return Integer.sum(sum, item);
});
//等效
Optional<Integer> optional1 = Stream.of(1, 2, 3, 4, 5).reduce((sum, item) ->
Integer.sum(sum, item)
);
//等效
Optional<Integer> optional2 = Stream.of(1, 2, 3, 4, 5).reduce(Integer::sum);
System.out.println("integer = " + optional.orElse(-1));
System.out.println("*****************************************");
//给定初始值,第一个参数为初始值,第二个参数为stream的第一个元素,计算的结果赋值给下一轮计算的sum
Integer reduce = Stream.of(1, 2, 3, 4, 5).reduce(5, (sum, item) -> {
System.out.println("sum2 before:" + sum);
System.out.println("item:" + item);
sum = sum + item;
System.out.println("sum2 after:" + sum);
return sum;
});
//等效
Integer reduce2 = Stream.of(1, 2, 3, 4, 5).reduce(0, (sum, item) ->
Integer.sum(sum, item)
);
//等效
Integer reduce3 = Stream.of(1, 2, 3, 4, 5).reduce(0, Integer::sum);
System.out.println("reduce = " + reduce);
System.out.println("*********************collect********************");
List<Integer> toList = Stream.of(1, 2, 3, 4)
.collect(Collectors.toList());
List<Integer> toList2 = Stream.of(1, 2, 3, 4)
.collect(Collectors.toCollection(ArrayList::new));
System.out.println("toList: " + toList);
Set<Integer> toSet = Stream.of(1, 2, 3, 4)
.collect(Collectors.toSet());
Set<Integer> toSet2 = Stream.of(1, 2, 3, 4)
.collect(Collectors.toCollection(() -> new TreeSet()));
System.out.println("toSet: " + toSet);
//(value1, value2) -> value1 用前面的value覆盖后面的value,保持不变
List<User> userList = UserUtil.getUsers(5);
userList.add(new User(2, "fjw"));
Map<Integer, String> toMap = userList.stream()
.collect(Collectors.toMap(User::getId, User::getName, (value1, value2) -> value1));
System.out.println("(value1, value2) -> value1");
toMap.forEach((k, v) -> System.out.println(k + "-" + v));
// 对value值进行了限定不能为null,否则抛出空指针异常
// userList.add(new User(3, null));
//(value1, value2) -> value2 用后面的value覆盖前面的value
Map<Integer, String> toMap2 = userList.stream()
.collect(Collectors.toMap(User::getId, User::getName, (value1, value2) -> value2));
System.out.println("(value1, value2) -> value2");
toMap2.forEach((k, v) -> System.out.println(k + "-" + v));
// 解决value值为null方式
userList.add(new User(4, null));
Map<Integer, String> toMap3 = userList.stream()
.collect(HashMap::new, (m, u) -> m.put(u.getId(), u.getName()), HashMap::putAll);
toMap3.forEach((k, v) -> System.out.println(k + "-" + v));
HashMap<Integer, User> collect4 = userList.stream()
.collect(HashMap::new, (m, u) -> m.put(u.getId(), u), HashMap::putAll);
toMap3.forEach((k, v) -> System.out.println(k + "-" + v));
Optional<Integer> maxBy = Stream.of(1, 2, 3, 4)
.collect(Collectors.maxBy(Comparator.comparingInt(o -> o)));
System.out.println("maxBy:" + maxBy.get());
Long counting = Stream.of(1, 2, 3, 4)
.collect(Collectors.counting());
System.out.println("counting:" + counting);
//分割数据块
Map<Boolean, List<Integer>> partitioningBy = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.partitioningBy(item -> item > 3));
//partitioningBy : {false=[1, 2, 3], true=[4, 5]}
System.out.println("partitioningBy : " + partitioningBy);
Map<Boolean, Long> collect = Stream.of(1, 2, 3, 4)
.collect(Collectors.partitioningBy(item -> item > 3, Collectors.counting()));
System.out.println("collect: " + collect);
//数据分组
Map<Boolean, List<Integer>> groupingBy = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.groupingBy(item -> item > 3));
//partitioningBy : {false=[1, 2, 3], true=[4, 5]}
System.out.println("groupingBy : " + groupingBy);
//字符串
String joining = Stream.of("a", "b", "c", "d")
.collect(Collectors.joining(","));
System.out.println(joining);
String joining2 = Stream.of("a", "b", "c", "d")
.collect(Collectors.joining(",", "[", "]"));
System.out.println(joining2);
System.out.println(userList);
User uu = new User(1, "kk", Lists.newArrayList("i66"));
userList.add(uu);
// 根据id分组
Map<Integer, List<User>> collect3 = userList.stream().collect(Collectors.groupingBy(User::getId));
// 将id映射为id集合
List<Integer> collect1 = userList.stream().collect(Collectors.mapping(User::getId, Collectors.toList()));
// 根据id分组后将interests映射成集合
Map<Integer, List<List<String>>> collect2 = userList.stream()
.collect(Collectors.groupingBy(User::getId, Collectors.mapping(User::getInterests, Collectors.toList())));
System.out.println(collect3);
System.out.println(collect1);
System.out.println(collect2);
}
}
|
9232767b591d96f6e5e5e65f7d6e180af08443bb | 621 | java | Java | sso-support/src/main/java/com/joindata/inf/common/support/sso/entity/RoleConfigAttribute.java | bizwell/Pangu | fbc6ced0b39c718b2a2048a133b1a55deb04e48c | [
"Apache-2.0"
] | 7 | 2018-02-28T05:46:38.000Z | 2021-12-09T08:50:40.000Z | sso-support/src/main/java/com/joindata/inf/common/support/sso/entity/RoleConfigAttribute.java | Rayeee/Pangu | c1bf7f30414e78b26ba96e2ec270a068e6ed3c8f | [
"Apache-2.0"
] | null | null | null | sso-support/src/main/java/com/joindata/inf/common/support/sso/entity/RoleConfigAttribute.java | Rayeee/Pangu | c1bf7f30414e78b26ba96e2ec270a068e6ed3c8f | [
"Apache-2.0"
] | 7 | 2018-02-28T05:36:07.000Z | 2021-07-05T09:45:43.000Z | 19.5625 | 72 | 0.629393 | 996,224 | package com.joindata.inf.common.support.sso.entity;
import org.springframework.security.access.ConfigAttribute;
/**
* 角色权限属性
*
* @author <a href="mailto:upchh@example.com">宋翔</a>
* @date Dec 21, 2016 2:12:37 PM
*/
public class RoleConfigAttribute implements ConfigAttribute
{
private static final long serialVersionUID = -1191869521718241378L;
private Role role;
public RoleConfigAttribute(Role role)
{
this.role = role;
}
/**
* 返回的是角色 ID
*/
@Override
public String getAttribute()
{
return role.getRoleId();
}
}
|
9232772778a4c49553d35f712edadfde56f28a82 | 40,268 | java | Java | core/src/test/java/io/grpc/internal/AutoConfiguredLoadBalancerFactoryTest.java | dapengzhang0/grpc-java | ad0e2396a821de5423f39b436d43911e21438cae | [
"Apache-2.0"
] | 2 | 2020-05-06T04:17:16.000Z | 2021-11-23T07:39:53.000Z | core/src/test/java/io/grpc/internal/AutoConfiguredLoadBalancerFactoryTest.java | quynhvi98/grpc-java | e9882ec78db581106f709ab5130bfe30af660e79 | [
"Apache-2.0"
] | 1 | 2016-05-02T17:13:23.000Z | 2016-05-02T17:13:23.000Z | core/src/test/java/io/grpc/internal/AutoConfiguredLoadBalancerFactoryTest.java | quynhvi98/grpc-java | e9882ec78db581106f709ab5130bfe30af660e79 | [
"Apache-2.0"
] | 3 | 2017-08-21T02:33:31.000Z | 2020-05-06T04:17:35.000Z | 41.00611 | 100 | 0.727103 | 996,225 | /*
* Copyright 2018 The gRPC 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 io.grpc.internal;
import static com.google.common.truth.Truth.assertThat;
import static io.grpc.LoadBalancer.ATTR_LOAD_BALANCING_CONFIG;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.Preconditions;
import io.grpc.Attributes;
import io.grpc.ChannelLogger;
import io.grpc.ChannelLogger.ChannelLogLevel;
import io.grpc.ConnectivityState;
import io.grpc.ConnectivityStateInfo;
import io.grpc.EquivalentAddressGroup;
import io.grpc.LoadBalancer;
import io.grpc.LoadBalancer.CreateSubchannelArgs;
import io.grpc.LoadBalancer.Helper;
import io.grpc.LoadBalancer.ResolvedAddresses;
import io.grpc.LoadBalancer.Subchannel;
import io.grpc.LoadBalancer.SubchannelPicker;
import io.grpc.LoadBalancer.SubchannelStateListener;
import io.grpc.LoadBalancerProvider;
import io.grpc.LoadBalancerRegistry;
import io.grpc.ManagedChannel;
import io.grpc.NameResolver.ConfigOrError;
import io.grpc.Status;
import io.grpc.SynchronizationContext;
import io.grpc.grpclb.GrpclbLoadBalancerProvider;
import io.grpc.internal.AutoConfiguredLoadBalancerFactory.AutoConfiguredLoadBalancer;
import io.grpc.internal.AutoConfiguredLoadBalancerFactory.PolicyException;
import io.grpc.internal.AutoConfiguredLoadBalancerFactory.PolicySelection;
import io.grpc.internal.AutoConfiguredLoadBalancerFactory.ResolvedPolicySelection;
import io.grpc.util.ForwardingLoadBalancerHelper;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
/**
* Unit tests for {@link AutoConfiguredLoadBalancerFactory}.
*/
@RunWith(JUnit4.class)
// TODO(creamsoup) remove backward compatible check when fully migrated
@SuppressWarnings("deprecation")
public class AutoConfiguredLoadBalancerFactoryTest {
private static final LoadBalancerRegistry defaultRegistry =
LoadBalancerRegistry.getDefaultRegistry();
private final AutoConfiguredLoadBalancerFactory lbf =
new AutoConfiguredLoadBalancerFactory(GrpcUtil.DEFAULT_LB_POLICY);
private final ChannelLogger channelLogger = mock(ChannelLogger.class);
private final LoadBalancer testLbBalancer = mock(LoadBalancer.class);
private final LoadBalancer testLbBalancer2 = mock(LoadBalancer.class);
private final AtomicReference<ConfigOrError> nextParsedConfigOrError =
new AtomicReference<>(ConfigOrError.fromConfig("default"));
private final AtomicReference<ConfigOrError> nextParsedConfigOrError2 =
new AtomicReference<>(ConfigOrError.fromConfig("default2"));
private final FakeLoadBalancerProvider testLbBalancerProvider =
mock(FakeLoadBalancerProvider.class,
delegatesTo(
new FakeLoadBalancerProvider("test_lb", testLbBalancer, nextParsedConfigOrError)));
private final FakeLoadBalancerProvider testLbBalancerProvider2 =
mock(FakeLoadBalancerProvider.class,
delegatesTo(
new FakeLoadBalancerProvider("test_lb2", testLbBalancer2, nextParsedConfigOrError2)));
@Before
public void setUp() {
when(testLbBalancer.canHandleEmptyAddressListFromNameResolution()).thenCallRealMethod();
assertThat(testLbBalancer.canHandleEmptyAddressListFromNameResolution()).isFalse();
when(testLbBalancer2.canHandleEmptyAddressListFromNameResolution()).thenReturn(true);
defaultRegistry.register(testLbBalancerProvider);
defaultRegistry.register(testLbBalancerProvider2);
}
@After
public void tearDown() {
defaultRegistry.deregister(testLbBalancerProvider);
defaultRegistry.deregister(testLbBalancerProvider2);
}
@Test
public void newLoadBalancer_isAuto() {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
assertThat(lb).isInstanceOf(AutoConfiguredLoadBalancer.class);
}
@Test
public void defaultIsPickFirst() {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
assertThat(lb.getDelegateProvider()).isInstanceOf(PickFirstLoadBalancerProvider.class);
assertThat(lb.getDelegate().getClass().getName()).contains("PickFirst");
}
@Test
public void defaultIsConfigurable() {
AutoConfiguredLoadBalancer lb = new AutoConfiguredLoadBalancerFactory("test_lb")
.newLoadBalancer(new TestHelper());
assertThat(lb.getDelegateProvider()).isSameInstanceAs(testLbBalancerProvider);
assertThat(lb.getDelegate()).isSameInstanceAs(testLbBalancer);
}
@SuppressWarnings("deprecation")
@Test
public void forwardsCalls() {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
final AtomicInteger calls = new AtomicInteger();
TestLoadBalancer testlb = new TestLoadBalancer() {
@Override
public void handleNameResolutionError(Status error) {
calls.getAndSet(1);
}
@Override
public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
calls.getAndSet(2);
}
@Override
public void shutdown() {
calls.getAndSet(3);
}
};
lb.setDelegate(testlb);
lb.handleNameResolutionError(Status.RESOURCE_EXHAUSTED);
assertThat(calls.getAndSet(0)).isEqualTo(1);
lb.handleSubchannelState(null, null);
assertThat(calls.getAndSet(0)).isEqualTo(2);
lb.shutdown();
assertThat(calls.getAndSet(0)).isEqualTo(3);
}
@Test
public void handleResolvedAddressGroups_keepOldBalancer() {
final List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
Helper helper = new TestHelper() {
@Override
public Subchannel createSubchannel(CreateSubchannelArgs args) {
assertThat(args.getAddresses()).isEqualTo(servers);
return new TestSubchannel(args);
}
};
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(helper);
LoadBalancer oldDelegate = lb.getDelegate();
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setAttributes(Attributes.EMPTY)
.setLoadBalancingPolicyConfig(null)
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
assertThat(lb.getDelegate()).isSameInstanceAs(oldDelegate);
}
@Test
public void handleResolvedAddressGroups_shutsDownOldBalancer() throws Exception {
Map<String, ?> serviceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"round_robin\": { } } ] }");
ConfigOrError lbConfigs = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
final List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
Helper helper = new TestHelper() {
@Override
public Subchannel createSubchannel(CreateSubchannelArgs args) {
assertThat(args.getAddresses()).isEqualTo(servers);
return new TestSubchannel(args);
}
};
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(helper);
final AtomicBoolean shutdown = new AtomicBoolean();
TestLoadBalancer testlb = new TestLoadBalancer() {
@Override
public void handleNameResolutionError(Status error) {
// noop
}
@Override
public void shutdown() {
shutdown.set(true);
}
};
lb.setDelegate(testlb);
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setLoadBalancingPolicyConfig(lbConfigs.getConfig())
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
assertThat(lb.getDelegateProvider().getClass().getName()).isEqualTo(
"io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider");
assertTrue(shutdown.get());
}
@Test
@SuppressWarnings("unchecked")
public void handleResolvedAddressGroups_propagateLbConfigToDelegate() throws Exception {
Map<String, ?> rawServiceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"test_lb\": { \"setting1\": \"high\" } } ] }");
ConfigOrError lbConfigs = lbf.parseLoadBalancerPolicy(rawServiceConfig, channelLogger);
assertThat(lbConfigs.getConfig()).isNotNull();
final List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
Helper helper = new TestHelper();
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(helper);
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setLoadBalancingPolicyConfig(lbConfigs.getConfig())
.build());
verify(testLbBalancerProvider).newLoadBalancer(same(helper));
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
assertThat(lb.getDelegate()).isSameInstanceAs(testLbBalancer);
ArgumentCaptor<ResolvedAddresses> resultCaptor =
ArgumentCaptor.forClass(ResolvedAddresses.class);
verify(testLbBalancer).handleResolvedAddresses(resultCaptor.capture());
assertThat(resultCaptor.getValue().getAddresses()).containsExactlyElementsIn(servers).inOrder();
assertThat(resultCaptor.getValue().getAttributes().get(ATTR_LOAD_BALANCING_CONFIG))
.isEqualTo(rawServiceConfig);
verify(testLbBalancer, atLeast(0)).canHandleEmptyAddressListFromNameResolution();
ArgumentCaptor<Map<String, ?>> lbConfigCaptor = ArgumentCaptor.forClass(Map.class);
verify(testLbBalancerProvider).parseLoadBalancingPolicyConfig(lbConfigCaptor.capture());
assertThat(lbConfigCaptor.getValue()).containsExactly("setting1", "high");
verifyNoMoreInteractions(testLbBalancer);
rawServiceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"test_lb\": { \"setting1\": \"low\" } } ] }");
lbConfigs = lbf.parseLoadBalancerPolicy(rawServiceConfig, channelLogger);
handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setLoadBalancingPolicyConfig(lbConfigs.getConfig())
.build());
resultCaptor =
ArgumentCaptor.forClass(ResolvedAddresses.class);
verify(testLbBalancer, times(2)).handleResolvedAddresses(resultCaptor.capture());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
assertThat(resultCaptor.getValue().getAddresses()).containsExactlyElementsIn(servers).inOrder();
assertThat(resultCaptor.getValue().getAttributes().get(ATTR_LOAD_BALANCING_CONFIG))
.isEqualTo(rawServiceConfig);
verify(testLbBalancerProvider, times(2))
.parseLoadBalancingPolicyConfig(lbConfigCaptor.capture());
assertThat(lbConfigCaptor.getValue()).containsExactly("setting1", "low");
// Service config didn't change policy, thus the delegateLb is not swapped
verifyNoMoreInteractions(testLbBalancer);
verify(testLbBalancerProvider).newLoadBalancer(any(Helper.class));
}
@Test
public void handleResolvedAddressGroups_propagateOnlyBackendAddrsToDelegate() throws Exception {
// This case only happens when grpclb is missing. We will use a local registry
LoadBalancerRegistry registry = new LoadBalancerRegistry();
registry.register(new PickFirstLoadBalancerProvider());
registry.register(
new FakeLoadBalancerProvider(
"round_robin", testLbBalancer, /* nextParsedLbPolicyConfig= */ null));
final List<EquivalentAddressGroup> servers =
Arrays.asList(
new EquivalentAddressGroup(new SocketAddress(){}),
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()));
Helper helper = new TestHelper();
AutoConfiguredLoadBalancer lb = new AutoConfiguredLoadBalancerFactory(
registry, GrpcUtil.DEFAULT_LB_POLICY).newLoadBalancer(helper);
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setAttributes(Attributes.EMPTY)
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
assertThat(lb.getDelegate()).isSameInstanceAs(testLbBalancer);
verify(testLbBalancer).handleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(Collections.singletonList(servers.get(0)))
.setAttributes(Attributes.EMPTY)
.build());
}
@Test
public void handleResolvedAddressGroups_delegateDoNotAcceptEmptyAddressList_nothing()
throws Exception {
Helper helper = new TestHelper();
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(helper);
Map<String, ?> serviceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"test_lb\": { \"setting1\": \"high\" } } ] }");
ConfigOrError lbConfig = lbf.parseLoadBalancerPolicy(serviceConfig, helper.getChannelLogger());
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(Collections.<EquivalentAddressGroup>emptyList())
.setLoadBalancingPolicyConfig(lbConfig.getConfig())
.build());
assertThat(testLbBalancer.canHandleEmptyAddressListFromNameResolution()).isFalse();
assertThat(handleResult.getCode()).isEqualTo(Status.Code.UNAVAILABLE);
assertThat(handleResult.getDescription()).startsWith("NameResolver returned no usable address");
assertThat(lb.getDelegate()).isSameInstanceAs(testLbBalancer);
}
@Test
public void handleResolvedAddressGroups_delegateAcceptsEmptyAddressList()
throws Exception {
Helper helper = new TestHelper();
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(helper);
Map<String, ?> rawServiceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"test_lb2\": { \"setting1\": \"high\" } } ] }");
ConfigOrError lbConfigs =
lbf.parseLoadBalancerPolicy(rawServiceConfig, helper.getChannelLogger());
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(Collections.<EquivalentAddressGroup>emptyList())
.setLoadBalancingPolicyConfig(lbConfigs.getConfig())
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
assertThat(lb.getDelegate()).isSameInstanceAs(testLbBalancer2);
assertThat(testLbBalancer2.canHandleEmptyAddressListFromNameResolution()).isTrue();
ArgumentCaptor<ResolvedAddresses> resultCaptor =
ArgumentCaptor.forClass(ResolvedAddresses.class);
verify(testLbBalancer2).handleResolvedAddresses(resultCaptor.capture());
assertThat(resultCaptor.getValue().getAddresses()).isEmpty();
assertThat(resultCaptor.getValue().getLoadBalancingPolicyConfig())
.isEqualTo(nextParsedConfigOrError2.get().getConfig());
assertThat(resultCaptor.getValue().getAttributes().get(ATTR_LOAD_BALANCING_CONFIG))
.isEqualTo(rawServiceConfig);
}
@Test
public void decideLoadBalancerProvider_noBalancerAddresses_noServiceConfig_pickFirst()
throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
PolicySelection policySelection = null;
List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider)
.isInstanceOf(PickFirstLoadBalancerProvider.class);
assertThat(selection.serverList).isEqualTo(servers);
assertThat(selection.policySelection.config).isNull();
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_noBalancerAddresses_noServiceConfig_customDefault()
throws Exception {
AutoConfiguredLoadBalancer lb = new AutoConfiguredLoadBalancerFactory("test_lb")
.newLoadBalancer(new TestHelper());
PolicySelection policySelection = null;
List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider).isSameInstanceAs(testLbBalancerProvider);
assertThat(selection.serverList).isEqualTo(servers);
assertThat(selection.policySelection.config).isNull();
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_oneBalancer_noServiceConfig_grpclb() throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
PolicySelection policySelection = null;
List<EquivalentAddressGroup> servers =
Collections.singletonList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider).isInstanceOf(GrpclbLoadBalancerProvider.class);
assertThat(selection.serverList).isEqualTo(servers);
assertThat(selection.policySelection.config).isNull();
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_serviceConfigLbPolicy() throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
Map<String, ?> rawServiceConfig =
parseConfig("{\"loadBalancingPolicy\": \"round_robin\"}");
ConfigOrError lbConfig = lbf.parseLoadBalancerPolicy(rawServiceConfig, channelLogger);
assertThat(lbConfig.getConfig()).isNotNull();
PolicySelection policySelection = (PolicySelection) lbConfig.getConfig();
List<EquivalentAddressGroup> servers =
Arrays.asList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()),
new EquivalentAddressGroup(
new SocketAddress(){}));
List<EquivalentAddressGroup> backends = Arrays.asList(servers.get(1));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider.getClass().getName()).isEqualTo(
"io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider");
assertThat(selection.serverList).isEqualTo(backends);
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_serviceConfigLbConfig() throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
Map<String, ?> rawServiceConfig =
parseConfig("{\"loadBalancingConfig\": [{\"round_robin\": {}}]}");
ConfigOrError lbConfig = lbf.parseLoadBalancerPolicy(rawServiceConfig, channelLogger);
assertThat(lbConfig.getConfig()).isNotNull();
PolicySelection policySelection = (PolicySelection) lbConfig.getConfig();
List<EquivalentAddressGroup> servers =
Arrays.asList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()),
new EquivalentAddressGroup(
new SocketAddress(){}));
List<EquivalentAddressGroup> backends = Arrays.asList(servers.get(1));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider.getClass().getName()).isEqualTo(
"io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider");
assertThat(selection.serverList).isEqualTo(backends);
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_grpclbConfigPropagated() throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
Map<String, ?> rawServiceConfig =
parseConfig(
"{\"loadBalancingConfig\": ["
+ "{\"grpclb\": {\"childPolicy\": [ {\"pick_first\": {} } ] } }"
+ "] }");
ConfigOrError lbConfig = lbf.parseLoadBalancerPolicy(rawServiceConfig, channelLogger);
assertThat(lbConfig.getConfig()).isNotNull();
PolicySelection policySelection = (PolicySelection) lbConfig.getConfig();
List<EquivalentAddressGroup> servers =
Collections.singletonList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider).isInstanceOf(GrpclbLoadBalancerProvider.class);
assertThat(selection.serverList).isEqualTo(servers);
assertThat(selection.policySelection.config)
.isEqualTo(((PolicySelection) lbConfig.getConfig()).config);
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_policyUnavailButGrpclbAddressPresent() throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
List<EquivalentAddressGroup> servers =
Collections.singletonList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, null);
assertThat(selection.policySelection.provider).isInstanceOf(GrpclbLoadBalancerProvider.class);
assertThat(selection.serverList).isEqualTo(servers);
assertThat(selection.policySelection.config).isNull();
verifyZeroInteractions(channelLogger);
}
@Test
public void decideLoadBalancerProvider_grpclbProviderNotFound_fallbackToRoundRobin()
throws Exception {
LoadBalancerRegistry registry = new LoadBalancerRegistry();
registry.register(new PickFirstLoadBalancerProvider());
LoadBalancerProvider fakeRoundRobinProvider =
new FakeLoadBalancerProvider("round_robin", testLbBalancer, null);
registry.register(fakeRoundRobinProvider);
AutoConfiguredLoadBalancer lb = new AutoConfiguredLoadBalancerFactory(
registry, GrpcUtil.DEFAULT_LB_POLICY).newLoadBalancer(new TestHelper());
List<EquivalentAddressGroup> servers =
Arrays.asList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()),
new EquivalentAddressGroup(new SocketAddress(){}));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, null);
assertThat(selection.policySelection.provider).isSameInstanceAs(fakeRoundRobinProvider);
assertThat(selection.policySelection.config).isNull();
verify(channelLogger).log(
eq(ChannelLogLevel.ERROR),
startsWith("Found balancer addresses but grpclb runtime is missing"));
// Called for the second time, the warning is only logged once
selection = lb.resolveLoadBalancerProvider(servers, null);
assertThat(selection.policySelection.provider).isSameInstanceAs(fakeRoundRobinProvider);
assertThat(selection.policySelection.config).isNull();
// Balancer addresses are filtered out in the server list passed to round_robin
assertThat(selection.serverList).containsExactly(servers.get(1));
verifyNoMoreInteractions(channelLogger);;
}
@Test
public void decideLoadBalancerProvider_grpclbProviderNotFound_noBackendAddress()
throws Exception {
LoadBalancerRegistry registry = new LoadBalancerRegistry();
registry.register(new PickFirstLoadBalancerProvider());
registry.register(new FakeLoadBalancerProvider("round_robin", testLbBalancer, null));
AutoConfiguredLoadBalancer lb = new AutoConfiguredLoadBalancerFactory(
registry, GrpcUtil.DEFAULT_LB_POLICY).newLoadBalancer(new TestHelper());
List<EquivalentAddressGroup> servers =
Collections.singletonList(
new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()));
try {
lb.resolveLoadBalancerProvider(servers, null);
fail("Should throw");
} catch (PolicyException e) {
assertThat(e)
.hasMessageThat()
.isEqualTo("Received ONLY balancer addresses but grpclb runtime is missing");
}
}
@Test
public void decideLoadBalancerProvider_serviceConfigLbConfigOverridesDefault() throws Exception {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
Map<String, ?> rawServiceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"round_robin\": {} } ] }");
ConfigOrError lbConfigs = lbf.parseLoadBalancerPolicy(rawServiceConfig, channelLogger);
assertThat(lbConfigs.getConfig()).isNotNull();
PolicySelection policySelection = (PolicySelection) lbConfigs.getConfig();
List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
ResolvedPolicySelection selection = lb.resolveLoadBalancerProvider(servers, policySelection);
assertThat(selection.policySelection.provider.getClass().getName()).isEqualTo(
"io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider");
verifyZeroInteractions(channelLogger);
}
@Test
public void channelTracing_lbPolicyChanged() throws Exception {
final FakeClock clock = new FakeClock();
List<EquivalentAddressGroup> servers =
Collections.singletonList(new EquivalentAddressGroup(new SocketAddress(){}));
Helper helper = new TestHelper() {
@Override
@Deprecated
public Subchannel createSubchannel(List<EquivalentAddressGroup> addrs, Attributes attrs) {
return new TestSubchannel(CreateSubchannelArgs.newBuilder()
.setAddresses(addrs)
.setAttributes(attrs)
.build());
}
@Override
public Subchannel createSubchannel(CreateSubchannelArgs args) {
return new TestSubchannel(args);
}
@Override
public ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority) {
return mock(ManagedChannel.class, RETURNS_DEEP_STUBS);
}
@Override
public String getAuthority() {
return "fake_authority";
}
@Override
public SynchronizationContext getSynchronizationContext() {
return new SynchronizationContext(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
throw new AssertionError(e);
}
});
}
@Override
public ScheduledExecutorService getScheduledExecutorService() {
return clock.getScheduledExecutorService();
}
};
AutoConfiguredLoadBalancer lb =
new AutoConfiguredLoadBalancerFactory(GrpcUtil.DEFAULT_LB_POLICY).newLoadBalancer(helper);
Status handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setAttributes(Attributes.EMPTY)
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
verifyNoMoreInteractions(channelLogger);
ConfigOrError testLbParsedConfig = ConfigOrError.fromConfig("foo");
nextParsedConfigOrError.set(testLbParsedConfig);
Map<String, ?> serviceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"test_lb\": { } } ] }");
ConfigOrError lbConfigs = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setLoadBalancingPolicyConfig(lbConfigs.getConfig())
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
verify(channelLogger).log(
eq(ChannelLogLevel.INFO),
eq("Load balancer changed from {0} to {1}"),
eq("PickFirstLoadBalancer"),
eq(testLbBalancer.getClass().getSimpleName()));
verify(channelLogger).log(
eq(ChannelLogLevel.DEBUG),
eq("Load-balancing config: {0}"),
eq(testLbParsedConfig.getConfig()));
verifyNoMoreInteractions(channelLogger);
testLbParsedConfig = ConfigOrError.fromConfig("bar");
nextParsedConfigOrError.set(testLbParsedConfig);
serviceConfig = parseConfig("{\"loadBalancingConfig\": [ {\"test_lb\": { } } ] }");
lbConfigs = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setLoadBalancingPolicyConfig(lbConfigs.getConfig())
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
verify(channelLogger).log(
eq(ChannelLogLevel.DEBUG),
eq("Load-balancing config: {0}"),
eq(testLbParsedConfig.getConfig()));
verifyNoMoreInteractions(channelLogger);
servers = Collections.singletonList(new EquivalentAddressGroup(
new SocketAddress(){},
Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "ok").build()));
handleResult = lb.tryHandleResolvedAddresses(
ResolvedAddresses.newBuilder()
.setAddresses(servers)
.setAttributes(Attributes.EMPTY)
.build());
assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
verify(channelLogger).log(
eq(ChannelLogLevel.INFO),
eq("Load balancer changed from {0} to {1}"),
eq(testLbBalancer.getClass().getSimpleName()), eq("GrpclbLoadBalancer"));
verifyNoMoreInteractions(channelLogger);
}
@Test
public void parseLoadBalancerConfig_failedOnUnknown() throws Exception {
Map<String, ?> serviceConfig =
parseConfig("{\"loadBalancingConfig\": [ {\"magic_balancer\": {} } ] }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed.getError()).isNotNull();
assertThat(parsed.getError().getDescription())
.isEqualTo("None of [magic_balancer] specified by Service Config are available.");
}
@Test
public void parseLoadBalancerPolicy_failedOnUnknown() throws Exception {
Map<String, ?> serviceConfig =
parseConfig("{\"loadBalancingPolicy\": \"magic_balancer\"}");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed.getError()).isNotNull();
assertThat(parsed.getError().getDescription())
.isEqualTo("None of [magic_balancer] specified by Service Config are available.");
}
@Test
public void parseLoadBalancerConfig_multipleValidPolicies() throws Exception {
Map<String, ?> serviceConfig =
parseConfig(
"{\"loadBalancingConfig\": ["
+ "{\"round_robin\": {}},"
+ "{\"test_lb\": {} } ] }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed).isNotNull();
assertThat(parsed.getError()).isNull();
assertThat(parsed.getConfig()).isInstanceOf(PolicySelection.class);
assertThat(((PolicySelection) parsed.getConfig()).provider.getClass().getName())
.isEqualTo("io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider");
}
@Test
public void parseLoadBalancerConfig_policyShouldBeIgnoredIfConfigExists() throws Exception {
Map<String, ?> serviceConfig =
parseConfig(
"{\"loadBalancingConfig\": [{\"round_robin\": {} } ],"
+ "\"loadBalancingPolicy\": \"pick_first\" }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed).isNotNull();
assertThat(parsed.getError()).isNull();
assertThat(parsed.getConfig()).isInstanceOf(PolicySelection.class);
assertThat(((PolicySelection) parsed.getConfig()).provider.getClass().getName())
.isEqualTo("io.grpc.util.SecretRoundRobinLoadBalancerProvider$Provider");
}
@Test
public void parseLoadBalancerConfig_policyShouldBeIgnoredEvenIfUnknownPolicyExists()
throws Exception {
Map<String, ?> serviceConfig =
parseConfig(
"{\"loadBalancingConfig\": [{\"magic_balancer\": {} } ],"
+ "\"loadBalancingPolicy\": \"round_robin\" }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed.getError()).isNotNull();
assertThat(parsed.getError().getDescription())
.isEqualTo("None of [magic_balancer] specified by Service Config are available.");
}
@Test
@SuppressWarnings("unchecked")
public void parseLoadBalancerConfig_firstInvalidPolicy() throws Exception {
when(testLbBalancerProvider.parseLoadBalancingPolicyConfig(any(Map.class)))
.thenReturn(ConfigOrError.fromError(Status.UNKNOWN));
Map<String, ?> serviceConfig =
parseConfig(
"{\"loadBalancingConfig\": ["
+ "{\"test_lb\": {}},"
+ "{\"round_robin\": {} } ] }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed).isNotNull();
assertThat(parsed.getConfig()).isNull();
assertThat(parsed.getError()).isEqualTo(Status.UNKNOWN);
}
@Test
@SuppressWarnings("unchecked")
public void parseLoadBalancerConfig_firstValidSecondInvalidPolicy() throws Exception {
when(testLbBalancerProvider.parseLoadBalancingPolicyConfig(any(Map.class)))
.thenReturn(ConfigOrError.fromError(Status.UNKNOWN));
Map<String, ?> serviceConfig =
parseConfig(
"{\"loadBalancingConfig\": ["
+ "{\"round_robin\": {}},"
+ "{\"test_lb\": {} } ] }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed).isNotNull();
assertThat(parsed.getConfig()).isNotNull();
assertThat(((PolicySelection) parsed.getConfig()).config).isNotNull();
}
@Test
public void parseLoadBalancerConfig_someProvidesAreNotAvailable() throws Exception {
Map<String, ?> serviceConfig =
parseConfig("{\"loadBalancingConfig\": [ "
+ "{\"magic_balancer\": {} },"
+ "{\"round_robin\": {}} ] }");
ConfigOrError parsed = lbf.parseLoadBalancerPolicy(serviceConfig, channelLogger);
assertThat(parsed).isNotNull();
assertThat(parsed.getConfig()).isNotNull();
assertThat(((PolicySelection) parsed.getConfig()).config).isNotNull();
verify(channelLogger).log(
eq(ChannelLogLevel.DEBUG),
eq("{0} specified by Service Config are not available"),
eq(new ArrayList<>(Collections.singletonList("magic_balancer"))));
}
public static class ForwardingLoadBalancer extends LoadBalancer {
private final LoadBalancer delegate;
public ForwardingLoadBalancer(LoadBalancer delegate) {
this.delegate = delegate;
}
protected LoadBalancer delegate() {
return delegate;
}
@Override
@Deprecated
public void handleResolvedAddressGroups(
List<EquivalentAddressGroup> servers, Attributes attributes) {
delegate().handleResolvedAddressGroups(servers, attributes);
}
@Override
public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
delegate().handleResolvedAddresses(resolvedAddresses);
}
@Override
public void handleNameResolutionError(Status error) {
delegate().handleNameResolutionError(error);
}
@Override
public void shutdown() {
delegate().shutdown();
}
}
@SuppressWarnings("unchecked")
private static Map<String, ?> parseConfig(String json) throws Exception {
return (Map<String, ?>) JsonParser.parse(json);
}
private static class TestLoadBalancer extends ForwardingLoadBalancer {
TestLoadBalancer() {
super(null);
}
}
private class TestHelper extends ForwardingLoadBalancerHelper {
@Override
protected Helper delegate() {
return null;
}
@Override
public ChannelLogger getChannelLogger() {
return channelLogger;
}
@Override
public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
// noop
}
}
private static class TestSubchannel extends Subchannel {
TestSubchannel(CreateSubchannelArgs args) {
this.addrs = args.getAddresses();
this.attrs = args.getAttributes();
}
List<EquivalentAddressGroup> addrs;
final Attributes attrs;
@Override
public void start(SubchannelStateListener listener) {
}
@Override
public void shutdown() {
}
@Override
public void requestConnection() {
}
@Override
public List<EquivalentAddressGroup> getAllAddresses() {
return addrs;
}
@Override
public Attributes getAttributes() {
return attrs;
}
@Override
public void updateAddresses(List<EquivalentAddressGroup> addrs) {
Preconditions.checkNotNull(addrs, "addrs");
this.addrs = addrs;
}
}
private static class FakeLoadBalancerProvider extends LoadBalancerProvider {
private final String policyName;
private final LoadBalancer balancer;
private final AtomicReference<ConfigOrError> nextParsedLbPolicyConfig;
FakeLoadBalancerProvider(
String policyName,
LoadBalancer balancer,
AtomicReference<ConfigOrError> nextParsedLbPolicyConfig) {
this.policyName = policyName;
this.balancer = balancer;
this.nextParsedLbPolicyConfig = nextParsedLbPolicyConfig;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public int getPriority() {
return 5;
}
@Override
public String getPolicyName() {
return policyName;
}
@Override
public LoadBalancer newLoadBalancer(Helper helper) {
return balancer;
}
@Override
public ConfigOrError parseLoadBalancingPolicyConfig(
Map<String, ?> rawLoadBalancingPolicyConfig) {
if (nextParsedLbPolicyConfig == null) {
return super.parseLoadBalancingPolicyConfig(rawLoadBalancingPolicyConfig);
}
return nextParsedLbPolicyConfig.get();
}
}
}
|
923278e4bd810b9b5d9aa791acdad6132931d455 | 8,496 | java | Java | framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/envops/Iterate.java | aracwong/ofbiz | 7ba7f3c2e16df6c8db0d8114e124957199cea1ff | [
"Apache-2.0"
] | 752 | 2015-01-02T16:52:36.000Z | 2022-03-03T11:22:14.000Z | framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/envops/Iterate.java | aracwong/ofbiz | 7ba7f3c2e16df6c8db0d8114e124957199cea1ff | [
"Apache-2.0"
] | 38 | 2021-06-02T09:14:31.000Z | 2022-02-02T01:25:45.000Z | framework/minilang/src/main/java/org/apache/ofbiz/minilang/method/envops/Iterate.java | aracwong/ofbiz | 7ba7f3c2e16df6c8db0d8114e124957199cea1ff | [
"Apache-2.0"
] | 687 | 2015-01-07T07:56:48.000Z | 2022-03-18T03:42:33.000Z | 41.852217 | 150 | 0.573329 | 996,226 | /*******************************************************************************
* 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.ofbiz.minilang.method.envops;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityListIterator;
import org.apache.ofbiz.minilang.MiniLangException;
import org.apache.ofbiz.minilang.MiniLangRuntimeException;
import org.apache.ofbiz.minilang.MiniLangValidate;
import org.apache.ofbiz.minilang.SimpleMethod;
import org.apache.ofbiz.minilang.artifact.ArtifactInfoContext;
import org.apache.ofbiz.minilang.method.MethodContext;
import org.apache.ofbiz.minilang.method.MethodOperation;
import org.apache.ofbiz.minilang.method.envops.Break.BreakElementException;
import org.apache.ofbiz.minilang.method.envops.Continue.ContinueElementException;
import org.w3c.dom.Element;
/**
* Implements the <iterate> element.
*
* @see <a href="https://cwiki.apache.org/confluence/display/OFBADMIN/Mini+Language+-+minilang+-+simple-method+-+Reference">Mini-language Referenc</a>
*/
public final class Iterate extends MethodOperation {
public static final String module = Iterate.class.getName();
private final FlexibleMapAccessor<Object> entryFma;
private final FlexibleMapAccessor<Object> listFma;
private final List<MethodOperation> subOps;
public Iterate(Element element, SimpleMethod simpleMethod) throws MiniLangException {
super(element, simpleMethod);
if (MiniLangValidate.validationOn()) {
MiniLangValidate.attributeNames(simpleMethod, element, "entry", "list");
MiniLangValidate.expressionAttributes(simpleMethod, element, "entry", "list");
MiniLangValidate.requiredAttributes(simpleMethod, element, "entry", "list");
}
this.entryFma = FlexibleMapAccessor.getInstance(element.getAttribute("entry"));
this.listFma = FlexibleMapAccessor.getInstance(element.getAttribute("list"));
this.subOps = Collections.unmodifiableList(SimpleMethod.readOperations(element, simpleMethod));
}
@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
if (listFma.isEmpty()) {
if (Debug.verboseOn())
Debug.logVerbose("Collection not found, doing nothing: " + this, module);
return true;
}
Object oldEntryValue = entryFma.get(methodContext.getEnvMap());
Object objList = listFma.get(methodContext.getEnvMap());
if (objList instanceof EntityListIterator) {
EntityListIterator eli = (EntityListIterator) objList;
GenericValue theEntry;
try {
while ((theEntry = eli.next()) != null) {
entryFma.put(methodContext.getEnvMap(), theEntry);
try {
for (MethodOperation methodOperation : subOps) {
if (!methodOperation.exec(methodContext)) {
return false;
}
}
} catch (MiniLangException e) {
if (e instanceof BreakElementException) {
break;
}
if (e instanceof ContinueElementException) {
continue;
}
throw e;
}
}
} finally {
try {
eli.close();
} catch (GenericEntityException e) {
throw new MiniLangRuntimeException("Error closing entityListIterator: " + e.getMessage(), this);
}
}
} else if (objList instanceof Collection<?>) {
Collection<Object> theCollection = UtilGenerics.checkCollection(objList);
if (theCollection.size() == 0) {
if (Debug.verboseOn())
Debug.logVerbose("Collection has zero entries, doing nothing: " + this, module);
return true;
}
for (Object theEntry : theCollection) {
entryFma.put(methodContext.getEnvMap(), theEntry);
try {
for (MethodOperation methodOperation : subOps) {
if (!methodOperation.exec(methodContext)) {
return false;
}
}
} catch (MiniLangException e) {
if (e instanceof BreakElementException) {
break;
}
if (e instanceof ContinueElementException) {
continue;
}
throw e;
}
}
} else if (objList instanceof Iterator<?>) {
Iterator<Object> theIterator = UtilGenerics.cast(objList);
if (!theIterator.hasNext()) {
if (Debug.verboseOn())
Debug.logVerbose("Iterator has zero entries, doing nothing: " + this, module);
return true;
}
while (theIterator.hasNext()) {
Object theEntry = theIterator.next();
entryFma.put(methodContext.getEnvMap(), theEntry);
try {
for (MethodOperation methodOperation : subOps) {
if (!methodOperation.exec(methodContext)) {
return false;
}
}
} catch (MiniLangException e) {
if (e instanceof BreakElementException) {
break;
}
if (e instanceof ContinueElementException) {
continue;
}
throw e;
}
}
} else {
if (Debug.verboseOn()) {
Debug.logVerbose("Cannot iterate over a " + objList == null ? "null object" : objList.getClass().getName()
+ ", doing nothing: " + this, module);
}
return true;
}
entryFma.put(methodContext.getEnvMap(), oldEntryValue);
return true;
}
@Override
public void gatherArtifactInfo(ArtifactInfoContext aic) {
for (MethodOperation method : this.subOps) {
method.gatherArtifactInfo(aic);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("<iterate ");
if (!this.entryFma.isEmpty()) {
sb.append("entry=\"").append(this.entryFma).append("\" ");
}
if (!this.listFma.isEmpty()) {
sb.append("list=\"").append(this.listFma).append("\" ");
}
sb.append("/>");
return sb.toString();
}
/**
* A factory for the <iterate> element.
*/
public static final class IterateFactory implements Factory<Iterate> {
@Override
public Iterate createMethodOperation(Element element, SimpleMethod simpleMethod) throws MiniLangException {
return new Iterate(element, simpleMethod);
}
@Override
public String getName() {
return "iterate";
}
}
}
|
923279d4949774f2ab8f5f3a1ab78ca602325fd7 | 4,399 | java | Java | java/smallboy/LinkedStringListtemp.java | smallkidsforworld/leetcode | 5c9f49dea9d14dbeb9c075fa414cbd26b6a3679b | [
"MIT"
] | null | null | null | java/smallboy/LinkedStringListtemp.java | smallkidsforworld/leetcode | 5c9f49dea9d14dbeb9c075fa414cbd26b6a3679b | [
"MIT"
] | null | null | null | java/smallboy/LinkedStringListtemp.java | smallkidsforworld/leetcode | 5c9f49dea9d14dbeb9c075fa414cbd26b6a3679b | [
"MIT"
] | null | null | null | 22.675258 | 84 | 0.497158 | 996,227 | import java.util.NoSuchElementException;
public class LinkedStringListtemp {
private Node first;
private Node currentNode;
private int length;
class Node
{
private String data;
private Node next;
public void printNodeData()
{
System.out.println("Node data: " + this.data);
}
public Node getNext()
{
return this.next;
}
}
public LinkedStringList()
{
first = null;
currentNode = null;
length = 0;
}
public void addFirst(String value)
{
//Create the node & set its value
Node newNode = new Node();
newNode.data = value;
//if newNode is the first node, this will be null
//else, it will point to the former "first" now
newNode.next = first;
//update "first" to point to node we just created
first = newNode;
currentNode = newNode;
length++;
}
public void setFirstValue(String value)
{
first.data = value;
}
public void setCurrentValue(String value)
{
currentNode.data = value;
}
public void moveNext()
{
if (currentNode.next == null)
{
throw new NoSuchElementException();
}
else
{
currentNode = currentNode.next;
}
}
public void moveFirst()
{
currentNode = first;
}
public boolean isEmpty()
{
return(first==null);
}
public int getLength()
{
return length;
}
public String getFirstValue()
{
if (first == null)
{
throw new NoSuchElementException();
}
else
{
return(first.data);
}
}
public String getCurrentValue()
{
if (currentNode == null)
{
throw new NoSuchElementException();
}
else
{
return(currentNode.data);
}
}
public void displayList()
{
Node tempNode = first;
System.out.println("List contents:");
while(tempNode != null)
{
tempNode.printNodeData();
tempNode = tempNode.getNext();
}
}
public void add(String value) {
if (first == null) {
addFirst(value);
return;
}
Node newNode = new Node();
newNode.data = value;
newNode.next = currentNode.next;
currentNode.next = newNode;
currentNode = newNode;
length++;
}
public void removeFirst() {
first = first.next;
if(first!=currentNode)
currentNode =first;
}
public void remove() {
System.out.println("currentNode "+currentNode.data);
if (currentNode == first)
removeFirst();
else {
Node head = first;
while (head.next != currentNode)
head = head.next;
head.next = currentNode.next;
currentNode = head.next;
}
}
public String indexOf(int index) {
Node head = first;
while (index >= 0 && head != null) {
head = head.next;
index--;
}
if (index >= 0)
throw new NoSuchElementException();
return head.data;
}
public void sortAscending() {
moveFirst();
for (int i = 0; i < length - 1; ++i) {
for (int j = i; j < length - 1; ++j) {
if (compareTWoString(currentNode.data, currentNode.next.data) > 0) {
String temp = currentNode.data;
currentNode.data = currentNode.next.data;
currentNode.next.data = temp;
}
moveNext();
}
moveFirst();
}
moveFirst();
}
// positive one > two ; negative one < two;
public static int compareTWoString(String str_one, String str_two) {
int i = 0;
while (i < str_one.length() && i < str_two.length()) {
if (str_one.charAt(i) != str_two.charAt(i))
break;
i++;
}
if (str_one.charAt(i) == str_two.charAt(i))
return str_one.length() - str_two.length();
else
return str_one.charAt(i) - str_two.charAt(i);
}
} |
92327ae088cff697fb8c1adf1d1b6ebdede42556 | 13,978 | java | Java | src/test/resources/gnss/attitude/reference-attitude-generator/GenerateBaseSample.java | paolo-aiko/Orekit | 923de038a4b783fb054bbb3c8ba8e069a29d23e9 | [
"Apache-2.0"
] | null | null | null | src/test/resources/gnss/attitude/reference-attitude-generator/GenerateBaseSample.java | paolo-aiko/Orekit | 923de038a4b783fb054bbb3c8ba8e069a29d23e9 | [
"Apache-2.0"
] | null | null | null | src/test/resources/gnss/attitude/reference-attitude-generator/GenerateBaseSample.java | paolo-aiko/Orekit | 923de038a4b783fb054bbb3c8ba8e069a29d23e9 | [
"Apache-2.0"
] | null | null | null | 52.74717 | 140 | 0.559451 | 996,228 | /* Copyright 2002-2018 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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 fr.cs.examples.gnss;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.util.FastMath;
import org.orekit.bodies.CelestialBody;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.data.NamedData;
import org.orekit.data.UnixCompressFilter;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.files.sp3.SP3File;
import org.orekit.files.sp3.SP3File.SP3Ephemeris;
import org.orekit.files.sp3.SP3Parser;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.Transform;
import org.orekit.gnss.SatelliteSystem;
import org.orekit.gnss.antenna.AntexLoader;
import org.orekit.gnss.antenna.SatelliteAntenna;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.AlignmentDetector;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.events.handlers.EventHandler;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;
import org.orekit.utils.TimeSpanMap;
public class GenerateBaseSample {
/** Option for orekit data directory. */
private static final String OPTION_OREKIT_DATA_DIR = "-orekit-data-dir";
/** Option for SP3 files directory. */
private static final String OPTION_SP3_DIR = "-sp3-dir";
/** Option for output directory. */
private static final String OPTION_OUTPUT_DIR = "-output-dir";
/** Option for antex file. */
private static final String OPTION_ANTEX_FILE = "-antex";
public static void main(String[] args) {
try {
File orekitDataDir = null;
File sp3Dir = null;
File outputDir = null;
File antexDir = null;
String antexName = null;
for (int i = 0; i < args.length - 1; ++i) {
switch (args[i]) {
case OPTION_OREKIT_DATA_DIR :
orekitDataDir = new File(args[++i]);
break;
case OPTION_SP3_DIR :
sp3Dir = new File(args[++i]);
break;
case OPTION_OUTPUT_DIR :
outputDir = new File(args[++i]);
break;
case OPTION_ANTEX_FILE : {
final File fullPath = new File(args[++i]);
antexDir = fullPath.getParentFile();
antexName = fullPath.getName();
break;
}
default :
throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE,
"unknown option " + args[i]);
}
}
if (orekitDataDir == null || sp3Dir == null || outputDir == null || antexDir == null) {
throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE,
"usage: java fr.cs.examples.gnss.GenerateBaseSample " +
OPTION_OREKIT_DATA_DIR + " <directory> " +
OPTION_SP3_DIR + " <directory> " +
OPTION_ANTEX_FILE + " <file>");
}
for (File directory : Arrays.asList(orekitDataDir, sp3Dir, outputDir, antexDir)) {
if (!directory.exists() || !directory.isDirectory()) {
throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE,
directory + " does not exist or is not a directory");
}
}
DataProvidersManager.getInstance().addProvider(new DirectoryCrawler(orekitDataDir));
DataProvidersManager.getInstance().addProvider(new DirectoryCrawler(antexDir));
final AntexLoader loader = new AntexLoader(antexName);
final CelestialBody sun = CelestialBodyFactory.getSun();
// find the available Unix-compressed sp3 files in lexicographic order
// (which is here chronological order too)
final List<String> sp3Names = Arrays.asList(sp3Dir.list()).
stream().
filter(name -> name.endsWith(".sp3.Z")).
collect(Collectors.toList());
Collections.sort(sp3Names);
try (PrintStream outLargeNeg = new PrintStream(new File(outputDir, "beta-large-negative.txt"));
PrintStream outSmallNeg = new PrintStream(new File(outputDir, "beta-small-negative.txt"));
PrintStream outCrossing = new PrintStream(new File(outputDir, "beta-crossing.txt"));
PrintStream outSmallPos = new PrintStream(new File(outputDir, "beta-small-positive.txt"));
PrintStream outLargePos = new PrintStream(new File(outputDir, "beta-large-positive.txt"));) {
final String header = "# GPS date week milliseconds" +
" Id type satCode" +
" PxSat (m) PySat (m) PzSat (m) VxSat (m/s) VySat (m/s) VZsat (m/s)" +
" PxSun (m) PySun (m) PzSun (m) β (deg) Δ (deg)" +
" xsatX (nominal) ysatX (nominal) zsatX (nominal) ψ nom. (deg)" +
" xsatX (eclips) ysatX (eclips) zsatX (eclips) ψ ecl. (deg)%n";
outLargeNeg.format(Locale.US, header);
outSmallNeg.format(Locale.US, header);
outCrossing.format(Locale.US, header);
outSmallPos.format(Locale.US, header);
outLargePos.format(Locale.US, header);
for (String sp3Name : sp3Names) {
System.out.println(" " + sp3Name);
final File f = new File(sp3Dir, sp3Name);
final NamedData compressed = new NamedData(sp3Name, ()-> new FileInputStream(f));
try (InputStream is = new UnixCompressFilter().filter(compressed).getStreamOpener().openStream()) {
final SP3File sp3 = new SP3Parser().parse(is);
for (final Map.Entry<String, SP3Ephemeris> entry : sp3.getSatellites().entrySet()) {
try {
final BoundedPropagator propagator = entry.getValue().getPropagator();
propagator.addEventDetector(new AlignmentDetector(900.0, 1.0, sun, 0.0).
withHandler(new SunHandler<>(sun, loader, -19.0, outLargeNeg, entry.getKey())));
propagator.addEventDetector(new AlignmentDetector(900.0, 1.0, sun, 0.0).
withHandler(new SunHandler<>(sun, loader, -1.5, outSmallNeg, entry.getKey())));
propagator.addEventDetector(new AlignmentDetector(900.0, 1.0, sun, 0.0).
withHandler(new SunHandler<>(sun, loader, 0.0, outCrossing, entry.getKey())));
propagator.addEventDetector(new AlignmentDetector(900.0, 1.0, sun, 0.0).
withHandler(new SunHandler<>(sun, loader, +1.5, outSmallPos, entry.getKey())));
propagator.addEventDetector(new AlignmentDetector(900.0, 1.0, sun, 0.0).
withHandler(new SunHandler<>(sun, loader, +30.0, outLargePos, entry.getKey())));
propagator.propagate(propagator.getMinDate().shiftedBy( 10),
propagator.getMaxDate().shiftedBy(-10));
} catch (OrekitException oe) {
if (oe.getSpecifier() != OrekitMessages.CANNOT_FIND_SATELLITE_IN_SYSTEM) {
System.err.println("# unable to propagate " + entry.getKey());
}
}
}
}
}
}
} catch (OrekitException | IOException e) {
System.err.println(e.getLocalizedMessage());
}
}
private static class SunHandler<T extends EventDetector> implements EventHandler<T> {
final CelestialBody sun;
final double betaRef;
final String sat;
final PrintStream out;
final TimeSpanMap<SatelliteAntenna> map;
final TimeScale gps;
final Frame itrf;
SunHandler(final CelestialBody sun, final AntexLoader loader,
final double betaRef, final PrintStream out, final String sat)
throws OrekitException {
this.sun = sun;
this.betaRef = betaRef;
this.sat = sat;
this.out = out;
this.map = loader.findSatelliteAntenna(SatelliteSystem.parseSatelliteSystem(sat.substring(0, 1)),
Integer.parseInt(sat.substring(1)));
this.gps = TimeScalesFactory.getGPS();
this.itrf = FramesFactory.getITRF(IERSConventions.IERS_2010, false);
}
@Override
public Action eventOccurred(SpacecraftState s, T detector, boolean increasing)
throws OrekitException {
if (FastMath.abs(beta(s) - betaRef) < 0.5 &&
(beta(s.shiftedBy(-1800)) - betaRef) * (beta(s.shiftedBy(+1800)) - betaRef) < 0) {
for (int dt = -39; dt <= 39; dt += 6) {
display(s.shiftedBy(dt * 60.0));
}
}
return Action.CONTINUE;
}
private void display(final SpacecraftState s) throws OrekitException {
SatelliteAntenna antenna = map.get(s.getDate());
int week = gpsWeek(s.getDate());
double milli = gpsMilli(s.getDate());
PVCoordinates pvSatInert = s.getPVCoordinates();
Transform t = s.getFrame().getTransformTo(itrf, s.getDate());
Vector3D pSat = t.transformPosition(pvSatInert.getPosition());
Vector3D vSat = t.transformVector(pvSatInert.getVelocity());
Vector3D pSun = t.transformPosition(sun.getPVCoordinates(s.getDate(), s.getFrame()).getPosition());
out.format(Locale.US,
"%s %4d %16.6f %3s %-11s %-4s" +
" %16.6f %16.6f %16.6f %16.9f %16.9f %16.9f" +
" %16.2f %16.2f %16.2f" +
" %15.11f %15.11f%n",
s.getDate().getComponents(gps).getDate(), week, milli,
sat, antenna.getType().replaceAll(" ", "-"), sat.substring(0, 1) + antenna.getSatelliteCode(),
pSat.getX(), pSat.getY(), pSat.getZ(), vSat.getX(), vSat.getY(), vSat.getZ(),
pSun.getX(), pSun.getY(), pSun.getZ(),
beta(s), delta(s));
}
private int gpsWeek(final AbsoluteDate date) {
return (int) FastMath.floor(date.durationFrom(AbsoluteDate.GPS_EPOCH) / (7 * Constants.JULIAN_DAY));
}
private double gpsMilli(final AbsoluteDate date) {
return 1000 * date.durationFrom(AbsoluteDate.createGPSDate(gpsWeek(date), 0));
}
private double beta(final SpacecraftState s) throws OrekitException{
final Vector3D pSun = sun.getPVCoordinates(s.getDate(), s.getFrame()).getPosition();
final Vector3D mSat = s.getPVCoordinates().getMomentum();
return FastMath.toDegrees(0.5 * FastMath.PI - Vector3D.angle(pSun, mSat));
}
private double delta(final SpacecraftState s) throws OrekitException{
final Vector3D pSun = sun.getPVCoordinates(s.getDate(), s.getFrame()).getPosition();
return FastMath.toDegrees(Vector3D.angle(pSun, s.getPVCoordinates().getPosition()));
}
}
}
|
92327b07091b25f4ea6dbe0aa1711985ed4534f6 | 257 | java | Java | core-java/core-java-concurrent/src/main/java/io/github/kavahub/learnjava/sequence/SequenceGenerator.java | kavahub/learnjava | 9fbf59d5e5d9712eb88c4856fce329ba3e21e978 | [
"MIT"
] | null | null | null | core-java/core-java-concurrent/src/main/java/io/github/kavahub/learnjava/sequence/SequenceGenerator.java | kavahub/learnjava | 9fbf59d5e5d9712eb88c4856fce329ba3e21e978 | [
"MIT"
] | 1 | 2021-11-18T10:01:48.000Z | 2021-11-29T11:12:38.000Z | core-java/core-java-concurrent/src/main/java/io/github/kavahub/learnjava/sequence/SequenceGenerator.java | kavahub/learnjava | 9fbf59d5e5d9712eb88c4856fce329ba3e21e978 | [
"MIT"
] | null | null | null | 15.117647 | 45 | 0.642023 | 996,229 | package io.github.kavahub.learnjava.sequence;
/**
*
* 序列生成器,非线程安全
*
* @author PinWei Wan
* @since 1.0.0
*/
public class SequenceGenerator {
private int currentValue = 0;
public int getNextSequence() {
return currentValue++;
}
}
|
92327b7c2d03992b3808f385bb35c10867265c8c | 3,096 | java | Java | smartparam-engine/src/test/java/org/smartparam/engine/index/FastLevelNodeInspectorTest.java | akarazniewicz/smartparam | 81d4b0022c15d86fd5163990d392fb759d25ccf7 | [
"Apache-2.0"
] | 17 | 2015-05-15T23:22:45.000Z | 2021-03-30T01:51:41.000Z | smartparam-engine/src/test/java/org/smartparam/engine/index/FastLevelNodeInspectorTest.java | smartparam/smartparam | dd6b30bbd7abcf27ad1e218912b20aa6336d173d | [
"Apache-2.0"
] | 3 | 2016-08-17T14:45:32.000Z | 2019-02-10T14:03:36.000Z | smartparam-engine/src/test/java/org/smartparam/engine/index/FastLevelNodeInspectorTest.java | akarazniewicz/smartparam | 81d4b0022c15d86fd5163990d392fb759d25ccf7 | [
"Apache-2.0"
] | 7 | 2016-07-21T13:10:26.000Z | 2021-04-10T04:23:17.000Z | 34.021978 | 101 | 0.653747 | 996,230 | /*
* Copyright 2014 Adam Dubiel.
*
* 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.smartparam.engine.index;
import java.util.List;
import org.smartparam.engine.core.index.LevelIndex;
import org.testng.annotations.Test;
import static org.smartparam.engine.core.index.LevelIndexTestBuilder.levelIndex;
import static org.smartparam.engine.index.IndexTraversalOverridesTestBuilder.indexTraversalOverrides;
import static org.smartparam.engine.test.ParamEngineAssertions.assertThat;
/**
*
* @author Adam Dubiel
*/
public class FastLevelNodeInspectorTest {
@Test
public void shouldInspectOnlyChildWithBestMatch() {
// given
LevelIndex<String> index = levelIndex().withLevelCount(1).build();
index.add(new String[]{"*"}, "default");
index.add(new String[]{"A"}, "value");
index.add(new String[]{"C"}, "noise");
CustomizableLevelIndexWalker<String> crawler = new CustomizableLevelIndexWalker<String>(
indexTraversalOverrides().withGreediness(false).build(),
new SimpleLevelLeafValuesExtractor<String>(),
index,
"A");
// when
List<String> values = crawler.find();
// then
assertThat(values).containsOnly("value");
}
@Test
public void shouldFallBackToDefaultWhenNoBestMatchFound() {
// given
LevelIndex<String> index = levelIndex().withLevelCount(1).build();
index.add(new String[]{"*"}, "default");
index.add(new String[]{"C"}, "noise");
CustomizableLevelIndexWalker<String> crawler = new CustomizableLevelIndexWalker<String>(
indexTraversalOverrides().withGreediness(false).build(),
new SimpleLevelLeafValuesExtractor<String>(),
index,
"A");
// when
List<String> values = crawler.find();
// then
assertThat(values).containsOnly("default");
}
@Test
public void shouldReturnEmptyArrayWhenNoMatchFoundAtLevel() {
// given
LevelIndex<String> index = levelIndex().withLevelCount(1).build();
index.add(new String[]{"C"}, "noise");
CustomizableLevelIndexWalker<String> crawler = new CustomizableLevelIndexWalker<String>(
indexTraversalOverrides().withGreediness(false).build(),
new SimpleLevelLeafValuesExtractor<String>(),
index,
"A");
// when
List<String> values = crawler.find();
// then
assertThat(values).isEmpty();
}
}
|
92327ba5cb27db723bc13ba99158389a9c0a9f40 | 2,347 | java | Java | cloud-yblog-user/cloud-yblog-user1901/src/main/java/com/boot/service/impl/UserServiceImpl.java | youzhengjie9/cloud-yblog | cde6fcbfd98415baec0b25976122e42aff3f7615 | [
"Apache-2.0"
] | 176 | 2021-07-30T09:28:17.000Z | 2022-01-13T06:13:24.000Z | cloud-yblog-user/cloud-yblog-user1901/src/main/java/com/boot/service/impl/UserServiceImpl.java | Agora-Robot/cloud-yblog | cde6fcbfd98415baec0b25976122e42aff3f7615 | [
"Apache-2.0"
] | null | null | null | cloud-yblog-user/cloud-yblog-user1901/src/main/java/com/boot/service/impl/UserServiceImpl.java | Agora-Robot/cloud-yblog | cde6fcbfd98415baec0b25976122e42aff3f7615 | [
"Apache-2.0"
] | 7 | 2021-08-01T03:28:58.000Z | 2021-11-17T10:33:35.000Z | 25.791209 | 83 | 0.722199 | 996,231 | package com.boot.service.impl;
import com.boot.dao.UserMapper;
import com.boot.pojo.User;
import com.boot.pojo.UserAuthority;
import com.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User user) {
userMapper.addUser(user);
}
@Override
public void addUserAuthority(UserAuthority UserAuthority) {
userMapper.addUserAuthority(UserAuthority);
}
@Override
public void updateEmail(String email, String username) {
userMapper.updateEmail(email, username);
}
@Override
public User selectUserInfoByuserName(String name) {
return userMapper.selectUserInfoByuserName(name);
}
@Override
public String selectPasswordByuserName(String username) {
return userMapper.selectPasswordByuserName(username);
}
@Override
public void updatePassword(String username, String password) {
userMapper.updatePassword(username,password);
}
@Override
public List<User> selectAllUser() {
return userMapper.selectAllUser();
}
@Override
public void updateValidTo_0(String username) {
userMapper.updateValidTo_0(username);
}
@Override
public void updateValidTo_1(String username) {
userMapper.updateValidTo_1(username);
}
@Override
public void updateUserForEmail(long id, String email) {
userMapper.updateUserForEmail(id, email);
}
@Override
public int selectUseridByUserName(String username) {
return userMapper.selectUseridByUserName(username);
}
@Override
public int userCount() {
return userMapper.userCount();
}
@Override
public List<User> selectUserByUsernameAndEmail(String username, String email) {
return userMapper.selectUserByUsernameAndEmail(username,email);
}
@Override
public int selectUserCountByUsernameAndEmail(String username, String email) {
return userMapper.selectUserCountByUsernameAndEmail(username,email);
}
}
|
92327c42f6d8675a18e9f235bbd3d05c7ce6bb4e | 12,097 | java | Java | src/main/java/com/qubole/utility/RedisCache.java | qubole/caching-metastore-client | 89ad0a0bfb44f55b0fbf727f71080951fd522e08 | [
"Apache-2.0"
] | 5 | 2017-10-28T10:52:27.000Z | 2020-04-13T15:26:13.000Z | src/main/java/com/qubole/utility/RedisCache.java | qubole/caching-metastore-client | 89ad0a0bfb44f55b0fbf727f71080951fd522e08 | [
"Apache-2.0"
] | 10 | 2017-07-19T09:17:43.000Z | 2018-02-20T12:24:33.000Z | src/main/java/com/qubole/utility/RedisCache.java | qubole/caching-metastore-client | 89ad0a0bfb44f55b0fbf727f71080951fd522e08 | [
"Apache-2.0"
] | 4 | 2017-07-19T07:19:52.000Z | 2018-02-09T05:41:57.000Z | 32.258667 | 100 | 0.641895 | 996,232 | /*
* Copyright (c) 2016 Liwen Fan
* 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 com.qubole.utility;
import com.google.common.cache.AbstractLoadingCache;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.primitives.Bytes;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
/**
* Created by sakshibansal on 28/04/17.
*/
/**
* @param <K> Type: Key
* @param <V> Type: Value
*/
public class RedisCache<K, V> extends AbstractLoadingCache<K, V> implements LoadingCache<K, V> {
static final Logger LOGGER = LoggerFactory.getLogger(RedisCache.class);
private static JedisPool jedisPool;
private final Serializer keySerializer;
private final Serializer valueSerializer;
private final byte[] keyPrefix;
private final byte[] notFoundPrefix;
private final int missingCacheExpiration;
private final int expiration;
private final boolean enableMissingCache;
private final CacheLoader<K, V> loader;
public RedisCache(
JedisPool jedisPool,
byte[] keyPrefix,
int expiration, int missingCacheExpiration,
CacheLoader<K, V> loader, boolean enableMissingCache) {
this.jedisPool = jedisPool;
this.keySerializer = new JdkSerializer<K>();
this.valueSerializer = new JdkSerializer<V>();
this.keyPrefix = keyPrefix;
this.notFoundPrefix = Bytes.concat("Doesn'tExist.".getBytes(), keyPrefix);
this.expiration = expiration;
this.loader = loader;
this.enableMissingCache = enableMissingCache;
this.missingCacheExpiration = missingCacheExpiration;
}
public V getIfPresent(Object o) {
try (Jedis jedis = jedisPool.getResource()) {
byte[] key = Bytes.concat(keyPrefix, keySerializer.serialize(o));
byte[] reply = jedis.get(key);
if (reply == null) {
LOGGER.info("cache miss, key: " + new String(key));
return null;
} else {
LOGGER.info("cache hit, key: " + new String(key));
return valueSerializer.deserialize(reply);
}
} catch (Exception e) {
LOGGER.warn("getIfPresent failed for key: " + o + " with exception: " + e.toString());
return null;
}
}
public boolean checkMissingCache(Object o) {
try (Jedis jedis = jedisPool.getResource()) {
byte[] key = Bytes.concat(notFoundPrefix, keySerializer.serialize(o));
boolean reply = jedis.exists(key);
if (!reply) {
LOGGER.info("cache miss, key: " + new String(key));
} else {
LOGGER.info("cache hit, key: " + new String(key));
}
return reply;
} catch (Exception e) {
LOGGER.warn("checkMissingCache failed for key: " + o + " with exception: " + e.toString());
return false;
}
}
@Override
public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException {
V value = getIfPresent(key);
//get value from valueloader and update cache accordingly.
if (value == null) {
//Missing cache is enabled and the key is present in missing cache.
if (enableMissingCache && checkMissingCache(key)) {
convertAndThrow(
new ExecutionException("key found in missing cache, key doesn't exist.", null));
} else {
//Either the missing cache is not enabled
//or, it's enabled and the key is not present in missing cache
value = getFromSource(key, valueLoader);
}
}
return value;
}
public V getFromSource(K key, Callable<? extends V> valueLoader)
throws ExecutionException {
V value = null;
try {
value = valueLoader.call();
} catch (Throwable e) {
if (enableMissingCache) {
this.putNotFound(key, "Does not exist.");
}
convertAndThrow(e);
}
if (value == null) {
throw new CacheLoader
.InvalidCacheLoadException("valueLoader must not return null, key=" + key);
}
this.put(key, value);
return value;
}
@Override
public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
try (Jedis jedis = jedisPool.getResource()) {
List<byte[]> keyBytes = new ArrayList<>();
for (Object key : keys) {
keyBytes.add(Bytes.concat(keyPrefix, keySerializer.serialize(key)));
}
List<byte[]> valueBytes = jedis.mget(Iterables.toArray(keyBytes, byte[].class));
Map<K, V> map = new LinkedHashMap<>();
int i = 0;
// mget always return an array of keys size.
// Each entry would correspond the key of that index.
// if no such key exists vaue will be null.
for (Object key : keys) {
if (valueBytes.get(i) != null) {
@SuppressWarnings("unchecked")
K castKey = (K) key;
map.put(castKey, valueSerializer.<V>deserialize(valueBytes.get(i)));
i++;
}
}
return ImmutableMap.copyOf(map);
} catch (Exception e) {
LOGGER.error("Exception in getAllPresent: " + e.toString());
return ImmutableMap.of();
}
}
@Override
public void put(K key, V value) {
try (Jedis jedis = jedisPool.getResource()) {
byte[] keyBytes = Bytes.concat(keyPrefix, keySerializer.serialize(key));
byte[] valueBytes = valueSerializer.serialize(value);
if (expiration > 0) {
jedis.setex(keyBytes, expiration, valueBytes);
} else {
jedis.set(keyBytes, valueBytes);
}
} catch (Exception e) {
LOGGER.error("Failed to put the key: " + key + ", with exception: " + e.toString());
}
}
public void putNotFound(K key, String value) {
try (Jedis jedis = jedisPool.getResource()) {
byte[] keyBytes = Bytes.concat(notFoundPrefix, keySerializer.serialize(key));
byte[] valueBytes = value.getBytes();
if (missingCacheExpiration > 0) {
jedis.setex(keyBytes, missingCacheExpiration, valueBytes);
} else {
jedis.set(keyBytes, valueBytes);
}
} catch (Exception e) {
LOGGER.error("Error in putting the key to not-found redis");
}
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
try (Jedis jedis = jedisPool.getResource()) {
List<byte[]> keysvalues = new ArrayList<>();
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
keysvalues.add(Bytes.concat(keyPrefix, keySerializer.serialize(entry.getKey())));
keysvalues.add(valueSerializer.serialize(entry.getValue()));
}
if (expiration > 0) {
Pipeline pipeline = jedis.pipelined();
pipeline.mset(Iterables.toArray(keysvalues, byte[].class));
for (int i = 0; i < keysvalues.size(); i += 2) {
pipeline.expire(keysvalues.get(i), expiration);
}
pipeline.sync();
} else {
jedis.mset(Iterables.toArray(keysvalues, byte[].class));
}
} catch (Exception e) {
LOGGER.error("Exception in putAll: " + e.toString());
}
}
@Override
public void invalidate(Object key) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.del(Bytes.concat(keyPrefix, keySerializer.serialize(key)));
} catch (Exception e) {
LOGGER.error("Failed to invalidate key: " + key + " with exception: " + e.toString());
}
}
@Override
public void invalidateAll(Iterable<?> keys) {
Set<byte[]> keyBytes = new LinkedHashSet<>();
for (Object key : keys) {
keyBytes.add(Bytes.concat(keyPrefix, keySerializer.serialize(key)));
}
try (Jedis jedis = jedisPool.getResource()) {
jedis.del(Iterables.toArray(keyBytes, byte[].class));
}
}
@Override
public V get(final K key) throws ExecutionException {
return this.get(key, new Callable<V>() {
@Override
public V call() throws Exception {
return loader.load(key);
}
});
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
Map<K, V> result = Maps.newLinkedHashMap(this.getAllPresent(keys));
Set<K> keysToLoad = Sets.newLinkedHashSet(keys);
keysToLoad.removeAll(result.keySet());
if (!keysToLoad.isEmpty()) {
try {
Map<K, V> newEntries = loader.loadAll(keysToLoad);
if (newEntries == null) {
throw new CacheLoader
.InvalidCacheLoadException(loader + " returned null map from loadAll");
}
this.putAll(newEntries);
for (K key : keysToLoad) {
V value = newEntries.get(key);
if (value == null) {
throw new CacheLoader
.InvalidCacheLoadException("loadAll failed to return a value for " + key);
}
result.put(key, value);
}
} catch (CacheLoader.InvalidCacheLoadException e) {
Map<K, V> newEntries = new LinkedHashMap<>();
boolean nullsPresent = false;
Throwable t = null;
for (K key : keysToLoad) {
try {
V value = loader.load(key);
if (value == null) {
// delay failure until non-null entries are stored
nullsPresent = true;
} else {
newEntries.put(key, value);
}
} catch (Throwable tt) {
t = tt;
break;
}
}
this.putAll(newEntries);
if (nullsPresent) {
throw new CacheLoader
.InvalidCacheLoadException(loader + " returned null keys or values from loadAll");
} else if (t != null) {
convertAndThrow(t);
} else {
result.putAll(newEntries);
}
} catch (Throwable e) {
convertAndThrow(e);
}
}
return ImmutableMap.copyOf(result);
}
@Override
public void refresh(K key) {
try {
V value = loader.load(key);
this.put(key, value);
} catch (Exception e) {
LOGGER.warn("Exception thrown during refresh", e);
}
}
private static void convertAndThrow(Throwable t) throws ExecutionException {
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
throw new ExecutionException(t);
} else if (t instanceof RuntimeException) {
throw new UncheckedExecutionException(t);
} else if (t instanceof Exception) {
throw new ExecutionException(t);
} else {
throw new ExecutionError((Error) t);
}
}
byte[] getNotFoundPrefix() {
return this.notFoundPrefix;
}
}
|
92327eadc7c422a4e68c75c6a5a9643284ce8d7f | 1,126 | java | Java | android/java/src/com/yahoo/cnet/ResponseCompletion.java | yahoo/cnet | d36ee43bd86ac13df5bd034f61af96b98bfed65a | [
"BSD-3-Clause"
] | 16 | 2015-02-04T17:15:04.000Z | 2019-05-14T11:53:29.000Z | android/java/src/com/yahoo/cnet/ResponseCompletion.java | yahoo/cnet | d36ee43bd86ac13df5bd034f61af96b98bfed65a | [
"BSD-3-Clause"
] | null | null | null | android/java/src/com/yahoo/cnet/ResponseCompletion.java | yahoo/cnet | d36ee43bd86ac13df5bd034f61af96b98bfed65a | [
"BSD-3-Clause"
] | 13 | 2015-04-15T07:28:05.000Z | 2019-06-19T01:47:26.000Z | 38.827586 | 80 | 0.721137 | 996,233 | // Copyright 2014, Yahoo! Inc.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package com.yahoo.cnet;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
@JNINamespace("cnet::android")
public interface ResponseCompletion {
public static final boolean RELEASE_NOW = true;
public static final boolean RELEASE_LATER = false;
/**
* Invoked when a fetch has completed.
* This is called on a work thread shared by all fetchers in a Cnet pool.
* @param fetcher The fetcher that has completed.
* @param response The response state from the fetch.
* @return If true, then immediately release all native fetcher and response
* resources. If false, then resources will be retained until garbage
* collected or manually released. Note that the garbage collector is
* unaware of how many resources the native objects hold --- the
* response body might be multiple megabytes.
*/
@CalledByNative
boolean onBackgroundComplete(Fetcher fetcher, Response response);
}
|
92327ef9a8c9351bcc0bc8bc51b5d235f6dad2f9 | 5,113 | java | Java | src/client/streamalert/util/LiveTestServiceLocator.java | RyanHotton/streamalert-ws | ba2e68100222fb635726a66294eb2e1e3c22bf3e | [
"Apache-2.0"
] | null | null | null | src/client/streamalert/util/LiveTestServiceLocator.java | RyanHotton/streamalert-ws | ba2e68100222fb635726a66294eb2e1e3c22bf3e | [
"Apache-2.0"
] | null | null | null | src/client/streamalert/util/LiveTestServiceLocator.java | RyanHotton/streamalert-ws | ba2e68100222fb635726a66294eb2e1e3c22bf3e | [
"Apache-2.0"
] | null | null | null | 35.755245 | 188 | 0.666732 | 996,234 | /**
* LiveTestServiceLocator.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package streamalert.util;
public class LiveTestServiceLocator extends org.apache.axis.client.Service implements streamalert.util.LiveTestService {
public LiveTestServiceLocator() {
}
public LiveTestServiceLocator(org.apache.axis.EngineConfiguration config) {
super(config);
}
public LiveTestServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException {
super(wsdlLoc, sName);
}
// Use to get a proxy class for LiveTest
private java.lang.String LiveTest_address = "http://localhost:9999/PM1_StreamAlert_Service/services/LiveTest";
public java.lang.String getLiveTestAddress() {
return LiveTest_address;
}
// The WSDD service name defaults to the port name.
private java.lang.String LiveTestWSDDServiceName = "LiveTest";
public java.lang.String getLiveTestWSDDServiceName() {
return LiveTestWSDDServiceName;
}
public void setLiveTestWSDDServiceName(java.lang.String name) {
LiveTestWSDDServiceName = name;
}
public streamalert.util.LiveTest getLiveTest() throws javax.xml.rpc.ServiceException {
java.net.URL endpoint;
try {
endpoint = new java.net.URL(LiveTest_address);
}
catch (java.net.MalformedURLException e) {
throw new javax.xml.rpc.ServiceException(e);
}
return getLiveTest(endpoint);
}
public streamalert.util.LiveTest getLiveTest(java.net.URL portAddress) throws javax.xml.rpc.ServiceException {
try {
streamalert.util.LiveTestSoapBindingStub _stub = new streamalert.util.LiveTestSoapBindingStub(portAddress, this);
_stub.setPortName(getLiveTestWSDDServiceName());
return _stub;
}
catch (org.apache.axis.AxisFault e) {
return null;
}
}
public void setLiveTestEndpointAddress(java.lang.String address) {
LiveTest_address = address;
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
try {
if (streamalert.util.LiveTest.class.isAssignableFrom(serviceEndpointInterface)) {
streamalert.util.LiveTestSoapBindingStub _stub = new streamalert.util.LiveTestSoapBindingStub(new java.net.URL(LiveTest_address), this);
_stub.setPortName(getLiveTestWSDDServiceName());
return _stub;
}
}
catch (java.lang.Throwable t) {
throw new javax.xml.rpc.ServiceException(t);
}
throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
if (portName == null) {
return getPort(serviceEndpointInterface);
}
java.lang.String inputPortName = portName.getLocalPart();
if ("LiveTest".equals(inputPortName)) {
return getLiveTest();
}
else {
java.rmi.Remote _stub = getPort(serviceEndpointInterface);
((org.apache.axis.client.Stub) _stub).setPortName(portName);
return _stub;
}
}
public javax.xml.namespace.QName getServiceName() {
return new javax.xml.namespace.QName("http://util.streamalert", "LiveTestService");
}
private java.util.HashSet ports = null;
public java.util.Iterator getPorts() {
if (ports == null) {
ports = new java.util.HashSet();
ports.add(new javax.xml.namespace.QName("http://util.streamalert", "LiveTest"));
}
return ports.iterator();
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
if ("LiveTest".equals(portName)) {
setLiveTestEndpointAddress(address);
}
else
{ // Unknown Port Name
throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName);
}
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
setEndpointAddress(portName.getLocalPart(), address);
}
}
|
92327f21d3d12de120b6855dcc54585c5ab095a4 | 7,131 | java | Java | main/smyld-bw/src/main/java/org/smyld/bw/util/BWUtility.java | MFJamil/smyld-java | 66bcf92b8b95edd47263976f9088098487fa89ce | [
"Apache-2.0"
] | 2 | 2019-09-26T09:22:07.000Z | 2019-10-22T16:50:48.000Z | main/smyld-bw/src/main/java/org/smyld/bw/util/BWUtility.java | MFJamil/smyld-java | 66bcf92b8b95edd47263976f9088098487fa89ce | [
"Apache-2.0"
] | 2 | 2020-04-23T19:24:37.000Z | 2020-06-18T16:49:02.000Z | main/smyld-bw/src/main/java/org/smyld/bw/util/BWUtility.java | MFJamil/smyld-java | 66bcf92b8b95edd47263976f9088098487fa89ce | [
"Apache-2.0"
] | null | null | null | 31.004348 | 105 | 0.703267 | 996,235 | package org.smyld.bw.util;
import java.io.File;
import org.smyld.bw.data.structurs.SystemJob;
import org.smyld.bw.db.BWDBAccess;
import org.smyld.bw.db.DBValue;
import org.smyld.text.TextUtil;
import org.smyld.util.SMYLDDate;
import org.smyld.util.Util;
public class BWUtility extends Util {
/**
*
*/
private static final long serialVersionUID = 1L;
public BWUtility() {
}
public static synchronized String createAuditTrial(
SystemJob currentSystemJob, String trnID) {
return createAuditTrial(currentSystemJob.getUserID(),currentSystemJob.getStationNo(), trnID);
}
public static synchronized String createAuditTrial(String userID,String stationNo, String trnID) {
SMYLDDate currentDate = new SMYLDDate();
if (trnID == null)
trnID = AUDIT_TRIAL_TRN_NO;
String auditTrial = currentDate.toString(SMYLDDate.FRM_yyDDD_HHmmss)
+ "-" + userID + "-"+ stationNo + (trnID!=null? "-" + trnID:"");
//+ "-"+ currentDate.getTimeSinceMidNight(); Old implementation for HVE, must be equal to 35 as maximum
return auditTrial;
}
public static synchronized String getValidValueRange(String value,
int from, int to) {
if (TextUtil.isEmpty(value))
return null;
int intValue = -1;
try {
intValue = Integer.parseInt(value);
} catch (Exception ex) {
}
if (((intValue < from) && (intValue > to)) || (intValue == -1))
return null;
return value;
}
public static synchronized String validateCityName(String cityOriginalName) {
char[] cityName = cityOriginalName.toCharArray();
if (cityName[0] != Character.SPACE_SEPARATOR) {
if (!Character.isDigit(cityName[0])) {
for (int i = 0; i < cityName.length; i++)
if (!((Character.isLetterOrDigit(cityName[i])) || (cityName[i] == '*')))
cityName[i] = ' ';
if (cityName[0] != ' ')
return new String(cityName);
}
}
return COUNTRY_CODE_DEFAULT;
}
public static synchronized double getISOAmount(String amount,
int CurrencyExp) {
double result = 0;
if (!TextUtil.isEmpty(amount)) {
amount = amount.trim();
if (CurrencyExp >= 0) {
try {
result = Integer.parseInt(amount)
/ (Math.pow(10, CurrencyExp));
} catch (Exception ex) {
result = Integer.parseInt(amount.substring(1))
/ (Math.pow(10, CurrencyExp));
if (amount.startsWith("D"))
result = -1 * result;
}
}
}
return result;
}
private static synchronized String addTrailingZeros(String value, int exp) {
int dotLoc = value.indexOf('.');
if (dotLoc != -1) {
String decimalPart = value.substring(0, dotLoc);
String partialPart = value.substring(dotLoc + 1);
if (partialPart.length() < exp)
partialPart = TextUtil.fillRightSide(partialPart, exp, '0');
return decimalPart + '.' + partialPart;
}
return value;
}
public static synchronized double getISOAmount(String amount,
String CurrCode) {
int currExp = BWDBAccess.getCurrencyExponent(CurrCode);
if (currExp != -1)
return getISOAmount(amount, currExp);
return 0;
}
public static synchronized String getISOAmountText(String amount,
String CurrCode, boolean withTrailingZeros) {
String result = Double.toString(getISOAmount(amount, CurrCode));
if (withTrailingZeros)
return addTrailingZeros(result, BWDBAccess
.getCurrencyExponent(CurrCode));
return result;
// return Double.toString(getISOAmount(amount,CurrCode));
}
public static synchronized String getISOAmountText(String amount,
String CurrCode) {
return Double.toString(getISOAmount(amount, CurrCode));
}
public static synchronized String getISOAmountText(String amount,
int CurrencyExp) {
return Double.toString(getISOAmount(amount, CurrencyExp));
}
public static synchronized String getISOAmountText(String amount,
int CurrencyExp, boolean withTrailingZeros) {
String result = Double.toString(getISOAmount(amount, CurrencyExp));
if (withTrailingZeros)
return addTrailingZeros(result, CurrencyExp);
return result;
}
public static synchronized String getCountryCode(String code) {
if (!TextUtil.isEmpty(code)) {
if (code.length() == 2)
return (String) BWDBAccess.countryCodes2.get(code);
if (code.length() == 3)
return (String) BWDBAccess.countryCodes3.get(code);
}
return DBValue.DB_VALUE_NOT_EXIST;
}
public static synchronized String getCountryByStateCode(String code) {
return (String) BWDBAccess.countryStateCodes.get(code);
}
public static synchronized boolean validateCountryState(String country,
String state) {
if (doHaveStateCode(country)) {
String countryCode = (String) BWDBAccess.countryStateCodes
.get(state);
if (countryCode != null)
return country.equals(countryCode);
} else if (TextUtil.isEmpty(state)) {
return true;
}
return false;
}
public static synchronized boolean doHaveStateCode(String CountryCode) {
return ((CountryCode != null) && ((CountryCode
.equals(DBValue.COUNTRY_UNITED_STATES))
|| (CountryCode.equals(DBValue.COUNTRY_CANADA)) || (CountryCode
.equals(DBValue.COUNTRY_AUSTRALIA))));
}
/**
* This method will validate the given address and will return the result,
* the validation contains whether the given country code exists and if so,
* whether the given state exists.
*/
public static synchronized boolean validateAddress(String countryCode,
String cityName, String stateCode, String postalCode) {
boolean result = false;
if ((!TextUtil.isEmpty(countryCode)) && (!TextUtil.isEmpty(cityName))) {
if (doHaveStateCode(countryCode)) {
if (!TextUtil.isEmpty(stateCode)) {
if ((!countryCode.equals(DBValue.COUNTRY_AUSTRALIA))
&& (!countryCode
.equals(getCountryByStateCode(stateCode))))
stateCode = null;
if ((stateCode != null) && (!TextUtil.isEmpty(postalCode)))
result = true;
} else if (countryCode.equals(DBValue.COUNTRY_AUSTRALIA)) {
// CHG need to load it from sys_configuration table -
// processing - AllowSpacesAsState
// Australia allows spaces in state
result = true;
}
} else if (TextUtil.isEmpty(stateCode)) {
result = true;
}
}
return result;
}
public static synchronized String generateMaskFileName(String origNAme)
throws Exception {
File testFile = new File(origNAme);
String fileName = testFile.getName();
String pathName = testFile.getParent();
StringBuffer buffer = new StringBuffer(fileName.length());
StringBuffer dateBuffer = new StringBuffer();
int datePos = 0;
boolean insideMask = false;
for (int i = 0; i < fileName.length(); i++) {
char curChar = fileName.charAt(i);
if (curChar == '[') {
insideMask = true;
datePos = i;
} else if (curChar == ']') {
insideMask = false;
} else if (insideMask) {
dateBuffer.append(curChar);
} else {
buffer.append(curChar);
}
}
SMYLDDate targetDate = new SMYLDDate(dateBuffer.toString());
buffer.insert(datePos, targetDate.toString());
String originalFile = pathName + File.separator + buffer.toString();
return originalFile;
}
public static final String COUNTRY_CODE_DEFAULT = "";
public static final String AUDIT_TRIAL_TRN_NO = "99998";
}
|
92327f50d774dec7d85ea65db7bbba54017598fa | 2,356 | java | Java | cache/src/test/java/net/runelite/cache/HeightMapDumperTest.java | robmonte/runelite | e73ccc30691be9ffe9a85e7a89900194698447ed | [
"BSD-2-Clause"
] | 4,320 | 2016-05-10T02:31:13.000Z | 2022-03-30T02:21:42.000Z | cache/src/test/java/net/runelite/cache/HeightMapDumperTest.java | robmonte/runelite | e73ccc30691be9ffe9a85e7a89900194698447ed | [
"BSD-2-Clause"
] | 11,197 | 2016-12-27T16:07:13.000Z | 2022-03-31T23:32:34.000Z | cache/src/test/java/net/runelite/cache/HeightMapDumperTest.java | robmonte/runelite | e73ccc30691be9ffe9a85e7a89900194698447ed | [
"BSD-2-Clause"
] | 6,362 | 2016-05-11T15:20:38.000Z | 2022-03-31T22:24:54.000Z | 35.69697 | 89 | 0.759762 | 996,236 | /*
* Copyright (c) 2016-2017, Adam <lyhxr@example.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.cache;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.runelite.cache.fs.Store;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HeightMapDumperTest
{
private static final Logger logger = LoggerFactory.getLogger(HeightMapDumperTest.class);
@Rule
public TemporaryFolder folder = StoreLocation.getTemporaryFolder();
//@Test
public void extract() throws IOException
{
File base = StoreLocation.LOCATION,
outDir = folder.newFolder();
try (Store store = new Store(base))
{
store.load();
HeightMapDumper dumper = new HeightMapDumper(store);
dumper.load();
BufferedImage image = dumper.drawHeightMap(0);
File imageFile = new File(outDir, "heightmap-0.png");
ImageIO.write(image, "png", imageFile);
logger.info("Wrote image {}", imageFile);
}
}
}
|
92327f60cbd3027a7edbf08329bdff4d6635c60e | 2,158 | java | Java | ClaynFileSystem2/ClaynFileSystem2-API/src/main/java/net/bplaced/clayn/cfs2/api/VirtualFileSystem.java | Clayn/cfs2 | 1788604b14117556193e384b54c8a6adf2973fab | [
"MIT"
] | null | null | null | ClaynFileSystem2/ClaynFileSystem2-API/src/main/java/net/bplaced/clayn/cfs2/api/VirtualFileSystem.java | Clayn/cfs2 | 1788604b14117556193e384b54c8a6adf2973fab | [
"MIT"
] | 3 | 2017-12-29T11:10:57.000Z | 2019-01-01T18:13:36.000Z | ClaynFileSystem2/ClaynFileSystem2-API/src/main/java/net/bplaced/clayn/cfs2/api/VirtualFileSystem.java | Clayn/cfs2 | 1788604b14117556193e384b54c8a6adf2973fab | [
"MIT"
] | null | null | null | 33.261538 | 80 | 0.722479 | 996,237 | /*
* The MIT License
*
* Copyright 2017 Clayn <envkt@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.
*/
package net.bplaced.clayn.cfs2.api;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import net.bplaced.clayn.cfs2.api.util.Copyable;
import net.bplaced.clayn.cfs2.api.util.FileSystemProvider;
/**
*
* @author Clayn <envkt@example.com>
* @since 0.2.0
*/
public interface VirtualFileSystem extends Copyable<VirtualFileSystem>
{
/**
* Returns the root directory for this file system.
*
* @return the root for this file system.
*/
public VirtualDirectory getRoot();
@Override
public default void copy(VirtualFileSystem dest) throws IOException
{
getRoot().copy(dest.getRoot());
}
/**
* Returns a map with all required parameters for using the
* {@link FileSystemProvider file system provider}.
*
* @return a non {@code null} map with all parameters for this filesystem
*/
public default Map<String, Class<?>> getProviderInformation()
{
return Collections.emptyMap();
}
}
|
92327f765bbde9fa0e14adbf3048353542261b55 | 852 | java | Java | XtextCalculatorForm/src/main/xtext-gen/de/htwg/zeta/xtext/calculatorForm/impl/BooleanNegationImpl.java | phaldan/htwg-xtext-cform | 00ddf5bedb1be1db33614f0b1d15ddcbe762eabc | [
"MIT"
] | 1 | 2019-06-04T22:43:32.000Z | 2019-06-04T22:43:32.000Z | XtextCalculatorForm/src/main/xtext-gen/de/htwg/zeta/xtext/calculatorForm/impl/BooleanNegationImpl.java | phaldan/htwg-xtext-cform | 00ddf5bedb1be1db33614f0b1d15ddcbe762eabc | [
"MIT"
] | null | null | null | XtextCalculatorForm/src/main/xtext-gen/de/htwg/zeta/xtext/calculatorForm/impl/BooleanNegationImpl.java | phaldan/htwg-xtext-cform | 00ddf5bedb1be1db33614f0b1d15ddcbe762eabc | [
"MIT"
] | null | null | null | 20.285714 | 86 | 0.656103 | 996,238 | /**
* generated by Xtext 2.9.2
*/
package de.htwg.zeta.xtext.calculatorForm.impl;
import de.htwg.zeta.xtext.calculatorForm.BooleanNegation;
import de.htwg.zeta.xtext.calculatorForm.CalculatorFormPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Boolean Negation</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class BooleanNegationImpl extends UnaryOperationImpl implements BooleanNegation
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BooleanNegationImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return CalculatorFormPackage.Literals.BOOLEAN_NEGATION;
}
} //BooleanNegationImpl
|
92327fd2b2e9a093aa1141e7996790a0bcf850b5 | 25,169 | java | Java | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionVertex.java | TU-Berlin-DIMA/sage-flink | 7439cc4e57889e752fd3da71e16696af1baf82ce | [
"BSD-3-Clause"
] | 80 | 2016-08-11T03:07:28.000Z | 2022-03-27T06:47:09.000Z | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionVertex.java | TU-Berlin-DIMA/sage-flink | 7439cc4e57889e752fd3da71e16696af1baf82ce | [
"BSD-3-Clause"
] | 1 | 2021-11-11T02:46:51.000Z | 2021-11-11T02:46:51.000Z | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionVertex.java | TU-Berlin-DIMA/sage-flink | 7439cc4e57889e752fd3da71e16696af1baf82ce | [
"BSD-3-Clause"
] | 40 | 2016-08-12T05:40:51.000Z | 2022-01-11T08:01:04.000Z | 33.874832 | 132 | 0.708888 | 996,239 | /*
* 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.flink.runtime.executiongraph;
import org.apache.flink.api.common.Archiveable;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.JobException;
import org.apache.flink.runtime.deployment.InputChannelDeploymentDescriptor;
import org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor;
import org.apache.flink.runtime.deployment.PartialInputChannelDeploymentDescriptor;
import org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor;
import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.instance.SimpleSlot;
import org.apache.flink.runtime.instance.SlotProvider;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.DistributionPattern;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
import org.apache.flink.runtime.jobgraph.JobEdge;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobmanager.JobManagerOptions;
import org.apache.flink.runtime.jobmanager.scheduler.CoLocationConstraint;
import org.apache.flink.runtime.jobmanager.scheduler.CoLocationGroup;
import org.apache.flink.runtime.state.KeyGroupRangeAssignment;
import org.apache.flink.runtime.state.TaskStateHandles;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.runtime.util.EvictingBoundedList;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.SerializedValue;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.flink.runtime.execution.ExecutionState.CANCELED;
import static org.apache.flink.runtime.execution.ExecutionState.FAILED;
import static org.apache.flink.runtime.execution.ExecutionState.FINISHED;
/**
* The ExecutionVertex is a parallel subtask of the execution. It may be executed once, or several times, each of
* which time it spawns an {@link Execution}.
*/
public class ExecutionVertex implements AccessExecutionVertex, Archiveable<ArchivedExecutionVertex> {
private static final Logger LOG = ExecutionGraph.LOG;
private static final int MAX_DISTINCT_LOCATIONS_TO_CONSIDER = 8;
// --------------------------------------------------------------------------------------------
private final ExecutionJobVertex jobVertex;
private final Map<IntermediateResultPartitionID, IntermediateResultPartition> resultPartitions;
private final ExecutionEdge[][] inputEdges;
private final int subTaskIndex;
private final EvictingBoundedList<Execution> priorExecutions;
private final Time timeout;
/** The name in the format "myTask (2/7)", cached to avoid frequent string concatenations */
private final String taskNameWithSubtask;
private volatile CoLocationConstraint locationConstraint;
/** The current or latest execution attempt of this vertex's task */
private volatile Execution currentExecution; // this field must never be null
// --------------------------------------------------------------------------------------------
public ExecutionVertex(
ExecutionJobVertex jobVertex,
int subTaskIndex,
IntermediateResult[] producedDataSets,
Time timeout) {
this(
jobVertex,
subTaskIndex,
producedDataSets,
timeout,
System.currentTimeMillis(),
JobManagerOptions.MAX_ATTEMPTS_HISTORY_SIZE.defaultValue());
}
public ExecutionVertex(
ExecutionJobVertex jobVertex,
int subTaskIndex,
IntermediateResult[] producedDataSets,
Time timeout,
int maxPriorExecutionHistoryLength) {
this(jobVertex, subTaskIndex, producedDataSets, timeout, System.currentTimeMillis(), maxPriorExecutionHistoryLength);
}
public ExecutionVertex(
ExecutionJobVertex jobVertex,
int subTaskIndex,
IntermediateResult[] producedDataSets,
Time timeout,
long createTimestamp,
int maxPriorExecutionHistoryLength) {
this.jobVertex = jobVertex;
this.subTaskIndex = subTaskIndex;
this.taskNameWithSubtask = String.format("%s (%d/%d)",
jobVertex.getJobVertex().getName(), subTaskIndex + 1, jobVertex.getParallelism());
this.resultPartitions = new LinkedHashMap<IntermediateResultPartitionID, IntermediateResultPartition>(producedDataSets.length, 1);
for (IntermediateResult result : producedDataSets) {
IntermediateResultPartition irp = new IntermediateResultPartition(result, this, subTaskIndex);
result.setPartition(subTaskIndex, irp);
resultPartitions.put(irp.getPartitionId(), irp);
}
this.inputEdges = new ExecutionEdge[jobVertex.getJobVertex().getInputs().size()][];
this.priorExecutions = new EvictingBoundedList<>(maxPriorExecutionHistoryLength);
this.currentExecution = new Execution(
getExecutionGraph().getFutureExecutor(),
this,
0,
createTimestamp,
timeout);
// create a co-location scheduling hint, if necessary
CoLocationGroup clg = jobVertex.getCoLocationGroup();
if (clg != null) {
this.locationConstraint = clg.getLocationConstraint(subTaskIndex);
}
else {
this.locationConstraint = null;
}
this.timeout = timeout;
}
// --------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------
public JobID getJobId() {
return this.jobVertex.getJobId();
}
public ExecutionJobVertex getJobVertex() {
return jobVertex;
}
public JobVertexID getJobvertexId() {
return this.jobVertex.getJobVertexId();
}
public String getTaskName() {
return this.jobVertex.getJobVertex().getName();
}
@Override
public String getTaskNameWithSubtaskIndex() {
return this.taskNameWithSubtask;
}
public int getTotalNumberOfParallelSubtasks() {
return this.jobVertex.getParallelism();
}
public int getMaxParallelism() {
return this.jobVertex.getMaxParallelism();
}
@Override
public int getParallelSubtaskIndex() {
return this.subTaskIndex;
}
public int getNumberOfInputs() {
return this.inputEdges.length;
}
public ExecutionEdge[] getInputEdges(int input) {
if (input < 0 || input >= this.inputEdges.length) {
throw new IllegalArgumentException(String.format("Input %d is out of range [0..%d)", input, this.inputEdges.length));
}
return inputEdges[input];
}
public CoLocationConstraint getLocationConstraint() {
return locationConstraint;
}
@Override
public Execution getCurrentExecutionAttempt() {
return currentExecution;
}
@Override
public ExecutionState getExecutionState() {
return currentExecution.getState();
}
@Override
public long getStateTimestamp(ExecutionState state) {
return currentExecution.getStateTimestamp(state);
}
@Override
public String getFailureCauseAsString() {
return ExceptionUtils.stringifyException(getFailureCause());
}
public Throwable getFailureCause() {
return currentExecution.getFailureCause();
}
public SimpleSlot getCurrentAssignedResource() {
return currentExecution.getAssignedResource();
}
@Override
public TaskManagerLocation getCurrentAssignedResourceLocation() {
return currentExecution.getAssignedResourceLocation();
}
@Override
public Execution getPriorExecutionAttempt(int attemptNumber) {
synchronized (priorExecutions) {
if (attemptNumber >= 0 && attemptNumber < priorExecutions.size()) {
return priorExecutions.get(attemptNumber);
} else {
throw new IllegalArgumentException("attempt does not exist");
}
}
}
/**
* Gets the location where the latest completed/canceled/failed execution of the vertex's
* task happened.
*
* @return The latest prior execution location, or null, if there is none, yet.
*/
public TaskManagerLocation getLatestPriorLocation() {
synchronized (priorExecutions) {
final int size = priorExecutions.size();
if (size > 0) {
return priorExecutions.get(size - 1).getAssignedResourceLocation();
}
else {
return null;
}
}
}
EvictingBoundedList<Execution> getCopyOfPriorExecutionsList() {
synchronized (priorExecutions) {
return new EvictingBoundedList<>(priorExecutions);
}
}
public ExecutionGraph getExecutionGraph() {
return this.jobVertex.getGraph();
}
public Map<IntermediateResultPartitionID, IntermediateResultPartition> getProducedPartitions() {
return resultPartitions;
}
// --------------------------------------------------------------------------------------------
// Graph building
// --------------------------------------------------------------------------------------------
public void connectSource(int inputNumber, IntermediateResult source, JobEdge edge, int consumerNumber) {
final DistributionPattern pattern = edge.getDistributionPattern();
final IntermediateResultPartition[] sourcePartitions = source.getPartitions();
ExecutionEdge[] edges;
switch (pattern) {
case POINTWISE:
edges = connectPointwise(sourcePartitions, inputNumber);
break;
case ALL_TO_ALL:
edges = connectAllToAll(sourcePartitions, inputNumber);
break;
default:
throw new RuntimeException("Unrecognized distribution pattern.");
}
this.inputEdges[inputNumber] = edges;
// add the consumers to the source
// for now (until the receiver initiated handshake is in place), we need to register the
// edges as the execution graph
for (ExecutionEdge ee : edges) {
ee.getSource().addConsumer(ee, consumerNumber);
}
}
private ExecutionEdge[] connectAllToAll(IntermediateResultPartition[] sourcePartitions, int inputNumber) {
ExecutionEdge[] edges = new ExecutionEdge[sourcePartitions.length];
for (int i = 0; i < sourcePartitions.length; i++) {
IntermediateResultPartition irp = sourcePartitions[i];
edges[i] = new ExecutionEdge(irp, this, inputNumber);
}
return edges;
}
private ExecutionEdge[] connectPointwise(IntermediateResultPartition[] sourcePartitions, int inputNumber) {
final int numSources = sourcePartitions.length;
final int parallelism = getTotalNumberOfParallelSubtasks();
// simple case same number of sources as targets
if (numSources == parallelism) {
return new ExecutionEdge[] { new ExecutionEdge(sourcePartitions[subTaskIndex], this, inputNumber) };
}
else if (numSources < parallelism) {
int sourcePartition;
// check if the pattern is regular or irregular
// we use int arithmetics for regular, and floating point with rounding for irregular
if (parallelism % numSources == 0) {
// same number of targets per source
int factor = parallelism / numSources;
sourcePartition = subTaskIndex / factor;
}
else {
// different number of targets per source
float factor = ((float) parallelism) / numSources;
sourcePartition = (int) (subTaskIndex / factor);
}
return new ExecutionEdge[] { new ExecutionEdge(sourcePartitions[sourcePartition], this, inputNumber) };
}
else {
if (numSources % parallelism == 0) {
// same number of targets per source
int factor = numSources / parallelism;
int startIndex = subTaskIndex * factor;
ExecutionEdge[] edges = new ExecutionEdge[factor];
for (int i = 0; i < factor; i++) {
edges[i] = new ExecutionEdge(sourcePartitions[startIndex + i], this, inputNumber);
}
return edges;
}
else {
float factor = ((float) numSources) / parallelism;
int start = (int) (subTaskIndex * factor);
int end = (subTaskIndex == getTotalNumberOfParallelSubtasks() - 1) ?
sourcePartitions.length :
(int) ((subTaskIndex + 1) * factor);
ExecutionEdge[] edges = new ExecutionEdge[end - start];
for (int i = 0; i < edges.length; i++) {
edges[i] = new ExecutionEdge(sourcePartitions[start + i], this, inputNumber);
}
return edges;
}
}
}
/**
* Gets the overall preferred execution location for this vertex's current execution.
* The preference is determined as follows:
*
* <ol>
* <li>If the task execution has state to load (from a checkpoint), then the location preference
* is the location of the previous execution (if there is a previous execution attempt).
* <li>If the task execution has no state or no previous location, then the location preference
* is based on the task's inputs.
* </ol>
*
* These rules should result in the following behavior:
*
* <ul>
* <li>Stateless tasks are always scheduled based on co-location with inputs.
* <li>Stateful tasks are on their initial attempt executed based on co-location with inputs.
* <li>Repeated executions of stateful tasks try to co-locate the execution with its state.
* </ul>
*
* @return The preferred excution locations for the execution attempt.
*
* @see #getPreferredLocationsBasedOnState()
* @see #getPreferredLocationsBasedOnInputs()
*/
public Iterable<TaskManagerLocation> getPreferredLocations() {
Iterable<TaskManagerLocation> basedOnState = getPreferredLocationsBasedOnState();
return basedOnState != null ? basedOnState : getPreferredLocationsBasedOnInputs();
}
/**
* Gets the preferred location to execute the current task execution attempt, based on the state
* that the execution attempt will resume.
*
* @return A size-one iterable with the location preference, or null, if there is no
* location preference based on the state.
*/
public Iterable<TaskManagerLocation> getPreferredLocationsBasedOnState() {
TaskManagerLocation priorLocation;
if (currentExecution.getTaskStateHandles() != null && (priorLocation = getLatestPriorLocation()) != null) {
return Collections.singleton(priorLocation);
}
else {
return null;
}
}
/**
* Gets the location preferences of the vertex's current task execution, as determined by the locations
* of the predecessors from which it receives input data.
* If there are more than MAX_DISTINCT_LOCATIONS_TO_CONSIDER different locations of source data, this
* method returns {@code null} to indicate no location preference.
*
* @return The preferred locations based in input streams, or an empty iterable,
* if there is no input-based preference.
*/
public Iterable<TaskManagerLocation> getPreferredLocationsBasedOnInputs() {
// otherwise, base the preferred locations on the input connections
if (inputEdges == null) {
return Collections.emptySet();
}
else {
Set<TaskManagerLocation> locations = new HashSet<>();
Set<TaskManagerLocation> inputLocations = new HashSet<>();
// go over all inputs
for (int i = 0; i < inputEdges.length; i++) {
inputLocations.clear();
ExecutionEdge[] sources = inputEdges[i];
if (sources != null) {
// go over all input sources
for (int k = 0; k < sources.length; k++) {
// look-up assigned slot of input source
SimpleSlot sourceSlot = sources[k].getSource().getProducer().getCurrentAssignedResource();
if (sourceSlot != null) {
// add input location
inputLocations.add(sourceSlot.getTaskManagerLocation());
// inputs which have too many distinct sources are not considered
if (inputLocations.size() > MAX_DISTINCT_LOCATIONS_TO_CONSIDER) {
inputLocations.clear();
break;
}
}
}
}
// keep the locations of the input with the least preferred locations
if (locations.isEmpty() || // nothing assigned yet
(!inputLocations.isEmpty() && inputLocations.size() < locations.size())) {
// current input has fewer preferred locations
locations.clear();
locations.addAll(inputLocations);
}
}
return locations.isEmpty() ? Collections.<TaskManagerLocation>emptyList() : locations;
}
}
// --------------------------------------------------------------------------------------------
// Actions
// --------------------------------------------------------------------------------------------
public void resetForNewExecution() {
LOG.debug("Resetting execution vertex {} for new execution.", getSimpleName());
synchronized (priorExecutions) {
Execution execution = currentExecution;
ExecutionState state = execution.getState();
if (state == FINISHED || state == CANCELED || state == FAILED) {
priorExecutions.add(execution);
currentExecution = new Execution(
getExecutionGraph().getFutureExecutor(),
this,
execution.getAttemptNumber()+1,
System.currentTimeMillis(),
timeout);
CoLocationGroup grp = jobVertex.getCoLocationGroup();
if (grp != null) {
this.locationConstraint = grp.getLocationConstraint(subTaskIndex);
}
}
else {
throw new IllegalStateException("Cannot reset a vertex that is in state " + state);
}
}
}
public boolean scheduleForExecution(SlotProvider slotProvider, boolean queued) {
return this.currentExecution.scheduleForExecution(slotProvider, queued);
}
public void deployToSlot(SimpleSlot slot) throws JobException {
this.currentExecution.deployToSlot(slot);
}
public void cancel() {
this.currentExecution.cancel();
}
public void stop() {
this.currentExecution.stop();
}
public void fail(Throwable t) {
this.currentExecution.fail(t);
}
/**
* Schedules or updates the consumer tasks of the result partition with the given ID.
*/
void scheduleOrUpdateConsumers(ResultPartitionID partitionId) {
final Execution execution = currentExecution;
// Abort this request if there was a concurrent reset
if (!partitionId.getProducerId().equals(execution.getAttemptId())) {
return;
}
final IntermediateResultPartition partition = resultPartitions.get(partitionId.getPartitionId());
if (partition == null) {
throw new IllegalStateException("Unknown partition " + partitionId + ".");
}
if (partition.getIntermediateResult().getResultType().isPipelined()) {
// Schedule or update receivers of this partition
execution.scheduleOrUpdateConsumers(partition.getConsumers());
}
else {
throw new IllegalArgumentException("ScheduleOrUpdateConsumers msg is only valid for" +
"pipelined partitions.");
}
}
public void cachePartitionInfo(PartialInputChannelDeploymentDescriptor partitionInfo){
getCurrentExecutionAttempt().cachePartitionInfo(partitionInfo);
}
void sendPartitionInfos() {
currentExecution.sendPartitionInfos();
}
/**
* Returns all blocking result partitions whose receivers can be scheduled/updated.
*/
List<IntermediateResultPartition> finishAllBlockingPartitions() {
List<IntermediateResultPartition> finishedBlockingPartitions = null;
for (IntermediateResultPartition partition : resultPartitions.values()) {
if (partition.getResultType().isBlocking() && partition.markFinished()) {
if (finishedBlockingPartitions == null) {
finishedBlockingPartitions = new LinkedList<IntermediateResultPartition>();
}
finishedBlockingPartitions.add(partition);
}
}
if (finishedBlockingPartitions == null) {
return Collections.emptyList();
}
else {
return finishedBlockingPartitions;
}
}
// --------------------------------------------------------------------------------------------
// Notifications from the Execution Attempt
// --------------------------------------------------------------------------------------------
void executionFinished() {
jobVertex.vertexFinished(subTaskIndex);
}
void executionCanceled() {
jobVertex.vertexCancelled(subTaskIndex);
}
void executionFailed(Throwable t) {
jobVertex.vertexFailed(subTaskIndex, t);
}
// --------------------------------------------------------------------------------------------
// Miscellaneous
// --------------------------------------------------------------------------------------------
/**
* Simply forward this notification. This is for logs and event archivers.
*/
void notifyStateTransition(ExecutionAttemptID executionId, ExecutionState newState, Throwable error) {
getExecutionGraph().notifyExecutionChange(getJobvertexId(), subTaskIndex, executionId, newState, error);
}
/**
* Creates a task deployment descriptor to deploy a subtask to the given target slot.
*
* TODO: This should actually be in the EXECUTION
*/
TaskDeploymentDescriptor createDeploymentDescriptor(
ExecutionAttemptID executionId,
SimpleSlot targetSlot,
TaskStateHandles taskStateHandles,
int attemptNumber) throws ExecutionGraphException {
// Produced intermediate results
List<ResultPartitionDeploymentDescriptor> producedPartitions = new ArrayList<>(resultPartitions.size());
// Consumed intermediate results
List<InputGateDeploymentDescriptor> consumedPartitions = new ArrayList<>(inputEdges.length);
boolean lazyScheduling = getExecutionGraph().getScheduleMode().allowLazyDeployment();
for (IntermediateResultPartition partition : resultPartitions.values()) {
List<List<ExecutionEdge>> consumers = partition.getConsumers();
if (consumers.isEmpty()) {
//TODO this case only exists for test, currently there has to be exactly one consumer in real jobs!
producedPartitions.add(ResultPartitionDeploymentDescriptor.from(
partition,
KeyGroupRangeAssignment.UPPER_BOUND_MAX_PARALLELISM,
lazyScheduling));
} else {
Preconditions.checkState(1 == consumers.size(),
"Only one consumer supported in the current implementation! Found: " + consumers.size());
List<ExecutionEdge> consumer = consumers.get(0);
ExecutionJobVertex vertex = consumer.get(0).getTarget().getJobVertex();
int maxParallelism = vertex.getMaxParallelism();
producedPartitions.add(ResultPartitionDeploymentDescriptor.from(partition, maxParallelism, lazyScheduling));
}
}
for (ExecutionEdge[] edges : inputEdges) {
InputChannelDeploymentDescriptor[] partitions = InputChannelDeploymentDescriptor
.fromEdges(edges, targetSlot, lazyScheduling);
// If the produced partition has multiple consumers registered, we
// need to request the one matching our sub task index.
// TODO Refactor after removing the consumers from the intermediate result partitions
int numConsumerEdges = edges[0].getSource().getConsumers().get(0).size();
int queueToRequest = subTaskIndex % numConsumerEdges;
IntermediateDataSetID resultId = edges[0].getSource().getIntermediateResult().getId();
consumedPartitions.add(new InputGateDeploymentDescriptor(resultId, queueToRequest, partitions));
}
SerializedValue<JobInformation> serializedJobInformation = getExecutionGraph().getSerializedJobInformation();
SerializedValue<TaskInformation> serializedJobVertexInformation = null;
try {
serializedJobVertexInformation = jobVertex.getSerializedTaskInformation();
} catch (IOException e) {
throw new ExecutionGraphException(
"Could not create a serialized JobVertexInformation for " + jobVertex.getJobVertexId(), e);
}
return new TaskDeploymentDescriptor(
serializedJobInformation,
serializedJobVertexInformation,
executionId,
targetSlot.getAllocatedSlot().getSlotAllocationId(),
subTaskIndex,
attemptNumber,
targetSlot.getRoot().getSlotNumber(),
taskStateHandles,
producedPartitions,
consumedPartitions);
}
// --------------------------------------------------------------------------------------------
// Utilities
// --------------------------------------------------------------------------------------------
/**
* Creates a simple name representation in the style 'taskname (x/y)', where
* 'taskname' is the name as returned by {@link #getTaskName()}, 'x' is the parallel
* subtask index as returned by {@link #getParallelSubtaskIndex()}{@code + 1}, and 'y' is the total
* number of tasks, as returned by {@link #getTotalNumberOfParallelSubtasks()}.
*
* @return A simple name representation.
*/
public String getSimpleName() {
return taskNameWithSubtask;
}
@Override
public String toString() {
return getSimpleName();
}
@Override
public ArchivedExecutionVertex archive() {
return new ArchivedExecutionVertex(this);
}
}
|
923280185b6918747b8b9ca2e1b11c830c8eab60 | 366 | java | Java | app/src/main/java/com/faruksahin/twitterclone/searchModel.java | kodsa25/TwitterClone | f6cd285f64153f54c216e5494af3fe3b5f314767 | [
"Apache-2.0"
] | 4 | 2018-10-20T07:17:42.000Z | 2021-04-30T03:17:55.000Z | app/src/main/java/com/faruksahin/twitterclone/searchModel.java | kodsa25/TwitterClone | f6cd285f64153f54c216e5494af3fe3b5f314767 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/faruksahin/twitterclone/searchModel.java | kodsa25/TwitterClone | f6cd285f64153f54c216e5494af3fe3b5f314767 | [
"Apache-2.0"
] | 3 | 2018-10-20T07:17:45.000Z | 2020-01-03T13:26:13.000Z | 14.64 | 40 | 0.595628 | 996,240 | package com.faruksahin.twitterclone;
public class searchModel
{
private String mail,photo;
public String getMail() {
return mail;
}
public String getPhoto() {
return photo;
}
public void setMail(String mail) {
this.mail = mail;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
|
9232807eac9c2508f93bfef66871dffc44224712 | 15,651 | java | Java | msal/src/main/java/com/microsoft/identity/client/AccountAdapter.java | VansonLeung/microsoft-authentication-library-for-android | a01ededadfb422508a3bf9f844e1677043a95811 | [
"MIT"
] | 139 | 2017-05-02T17:03:36.000Z | 2022-03-18T22:28:14.000Z | msal/src/main/java/com/microsoft/identity/client/AccountAdapter.java | VansonLeung/microsoft-authentication-library-for-android | a01ededadfb422508a3bf9f844e1677043a95811 | [
"MIT"
] | 871 | 2017-05-01T19:52:47.000Z | 2022-03-31T11:34:52.000Z | msal/src/main/java/com/microsoft/identity/client/AccountAdapter.java | VansonLeung/microsoft-authentication-library-for-android | a01ededadfb422508a3bf9f844e1677043a95811 | [
"MIT"
] | 113 | 2017-06-05T23:38:05.000Z | 2022-03-31T16:44:59.000Z | 41.295515 | 113 | 0.609929 | 996,241 | // Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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 com.microsoft.identity.client;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.microsoft.identity.common.java.exception.ServiceException;
import com.microsoft.identity.common.java.cache.ICacheRecord;
import com.microsoft.identity.common.java.dto.AccountRecord;
import com.microsoft.identity.common.java.providers.oauth2.IDToken;
import com.microsoft.identity.common.java.providers.oauth2.OAuth2TokenCache;
import com.microsoft.identity.common.java.util.StringUtil;
import com.microsoft.identity.common.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class AccountAdapter {
private static final String TAG = AccountAdapter.class.getSimpleName();
/**
* Abstract class representing a filter for ICacheRecords.
*/
private interface CacheRecordFilter {
List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records);
}
private static class GuestAccountFilter implements CacheRecordFilter {
@Override
public List<ICacheRecord> filter(@NonNull List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
for (final ICacheRecord cacheRecord : records) {
final String acctHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
final String acctLocalAccountId = cacheRecord.getAccount().getLocalAccountId();
if (!acctHomeAccountId.contains(acctLocalAccountId)) {
result.add(cacheRecord);
}
}
return result;
}
}
/**
* A filter for ICacheRecords that filters out home or guest accounts, based on its
* constructor initialization.
*/
private static class HomeAccountFilter implements CacheRecordFilter {
@Override
public List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
for (final ICacheRecord cacheRecord : records) {
final String acctHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
final String acctLocalAccountId = cacheRecord.getAccount().getLocalAccountId();
if (acctHomeAccountId.contains(acctLocalAccountId)) {
result.add(cacheRecord);
}
}
return result;
}
}
/**
* A filter which finds guest accounts which have no corresponding home tenant account.
*/
private static final CacheRecordFilter guestAccountsWithNoHomeTenantAccountFilter = new CacheRecordFilter() {
private boolean hasNoCorrespondingHomeAccount(@NonNull final ICacheRecord guestRecord,
@NonNull final List<ICacheRecord> homeRecords) {
// Init our sought value
final String guestAccountHomeAccountId = guestRecord.getAccount().getHomeAccountId();
// Create a List of home_account_ids from the homeRecords...
final List<String> homeAccountIds = new ArrayList<String>() {{
for (final ICacheRecord cacheRecord : homeRecords) {
add(cacheRecord.getAccount().getHomeAccountId());
}
}};
return !homeAccountIds.contains(guestAccountHomeAccountId);
}
@Override
public List<ICacheRecord> filter(@NonNull final List<ICacheRecord> records) {
final List<ICacheRecord> result = new ArrayList<>();
// First, get the home accounts....
final List<ICacheRecord> homeRecords =
filterCacheRecords(
records,
new HomeAccountFilter()
);
// Then, get the guest accounts...
final List<ICacheRecord> guestRecords =
filterCacheRecords(
records,
new GuestAccountFilter()
);
// Iterate over the guest accounts and find those which have no associated home account
for (final ICacheRecord guestRecord : guestRecords) {
if (hasNoCorrespondingHomeAccount(guestRecord, homeRecords)) {
result.add(guestRecord);
}
}
return result;
}
};
/**
* For a supplied List of ICacheRecords, create each root IAccount based on the home
* account and then add child-nodes based on any authorized tenants.
*
* @param allCacheRecords
* @return
*/
@NonNull
static List<IAccount> adapt(@NonNull final List<ICacheRecord> allCacheRecords) {
// First, get all of the ICacheRecords for home accounts...
final List<ICacheRecord> homeCacheRecords = filterCacheRecords(
allCacheRecords,
new HomeAccountFilter()
);
// Then, get all of the guest accounts...
// Note that the guestCacheRecordsWithNoHomeAccount (see below) will be *removed* from this
// List.
final List<ICacheRecord> guestCacheRecords = filterCacheRecords(
allCacheRecords,
new GuestAccountFilter()
);
// Get the guest cache records which have no homeAccount
final List<ICacheRecord> guestCacheRecordsWithNoHomeAccount = filterCacheRecords(
allCacheRecords,
guestAccountsWithNoHomeTenantAccountFilter
);
// Remove the guest records that have no corresponding home account from the complete list of
// guest records...
guestCacheRecords.removeAll(guestCacheRecordsWithNoHomeAccount);
final List<IAccount> rootAccounts = createRootAccounts(homeCacheRecords);
appendChildren(rootAccounts, guestCacheRecords);
rootAccounts.addAll(
createIAccountsForGuestsNotSignedIntoHomeTenant(guestCacheRecordsWithNoHomeAccount)
);
return rootAccounts;
}
@NonNull
private static List<IAccount> createIAccountsForGuestsNotSignedIntoHomeTenant(
@NonNull final List<ICacheRecord> guestCacheRecords) {
// First, bucket the records by homeAccountId to create affinities
final Map<String, List<ICacheRecord>> bucketedRecords = new HashMap<>();
for (final ICacheRecord cacheRecord : guestCacheRecords) {
final String cacheRecordHomeAccountId = cacheRecord.getAccount().getHomeAccountId();
// Initialize the multi-map
if (null == bucketedRecords.get(cacheRecordHomeAccountId)) {
bucketedRecords.put(cacheRecordHomeAccountId, new ArrayList<ICacheRecord>());
}
// Add the record to the multi-map
bucketedRecords.get(cacheRecordHomeAccountId).add(cacheRecord);
}
// Declare our result holder...
final List<IAccount> result = new ArrayList<>();
// Now that all of the tokens have been bucketed by an account affinity
// box those into a 'rootless' IAccount
for (final Map.Entry<String, List<ICacheRecord>> entry : bucketedRecords.entrySet()) {
// Create our empty root...
final MultiTenantAccount emptyRoot = new MultiTenantAccount(
null,
null // home tenant IdToken.... doesn't exist!
);
// Set the home oid & home tid of the root, even though we don't have the IdToken...
// hooray for client_info
emptyRoot.setId(StringUtil.getTenantInfo(entry.getKey()).getKey());
emptyRoot.setTenantId(StringUtil.getTenantInfo(entry.getKey()).getValue());
emptyRoot.setEnvironment( // Look ahead into our CacheRecords to determine the environment
entry
.getValue()
.get(0)
.getAccount()
.getEnvironment()
);
// Create the Map of TenantProfiles to set...
final Map<String, ITenantProfile> tenantProfileMap = new HashMap<>();
for (final ICacheRecord cacheRecord : entry.getValue()) {
final String tenantId = cacheRecord.getAccount().getRealm();
final TenantProfile profile = new TenantProfile(
// Intentionally do NOT supply the client info here.
// If client info is present, getId() will return the home tenant OID
// instead of the OID from the guest tenant.
null,
getIdToken(cacheRecord)
);
tenantProfileMap.put(tenantId, profile);
}
emptyRoot.setTenantProfiles(tenantProfileMap);
result.add(emptyRoot);
}
return result;
}
private static void appendChildren(@NonNull final List<IAccount> rootAccounts,
@NonNull final List<ICacheRecord> guestCacheRecords) {
// Iterate over the roots, adding the children as we go...
for (final IAccount account : rootAccounts) {
// Iterate over the potential children, adding them if they match
final Map<String, ITenantProfile> tenantProfiles = new HashMap<>();
for (final ICacheRecord guestRecord : guestCacheRecords) {
final String guestRecordHomeAccountId = guestRecord.getAccount().getHomeAccountId();
if (guestRecordHomeAccountId.contains(account.getId())) {
final TenantProfile profile = new TenantProfile(
// Intentionally do NOT supply the client info here.
// If client info is present, getId() will return the home tenant OID
// instead of the OID from the guest tenant.
null,
getIdToken(guestRecord)
);
profile.setEnvironment(guestRecord.getAccount().getEnvironment());
tenantProfiles.put(guestRecord.getAccount().getRealm(), profile);
}
}
// Cast the root account for initialization...
final MultiTenantAccount multiTenantAccount = (MultiTenantAccount) account;
multiTenantAccount.setTenantProfiles(tenantProfiles);
}
}
@NonNull
private static List<IAccount> createRootAccounts(
@NonNull final List<ICacheRecord> homeCacheRecords) {
final List<IAccount> result = new ArrayList<>();
for (ICacheRecord homeCacheRecord : homeCacheRecords) {
// Each IAccount will be initialized as a MultiTenantAccount whether it really is or not...
// This allows us to cast the results however the caller sees fit...
final IAccount rootAccount;
rootAccount = new MultiTenantAccount(
// Because this is a home account, we'll supply the client info
// the uid value is the "id" of the account.
// For B2C, this value will contain the policy name appended to the OID.
homeCacheRecord.getAccount().getClientInfo(),
getIdToken(homeCacheRecord)
);
// Set the tenant_id
((MultiTenantAccount) rootAccount).setTenantId(
StringUtil.getTenantInfo(
homeCacheRecord
.getAccount()
.getHomeAccountId()
).getValue()
);
// Set the environment...
((MultiTenantAccount) rootAccount).setEnvironment(
homeCacheRecord
.getAccount()
.getEnvironment()
);
result.add(rootAccount);
}
return result;
}
@Nullable
private static IDToken getIdToken(@NonNull final ICacheRecord cacheRecord) {
final String rawIdToken;
if (null != cacheRecord.getIdToken()) {
rawIdToken = cacheRecord.getIdToken().getSecret();
} else if (null != cacheRecord.getV1IdToken()) {
rawIdToken = cacheRecord.getV1IdToken().getSecret();
} else {
// We have no id_token for this account
return null;
}
try {
return new IDToken(rawIdToken);
} catch (ServiceException e) {
// This should never happen - the IDToken was verified when it was originally
// returned from the service and saved.
throw new IllegalStateException("Failed to restore IdToken");
}
}
/**
* Filters ICacheRecords based on the criteria specified by the {@link CacheRecordFilter}.
* Results may be empty, but never null.
*
* @param allCacheRecords The ICacheRecords to inspect.
* @param filter The CacheRecordFilter to consult.
* @return A List of ICacheRecords matching the supplied filter criteria.
*/
@NonNull
private static List<ICacheRecord> filterCacheRecords(
@NonNull final List<ICacheRecord> allCacheRecords,
@NonNull final CacheRecordFilter filter) {
return filter.filter(allCacheRecords);
}
@Nullable
static AccountRecord getAccountInternal(@NonNull final String clientId,
@NonNull OAuth2TokenCache oAuth2TokenCache,
@NonNull final String homeAccountIdentifier,
@Nullable final String realm) {
final AccountRecord accountToReturn;
if (!StringUtil.isNullOrEmpty(homeAccountIdentifier)) {
accountToReturn = oAuth2TokenCache.getAccount(
null, // * wildcard
clientId,
homeAccountIdentifier,
realm
);
} else {
Logger.warn(TAG, "homeAccountIdentifier was null or empty -- invalid criteria");
accountToReturn = null;
}
return accountToReturn;
}
}
|
9232807f97527cf13101e8448346706a80d14036 | 3,878 | java | Java | src/main/java/org/mycore/xml/alto/v4/SPType.java | Mewel/abbyy-to-alto | 937a06104505c7cf3fbe5e72c45a75eef7737518 | [
"MIT"
] | 7 | 2016-06-01T15:39:42.000Z | 2019-10-21T13:27:09.000Z | src/main/java/org/mycore/xml/alto/v4/SPType.java | Mewel/abbyy-to-alto | 937a06104505c7cf3fbe5e72c45a75eef7737518 | [
"MIT"
] | 6 | 2017-02-08T02:49:36.000Z | 2019-10-19T23:50:40.000Z | src/main/java/org/mycore/xml/alto/v4/SPType.java | Mewel/abbyy-to-alto | 937a06104505c7cf3fbe5e72c45a75eef7737518 | [
"MIT"
] | 3 | 2017-07-20T05:29:08.000Z | 2019-10-15T20:43:50.000Z | 22.287356 | 95 | 0.550026 | 996,242 |
package org.mycore.xml.alto.v4;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* A white space.
*
* <p>Java class for SPType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SPType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="ID" type="{http://www.loc.gov/standards/alto/ns-v4#}SPTypeID" />
* <attribute name="HEIGHT" type="{http://www.w3.org/2001/XMLSchema}float" />
* <attribute name="WIDTH" type="{http://www.w3.org/2001/XMLSchema}float" />
* <attribute name="HPOS" type="{http://www.w3.org/2001/XMLSchema}float" />
* <attribute name="VPOS" type="{http://www.w3.org/2001/XMLSchema}float" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SPType")
public class SPType {
@XmlAttribute(name = "ID")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
@XmlAttribute(name = "HEIGHT")
protected Float height;
@XmlAttribute(name = "WIDTH")
protected Float width;
@XmlAttribute(name = "HPOS")
protected Float hpos;
@XmlAttribute(name = "VPOS")
protected Float vpos;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* Gets the value of the height property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getHEIGHT() {
return height;
}
/**
* Sets the value of the height property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setHEIGHT(Float value) {
this.height = value;
}
/**
* Gets the value of the width property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getWIDTH() {
return width;
}
/**
* Sets the value of the width property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setWIDTH(Float value) {
this.width = value;
}
/**
* Gets the value of the hpos property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getHPOS() {
return hpos;
}
/**
* Sets the value of the hpos property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setHPOS(Float value) {
this.hpos = value;
}
/**
* Gets the value of the vpos property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getVPOS() {
return vpos;
}
/**
* Sets the value of the vpos property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setVPOS(Float value) {
this.vpos = value;
}
}
|
9232828354b3e5c864de116e87863c0584604360 | 9,320 | java | Java | src/de/topocare/topocareXiota/iotaMachineWallet/tangleTransactions/TangleTransaction.java | topocare/iota-pay-on-production | 93f7f44f3cf4b51a72daaee1d7cc23cfff42c1d1 | [
"Apache-2.0"
] | null | null | null | src/de/topocare/topocareXiota/iotaMachineWallet/tangleTransactions/TangleTransaction.java | topocare/iota-pay-on-production | 93f7f44f3cf4b51a72daaee1d7cc23cfff42c1d1 | [
"Apache-2.0"
] | null | null | null | src/de/topocare/topocareXiota/iotaMachineWallet/tangleTransactions/TangleTransaction.java | topocare/iota-pay-on-production | 93f7f44f3cf4b51a72daaee1d7cc23cfff42c1d1 | [
"Apache-2.0"
] | null | null | null | 31.808874 | 198 | 0.720923 | 996,243 | package de.topocare.topocareXiota.iotaMachineWallet.tangleTransactions;
import static de.topocare.topocareXiota.iotaMachineWallet.IotaConfig.*;
import java.time.*;
import java.util.*;
import de.topocare.topocareXiota.iotaMachineWallet.address.IotaAddress;
import de.topocare.topocareXiota.iotaMachineWallet.poolTransactions.PoolTransactionInput;
import de.topocare.topocareXiota.iotaMachineWallet.poolTransactions.PoolTransactionTransfer;
import jota.dto.response.SendTransferResponse;
import jota.error.ArgumentException;
import jota.model.*;
/**
* Abstract core of an TangleTransaction (Transaction-Bundle on the Iota-tangle).
* <p>
* Each TangleTransaction-Object will be used at three different points, by different threads:<br>
* external thread: <br>
* - just constructor with required data, should not block the thread for long <br>
* ExecutionPool of the Transaction-Manager: <br>
* - collect addresses and balances (as defined by specific sub-class) <br>
* - attach the transaction-bundle to the IOTA-tangle, including proof of work <br>
* IotaLoopTask: <br>
* - checkTransaction() will be called to validate if transaction has been confirmed or needs to be promoted/reattached after a a specified time <br>
* - whenDone() if something else is needed after confirmation
* <p>
*
* @author Stefan Kuenne [info@topocare.de]
*/
public abstract class TangleTransaction implements Runnable {
public TransactionManager transactionManager;
public TangleTransaction(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* Determines what the run() method does next.
*/
private NextRun nextrun = NextRun.newAttach;
// dataForTransaction
/**
* List of PoolTransactionInput Objects, contains the PoolTransactions of all the "IOTA-Input", providing the funding. To be filled in collectAddresses.
*/
List<PoolTransactionInput> inputs = new ArrayList<PoolTransactionInput>();
/**
* List of PoolTransactionTransfer Objects, contains the PoolTransactions of all the "IOTA-Transfer", providing the target-addresses where the funding goes. To be filled in collectAddresses.
*/
List<PoolTransactionTransfer> outputs = new ArrayList<PoolTransactionTransfer>();
/**
* If IOTA-Transactions need specific messages they can be set here (during collectAddresses()).
*/
Map<PoolTransactionTransfer, String> message = new HashMap<PoolTransactionTransfer, String>();
/**
* If IOTA-Transactions need specific tags they can be set here (during collectAddresses()).
*/
Map<PoolTransactionTransfer, String> tag = new HashMap<PoolTransactionTransfer, String>();
//data for confirmation, promote and reattach
SendTransferResponse sendTransferResponse;
IotaAddress refForConfirmation;
long refValue;
LocalDateTime attachTime_latest;
/**
* Collects all the needed data for a transaction bundle.
* <p>
* Required data is gained by using take- and give-methods of pools.
* <P>
* a non-abstract child of this class needs to fill: <br>
* List<PoolTransactionInput> inputs <br>
* List<PoolTransactionTransfer> outputs <br>
* Optional:
* Map<PoolTransactionTransfer, String> message <br>
* Map<PoolTransactionTransfer, String> tag <br>
*/
abstract void collectAddresses();
/**
* If after the confirmation of the bundle something special needs to be done, it goes here. Example: TangleTransactionPay
*/
abstract void whenDone();
/**
* normally starts createTransactionsAndSend(), but also used for promotion or reattachment when needed.
*/
@Override
public void run() {
if (nextrun == NextRun.newAttach)
createTransactionsAndSend();
else if (nextrun == NextRun.promoteOrReattach)
promoteOrReattach();
else {
Error e = new Error("TangeTransaction.run without defined nextrun-state");
e.printStackTrace();
}
nextrun = NextRun.undefined;
}
// Transaction-Monitor-Functionality
boolean isConfirmed = false;
/**
* Attaches the transaction-bundles to the Iota-tangle, build from the data collected in collectAddresses()
*/
private void createTransactionsAndSend() {
// register as pre-pow
// now in Transaction Manager
collectAddresses();
// prepare attach
// get Input
List<Input> inputAPI = new ArrayList<Input>();
for (int pt = 0; pt < inputs.size(); pt++)
inputAPI.addAll(inputs.get(pt).getAsJotaInputs());
// get Transfer
List<Transfer> outputAPI = new ArrayList<Transfer>();
for (int pt = 0; pt < outputs.size(); pt++)
outputAPI.addAll(outputs.get(pt).getAsJotaTransfer(message.get(outputs.get(pt)), tag.get(outputs.get(pt))));
// get managed address for confirmation
// first tries inputs
for (int i = 0; i < inputs.size(); i++) {
refForConfirmation = inputs.get(i).getManagedAddress();
refValue = 0;
if (refForConfirmation != null)
break;
}
if (refForConfirmation == null) {
for (int i = 0; i < outputs.size(); i++) {
refForConfirmation = outputs.get(i).getManagedAddress();
refValue = refForConfirmation.getBalance();
if (refForConfirmation != null)
break;
}
}
// TODO what if still no address found?!
// attach
synchronized (transactionManager.powLock) {
transactionManager.transactionCounterPreServer.decrement();
transactionManager.transactionCounterAtServer.increment();
try {
if (!inputAPI.isEmpty() && !outputAPI.isEmpty()) {
int depthLocal = depth;
boolean done = false;
// attach, retries for "random" "reference transaction is too old"-error
while (!done && depthLocal <= maxDepth) {
try {
sendTransferResponse = api.sendTransfer(seed, security, depthLocal, minWeightMagnitude,
outputAPI, inputAPI, null, false, false, null);
boolean allSuccessful = true;
Boolean successfully[] = sendTransferResponse.getSuccessfully();
if (successfully != null)
for (int i = 0; i < successfully.length; i++)
if (!successfully[i]) {
allSuccessful = false;
break;
}
if (!allSuccessful)
throw new Exception("Transaction not successful");
done = true;
attachTime_latest = LocalDateTime.now();
} catch (ArgumentException e) {
System.err.println("Transaction failed with depth:" + depthLocal);
if (depthLocal == maxDepth) // lastRetry
{
e.printStackTrace();
}
}
depthLocal++;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
transactionManager.transactionCounterAtServer.decrement();
}
}
// register Expected values
transactionManager.confirmOnTangle.registerForConfirmation(refForConfirmation, refValue);
transactionManager.transactionsAtConfirmation.add(this);
transactionManager.transsactionCounterAtConfirmation.increment();
}
/**
* checks if the transaction can be promoted or must be reattached
*/
private void promoteOrReattach() {
synchronized (transactionManager.powLock) {
transactionManager.transactionCounterPreServer.decrement();
transactionManager.transactionCounterAtServer.increment();
try {
Bundle bundle = new Bundle(sendTransferResponse.getTransactions(),
sendTransferResponse.getTransactions().size());
String tail = bundle.getTransactions().get(bundle.getLength() - 1).getHash();
if (api.checkConsistency(new String[] { tail }).getState()) {
api.promoteTransaction(tail, depth, minWeightMagnitude, bundle);
transactionManager.promotions.incrementAndGet();
} else {
api.replayBundle(tail, depth, minWeightMagnitude, null);
transactionManager.reattachments.incrementAndGet();
}
attachTime_latest = LocalDateTime.now();
} catch (Exception e) {
e.printStackTrace();
} finally {
transactionManager.transactionCounterAtServer.decrement();
}
}
transactionManager.transactionsAtConfirmation.add(this);
transactionManager.transsactionCounterAtConfirmation.increment();
}
/**
* Checks if the transaction-bundle was confirmed on the tangle.
* If confirmed, then all used PoolTransactions are committed.
*
* If false and a specific time has passed since attachment, then promote/reattach.
*
*
* @return If the TangleTransaction can be removed from the List of transactions to be confirmed. This happens if it is confirmed or if it must be go back to the ThreadPool for a new Proof of work.
*/
public boolean checkTransaction() {
if (!isConfirmed) {
//only stays true if all checks are positive
Boolean nothingUnconfirmed = true;
// check ref-address
nothingUnconfirmed = transactionManager.confirmOnTangle.isConfirmed(refForConfirmation);
if (nothingUnconfirmed) {
inputs.forEach(e -> e.commit());
outputs.forEach(e -> e.commit());
isConfirmed = true;
whenDone();
}
}
if (!isConfirmed)
if (attachTime_latest.isBefore(LocalDateTime.now().minusMinutes(promoteOrReattachAfterMinutes))) {
System.out.println("promoteOrReattach needed...");
nextrun = NextRun.promoteOrReattach;
transactionManager.submitIgnoreRefundingLock(this);
return true;
}
return isConfirmed;
}
/**
* Determines what the run() method does next. See: nextRun
*/
private enum NextRun {
undefined, newAttach, promoteOrReattach
}
}
|
92328293ae99013d442971f99ab40f31bc1b430d | 572 | java | Java | src/controller/ModeToggleController.java | PaulBryden/Project-Pinball | 4563a0a07f6aceaabd5cd3766da1f7c734ffcc30 | [
"MIT"
] | 1 | 2019-10-13T21:32:36.000Z | 2019-10-13T21:32:36.000Z | src/controller/ModeToggleController.java | PaulBryden/Project-Pinball | 4563a0a07f6aceaabd5cd3766da1f7c734ffcc30 | [
"MIT"
] | null | null | null | src/controller/ModeToggleController.java | PaulBryden/Project-Pinball | 4563a0a07f6aceaabd5cd3766da1f7c734ffcc30 | [
"MIT"
] | null | null | null | 22.88 | 68 | 0.671329 | 996,244 | package controller;
import view.Board;
import view.MainWindow;
import static view.CUR_GIZMO.NONE;
import static view.STATE.BUILD;
import static view.STATE.RUN;
public class ModeToggleController {
private MainWindow mainWindow;
ModeToggleController(MainWindow mainWindow){
this.mainWindow = mainWindow;
}
public void start() {
Board board = mainWindow.getBoard();
board.setState(board.getState().equals(RUN) ? BUILD : RUN);
board.setSelectedGizmo(NONE);
mainWindow.toggleView();
}
}
|
92328319dbea038e3b7f28ae8c5254b072cc10d7 | 549 | java | Java | src/softuni/advanced/iterators_comparators/StrategyPattern/ComparatorByName.java | NikolayDobrinski/SoftUni | eda8d838db1aaa9e8119ffa2015fe6121c0ee49a | [
"Apache-2.0"
] | null | null | null | src/softuni/advanced/iterators_comparators/StrategyPattern/ComparatorByName.java | NikolayDobrinski/SoftUni | eda8d838db1aaa9e8119ffa2015fe6121c0ee49a | [
"Apache-2.0"
] | null | null | null | src/softuni/advanced/iterators_comparators/StrategyPattern/ComparatorByName.java | NikolayDobrinski/SoftUni | eda8d838db1aaa9e8119ffa2015fe6121c0ee49a | [
"Apache-2.0"
] | null | null | null | 30.5 | 70 | 0.64663 | 996,245 | package softuni.advanced.iterators_comparators.StrategyPattern;
import java.util.Comparator;
public class ComparatorByName implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
int result = p1.getName().length() - p2.getName().length();
if (result == 0) {
char p1FirstLetter = p1.getName().toLowerCase().charAt(0);
char p2FirstLetter = p2.getName().toLowerCase().charAt(0);
result = p1FirstLetter - p2FirstLetter;
}
return result;
}
}
|
923283bd14fa90252c2e7c233e46cf49c136baf7 | 14,856 | java | Java | app/src/main/java/com/matrix/autoreply/ui/fragment/MainFragment.java | snandans/Auto-Reply-Android | 0677f92f488f9d0b725187166dc4ba9ea6d150ca | [
"MIT"
] | null | null | null | app/src/main/java/com/matrix/autoreply/ui/fragment/MainFragment.java | snandans/Auto-Reply-Android | 0677f92f488f9d0b725187166dc4ba9ea6d150ca | [
"MIT"
] | null | null | null | app/src/main/java/com/matrix/autoreply/ui/fragment/MainFragment.java | snandans/Auto-Reply-Android | 0677f92f488f9d0b725187166dc4ba9ea6d150ca | [
"MIT"
] | null | null | null | 43.186047 | 147 | 0.693525 | 996,246 | package com.matrix.autoreply.ui.fragment;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.matrix.autoreply.services.ForegroundNotificationService;
import com.matrix.autoreply.R;
import com.matrix.autoreply.ui.activity.customreplyeditor.CustomReplyEditorActivity;
import com.matrix.autoreply.model.App;
import com.matrix.autoreply.model.CustomRepliesData;
import com.matrix.autoreply.model.preferences.PreferencesManager;
import com.matrix.autoreply.model.utils.Constants;
import com.matrix.autoreply.model.utils.CustomDialog;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS;
import static com.matrix.autoreply.model.utils.Constants.MAX_DAYS;
import static com.matrix.autoreply.model.utils.Constants.MIN_DAYS;
public class MainFragment extends Fragment {
private static final int REQ_NOTIFICATION_LISTENER = 100;
private final int MINUTE_FACTOR = 60;
CardView autoReplyTextPreviewCard, timePickerCard;
TextView autoReplyTextPreview, timeSelectedTextPreview, timePickerSubTitleTextPreview;
CustomRepliesData customRepliesData;
String autoReplyTextPlaceholder;
SwitchMaterial mainAutoReplySwitch, groupReplySwitch;
CardView supportedAppsCard;
private PreferencesManager preferencesManager;
private int days = 0;
private ImageView imgMinus, imgPlus;
private LinearLayout supportedAppsLayout;
private List<MaterialCheckBox> supportedAppsCheckboxes = new ArrayList<>();
private List<View> supportedAppsDummyViews = new ArrayList<>();
private Activity mActivity;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
mActivity = getActivity();
customRepliesData = CustomRepliesData.getInstance(mActivity);
preferencesManager = PreferencesManager.getPreferencesInstance(mActivity);
// Assign Views
mainAutoReplySwitch = view.findViewById(R.id.mainAutoReplySwitch);
groupReplySwitch = view.findViewById(R.id.groupReplySwitch);
autoReplyTextPreviewCard = view.findViewById(R.id.mainAutoReplyTextCardView);
autoReplyTextPreview = view.findViewById(R.id.textView4);
supportedAppsLayout = view.findViewById(R.id.supportedPlatformsLayout);
supportedAppsCard = view.findViewById(R.id.supportedAppsSelectorCardView);
autoReplyTextPlaceholder = getResources().getString(R.string.mainAutoReplyTextPlaceholder);
timePickerCard = view.findViewById(R.id.replyFrequencyTimePickerCardView);
timePickerSubTitleTextPreview = view.findViewById(R.id.timePickerSubTitle);
timeSelectedTextPreview = view.findViewById(R.id.timeSelectedText);
imgMinus = view.findViewById(R.id.imgMinus);
imgPlus = view.findViewById(R.id.imgPlus);
autoReplyTextPreviewCard.setOnClickListener(this::openCustomReplyEditorActivity);
autoReplyTextPreview.setText(customRepliesData.getTextToSendOrElse(autoReplyTextPlaceholder));
// Enable group chat switch only if main switch id ON
groupReplySwitch.setEnabled(mainAutoReplySwitch.isChecked());
mainAutoReplySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(isChecked && !isListenerEnabled(mActivity, ForegroundNotificationService.class)){
// launchNotificationAccessSettings();
showPermissionsDialog();
}else {
preferencesManager.setServicePref(isChecked);
enableService(isChecked);
mainAutoReplySwitch.setText(
isChecked
? R.string.mainAutoReplySwitchOnLabel
: R.string.mainAutoReplySwitchOffLabel
);
setSwitchState();
// Enable group chat switch only if main switch id ON
groupReplySwitch.setEnabled(isChecked);
}
});
groupReplySwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
// Ignore if this is not triggered by user action but just UI update in onResume() #62
if (preferencesManager.isGroupReplyEnabled() == isChecked) { return;}
if(isChecked){
Toast.makeText(mActivity, R.string.group_reply_on_info_message, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mActivity, R.string.group_reply_off_info_message, Toast.LENGTH_SHORT).show();
}
preferencesManager.setGroupReplyPref(isChecked);
});
imgMinus.setOnClickListener(v -> {
if(days > MIN_DAYS){
days--;
saveNumDays();
}
});
imgPlus.setOnClickListener(v -> {
if(days < MAX_DAYS){
days++;
saveNumDays();
}
});
setNumDays();
createSupportedAppCheckboxes();
return view;
}
private void enableOrDisableEnabledAppsCheckboxes(boolean enabled){
for (MaterialCheckBox checkbox: supportedAppsCheckboxes) {
checkbox.setEnabled(enabled);
}
for (View dummyView: supportedAppsDummyViews) {
dummyView.setVisibility(enabled ? View.GONE : View.VISIBLE);
}
}
private void createSupportedAppCheckboxes() {
supportedAppsLayout.removeAllViews();
//inflate the views
LayoutInflater inflater = getLayoutInflater();
for (App supportedApp: Constants.SUPPORTED_APPS) {
View view = inflater.inflate(R.layout.enable_app_main_layout, null);
MaterialCheckBox checkBox = view.findViewById(R.id.platform_checkbox);
checkBox.setText(supportedApp.getName());
checkBox.setTag(supportedApp);
checkBox.setChecked(preferencesManager.isAppEnabled(supportedApp));
checkBox.setEnabled(mainAutoReplySwitch.isChecked());
checkBox.setOnCheckedChangeListener(supportedAppsCheckboxListener);
supportedAppsCheckboxes.add(checkBox);
View platformDummyView = view.findViewById(R.id.platform_dummy_view);
if(mainAutoReplySwitch.isChecked()){
platformDummyView.setVisibility(View.GONE);
}
platformDummyView.setOnClickListener(v -> {
if(!mainAutoReplySwitch.isChecked()){
Toast.makeText(mActivity, getResources().getString(R.string.enable_auto_reply_switch_msg), Toast.LENGTH_SHORT).show();
}
});
supportedAppsDummyViews.add(platformDummyView);
supportedAppsLayout.addView(view);
}
}
private CompoundButton.OnCheckedChangeListener supportedAppsCheckboxListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked && preferencesManager.getEnabledApps().size() <= 1) { // Keep at-least one app selected
Toast.makeText(mActivity, getResources().getString(R.string.error_atleast_single_app_must_be_selected), Toast.LENGTH_SHORT).show();
buttonView.setChecked(true);
} else {
preferencesManager.saveEnabledApps((App) buttonView.getTag(), isChecked);
}
}
};
private void saveNumDays(){
preferencesManager.setAutoReplyDelay(days * 24 * 60 * 60 * 1000);//Save in Milliseconds
setNumDays();
}
private void setNumDays(){
long timeDelay = (preferencesManager.getAutoReplyDelay()/(60 * 1000));//convert back to minutes
days = (int)timeDelay/(60 * 24);//convert back to days
if(days == 0){
timeSelectedTextPreview.setText("•");
timePickerSubTitleTextPreview.setText(R.string.time_picker_sub_title_default);
}else{
timeSelectedTextPreview.setText("" + days);
timePickerSubTitleTextPreview.setText(String.format(getResources().getString(R.string.time_picker_sub_title), days));
}
}
@Override
public void onResume() {
super.onResume();
//If user directly goes to Settings and removes notifications permission
//when app is launched check for permission and set appropriate app state
if(!isListenerEnabled(mActivity, ForegroundNotificationService.class)){
preferencesManager.setServicePref(false);
}
if(!preferencesManager.isServiceEnabled()){
enableService(false);
}
setSwitchState();
// set group chat switch state
groupReplySwitch.setChecked(preferencesManager.isGroupReplyEnabled());
// Set user auto reply text
autoReplyTextPreview.setText(customRepliesData.getTextToSendOrElse(autoReplyTextPlaceholder));
}
//REF: https://stackoverflow.com/questions/37539949/detect-if-an-app-is-installed-from-play-store
public static boolean isAppInstalledFromStore(Context context) {
// A list with valid installers package name
List<String> validInstallers = new ArrayList<>(Arrays.asList("com.android.vending", "com.google.android.feedback"));
// The package name of the app that has installed your app
final String installer = context.getPackageManager().getInstallerPackageName(context.getPackageName());
// true if your app has been downloaded from Play Store
return installer != null && validInstallers.contains(installer);
}
private void setSwitchState(){
mainAutoReplySwitch.setChecked(preferencesManager.isServiceEnabled());
groupReplySwitch.setEnabled(preferencesManager.isServiceEnabled());
enableOrDisableEnabledAppsCheckboxes(mainAutoReplySwitch.isChecked());
}
//https://stackoverflow.com/questions/20141727/check-if-user-has-granted-notificationlistener-access-to-my-app/28160115
//TODO: Use in UI to verify if it needs enabling or restarting
public boolean isListenerEnabled(Context context, Class notificationListenerCls) {
ComponentName cn = new ComponentName(context, notificationListenerCls);
String flat = Settings.Secure.getString(context.getContentResolver(), "enabled_notification_listeners");
return flat != null && flat.contains(cn.flattenToString());
}
private void openCustomReplyEditorActivity(View v) {
Intent intent = new Intent(mActivity, CustomReplyEditorActivity.class);
startActivity(intent);
}
private void showPermissionsDialog(){
CustomDialog customDialog = new CustomDialog(mActivity);
Bundle bundle = new Bundle();
bundle.putString(Constants.PERMISSION_DIALOG_TITLE, getString(R.string.permission_dialog_title));
bundle.putString(Constants.PERMISSION_DIALOG_MSG, getString(R.string.permission_dialog_msg));
customDialog.showDialog(bundle, null, (dialog, which) -> {
if(which == -2){
//Decline
showPermissionDeniedDialog();
}else{
//Accept
launchNotificationAccessSettings();
}
});
}
private void showPermissionDeniedDialog(){
CustomDialog customDialog = new CustomDialog(mActivity);
Bundle bundle = new Bundle();
bundle.putString(Constants.PERMISSION_DIALOG_DENIED_TITLE, getString(R.string.permission_dialog_denied_title));
bundle.putString(Constants.PERMISSION_DIALOG_DENIED_MSG, getString(R.string.permission_dialog_denied_msg));
bundle.putBoolean(Constants.PERMISSION_DIALOG_DENIED, true);
customDialog.showDialog(bundle, null, (dialog, which) -> {
if(which == -2){
//Decline
setSwitchState();
}else{
//Accept
launchNotificationAccessSettings();
}
});
}
public void launchNotificationAccessSettings() {
enableService(true);//we need to enable the service for it so show in settings
final String NOTIFICATION_LISTENER_SETTINGS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
NOTIFICATION_LISTENER_SETTINGS = ACTION_NOTIFICATION_LISTENER_SETTINGS;
}else{
NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";
}
Intent i = new Intent(NOTIFICATION_LISTENER_SETTINGS);
startActivityForResult(i, REQ_NOTIFICATION_LISTENER);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_NOTIFICATION_LISTENER){
if(isListenerEnabled(mActivity, ForegroundNotificationService.class)){
Toast.makeText(mActivity, "Permission Granted", Toast.LENGTH_LONG).show();
preferencesManager.setServicePref(true);
setSwitchState();
} else {
Toast.makeText(mActivity, "Permission Denied", Toast.LENGTH_LONG).show();
preferencesManager.setServicePref(false);
setSwitchState();
}
}
}
private void enableService(boolean enable) {
PackageManager packageManager = mActivity.getPackageManager();
ComponentName componentName = new ComponentName(mActivity, ForegroundNotificationService.class);
int settingCode = enable
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
// enable dummyActivity (as it is disabled in the manifest.xml)
packageManager.setComponentEnabledSetting(componentName, settingCode, PackageManager.DONT_KILL_APP);
}
}
|
9232846097b039421c05899e8919cbd7680fce56 | 4,049 | java | Java | aws-java-sdk-applicationautoscaling/src/main/java/com/amazonaws/services/applicationautoscaling/model/transform/PutScalingPolicyRequestMarshaller.java | erbrito/aws-java-sdk | 853b7e82d708465aca43c6013ab1221ce4d50852 | [
"Apache-2.0"
] | 1 | 2019-02-08T15:23:16.000Z | 2019-02-08T15:23:16.000Z | aws-java-sdk-applicationautoscaling/src/main/java/com/amazonaws/services/applicationautoscaling/model/transform/PutScalingPolicyRequestMarshaller.java | erbrito/aws-java-sdk | 853b7e82d708465aca43c6013ab1221ce4d50852 | [
"Apache-2.0"
] | 1 | 2020-09-21T09:46:45.000Z | 2020-09-21T09:46:45.000Z | aws-java-sdk-applicationautoscaling/src/main/java/com/amazonaws/services/applicationautoscaling/model/transform/PutScalingPolicyRequestMarshaller.java | erbrito/aws-java-sdk | 853b7e82d708465aca43c6013ab1221ce4d50852 | [
"Apache-2.0"
] | null | null | null | 44.01087 | 160 | 0.720672 | 996,247 | /*
* Copyright 2012-2017 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.applicationautoscaling.model.transform;
import java.io.ByteArrayInputStream;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.applicationautoscaling.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.json.*;
/**
* PutScalingPolicyRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PutScalingPolicyRequestMarshaller implements Marshaller<Request<PutScalingPolicyRequest>, PutScalingPolicyRequest> {
private final SdkJsonMarshallerFactory protocolFactory;
public PutScalingPolicyRequestMarshaller(SdkJsonMarshallerFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<PutScalingPolicyRequest> marshall(PutScalingPolicyRequest putScalingPolicyRequest) {
if (putScalingPolicyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<PutScalingPolicyRequest> request = new DefaultRequest<PutScalingPolicyRequest>(putScalingPolicyRequest, "AWSApplicationAutoScaling");
request.addHeader("X-Amz-Target", "AnyScaleFrontendService.PutScalingPolicy");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = protocolFactory.createGenerator();
jsonGenerator.writeStartObject();
if (putScalingPolicyRequest.getPolicyName() != null) {
jsonGenerator.writeFieldName("PolicyName").writeValue(putScalingPolicyRequest.getPolicyName());
}
if (putScalingPolicyRequest.getServiceNamespace() != null) {
jsonGenerator.writeFieldName("ServiceNamespace").writeValue(putScalingPolicyRequest.getServiceNamespace());
}
if (putScalingPolicyRequest.getResourceId() != null) {
jsonGenerator.writeFieldName("ResourceId").writeValue(putScalingPolicyRequest.getResourceId());
}
if (putScalingPolicyRequest.getScalableDimension() != null) {
jsonGenerator.writeFieldName("ScalableDimension").writeValue(putScalingPolicyRequest.getScalableDimension());
}
if (putScalingPolicyRequest.getPolicyType() != null) {
jsonGenerator.writeFieldName("PolicyType").writeValue(putScalingPolicyRequest.getPolicyType());
}
if (putScalingPolicyRequest.getStepScalingPolicyConfiguration() != null) {
jsonGenerator.writeFieldName("StepScalingPolicyConfiguration");
StepScalingPolicyConfigurationJsonMarshaller.getInstance().marshall(putScalingPolicyRequest.getStepScalingPolicyConfiguration(), jsonGenerator);
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length", Integer.toString(content.length));
request.addHeader("Content-Type", protocolFactory.getContentType());
} catch (Throwable t) {
throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
|
923284d515cd0bdf8715fad4709b097d7e3acc69 | 2,663 | java | Java | src/main/java/theGartic/vfx/ResoluteStanceAuraEffect.java | MistressAlison/TheGartic | 91e3e921cf16c907cdbf7a0bfdceefb5bd0acae1 | [
"MIT"
] | 1 | 2022-02-27T23:30:53.000Z | 2022-02-27T23:30:53.000Z | src/main/java/theGartic/vfx/ResoluteStanceAuraEffect.java | MistressAlison/TheGartic | 91e3e921cf16c907cdbf7a0bfdceefb5bd0acae1 | [
"MIT"
] | 2 | 2022-02-27T23:44:12.000Z | 2022-03-19T08:05:11.000Z | src/main/java/theGartic/vfx/ResoluteStanceAuraEffect.java | MistressAlison/TheGartic | 91e3e921cf16c907cdbf7a0bfdceefb5bd0acae1 | [
"MIT"
] | 21 | 2022-02-25T12:59:27.000Z | 2022-03-26T18:40:31.000Z | 39.161765 | 213 | 0.647766 | 996,248 | package theGartic.vfx;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.helpers.ImageMaster;
import com.megacrit.cardcrawl.vfx.AbstractGameEffect;
public class ResoluteStanceAuraEffect extends AbstractGameEffect {
private float x;
private float y;
private float vY;
private TextureAtlas.AtlasRegion img;
public static boolean switcher = true;
public ResoluteStanceAuraEffect() {
this.img = ImageMaster.EXHAUST_L;
this.duration = 2.0F;
this.scale = MathUtils.random(2.7F, 2.5F) * Settings.scale;
this.color = new Color(0.0F, MathUtils.random(0.5F, 1.0F), MathUtils.random(0.0F, 0.2F), 0.0F);
this.x = AbstractDungeon.player.hb.cX + MathUtils.random(-AbstractDungeon.player.hb.width / 16.0F, AbstractDungeon.player.hb.width / 16.0F);
this.y = AbstractDungeon.player.hb.cY + MathUtils.random(-AbstractDungeon.player.hb.height / 16.0F, AbstractDungeon.player.hb.height / 12.0F);
this.x -= (float)this.img.packedWidth / 2.0F;
this.y -= (float)this.img.packedHeight / 2.0F;
switcher = !switcher;
this.renderBehind = true;
this.rotation = MathUtils.random(360.0F);
if (switcher) {
this.renderBehind = true;
this.vY = MathUtils.random(0.0F, 40.0F);
} else {
this.renderBehind = false;
this.vY = MathUtils.random(0.0F, -40.0F);
}
}
public void update() {
if (this.duration > 1.0F) {
this.color.a = Interpolation.fade.apply(0.3F, 0.0F, this.duration - 1.0F);
} else {
this.color.a = Interpolation.fade.apply(0.0F, 0.3F, this.duration);
}
this.rotation += Gdx.graphics.getDeltaTime() * this.vY;
this.duration -= Gdx.graphics.getDeltaTime();
if (this.duration < 0.0F) {
this.isDone = true;
}
}
public void render(SpriteBatch sb) {
sb.setColor(this.color);
sb.setBlendFunction(770, 1);
sb.draw(this.img, this.x, this.y, (float)this.img.packedWidth / 2.0F, (float)this.img.packedHeight / 2.0F, (float)this.img.packedWidth, (float)this.img.packedHeight, this.scale, this.scale, this.rotation);
sb.setBlendFunction(770, 771);
}
public void dispose() {
}
}
|
92328787a3be665436192819c9f24c5daaf0bdec | 337 | java | Java | src/main/java/arfsoftwares/helper/ByteArrayHelper.java | alexferreiradev/gerador_certificado_java | 4b497e51bc479802221fd1a9bc586b5a8c88e15e | [
"MIT"
] | 3 | 2019-02-23T00:16:07.000Z | 2019-02-23T16:08:24.000Z | src/main/java/arfsoftwares/helper/ByteArrayHelper.java | alexferreiradev/gerador_certificado_java | 4b497e51bc479802221fd1a9bc586b5a8c88e15e | [
"MIT"
] | null | null | null | src/main/java/arfsoftwares/helper/ByteArrayHelper.java | alexferreiradev/gerador_certificado_java | 4b497e51bc479802221fd1a9bc586b5a8c88e15e | [
"MIT"
] | null | null | null | 16.85 | 62 | 0.617211 | 996,249 | package arfsoftwares.helper;
public final class ByteArrayHelper {
public static boolean isSameByteArray(byte[] b1, byte[] b2) {
if (b1.length != b2.length) {
return false;
}
for (int i = 0; i < b1.length; i++) {
byte byteComparing = b1[i];
if (byteComparing != b2[i]) {
return false;
}
}
return true;
}
}
|
92328865346c201deeaa435b9ab7ac9fbf6b5d79 | 324 | java | Java | sample-common/src/main/java/io/techery/analytics/sample_common/janet/action/BaseAnalyticsAction.java | techery/janet-analytics | 6f1118c003a68ec245bc8a539fccfcfde5f2171b | [
"Apache-2.0"
] | 4 | 2018-02-02T17:12:25.000Z | 2021-08-29T10:13:59.000Z | sample-common/src/main/java/io/techery/analytics/sample_common/janet/action/BaseAnalyticsAction.java | techery/janet-analytics | 6f1118c003a68ec245bc8a539fccfcfde5f2171b | [
"Apache-2.0"
] | 1 | 2018-03-07T10:35:33.000Z | 2018-03-07T10:35:33.000Z | sample-common/src/main/java/io/techery/analytics/sample_common/janet/action/BaseAnalyticsAction.java | techery/janet-analytics | 6f1118c003a68ec245bc8a539fccfcfde5f2171b | [
"Apache-2.0"
] | 1 | 2018-02-07T16:56:31.000Z | 2018-02-07T16:56:31.000Z | 36 | 114 | 0.768519 | 996,250 | package io.techery.analytics.sample_common.janet.action;
/**
* Empty interface to depend upon when creating {@link io.techery.janet.Janet} {@link io.techery.janet.ActionPipe}
* This is just one of the ways to manage janet usage - does not necessarily has to be this exact way
*/
public interface BaseAnalyticsAction {
}
|
923288af3658603f1a4aa96da4bf28121c8cdcb8 | 555 | java | Java | manager-api/src/main/java/myserver/api/modules/response/Response.java | pistolove/manager | 3af5483f7eb42687a1c821f738a2995e7f49234f | [
"Apache-2.0"
] | null | null | null | manager-api/src/main/java/myserver/api/modules/response/Response.java | pistolove/manager | 3af5483f7eb42687a1c821f738a2995e7f49234f | [
"Apache-2.0"
] | null | null | null | manager-api/src/main/java/myserver/api/modules/response/Response.java | pistolove/manager | 3af5483f7eb42687a1c821f738a2995e7f49234f | [
"Apache-2.0"
] | null | null | null | 16.323529 | 51 | 0.731532 | 996,251 | package myserver.api.modules.response;
public class Response<T> implements BaseResponse {
private String errorMessage;
private String errorCode;
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getErrorcode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.