content
stringlengths 15
442k
| obf_code
stringlengths 15
442k
| probability
float64 0
1
| obf_dict
stringlengths 0
13.5k
| lang
stringclasses 3
values | classification
stringclasses 5
values | confiability
stringlengths 1
10
|
|---|---|---|---|---|---|---|
/**
*
* Draws main-title and sub-title
*
*/
private void drawTitles(Graphics g){
Graphics2D g2d = (Graphics2D)g;
FontMetrics fm = getFontMetrics(getFont());
int font_height = fm.getHeight();
if(maintitle_field != null)
maintitle = maintitle_field.getText();
int title_width = fm.stringWidth(maintitle);
g2d.drawString(maintitle, (int)((getWidth()-title_width)/2),
font_height+1);
title_width = fm.stringWidth(subtitle);
g2d.drawString(subtitle,(int)((getWidth()-title_width)/2),
font_height*2+2);
}
|
/**
*
* Draws main-title and sub-title
*
*/
private void drawTitles(Graphics VAR_0){
CLASS_0 VAR_1 = (CLASS_0)VAR_0;
FontMetrics fm = getFontMetrics(FUNC_0());
int VAR_2 = fm.getHeight();
if(VAR_3 != null)
maintitle = VAR_3.FUNC_1();
int VAR_4 = fm.FUNC_2(maintitle);
VAR_1.FUNC_3(maintitle, (int)((FUNC_4()-VAR_4)/2),
VAR_2+1);
VAR_4 = fm.FUNC_2(subtitle);
VAR_1.FUNC_3(subtitle,(int)((FUNC_4()-VAR_4)/2),
VAR_2*2+2);
}
| 0.608774
|
{'VAR_0': 'g', 'CLASS_0': 'Graphics2D', 'VAR_1': 'g2d', 'FUNC_0': 'getFont', 'VAR_2': 'font_height', 'VAR_3': 'maintitle_field', 'FUNC_1': 'getText', 'VAR_4': 'title_width', 'FUNC_2': 'stringWidth', 'FUNC_3': 'drawString', 'FUNC_4': 'getWidth'}
|
java
|
Procedural
|
100.00%
|
/*
* This file is part of PV-Star for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.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 com.jcwhatever.pvs.signs;
import com.jcwhatever.nucleus.managed.language.Localizable;
import com.jcwhatever.nucleus.managed.signs.ISignContainer;
import com.jcwhatever.nucleus.managed.signs.SignHandler;
import com.jcwhatever.nucleus.utils.text.TextColor;
import com.jcwhatever.pvs.Lang;
import com.jcwhatever.pvs.players.ArenaPlayer;
import com.jcwhatever.pvs.api.PVStarAPI;
import com.jcwhatever.pvs.api.arena.IArena;
import com.jcwhatever.pvs.api.arena.IArenaPlayer;
import com.jcwhatever.pvs.api.arena.options.ArenaContext;
import com.jcwhatever.pvs.api.utils.Msg;
import org.bukkit.entity.Player;
/**
* A sign players can click to declare themselves ready to play.
*/
public class ReadySignHandler extends SignHandler {
@Localizable static final String _VOTE_NOT_IN_GAME = "You're not in a game.";
@Localizable static final String _VOTE_GAME_ALREADY_STARTED = "The game has already started.";
/**
* Constructor.
*/
public ReadySignHandler() {
super(PVStarAPI.getPlugin(), "Ready");
}
@Override
public String getDescription() {
return "A sign that votes to start when a player clicks on it.";
}
@Override
public String[] getUsage() {
return new String[] {
"Ready",
"--anything--",
"--anything--",
"--anything--"
};
}
@Override
public String getHeaderPrefix() {
return TextColor.BOLD.toString() + TextColor.DARK_GREEN;
}
@Override
protected void onSignLoad(ISignContainer sign) {
// do nothing
}
@Override
protected SignChangeResult onSignChange(Player player, ISignContainer sign) {
IArena arena = PVStarAPI.getArenaManager().getArena(sign.getLocation());
return arena != null
? SignChangeResult.VALID
: SignChangeResult.INVALID;
}
@Override
protected SignClickResult onSignClick(Player p, ISignContainer sign) {
IArenaPlayer player = ArenaPlayer.get(p);
if (player == null)
return SignClickResult.IGNORED;
IArena arena = player.getArena();
if (arena == null || player.getContext() == ArenaContext.SPECTATOR) {
Msg.tellError(p, Lang.get(_VOTE_NOT_IN_GAME));
return SignClickResult.IGNORED;
}
if (player.getContext() == ArenaContext.GAME) {
Msg.tellError(p, Lang.get(_VOTE_GAME_ALREADY_STARTED));
return SignClickResult.IGNORED;
}
player.setReady(true);
return SignClickResult.HANDLED;
}
@Override
protected SignBreakResult onSignBreak(Player player, ISignContainer sign) {
return SignBreakResult.ALLOW;
}
}
|
/*
* This file is part of PV-Star for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.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 com.IMPORT_0.IMPORT_1.signs;
import com.IMPORT_0.IMPORT_2.managed.IMPORT_3.IMPORT_4;
import com.IMPORT_0.IMPORT_2.managed.signs.ISignContainer;
import com.IMPORT_0.IMPORT_2.managed.signs.IMPORT_5;
import com.IMPORT_0.IMPORT_2.utils.IMPORT_6.IMPORT_7;
import com.IMPORT_0.IMPORT_1.Lang;
import com.IMPORT_0.IMPORT_1.IMPORT_8.ArenaPlayer;
import com.IMPORT_0.IMPORT_1.IMPORT_9.PVStarAPI;
import com.IMPORT_0.IMPORT_1.IMPORT_9.IMPORT_10.IArena;
import com.IMPORT_0.IMPORT_1.IMPORT_9.IMPORT_10.IArenaPlayer;
import com.IMPORT_0.IMPORT_1.IMPORT_9.IMPORT_10.IMPORT_11.ArenaContext;
import com.IMPORT_0.IMPORT_1.IMPORT_9.utils.Msg;
import org.IMPORT_12.IMPORT_13.IMPORT_14;
/**
* A sign players can click to declare themselves ready to play.
*/
public class ReadySignHandler extends IMPORT_5 {
@IMPORT_4 static final CLASS_0 VAR_0 = "You're not in a game.";
@IMPORT_4 static final CLASS_0 VAR_1 = "The game has already started.";
/**
* Constructor.
*/
public ReadySignHandler() {
super(PVStarAPI.FUNC_0(), "Ready");
}
@VAR_2
public CLASS_0 getDescription() {
return "A sign that votes to start when a player clicks on it.";
}
@VAR_2
public CLASS_0[] FUNC_1() {
return new CLASS_0[] {
"Ready",
"--anything--",
"--anything--",
"--anything--"
};
}
@VAR_2
public CLASS_0 getHeaderPrefix() {
return IMPORT_7.BOLD.toString() + IMPORT_7.DARK_GREEN;
}
@VAR_2
protected void FUNC_2(ISignContainer VAR_3) {
// do nothing
}
@VAR_2
protected SignChangeResult onSignChange(IMPORT_14 VAR_4, ISignContainer VAR_3) {
IArena IMPORT_10 = PVStarAPI.getArenaManager().getArena(VAR_3.getLocation());
return IMPORT_10 != null
? SignChangeResult.VALID
: SignChangeResult.VAR_5;
}
@VAR_2
protected CLASS_1 onSignClick(IMPORT_14 p, ISignContainer VAR_3) {
IArenaPlayer VAR_4 = ArenaPlayer.get(p);
if (VAR_4 == null)
return VAR_6.IGNORED;
IArena IMPORT_10 = VAR_4.getArena();
if (IMPORT_10 == null || VAR_4.getContext() == ArenaContext.VAR_7) {
Msg.FUNC_3(p, Lang.get(VAR_0));
return VAR_6.IGNORED;
}
if (VAR_4.getContext() == ArenaContext.GAME) {
Msg.FUNC_3(p, Lang.get(VAR_1));
return VAR_6.IGNORED;
}
VAR_4.setReady(true);
return VAR_6.HANDLED;
}
@VAR_2
protected CLASS_2 FUNC_4(IMPORT_14 VAR_4, ISignContainer VAR_3) {
return VAR_8.VAR_9;
}
}
| 0.521818
|
{'IMPORT_0': 'jcwhatever', 'IMPORT_1': 'pvs', 'IMPORT_2': 'nucleus', 'IMPORT_3': 'language', 'IMPORT_4': 'Localizable', 'IMPORT_5': 'SignHandler', 'IMPORT_6': 'text', 'IMPORT_7': 'TextColor', 'IMPORT_8': 'players', 'IMPORT_9': 'api', 'IMPORT_10': 'arena', 'IMPORT_11': 'options', 'IMPORT_12': 'bukkit', 'IMPORT_13': 'entity', 'IMPORT_14': 'Player', 'CLASS_0': 'String', 'VAR_0': '_VOTE_NOT_IN_GAME', 'VAR_1': '_VOTE_GAME_ALREADY_STARTED', 'FUNC_0': 'getPlugin', 'VAR_2': 'Override', 'FUNC_1': 'getUsage', 'FUNC_2': 'onSignLoad', 'VAR_3': 'sign', 'VAR_4': 'player', 'VAR_5': 'INVALID', 'CLASS_1': 'SignClickResult', 'VAR_6': 'SignClickResult', 'VAR_7': 'SPECTATOR', 'FUNC_3': 'tellError', 'CLASS_2': 'SignBreakResult', 'VAR_8': 'SignBreakResult', 'FUNC_4': 'onSignBreak', 'VAR_9': 'ALLOW'}
|
java
|
Hibrido
|
100.00%
|
/**
* Pause video. If video is already paused, stopped or ended nothing will happen.
*/
public void pause() {
if (getState() == State.PAUSE) {
Log.d("AdvancedVideoView", "pause() was called but video already paused.");
return;
}
if (getState() == State.STOP) {
Log.d("AdvancedVideoView", "pause() was called but video already stopped.");
return;
}
if (getState() == State.END) {
Log.d("AdvancedVideoView", "pause() was called but video already ended.");
return;
}
setState(State.PAUSE);
if (isPlaying()) {
mMediaPlayer.pause();
playedLength = mMediaPlayer.getCurrentPosition();
}
}
|
/**
* Pause video. If video is already paused, stopped or ended nothing will happen.
*/
public void FUNC_0() {
if (FUNC_1() == VAR_0.VAR_1) {
VAR_2.FUNC_2("AdvancedVideoView", "pause() was called but video already paused.");
return;
}
if (FUNC_1() == VAR_0.VAR_3) {
VAR_2.FUNC_2("AdvancedVideoView", "pause() was called but video already stopped.");
return;
}
if (FUNC_1() == VAR_0.VAR_4) {
VAR_2.FUNC_2("AdvancedVideoView", "pause() was called but video already ended.");
return;
}
FUNC_3(VAR_0.VAR_1);
if (FUNC_4()) {
VAR_5.FUNC_0();
VAR_6 = VAR_5.FUNC_5();
}
}
| 0.842471
|
{'FUNC_0': 'pause', 'FUNC_1': 'getState', 'VAR_0': 'State', 'VAR_1': 'PAUSE', 'VAR_2': 'Log', 'FUNC_2': 'd', 'VAR_3': 'STOP', 'VAR_4': 'END', 'FUNC_3': 'setState', 'FUNC_4': 'isPlaying', 'VAR_5': 'mMediaPlayer', 'VAR_6': 'playedLength', 'FUNC_5': 'getCurrentPosition'}
|
java
|
Procedural
|
100.00%
|
/**
* Called when the view controller is about to show UIActivityViewController after the user taps the action button.
*
* @param URL the URL of the web page.
* @param title the title of the web page.
* @return Returns an array of UIActivity instances that will be appended to UIActivityViewController.
*/
@Generated
@IsOptional
@Selector("safariViewController:activityItemsForURL:title:")
default NSArray<? extends UIActivity> safariViewControllerActivityItemsForURLTitle(
SFSafariViewController controller, NSURL URL, String title) {
throw new java.lang.UnsupportedOperationException();
}
|
/**
* Called when the view controller is about to show UIActivityViewController after the user taps the action button.
*
* @param URL the URL of the web page.
* @param title the title of the web page.
* @return Returns an array of UIActivity instances that will be appended to UIActivityViewController.
*/
@Generated
@IsOptional
@Selector("safariViewController:activityItemsForURL:title:")
default NSArray<? extends UIActivity> safariViewControllerActivityItemsForURLTitle(
SFSafariViewController controller, NSURL URL, String title) {
throw new java.lang.UnsupportedOperationException();
}
| 0.108285
|
{}
|
java
|
Procedural
|
100.00%
|
package fi.riista.integration.support;
import org.joda.time.LocalTime;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class LocalTimeAdapter extends XmlAdapter<String, LocalTime> {
@Override
public String marshal(LocalTime time) {
return time.toString();
}
@Override
public LocalTime unmarshal(String value) {
return new LocalTime(value);
}
}
|
package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_4.IMPORT_5.IMPORT_6.IMPORT_7;
import IMPORT_8.IMPORT_9.IMPORT_10.IMPORT_11.IMPORT_12.XmlAdapter;
public class CLASS_0 extends XmlAdapter<String, IMPORT_7> {
@VAR_0
public String marshal(IMPORT_7 IMPORT_6) {
return IMPORT_6.toString();
}
@VAR_0
public IMPORT_7 FUNC_0(String VAR_1) {
return new IMPORT_7(VAR_1);
}
}
| 0.871031
|
{'IMPORT_0': 'fi', 'IMPORT_1': 'riista', 'IMPORT_2': 'integration', 'IMPORT_3': 'support', 'IMPORT_4': 'org', 'IMPORT_5': 'joda', 'IMPORT_6': 'time', 'IMPORT_7': 'LocalTime', 'IMPORT_8': 'javax', 'IMPORT_9': 'xml', 'IMPORT_10': 'bind', 'IMPORT_11': 'annotation', 'IMPORT_12': 'adapters', 'CLASS_0': 'LocalTimeAdapter', 'VAR_0': 'Override', 'FUNC_0': 'unmarshal', 'VAR_1': 'value'}
|
java
|
OOP
|
100.00%
|
package pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.impl;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.ComplexMeasurement;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.ComplexMeasurementTask;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.UpdateType;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.annotation.Parameter;
import pl.edu.agh.dsm.monitor.core.model.measurement.complex.task.annotation.Task;
import pl.edu.agh.dsm.monitor.core.model.measurement.data.DataLimit;
import pl.edu.agh.dsm.monitor.core.model.measurement.data.MeasurementData;
import java.util.Date;
import java.util.List;
import static java.util.concurrent.TimeUnit.*;
/**
* Created by Tom on 2014-05-29.
*/
@Task(name="Moving average", code="move_avg", parameters = {
@Parameter(name="Interval (s)", code="interval"),
@Parameter(name="Time window (s)", code="time_window")})
public class MovingAverageTask extends ComplexMeasurementTask {
public MovingAverageTask(ComplexMeasurement complexMeasurement) {
super(complexMeasurement);
}
private long lastAddTimestamp = new Date().getTime();
@Override
public void update() {
if(hasIntervalTimePassed()) {
List<MeasurementData> data = getBaseMeasurementData(DataLimit.since, (int) getTimeWindow());
double value = calcAverage(data);
long timestamp = new Date().getTime();
addMeasurementData(new MeasurementData(timestamp, value));
lastAddTimestamp = timestamp;
}
}
public double calcAverage(List<MeasurementData> data) {
double avg=0;
for(int i=0; i< data.size();i++){
avg += data.get(i).getData();
}
avg = avg/data.size();
return avg;
}
public boolean hasIntervalTimePassed() {
long now = new Date().getTime();
long intervalSeconds = MILLISECONDS.convert(getInterval(), SECONDS);
return now - lastAddTimestamp > intervalSeconds;
}
@Override
public UpdateType getUpdateType() {
return UpdateType.TIME_BASED;
}
public long getInterval() {
return (long) getParamValue("interval");
}
public double getTimeWindow() {
return getParamValue("time_window");
}
}
|
package pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.complex.IMPORT_6.impl;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.complex.IMPORT_7;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.complex.IMPORT_6.IMPORT_8;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.complex.IMPORT_6.IMPORT_9;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.complex.IMPORT_6.IMPORT_10.IMPORT_11;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.complex.IMPORT_6.IMPORT_10.IMPORT_12;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.data.IMPORT_13;
import pl.edu.IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.data.IMPORT_14;
import IMPORT_15.util.IMPORT_16;
import IMPORT_15.util.IMPORT_17;
import static IMPORT_15.util.IMPORT_18.IMPORT_19.*;
/**
* Created by Tom on 2014-05-29.
*/
@IMPORT_12(VAR_0="Moving average", VAR_1="move_avg", VAR_2 = {
@IMPORT_11(VAR_0="Interval (s)", VAR_1="interval"),
@IMPORT_11(VAR_0="Time window (s)", VAR_1="time_window")})
public class CLASS_0 extends IMPORT_8 {
public CLASS_0(IMPORT_7 complexMeasurement) {
super(complexMeasurement);
}
private long VAR_3 = new IMPORT_16().FUNC_0();
@Override
public void update() {
if(FUNC_1()) {
IMPORT_17<IMPORT_14> data = FUNC_2(IMPORT_13.VAR_4, (int) getTimeWindow());
double VAR_5 = FUNC_3(data);
long VAR_6 = new IMPORT_16().FUNC_0();
FUNC_4(new IMPORT_14(VAR_6, VAR_5));
VAR_3 = VAR_6;
}
}
public double FUNC_3(IMPORT_17<IMPORT_14> data) {
double VAR_7=0;
for(int i=0; i< data.FUNC_5();i++){
VAR_7 += data.FUNC_6(i).FUNC_7();
}
VAR_7 = VAR_7/data.FUNC_5();
return VAR_7;
}
public boolean FUNC_1() {
long VAR_8 = new IMPORT_16().FUNC_0();
long VAR_9 = VAR_10.convert(getInterval(), SECONDS);
return VAR_8 - VAR_3 > VAR_9;
}
@Override
public IMPORT_9 FUNC_8() {
return IMPORT_9.VAR_11;
}
public long getInterval() {
return (long) FUNC_9("interval");
}
public double getTimeWindow() {
return FUNC_9("time_window");
}
}
| 0.550281
|
{'IMPORT_0': 'agh', 'IMPORT_1': 'dsm', 'IMPORT_2': 'monitor', 'IMPORT_3': 'core', 'IMPORT_4': 'model', 'IMPORT_5': 'measurement', 'IMPORT_6': 'task', 'IMPORT_7': 'ComplexMeasurement', 'IMPORT_8': 'ComplexMeasurementTask', 'IMPORT_9': 'UpdateType', 'IMPORT_10': 'annotation', 'IMPORT_11': 'Parameter', 'IMPORT_12': 'Task', 'IMPORT_13': 'DataLimit', 'IMPORT_14': 'MeasurementData', 'IMPORT_15': 'java', 'IMPORT_16': 'Date', 'IMPORT_17': 'List', 'IMPORT_18': 'concurrent', 'IMPORT_19': 'TimeUnit', 'VAR_0': 'name', 'VAR_1': 'code', 'VAR_2': 'parameters', 'CLASS_0': 'MovingAverageTask', 'VAR_3': 'lastAddTimestamp', 'FUNC_0': 'getTime', 'FUNC_1': 'hasIntervalTimePassed', 'FUNC_2': 'getBaseMeasurementData', 'VAR_4': 'since', 'VAR_5': 'value', 'FUNC_3': 'calcAverage', 'VAR_6': 'timestamp', 'FUNC_4': 'addMeasurementData', 'VAR_7': 'avg', 'FUNC_5': 'size', 'FUNC_6': 'get', 'FUNC_7': 'getData', 'VAR_8': 'now', 'VAR_9': 'intervalSeconds', 'VAR_10': 'MILLISECONDS', 'FUNC_8': 'getUpdateType', 'VAR_11': 'TIME_BASED', 'FUNC_9': 'getParamValue'}
|
java
|
Procedural
|
36.73%
|
package ic.xptdd.mario.decorator;
import ic.xptdd.mario.KeyCode;
import ic.xptdd.mario.Mario;
public class FlyingSquirrelMario implements Mario {
private Mario mario;
public FlyingSquirrelMario(Mario mario) {
this.mario = mario;
}
public void setMario(Mario mario) {
this.mario = mario;
}
@Override
public String onKeyPressed(KeyCode keyCode) {
switch (keyCode) {
case JUMP:
return glide();
default:
return mario.onKeyPressed(keyCode);
}
}
private String glide() {
return "Gliding";
}
}
|
package ic.xptdd.IMPORT_0.decorator;
import ic.xptdd.IMPORT_0.IMPORT_1;
import ic.xptdd.IMPORT_0.IMPORT_2;
public class FlyingSquirrelMario implements IMPORT_2 {
private IMPORT_2 IMPORT_0;
public FlyingSquirrelMario(IMPORT_2 IMPORT_0) {
this.IMPORT_0 = IMPORT_0;
}
public void FUNC_0(IMPORT_2 IMPORT_0) {
this.IMPORT_0 = IMPORT_0;
}
@Override
public String onKeyPressed(IMPORT_1 keyCode) {
switch (keyCode) {
case JUMP:
return FUNC_1();
default:
return IMPORT_0.onKeyPressed(keyCode);
}
}
private String FUNC_1() {
return "Gliding";
}
}
| 0.382059
|
{'IMPORT_0': 'mario', 'IMPORT_1': 'KeyCode', 'IMPORT_2': 'Mario', 'FUNC_0': 'setMario', 'FUNC_1': 'glide'}
|
java
|
OOP
|
100.00%
|
package arrayscript.parser.source;
import arrayscript.lang.Keyword;
import arrayscript.lang.Operator;
public class SourceKeyword implements SourceElement {
private static final SourceKeyword[] INSTANCES;
static {
// Create a single instance for every keyword
Keyword[] KEYWORDS = Keyword.values();
INSTANCES = new SourceKeyword[KEYWORDS.length];
// Now actually fill the array
for (int index = 0; index < INSTANCES.length; index++) {
INSTANCES[index] = new SourceKeyword(KEYWORDS[index]);
}
}
public static SourceKeyword getInstance(Keyword keyword) {
return INSTANCES[keyword.ordinal()];
}
private final Keyword keyword;
private SourceKeyword(Keyword keyword) {
this.keyword = keyword;
}
@Override
public SourceElementType getType() {
return SourceElementType.KEYWORD;
}
@Override
public Operator getOperator() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not an operator, but a keyword");
}
@Override
public String getStringContent() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not a string, but a keyword");
}
@Override
public String getWord() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not a normal word, but a keyword");
}
@Override
public Keyword getKeyword() throws UnsupportedOperationException {
return keyword;
}
@Override
public String toString() {
return keyword.name();
}
@Override
public double getNumber() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not a number, but a keyword");
}
}
|
package arrayscript.parser.source;
import arrayscript.lang.Keyword;
import arrayscript.lang.IMPORT_0;
public class SourceKeyword implements SourceElement {
private static final SourceKeyword[] INSTANCES;
static {
// Create a single instance for every keyword
Keyword[] KEYWORDS = Keyword.values();
INSTANCES = new SourceKeyword[KEYWORDS.length];
// Now actually fill the array
for (int index = 0; index < INSTANCES.length; index++) {
INSTANCES[index] = new SourceKeyword(KEYWORDS[index]);
}
}
public static SourceKeyword getInstance(Keyword keyword) {
return INSTANCES[keyword.ordinal()];
}
private final Keyword keyword;
private SourceKeyword(Keyword keyword) {
this.keyword = keyword;
}
@Override
public SourceElementType getType() {
return SourceElementType.KEYWORD;
}
@Override
public IMPORT_0 getOperator() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not an operator, but a keyword");
}
@Override
public String getStringContent() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not a string, but a keyword");
}
@Override
public String getWord() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not a normal word, but a keyword");
}
@Override
public Keyword getKeyword() throws UnsupportedOperationException {
return keyword;
}
@Override
public String toString() {
return keyword.name();
}
@Override
public double getNumber() throws UnsupportedOperationException {
throw new UnsupportedOperationException("This is not a number, but a keyword");
}
}
| 0.084988
|
{'IMPORT_0': 'Operator'}
|
java
|
OOP
|
100.00%
|
package util;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Symmetric Cipher Engine. A simple wrapper over Java's Cipher class which only supports the
* Symmetric Ciphers.
*
* @author <NAME>
*/
public class SymCipherEng {
/**
* Dependencies: <code>
* 1. util.CipherEngUtil
* </code>
*/
/**
* DES block size in bytes.
*/
public static final int DES_BLOCK_SIZE = 8;
/**
* AES block size in bytes.
*/
public static final int AES_BLOCK_SIZE = 16;
/**
* Blowfish block size in bytes.
*/
public static final int BLOWFISH_BLOCK_SIZE = 8;
/**
* Cipher engine.
*/
protected Cipher engine;
/**
* All supported Symmetric Cipher algorithms.
*
* @author <NAME>
*/
public static enum ALGO_SYM {
DES, DESede, AES, Blowfish;
};
/**
* @param algo
* the given cipher algorithm
*
* @return <code>KeyGenerator.getInstance(algo.name())</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static KeyGenerator getKeyGenerator(ALGO_SYM algo) throws NullPointerException {
try {
return KeyGenerator.getInstance(algo.name());
} catch (NoSuchAlgorithmException ex) {
throw new ExceptionInInitializerError(algo.name() + " key generator is not provided!");
}
}
/**
* Cipher key generators.
*/
protected static KeyGenerator[] keyGenerators = null;
/**
* Cipher algorithm.
*/
private ALGO_SYM algo;
/**
* Cipher secret key.
*/
protected SecretKey key;
/**
* Mode of operation.
*/
private CipherEngUtil.OPMODE opmode;
/**
* Padding algorithm.
*/
private CipherEngUtil.PADDING padding;
/**
* Initialization vector.
*/
protected IvParameterSpec iv;
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @param opmode
* the given mode of operation
*
* @param padding
* the given padding algorithm
*
* @param iv
* the given initialization vector
*
* @throws NullPointerException
* If
* <code>(algo == null) || (key == null) || (opmode == null) || (padding == null) || (iv == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key, CipherEngUtil.OPMODE opmode, CipherEngUtil.PADDING padding,
byte[] iv) throws NullPointerException {
try {
// The following is meant to be an assignment of
// this.engine, this.algo, this.opmode, and this.padding.
this.engine = CipherEngUtil.getEngine((this.algo = algo).name(), this.opmode = opmode,
this.padding = padding);
} catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
throw new ExceptionInInitializerError();
}
this.key(key);
this.iv(iv);
}
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @param opmode
* the given mode of operation
*
* @param padding
* the given padding algorithm
*
* @throws NullPointerException
* If
* <code>(algo == null) || (key == null) || (opmode == null) || (padding == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key, CipherEngUtil.OPMODE opmode, CipherEngUtil.PADDING padding)
throws NullPointerException {
try {
// The following is meant to be an assignment of
// this.engine, this.algo, this.opmode, and this.padding.
this.engine = CipherEngUtil.getEngine((this.algo = algo).name(), this.opmode = opmode,
this.padding = padding);
} catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
throw new ExceptionInInitializerError();
}
this.key(key);
this.iv = null;
}
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @param opmode
* the given mode of operation
*
* @throws NullPointerException
* If <code>(algo == null) || (key == null) || (opmode == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key, CipherEngUtil.OPMODE opmode) throws NullPointerException {
this(algo, key, opmode, CipherEngUtil.DEFAULT_PADDING);
}
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @throws NullPointerException
* If <code>(algo == null) || (key == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key) throws NullPointerException {
this(algo, key, CipherEngUtil.DEFAULT_MODE);
}
/**
* Copy ctor.
*
* @param other
* the given SymCipherEng object
*
* @throws NullPointerException
* If <code>other == null</code>
*/
public SymCipherEng(SymCipherEng other) throws NullPointerException {
this.engine = other.engine; // Since Cipher is singleton (accessed through getInstance).
this.algo = other.algo; // Since enum type assignment is a deep enough copy.
this.key = SymCipherEng.key(other.key.getEncoded(), this.algo);
this.opmode = other.opmode; // Since enum type assignment is a deep enough copy.
this.padding = other.padding; // Since enum type assignment is a deep enough copy.
this.iv = (other.iv == null) ? null : new IvParameterSpec(other.iv.getIV());
}
@Override
protected Object clone() throws CloneNotSupportedException { // semi-copy
throw new CloneNotSupportedException("Use the copy ctor instead.");
}
@Override
protected void finalize() { // semi-dtor
this.engine = null;
this.algo = null;
this.key = null;
this.opmode = null;
this.padding = null;
this.iv = null;
}
/**
* Initialize <code>SymCipherEng.keyGenerators[algo.ordinal()]</code> using the following:
*
* <pre>
* <code>
* if (SymCipherEng.keyGenerators == null) {
* SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.values().length];
* }
*
* final int index = algo.ordinal();
* if (SymCipherEng.keyGenerators[index] == null) {
* SymCipherEng.keyGenerators[index] = SymCipherEng.getKeyGenerator(algo);
* }
*
* if (random == null) {
* SymCipherEng.keyGenerators[index].init(keySize);
* } else {
* SymCipherEng.keyGenerators[index].init(keySize, random);
* }
* </code>
* </pre>
*
* @param algo
* the given cipher algorithm
*
* @param keySize
* algorithm-specific metric, such as key length, specified in number of bits
*
* @param random
* the source of randomness
*
* @return <code>SymCipherEng.keyGenerators[algo.ordinal()].generateKey()</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static SecretKey generateKey(ALGO_SYM algo, int keySize, SecureRandom random) throws NullPointerException {
// Construct SymCipherEng.keyGenerators if needed. Executed at most once.
if (SymCipherEng.keyGenerators == null) {
SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.values().length];
}
// Construct SymCipherEng.keyGenerators[index] if needed. Executed at most once.
final int index = algo.ordinal();
KeyGenerator keyGenerator = SymCipherEng.keyGenerators[index];
if (keyGenerator == null) {
keyGenerator = SymCipherEng.keyGenerators[index] = SymCipherEng.getKeyGenerator(algo);
}
// Initialize the key generator and return the generated key.
if (random == null) {
keyGenerator.init(keySize);
} else {
keyGenerator.init(keySize, random);
}
return keyGenerator.generateKey();
}
/**
* @param algo
* the given cipher algorithm
*
* @param keySize
* algorithm-specific metric, such as key length, specified in number of bits
*
* @return <code>SymCipherEng.generateKey(algo, keySize, null)</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static SecretKey generateKey(ALGO_SYM algo, int keySize) throws NullPointerException {
return SymCipherEng.generateKey(algo, keySize, null);
}
/**
* Initialize <code>SymCipherEng.keyGenerators[algo.ordinal()]</code> using the following:
*
* <pre>
* <code>
* if (SymCipherEng.keyGenerators == null) {
* SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.values().length];
* }
*
* final int index = algo.ordinal();
* if (SymCipherEng.keyGenerators[index] == null) {
* SymCipherEng.keyGenerators[index] = SymCipherEng.getKeyGenerator(algo);
* }
*
* if (random != null) {
* SymCipherEng.keyGenerators[index].init(random);
* }
* </code>
* </pre>
*
* @param algo
* the given cipher algorithm
*
* @param random
* the source of randomness
*
* @return <code>SymCipherEng.keyGenerators[algo.ordinal()].generateKey()</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static SecretKey generateKey(ALGO_SYM algo, SecureRandom random) throws NullPointerException {
// Construct SymCipherEng.keyGenerators if needed. Executed at most once.
if (SymCipherEng.keyGenerators == null) {
SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.values().length];
}
// Construct SymCipherEng.keyGenerators[index] if needed. Executed at most once.
final int index = algo.ordinal();
KeyGenerator keyGenerator = SymCipherEng.keyGenerators[index];
if (keyGenerator == null) {
keyGenerator = SymCipherEng.keyGenerators[index] = SymCipherEng.getKeyGenerator(algo);
}
// Initialize the key generator and return the generated key.
if (random != null) {
keyGenerator.init(random);
}
return keyGenerator.generateKey();
}
/**
* @return <code>this.algo</code>.
*/
public ALGO_SYM algo() {
return this.algo;
}
/**
* @param key
* the given cipher secret key
*
* @param algo
* the given cipher algorithm
*
* @return <code>new SecretKeySpec(key, algo.name())</code>.
*
* @throws NullPointerException
* If <code>(key == null) || (algo == null)</code>
*/
public static SecretKey key(byte[] key, ALGO_SYM algo) throws NullPointerException {
if (key == null) {
throw new NullPointerException();
}
return new SecretKeySpec(key, algo.name());
}
/**
* @return <code>this.key.getEncoded()</code>.
*/
public byte[] key() {
/*
* With a simple test, we can determine that the getEncoded method returns a copy and not the actual
* pointer. Therefore, it is safe to just return what it returns without making a copy, since it has
* made the copy for us.
*/
return this.key.getEncoded();
}
/**
* Set the calling object's cipher secret key to the given cipher secret key.
*
* @param key
* the given cipher secret key
*
* @throws NullPointerException
* If <code>key == null</code>
*/
public void key(byte[] key) throws NullPointerException {
this.key = SymCipherEng.key(key, this.algo);
}
/**
* @return <code>this.opmode</code>.
*/
public CipherEngUtil.OPMODE opmode() {
return this.opmode;
}
/**
* Set the calling object's mode of operation to the given mode of operation.
*
* @param opmode
* the given mode of operation
*
* @throws NullPointerException
* If <code>opmode == null</code>
*/
public void opmode(CipherEngUtil.OPMODE opmode) throws NullPointerException {
// The following is meant to be an assignment of this.engine and this.opmode.
try {
this.engine = CipherEngUtil.getEngine(this.algo.name(), opmode, this.padding);
} catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
throw new ExceptionInInitializerError();
}
this.opmode = opmode;
}
/**
* @return <code>this.padding</code>.
*/
public CipherEngUtil.PADDING padding() {
return this.padding;
}
/**
* Set the calling object's padding algorithm to the given padding algorithm.
*
* @param padding
* the given padding algorithm
*
* @throws NullPointerException
* If <code>padding == null</code>
*/
public void padding(CipherEngUtil.PADDING padding) throws NullPointerException {
// The following is meant to be an assignment of this.engine, and this.padding.
try {
this.engine = CipherEngUtil.getEngine(this.algo.name(), this.opmode, padding);
} catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
throw new ExceptionInInitializerError();
}
this.padding = padding;
}
/**
* <code>this.iv = null</code>.
*/
public void ivReset() {
this.iv = null;
}
/**
* Set the calling object's initialization vector to the given initialization vector.
*
* @param iv
* the given initialization vector
*
* @throws NullPointerException
* If <code>iv == null</code>
*/
public void iv(byte[] iv) throws NullPointerException {
if (iv == null) {
throw new NullPointerException();
}
this.iv = new IvParameterSpec(iv);
}
/**
* Since Cipher, SecretKey, and IvParameterSpec do not redeclare toString, hashCode, and equals then
* neither will SymCipherEng.
*/
/**
* Encrypt the given plaintext byte array.
*
* @param p
* the given plaintext byte array
*
* @return The encrypted ciphertext byte array.
*
* @throws NullPointerException
* If <code>p == null</code>
*
* @throws InvalidKeyException
* Thrown by <code>Cipher.init(Cipher.ENCRYPT_MODE, this.key)</code> or
* <code>Cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv)</code>
*
* @throws InvalidAlgorithmParameterException
* Thrown by <code>Cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv)</code>
*
* @throws BadPaddingException
* Thrown by <code>Cipher.doFinal(p)</code>
*
* @throws IllegalBlockSizeException
* Thrown by <code>Cipher.doFinal(p)</code>
*/
public byte[] encrypt(byte[] p) throws NullPointerException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
if (this.iv == null) {
this.engine.init(Cipher.ENCRYPT_MODE, this.key);
} else {
this.engine.init(Cipher.ENCRYPT_MODE, this.key, this.iv);
}
return this.engine.doFinal(p);
}
/**
* Decrypt the given ciphertext byte array.
*
* @param c
* the given ciphertext byte array
*
* @return The decrypted plaintext byte array.
*
* @throws NullPointerException
* If <code>c == null</code>
*
* @throws InvalidKeyException
* Thrown by <code>Cipher.init(Cipher.DECRYPT_MODE, this.key)</code> or
* <code>Cipher.init(Cipher.DECRYPT_MODE, this.key, this.iv)</code>
*
* @throws InvalidAlgorithmParameterException
* Thrown by <code>Cipher.init(Cipher.DECRYPT_MODE, this.key, this.iv)</code>
*
* @throws BadPaddingException
* Thrown by <code>Cipher.doFinal(c)</code>
*
* @throws IllegalBlockSizeException
* Thrown by <code>Cipher.doFinal(c)</code>
*/
public byte[] decrypt(byte[] c) throws NullPointerException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
if (this.iv == null) {
this.engine.init(Cipher.DECRYPT_MODE, this.key);
} else {
this.engine.init(Cipher.DECRYPT_MODE, this.key, this.iv);
}
return this.engine.doFinal(c);
}
}
|
package VAR_0;
import IMPORT_0.IMPORT_1.IMPORT_2;
import IMPORT_0.IMPORT_1.InvalidKeyException;
import IMPORT_0.IMPORT_1.NoSuchAlgorithmException;
import IMPORT_0.IMPORT_1.IMPORT_3;
import IMPORT_4.IMPORT_5.BadPaddingException;
import IMPORT_4.IMPORT_5.Cipher;
import IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_4.IMPORT_5.KeyGenerator;
import IMPORT_4.IMPORT_5.IMPORT_7;
import IMPORT_4.IMPORT_5.SecretKey;
import IMPORT_4.IMPORT_5.spec.IvParameterSpec;
import IMPORT_4.IMPORT_5.spec.SecretKeySpec;
/**
* Symmetric Cipher Engine. A simple wrapper over Java's Cipher class which only supports the
* Symmetric Ciphers.
*
* @author <NAME>
*/
public class SymCipherEng {
/**
* Dependencies: <code>
* 1. util.CipherEngUtil
* </code>
*/
/**
* DES block size in bytes.
*/
public static final int VAR_1 = 8;
/**
* AES block size in bytes.
*/
public static final int AES_BLOCK_SIZE = 16;
/**
* Blowfish block size in bytes.
*/
public static final int VAR_2 = 8;
/**
* Cipher engine.
*/
protected Cipher VAR_3;
/**
* All supported Symmetric Cipher algorithms.
*
* @author <NAME>
*/
public static enum ALGO_SYM {
VAR_4, VAR_5, VAR_6, Blowfish;
};
/**
* @param algo
* the given cipher algorithm
*
* @return <code>KeyGenerator.getInstance(algo.name())</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static KeyGenerator FUNC_0(ALGO_SYM algo) throws NullPointerException {
try {
return KeyGenerator.FUNC_1(algo.FUNC_2());
} catch (NoSuchAlgorithmException ex) {
throw new CLASS_0(algo.FUNC_2() + " key generator is not provided!");
}
}
/**
* Cipher key generators.
*/
protected static KeyGenerator[] keyGenerators = null;
/**
* Cipher algorithm.
*/
private ALGO_SYM algo;
/**
* Cipher secret key.
*/
protected SecretKey key;
/**
* Mode of operation.
*/
private CipherEngUtil.OPMODE VAR_7;
/**
* Padding algorithm.
*/
private CipherEngUtil.PADDING padding;
/**
* Initialization vector.
*/
protected IvParameterSpec iv;
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @param opmode
* the given mode of operation
*
* @param padding
* the given padding algorithm
*
* @param iv
* the given initialization vector
*
* @throws NullPointerException
* If
* <code>(algo == null) || (key == null) || (opmode == null) || (padding == null) || (iv == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key, CipherEngUtil.OPMODE VAR_7, CipherEngUtil.PADDING padding,
byte[] iv) throws NullPointerException {
try {
// The following is meant to be an assignment of
// this.engine, this.algo, this.opmode, and this.padding.
this.VAR_3 = CipherEngUtil.FUNC_4((this.algo = algo).FUNC_2(), this.VAR_7 = VAR_7,
this.padding = padding);
} catch (NoSuchAlgorithmException | IMPORT_7 ex) {
throw new CLASS_0();
}
this.key(key);
this.iv(iv);
}
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @param opmode
* the given mode of operation
*
* @param padding
* the given padding algorithm
*
* @throws NullPointerException
* If
* <code>(algo == null) || (key == null) || (opmode == null) || (padding == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key, CipherEngUtil.OPMODE VAR_7, CipherEngUtil.PADDING padding)
throws NullPointerException {
try {
// The following is meant to be an assignment of
// this.engine, this.algo, this.opmode, and this.padding.
this.VAR_3 = CipherEngUtil.FUNC_4((this.algo = algo).FUNC_2(), this.VAR_7 = VAR_7,
this.padding = padding);
} catch (NoSuchAlgorithmException | IMPORT_7 ex) {
throw new CLASS_0();
}
this.key(key);
this.iv = null;
}
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @param opmode
* the given mode of operation
*
* @throws NullPointerException
* If <code>(algo == null) || (key == null) || (opmode == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key, CipherEngUtil.OPMODE VAR_7) throws NullPointerException {
this(algo, key, VAR_7, CipherEngUtil.VAR_8);
}
/**
* Construct a SymCipherEng object from the given attributes.
*
* @param algo
* the given cipher algorithm
*
* @param key
* the given cipher secret key
*
* @throws NullPointerException
* If <code>(algo == null) || (key == null)</code>
*/
public SymCipherEng(ALGO_SYM algo, byte[] key) throws NullPointerException {
this(algo, key, CipherEngUtil.DEFAULT_MODE);
}
/**
* Copy ctor.
*
* @param other
* the given SymCipherEng object
*
* @throws NullPointerException
* If <code>other == null</code>
*/
public SymCipherEng(SymCipherEng VAR_9) throws NullPointerException {
this.VAR_3 = VAR_9.VAR_3; // Since Cipher is singleton (accessed through getInstance).
this.algo = VAR_9.algo; // Since enum type assignment is a deep enough copy.
this.key = SymCipherEng.key(VAR_9.key.getEncoded(), this.algo);
this.VAR_7 = VAR_9.VAR_7; // Since enum type assignment is a deep enough copy.
this.padding = VAR_9.padding; // Since enum type assignment is a deep enough copy.
this.iv = (VAR_9.iv == null) ? null : new IvParameterSpec(VAR_9.iv.FUNC_5());
}
@VAR_10
protected Object FUNC_6() throws CLASS_1 { // semi-copy
throw new CLASS_1("Use the copy ctor instead.");
}
@VAR_10
protected void FUNC_7() { // semi-dtor
this.VAR_3 = null;
this.algo = null;
this.key = null;
this.VAR_7 = null;
this.padding = null;
this.iv = null;
}
/**
* Initialize <code>SymCipherEng.keyGenerators[algo.ordinal()]</code> using the following:
*
* <pre>
* <code>
* if (SymCipherEng.keyGenerators == null) {
* SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.values().length];
* }
*
* final int index = algo.ordinal();
* if (SymCipherEng.keyGenerators[index] == null) {
* SymCipherEng.keyGenerators[index] = SymCipherEng.getKeyGenerator(algo);
* }
*
* if (random == null) {
* SymCipherEng.keyGenerators[index].init(keySize);
* } else {
* SymCipherEng.keyGenerators[index].init(keySize, random);
* }
* </code>
* </pre>
*
* @param algo
* the given cipher algorithm
*
* @param keySize
* algorithm-specific metric, such as key length, specified in number of bits
*
* @param random
* the source of randomness
*
* @return <code>SymCipherEng.keyGenerators[algo.ordinal()].generateKey()</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static SecretKey generateKey(ALGO_SYM algo, int keySize, IMPORT_3 VAR_11) throws NullPointerException {
// Construct SymCipherEng.keyGenerators if needed. Executed at most once.
if (SymCipherEng.keyGenerators == null) {
SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.FUNC_8().length];
}
// Construct SymCipherEng.keyGenerators[index] if needed. Executed at most once.
final int VAR_12 = algo.ordinal();
KeyGenerator keyGenerator = SymCipherEng.keyGenerators[VAR_12];
if (keyGenerator == null) {
keyGenerator = SymCipherEng.keyGenerators[VAR_12] = SymCipherEng.FUNC_0(algo);
}
// Initialize the key generator and return the generated key.
if (VAR_11 == null) {
keyGenerator.FUNC_9(keySize);
} else {
keyGenerator.FUNC_9(keySize, VAR_11);
}
return keyGenerator.generateKey();
}
/**
* @param algo
* the given cipher algorithm
*
* @param keySize
* algorithm-specific metric, such as key length, specified in number of bits
*
* @return <code>SymCipherEng.generateKey(algo, keySize, null)</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static SecretKey generateKey(ALGO_SYM algo, int keySize) throws NullPointerException {
return SymCipherEng.generateKey(algo, keySize, null);
}
/**
* Initialize <code>SymCipherEng.keyGenerators[algo.ordinal()]</code> using the following:
*
* <pre>
* <code>
* if (SymCipherEng.keyGenerators == null) {
* SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.values().length];
* }
*
* final int index = algo.ordinal();
* if (SymCipherEng.keyGenerators[index] == null) {
* SymCipherEng.keyGenerators[index] = SymCipherEng.getKeyGenerator(algo);
* }
*
* if (random != null) {
* SymCipherEng.keyGenerators[index].init(random);
* }
* </code>
* </pre>
*
* @param algo
* the given cipher algorithm
*
* @param random
* the source of randomness
*
* @return <code>SymCipherEng.keyGenerators[algo.ordinal()].generateKey()</code>.
*
* @throws NullPointerException
* If <code>algo == null</code>
*/
public static SecretKey generateKey(ALGO_SYM algo, IMPORT_3 VAR_11) throws NullPointerException {
// Construct SymCipherEng.keyGenerators if needed. Executed at most once.
if (SymCipherEng.keyGenerators == null) {
SymCipherEng.keyGenerators = new KeyGenerator[ALGO_SYM.FUNC_8().length];
}
// Construct SymCipherEng.keyGenerators[index] if needed. Executed at most once.
final int VAR_12 = algo.ordinal();
KeyGenerator keyGenerator = SymCipherEng.keyGenerators[VAR_12];
if (keyGenerator == null) {
keyGenerator = SymCipherEng.keyGenerators[VAR_12] = SymCipherEng.FUNC_0(algo);
}
// Initialize the key generator and return the generated key.
if (VAR_11 != null) {
keyGenerator.FUNC_9(VAR_11);
}
return keyGenerator.generateKey();
}
/**
* @return <code>this.algo</code>.
*/
public ALGO_SYM algo() {
return this.algo;
}
/**
* @param key
* the given cipher secret key
*
* @param algo
* the given cipher algorithm
*
* @return <code>new SecretKeySpec(key, algo.name())</code>.
*
* @throws NullPointerException
* If <code>(key == null) || (algo == null)</code>
*/
public static SecretKey key(byte[] key, ALGO_SYM algo) throws NullPointerException {
if (key == null) {
throw new NullPointerException();
}
return new SecretKeySpec(key, algo.FUNC_2());
}
/**
* @return <code>this.key.getEncoded()</code>.
*/
public byte[] key() {
/*
* With a simple test, we can determine that the getEncoded method returns a copy and not the actual
* pointer. Therefore, it is safe to just return what it returns without making a copy, since it has
* made the copy for us.
*/
return this.key.getEncoded();
}
/**
* Set the calling object's cipher secret key to the given cipher secret key.
*
* @param key
* the given cipher secret key
*
* @throws NullPointerException
* If <code>key == null</code>
*/
public void key(byte[] key) throws NullPointerException {
this.key = SymCipherEng.key(key, this.algo);
}
/**
* @return <code>this.opmode</code>.
*/
public CipherEngUtil.OPMODE FUNC_3() {
return this.VAR_7;
}
/**
* Set the calling object's mode of operation to the given mode of operation.
*
* @param opmode
* the given mode of operation
*
* @throws NullPointerException
* If <code>opmode == null</code>
*/
public void FUNC_3(CipherEngUtil.OPMODE VAR_7) throws NullPointerException {
// The following is meant to be an assignment of this.engine and this.opmode.
try {
this.VAR_3 = CipherEngUtil.FUNC_4(this.algo.FUNC_2(), VAR_7, this.padding);
} catch (NoSuchAlgorithmException | IMPORT_7 ex) {
throw new CLASS_0();
}
this.VAR_7 = VAR_7;
}
/**
* @return <code>this.padding</code>.
*/
public CipherEngUtil.PADDING padding() {
return this.padding;
}
/**
* Set the calling object's padding algorithm to the given padding algorithm.
*
* @param padding
* the given padding algorithm
*
* @throws NullPointerException
* If <code>padding == null</code>
*/
public void padding(CipherEngUtil.PADDING padding) throws NullPointerException {
// The following is meant to be an assignment of this.engine, and this.padding.
try {
this.VAR_3 = CipherEngUtil.FUNC_4(this.algo.FUNC_2(), this.VAR_7, padding);
} catch (NoSuchAlgorithmException | IMPORT_7 ex) {
throw new CLASS_0();
}
this.padding = padding;
}
/**
* <code>this.iv = null</code>.
*/
public void ivReset() {
this.iv = null;
}
/**
* Set the calling object's initialization vector to the given initialization vector.
*
* @param iv
* the given initialization vector
*
* @throws NullPointerException
* If <code>iv == null</code>
*/
public void iv(byte[] iv) throws NullPointerException {
if (iv == null) {
throw new NullPointerException();
}
this.iv = new IvParameterSpec(iv);
}
/**
* Since Cipher, SecretKey, and IvParameterSpec do not redeclare toString, hashCode, and equals then
* neither will SymCipherEng.
*/
/**
* Encrypt the given plaintext byte array.
*
* @param p
* the given plaintext byte array
*
* @return The encrypted ciphertext byte array.
*
* @throws NullPointerException
* If <code>p == null</code>
*
* @throws InvalidKeyException
* Thrown by <code>Cipher.init(Cipher.ENCRYPT_MODE, this.key)</code> or
* <code>Cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv)</code>
*
* @throws InvalidAlgorithmParameterException
* Thrown by <code>Cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv)</code>
*
* @throws BadPaddingException
* Thrown by <code>Cipher.doFinal(p)</code>
*
* @throws IllegalBlockSizeException
* Thrown by <code>Cipher.doFinal(p)</code>
*/
public byte[] encrypt(byte[] p) throws NullPointerException, InvalidKeyException,
IMPORT_2, IMPORT_6, BadPaddingException {
if (this.iv == null) {
this.VAR_3.FUNC_9(Cipher.ENCRYPT_MODE, this.key);
} else {
this.VAR_3.FUNC_9(Cipher.ENCRYPT_MODE, this.key, this.iv);
}
return this.VAR_3.FUNC_10(p);
}
/**
* Decrypt the given ciphertext byte array.
*
* @param c
* the given ciphertext byte array
*
* @return The decrypted plaintext byte array.
*
* @throws NullPointerException
* If <code>c == null</code>
*
* @throws InvalidKeyException
* Thrown by <code>Cipher.init(Cipher.DECRYPT_MODE, this.key)</code> or
* <code>Cipher.init(Cipher.DECRYPT_MODE, this.key, this.iv)</code>
*
* @throws InvalidAlgorithmParameterException
* Thrown by <code>Cipher.init(Cipher.DECRYPT_MODE, this.key, this.iv)</code>
*
* @throws BadPaddingException
* Thrown by <code>Cipher.doFinal(c)</code>
*
* @throws IllegalBlockSizeException
* Thrown by <code>Cipher.doFinal(c)</code>
*/
public byte[] decrypt(byte[] c) throws NullPointerException, InvalidKeyException,
IMPORT_2, IMPORT_6, BadPaddingException {
if (this.iv == null) {
this.VAR_3.FUNC_9(Cipher.VAR_13, this.key);
} else {
this.VAR_3.FUNC_9(Cipher.VAR_13, this.key, this.iv);
}
return this.VAR_3.FUNC_10(c);
}
}
| 0.460367
|
{'VAR_0': 'util', 'IMPORT_0': 'java', 'IMPORT_1': 'security', 'IMPORT_2': 'InvalidAlgorithmParameterException', 'IMPORT_3': 'SecureRandom', 'IMPORT_4': 'javax', 'IMPORT_5': 'crypto', 'IMPORT_6': 'IllegalBlockSizeException', 'IMPORT_7': 'NoSuchPaddingException', 'VAR_1': 'DES_BLOCK_SIZE', 'VAR_2': 'BLOWFISH_BLOCK_SIZE', 'VAR_3': 'engine', 'VAR_4': 'DES', 'VAR_5': 'DESede', 'VAR_6': 'AES', 'FUNC_0': 'getKeyGenerator', 'FUNC_1': 'getInstance', 'FUNC_2': 'name', 'CLASS_0': 'ExceptionInInitializerError', 'VAR_7': 'opmode', 'FUNC_3': 'opmode', 'FUNC_4': 'getEngine', 'VAR_8': 'DEFAULT_PADDING', 'VAR_9': 'other', 'FUNC_5': 'getIV', 'VAR_10': 'Override', 'FUNC_6': 'clone', 'CLASS_1': 'CloneNotSupportedException', 'FUNC_7': 'finalize', 'VAR_11': 'random', 'FUNC_8': 'values', 'VAR_12': 'index', 'FUNC_9': 'init', 'FUNC_10': 'doFinal', 'VAR_13': 'DECRYPT_MODE'}
|
java
|
OOP
|
100.00%
|
/*
* 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.calcite.plan;
/**
* A <code>CommonRelSubExprRule</code> is an abstract base class for rules
* that are fired only on relational expressions that appear more than once
* in a query tree.
*/
// TODO: obsolete this?
public abstract class CommonRelSubExprRule
extends RelRule<CommonRelSubExprRule.Config> {
//~ Constructors -----------------------------------------------------------
/** Creates a CommonRelSubExprRule. */
protected CommonRelSubExprRule(Config config) {
super(config);
}
@Deprecated // to be removed before 2.0
protected CommonRelSubExprRule(RelOptRuleOperand operand) {
this(Config.EMPTY.withOperandSupplier(b -> b.exactly(operand))
.as(Config.class));
}
/** Rule configuration. */
public interface Config extends RelRule.Config {
}
}
|
/*
* 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.IMPORT_0.calcite.IMPORT_1;
/**
* A <code>CommonRelSubExprRule</code> is an abstract base class for rules
* that are fired only on relational expressions that appear more than once
* in a query tree.
*/
// TODO: obsolete this?
public abstract class CLASS_0
extends RelRule<CLASS_0.CLASS_1> {
//~ Constructors -----------------------------------------------------------
/** Creates a CommonRelSubExprRule. */
protected CLASS_0(CLASS_1 VAR_1) {
super(VAR_1);
}
@VAR_2 // to be removed before 2.0
protected CLASS_0(RelOptRuleOperand operand) {
this(VAR_0.EMPTY.FUNC_0(b -> b.exactly(operand))
.FUNC_1(CLASS_1.class));
}
/** Rule configuration. */
public interface CLASS_1 extends RelRule.CLASS_1 {
}
}
| 0.441092
|
{'IMPORT_0': 'apache', 'IMPORT_1': 'plan', 'CLASS_0': 'CommonRelSubExprRule', 'CLASS_1': 'Config', 'VAR_0': 'Config', 'VAR_1': 'config', 'VAR_2': 'Deprecated', 'FUNC_0': 'withOperandSupplier', 'FUNC_1': 'as'}
|
java
|
Hibrido
|
93.64%
|
package com.smp.soundtouchandroid;
public interface AudioProcessor {
}
|
package IMPORT_0.IMPORT_1.IMPORT_2;
public interface AudioProcessor {
}
| 0.799741
|
{'IMPORT_0': 'com', 'IMPORT_1': 'smp', 'IMPORT_2': 'soundtouchandroid'}
|
java
|
Texto
|
88.89%
|
package jas.spawner.modern.spawner.creature.entry;
import jas.spawner.modern.DefaultProps;
import jas.spawner.modern.MVELProfile;
import jas.spawner.modern.spawner.creature.handler.LivingHandler;
import jas.spawner.modern.spawner.creature.handler.parsing.settings.OptionalSettings.Operand;
import java.io.Serializable;
import java.util.Locale;
import net.minecraft.util.WeightedRandom;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import org.mvel2.MVEL;
import com.google.common.base.Optional;
/**
* Every SpawnListEntry is assumed Unique for a EntityLivingClass given biome Spawn.
*
* It should be noted that Technically, f(Class, Biome, CreatureType) --> SpawnList, but since f(Class) --> CreatureType
* then f(Class, Biome) --> SpawnList
*/
// TODO: Large Constructor could probably use Factory / Or Split packSize into Its Own Immutable Class
public class SpawnListEntry extends WeightedRandom.Item {
public final String livingGroupID;
public final int packSize;
/* Refers to BiomeGroup or StructureGroup */
public final String locationGroup;
public final int minChunkPack;
public final int maxChunkPack;
public final String spawnExpression;
public final String postspawnExpression;
public final Optional<Operand> spawnOperand;
private Optional<Serializable> compSpawnExpression;
private Optional<Serializable> compPostSpawnExpression;
public Optional<Serializable> getOptionalSpawning() {
return compSpawnExpression;
}
public Optional<Serializable> getOptionalPostSpawning() {
return compPostSpawnExpression;
}
public static final String SpawnListCategoryComment = "Editable Format: SpawnWeight" + DefaultProps.DELIMETER
+ "SpawnPackSize" + DefaultProps.DELIMETER + "MinChunkPackSize" + DefaultProps.DELIMETER
+ "MaxChunkPackSize";
public SpawnListEntry(SpawnListEntryBuilder builder) {
super(builder.getWeight());
this.livingGroupID = builder.getLivingGroupId();
this.packSize = builder.getPackSize();
this.locationGroup = builder.getLocationGroupId();
this.minChunkPack = builder.getMinChunkPack();
this.maxChunkPack = builder.getMaxChunkPack();
this.spawnOperand = builder.getSpawnOperand();
this.spawnExpression = builder.getSpawnExpression();
this.postspawnExpression = builder.getPostSpawnExpression();
this.compSpawnExpression = !spawnExpression.trim().equals("") ? Optional.of(MVEL
.compileExpression(spawnExpression)) : Optional.<Serializable> absent();
this.compPostSpawnExpression = !postspawnExpression.trim().equals("") ? Optional.of(MVEL
.compileExpression(postspawnExpression)) : Optional.<Serializable> absent();
}
// TODO: Remove This. Hidden static dependency bad. Unnecessary. Alternatively, pass in livingHandlerRegistry
public LivingHandler getLivingHandler() {
return MVELProfile.worldSettings().livingHandlerRegistry().getLivingHandler(livingGroupID);
}
public static void setupConfigCategory(Configuration config) {
ConfigCategory category = config.getCategory("CreatureSettings.SpawnListEntry".toLowerCase(Locale.ENGLISH));
category.setComment(SpawnListEntry.SpawnListCategoryComment);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((locationGroup == null) ? 0 : locationGroup.hashCode());
result = prime * result + ((livingGroupID == null) ? 0 : livingGroupID.hashCode());
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other == null || getClass() != other.getClass()) {
return false;
}
SpawnListEntry otherEntry = (SpawnListEntry) other;
return locationGroup.equals(otherEntry.locationGroup) && livingGroupID.equals(otherEntry.livingGroupID);
}
}
|
package jas.spawner.modern.spawner.IMPORT_0.entry;
import jas.spawner.modern.DefaultProps;
import jas.spawner.modern.IMPORT_1;
import jas.spawner.modern.spawner.IMPORT_0.handler.LivingHandler;
import jas.spawner.modern.spawner.IMPORT_0.handler.parsing.settings.OptionalSettings.Operand;
import java.io.Serializable;
import java.IMPORT_2.Locale;
import net.minecraft.IMPORT_2.WeightedRandom;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import org.mvel2.MVEL;
import com.google.common.base.Optional;
/**
* Every SpawnListEntry is assumed Unique for a EntityLivingClass given biome Spawn.
*
* It should be noted that Technically, f(Class, Biome, CreatureType) --> SpawnList, but since f(Class) --> CreatureType
* then f(Class, Biome) --> SpawnList
*/
// TODO: Large Constructor could probably use Factory / Or Split packSize into Its Own Immutable Class
public class SpawnListEntry extends WeightedRandom.Item {
public final String livingGroupID;
public final int VAR_0;
/* Refers to BiomeGroup or StructureGroup */
public final String locationGroup;
public final int minChunkPack;
public final int maxChunkPack;
public final String spawnExpression;
public final String postspawnExpression;
public final Optional<Operand> spawnOperand;
private Optional<Serializable> compSpawnExpression;
private Optional<Serializable> compPostSpawnExpression;
public Optional<Serializable> FUNC_0() {
return compSpawnExpression;
}
public Optional<Serializable> getOptionalPostSpawning() {
return compPostSpawnExpression;
}
public static final String SpawnListCategoryComment = "Editable Format: SpawnWeight" + DefaultProps.DELIMETER
+ "SpawnPackSize" + DefaultProps.DELIMETER + "MinChunkPackSize" + DefaultProps.DELIMETER
+ "MaxChunkPackSize";
public SpawnListEntry(CLASS_0 builder) {
super(builder.getWeight());
this.livingGroupID = builder.getLivingGroupId();
this.VAR_0 = builder.getPackSize();
this.locationGroup = builder.getLocationGroupId();
this.minChunkPack = builder.getMinChunkPack();
this.maxChunkPack = builder.getMaxChunkPack();
this.spawnOperand = builder.getSpawnOperand();
this.spawnExpression = builder.getSpawnExpression();
this.postspawnExpression = builder.getPostSpawnExpression();
this.compSpawnExpression = !spawnExpression.trim().equals("") ? Optional.of(MVEL
.compileExpression(spawnExpression)) : Optional.<Serializable> absent();
this.compPostSpawnExpression = !postspawnExpression.trim().equals("") ? Optional.of(MVEL
.compileExpression(postspawnExpression)) : Optional.<Serializable> absent();
}
// TODO: Remove This. Hidden static dependency bad. Unnecessary. Alternatively, pass in livingHandlerRegistry
public LivingHandler getLivingHandler() {
return IMPORT_1.worldSettings().livingHandlerRegistry().getLivingHandler(livingGroupID);
}
public static void setupConfigCategory(Configuration config) {
ConfigCategory category = config.getCategory("CreatureSettings.SpawnListEntry".toLowerCase(Locale.ENGLISH));
category.setComment(SpawnListEntry.SpawnListCategoryComment);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((locationGroup == null) ? 0 : locationGroup.hashCode());
result = prime * result + ((livingGroupID == null) ? 0 : livingGroupID.hashCode());
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other == null || getClass() != other.getClass()) {
return false;
}
SpawnListEntry otherEntry = (SpawnListEntry) other;
return locationGroup.equals(otherEntry.locationGroup) && livingGroupID.equals(otherEntry.livingGroupID);
}
}
| 0.039925
|
{'IMPORT_0': 'creature', 'IMPORT_1': 'MVELProfile', 'IMPORT_2': 'util', 'VAR_0': 'packSize', 'FUNC_0': 'getOptionalSpawning', 'CLASS_0': 'SpawnListEntryBuilder'}
|
java
|
Hibrido
|
100.00%
|
/*
* 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.citrusframework.yaks.testcontainers;
import com.consol.citrus.Citrus;
import com.consol.citrus.TestCaseRunner;
import com.consol.citrus.annotations.CitrusFramework;
import com.consol.citrus.annotations.CitrusResource;
import com.consol.citrus.context.TestContext;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import io.cucumber.java.en.Given;
import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.utility.DockerImageName;
import static com.consol.citrus.container.FinallySequence.Builder.doFinally;
public class MongoDBSteps {
@CitrusFramework
private Citrus citrus;
@CitrusResource
private TestCaseRunner runner;
@CitrusResource
private TestContext context;
private String mongoDBVersion = TestContainersSettings.getMongoDBVersion();
private MongoDBContainer mongoDBContainer;
@Before
public void before(Scenario scenario) {
if (mongoDBContainer == null && citrus.getCitrusContext().getReferenceResolver().isResolvable(MongoDBContainer.class)) {
mongoDBContainer = citrus.getCitrusContext().getReferenceResolver().resolve("mongoDBContainer", MongoDBContainer.class);
setConnectionSettings(mongoDBContainer, context);
}
}
@Given("^MongoDB version (^\\s+)$")
public void setMongoDBVersion(String version) {
this.mongoDBVersion = version;
}
@Given("^start MongoDB container$")
public void startMongo() {
mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo").withTag(mongoDBVersion));
mongoDBContainer.start();
citrus.getCitrusContext().bind("mongoDBContainer", mongoDBContainer);
setConnectionSettings(mongoDBContainer, context);
if (TestContainersSteps.autoRemoveResources) {
runner.run(doFinally()
.actions(context -> mongoDBContainer.stop()));
}
}
@Given("^stop MongoDB container$")
public void stopMongo() {
if (mongoDBContainer != null) {
mongoDBContainer.stop();
}
}
/**
* Sets the connection settings in current test context in the form of test variables.
* @param mongoDBContainer
* @param context
*/
private void setConnectionSettings(MongoDBContainer mongoDBContainer, TestContext context) {
if (mongoDBContainer.isRunning()) {
String containerId = mongoDBContainer.getContainerId().substring(0, 12);
context.setVariable(TestContainersSteps.TESTCONTAINERS_VARIABLE_PREFIX + "MONGODB_CONTAINER_IP", mongoDBContainer.getContainerIpAddress());
context.setVariable(TestContainersSteps.TESTCONTAINERS_VARIABLE_PREFIX + "MONGODB_CONTAINER_ID", containerId);
context.setVariable(TestContainersSteps.TESTCONTAINERS_VARIABLE_PREFIX + "MONGODB_CONTAINER_NAME", mongoDBContainer.getContainerName());
context.setVariable(TestContainersSteps.TESTCONTAINERS_VARIABLE_PREFIX + "MONGODB_SERVICE_NAME", "kd-" + containerId);
context.setVariable(TestContainersSteps.TESTCONTAINERS_VARIABLE_PREFIX + "MONGODB_URL", mongoDBContainer.getReplicaSetUrl());
}
}
}
|
/*
* 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 IMPORT_0.citrusframework.IMPORT_1.IMPORT_2;
import IMPORT_3.IMPORT_4.citrus.IMPORT_5;
import IMPORT_3.IMPORT_4.citrus.TestCaseRunner;
import IMPORT_3.IMPORT_4.citrus.IMPORT_6.IMPORT_7;
import IMPORT_3.IMPORT_4.citrus.IMPORT_6.CitrusResource;
import IMPORT_3.IMPORT_4.citrus.IMPORT_8.IMPORT_9;
import IMPORT_10.IMPORT_11.IMPORT_12.IMPORT_13;
import IMPORT_10.IMPORT_11.IMPORT_12.IMPORT_14;
import IMPORT_10.IMPORT_11.IMPORT_12.IMPORT_15.IMPORT_16;
import IMPORT_0.IMPORT_2.IMPORT_17.IMPORT_18;
import IMPORT_0.IMPORT_2.IMPORT_19.DockerImageName;
import static IMPORT_3.IMPORT_4.citrus.container.FinallySequence.IMPORT_20.IMPORT_21;
public class CLASS_0 {
@IMPORT_7
private IMPORT_5 citrus;
@CitrusResource
private TestCaseRunner VAR_0;
@CitrusResource
private IMPORT_9 IMPORT_8;
private CLASS_1 VAR_1 = VAR_2.FUNC_0();
private IMPORT_18 mongoDBContainer;
@IMPORT_13
public void FUNC_1(IMPORT_14 VAR_3) {
if (mongoDBContainer == null && citrus.FUNC_2().FUNC_3().FUNC_4(IMPORT_18.class)) {
mongoDBContainer = citrus.FUNC_2().FUNC_3().FUNC_5("mongoDBContainer", IMPORT_18.class);
FUNC_6(mongoDBContainer, IMPORT_8);
}
}
@IMPORT_16("^MongoDB version (^\\s+)$")
public void FUNC_7(CLASS_1 VAR_4) {
this.VAR_1 = VAR_4;
}
@IMPORT_16("^start MongoDB container$")
public void FUNC_8() {
mongoDBContainer = new IMPORT_18(DockerImageName.FUNC_9("mongo").FUNC_10(VAR_1));
mongoDBContainer.FUNC_11();
citrus.FUNC_2().FUNC_12("mongoDBContainer", mongoDBContainer);
FUNC_6(mongoDBContainer, IMPORT_8);
if (VAR_5.VAR_6) {
VAR_0.FUNC_13(IMPORT_21()
.FUNC_14(IMPORT_8 -> mongoDBContainer.stop()));
}
}
@IMPORT_16("^stop MongoDB container$")
public void FUNC_15() {
if (mongoDBContainer != null) {
mongoDBContainer.stop();
}
}
/**
* Sets the connection settings in current test context in the form of test variables.
* @param mongoDBContainer
* @param context
*/
private void FUNC_6(IMPORT_18 mongoDBContainer, IMPORT_9 IMPORT_8) {
if (mongoDBContainer.FUNC_16()) {
CLASS_1 VAR_7 = mongoDBContainer.FUNC_17().substring(0, 12);
IMPORT_8.FUNC_18(VAR_5.VAR_8 + "MONGODB_CONTAINER_IP", mongoDBContainer.FUNC_19());
IMPORT_8.FUNC_18(VAR_5.VAR_8 + "MONGODB_CONTAINER_ID", VAR_7);
IMPORT_8.FUNC_18(VAR_5.VAR_8 + "MONGODB_CONTAINER_NAME", mongoDBContainer.FUNC_20());
IMPORT_8.FUNC_18(VAR_5.VAR_8 + "MONGODB_SERVICE_NAME", "kd-" + VAR_7);
IMPORT_8.FUNC_18(VAR_5.VAR_8 + "MONGODB_URL", mongoDBContainer.FUNC_21());
}
}
}
| 0.887076
|
{'IMPORT_0': 'org', 'IMPORT_1': 'yaks', 'IMPORT_2': 'testcontainers', 'IMPORT_3': 'com', 'IMPORT_4': 'consol', 'IMPORT_5': 'Citrus', 'IMPORT_6': 'annotations', 'IMPORT_7': 'CitrusFramework', 'IMPORT_8': 'context', 'IMPORT_9': 'TestContext', 'IMPORT_10': 'io', 'IMPORT_11': 'cucumber', 'IMPORT_12': 'java', 'IMPORT_13': 'Before', 'IMPORT_14': 'Scenario', 'IMPORT_15': 'en', 'IMPORT_16': 'Given', 'IMPORT_17': 'containers', 'IMPORT_18': 'MongoDBContainer', 'IMPORT_19': 'utility', 'IMPORT_20': 'Builder', 'IMPORT_21': 'doFinally', 'CLASS_0': 'MongoDBSteps', 'VAR_0': 'runner', 'CLASS_1': 'String', 'VAR_1': 'mongoDBVersion', 'VAR_2': 'TestContainersSettings', 'FUNC_0': 'getMongoDBVersion', 'FUNC_1': 'before', 'VAR_3': 'scenario', 'FUNC_2': 'getCitrusContext', 'FUNC_3': 'getReferenceResolver', 'FUNC_4': 'isResolvable', 'FUNC_5': 'resolve', 'FUNC_6': 'setConnectionSettings', 'FUNC_7': 'setMongoDBVersion', 'VAR_4': 'version', 'FUNC_8': 'startMongo', 'FUNC_9': 'parse', 'FUNC_10': 'withTag', 'FUNC_11': 'start', 'FUNC_12': 'bind', 'VAR_5': 'TestContainersSteps', 'VAR_6': 'autoRemoveResources', 'FUNC_13': 'run', 'FUNC_14': 'actions', 'FUNC_15': 'stopMongo', 'FUNC_16': 'isRunning', 'VAR_7': 'containerId', 'FUNC_17': 'getContainerId', 'FUNC_18': 'setVariable', 'VAR_8': 'TESTCONTAINERS_VARIABLE_PREFIX', 'FUNC_19': 'getContainerIpAddress', 'FUNC_20': 'getContainerName', 'FUNC_21': 'getReplicaSetUrl'}
|
java
|
Hibrido
|
68.31%
|
/**
* Includes all of the repository references and common methods to be used.
*/
@Controller
public class CommonController {
@Autowired
protected ProductRepository productRepository;
@Autowired
protected CartRepository cartRepository;
@Autowired
protected VoucherRepository voucherRepository;
@Autowired
protected CommentRepository commentRepository;
@Autowired
protected ReceiptRepository receiptRepository;
@Autowired
protected UserService userService;
/**
* Check if there is a logged in user.
*
* @return boolean
*/
protected boolean isThereLoggedInUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
return false;
}
return true;
}
/**
* Compare currently logged in user's role/authority.
*
* @param roleName - expected role/authority of user.
*
* @return boolean
*/
protected boolean hasRole(String roleName)
{
return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(roleName));
}
/**
* Get currently logged in user's role/authority.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void getUserRole(Model model) {
if (!isThereLoggedInUser()) {
model.addAttribute("userRole", "GUEST");
}
else {
model.addAttribute("userRole", SecurityContextHolder.
getContext().getAuthentication().getAuthorities().toString().replaceAll("[^a-zA-Z0-9]", ""));
}
}
/**
* Get currently logged in user's first and last name.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void getUserFirstAndLastName(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (isThereLoggedInUser()) {
User user = userService.getUserByEmail(authentication.getName()).get();
model.addAttribute("userFirstname", user.getFirstName());
model.addAttribute("userLastname", user.getLastName());
}
}
/**
* Total number of products in currently logged in user's cart.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void getNumberOfProductsInCart(Model model) {
if (isThereLoggedInUser()) {
Cart cart = cartRepository.getCartOfUser();
model.addAttribute("numberOfProductsInCart", cart.getNumberOfProducts());
}
}
/**
* Create a cart and new user voucher.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void createCartAndVoucher(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Get cart but if there is none create new cart for new user
if (cartRepository.getCartOfUser() == null) {
Voucher voucher = new Voucher();
voucher.setVoucherName("New user discount");
voucher.addUserInList(authentication.getName());
voucher.setDescription("20% off on any purchase.");
voucher.setDiscount(20);
voucher.setCreatedAt(LocalDateTime.now());
voucher.setExpiryDate(LocalDateTime.now());
Cart cart = new Cart();
cart.setCartOwner(authentication.getName());
List<Voucher> cartVouchers = new ArrayList<Voucher>();
cartVouchers.add(voucher);
cart.setVouchers(cartVouchers);
cart.setCreatedAt(LocalDateTime.now());
cart.setUpdatedAt(LocalDateTime.now());
voucherRepository.saveAndFlush(voucher);
cartRepository.saveAndFlush(cart);
model.addAttribute("cart", cartRepository.getCartOfUser());
}
else {
Cart cart = cartRepository.getCartOfUser();
Voucher voucher = voucherRepository.getVoucherByName("New user discount");
if (voucher.isUserInList(authentication.getName())) {
List<Voucher> cartVouchers = new ArrayList<Voucher>();
cartVouchers.add(voucher);
cart.setVouchers(cartVouchers);
}
model.addAttribute("cart", cart);
}
}
/**
* Add pages to a view.
*
* @param model - where to pass the attributes.
* @param maxItems - itmes per page.
* @param changePage - page to go to.
* @param newProductList - list divided based on max products.
* @param productsToTransfer - all products based on filters.
*
* @return void
*/
protected void pagination(
Model model, Integer maxItems, Integer changePage,
List<Product> newProductList, List<Product> productsToTransfer) {
int endOfProducts = maxItems * changePage;
double totalPages = productsToTransfer.size() / maxItems;
if ((productsToTransfer.size() % maxItems) > 0 ) {
totalPages = totalPages + 1;
}
model.addAttribute("totalPages" , (int) totalPages);
// When store is at first page
if (changePage == 1) {
for (int i = 0; i < maxItems; i++) {
try {
newProductList.add(productsToTransfer.get(i));
} catch (Exception e) {
break;
}
}
// Avoid showing NEXT when no other pages
if (totalPages != 1 && newProductList.size() != 0) {
model.addAttribute("showNext", true);
}
}
// When it is not in first page
if (changePage > 1) {
for (int i = endOfProducts - maxItems; i < endOfProducts; i++) {
try {
newProductList.add(productsToTransfer.get(i));
} catch (Exception e) {
break;
}
}
if (newProductList.size() != 0) {
model.addAttribute("showBack", true);
}
// Avoid showing NEXT when at last page
if (changePage != totalPages && newProductList.size() != 0) {
model.addAttribute("showNext", true);
}
}
// Get next page after running codes
model.addAttribute("newPage", changePage + 1);
}
}
|
/**
* Includes all of the repository references and common methods to be used.
*/
@Controller
public class CommonController {
@Autowired
protected CLASS_0 VAR_0;
@Autowired
protected CLASS_1 VAR_1;
@Autowired
protected CLASS_2 VAR_2;
@Autowired
protected CLASS_3 VAR_3;
@Autowired
protected ReceiptRepository receiptRepository;
@Autowired
protected CLASS_4 VAR_4;
/**
* Check if there is a logged in user.
*
* @return boolean
*/
protected boolean isThereLoggedInUser() {
CLASS_5 authentication = SecurityContextHolder.FUNC_0().FUNC_1();
if (authentication == null || authentication instanceof CLASS_6) {
return false;
}
return true;
}
/**
* Compare currently logged in user's role/authority.
*
* @param roleName - expected role/authority of user.
*
* @return boolean
*/
protected boolean FUNC_2(CLASS_7 VAR_5)
{
return SecurityContextHolder.FUNC_0().FUNC_1().getAuthorities().FUNC_3()
.FUNC_4(VAR_6 -> VAR_6.getAuthority().FUNC_5(VAR_5));
}
/**
* Get currently logged in user's role/authority.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void FUNC_6(CLASS_8 model) {
if (!isThereLoggedInUser()) {
model.addAttribute("userRole", "GUEST");
}
else {
model.addAttribute("userRole", SecurityContextHolder.
FUNC_0().FUNC_1().getAuthorities().FUNC_7().FUNC_8("[^a-zA-Z0-9]", ""));
}
}
/**
* Get currently logged in user's first and last name.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void FUNC_9(CLASS_8 model) {
CLASS_5 authentication = SecurityContextHolder.FUNC_0().FUNC_1();
if (isThereLoggedInUser()) {
User VAR_7 = VAR_4.FUNC_10(authentication.getName()).FUNC_11();
model.addAttribute("userFirstname", VAR_7.getFirstName());
model.addAttribute("userLastname", VAR_7.getLastName());
}
}
/**
* Total number of products in currently logged in user's cart.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void getNumberOfProductsInCart(CLASS_8 model) {
if (isThereLoggedInUser()) {
CLASS_9 cart = VAR_1.FUNC_12();
model.addAttribute("numberOfProductsInCart", cart.FUNC_13());
}
}
/**
* Create a cart and new user voucher.
*
* @param model - where to pass the attributes.
*
* @return void
*/
protected void FUNC_14(CLASS_8 model) {
CLASS_5 authentication = SecurityContextHolder.FUNC_0().FUNC_1();
// Get cart but if there is none create new cart for new user
if (VAR_1.FUNC_12() == null) {
Voucher VAR_8 = new Voucher();
VAR_8.FUNC_15("New user discount");
VAR_8.FUNC_16(authentication.getName());
VAR_8.FUNC_17("20% off on any purchase.");
VAR_8.FUNC_18(20);
VAR_8.FUNC_19(LocalDateTime.now());
VAR_8.FUNC_20(LocalDateTime.now());
CLASS_9 cart = new CLASS_9();
cart.FUNC_21(authentication.getName());
List<Voucher> cartVouchers = new CLASS_10<Voucher>();
cartVouchers.add(VAR_8);
cart.FUNC_22(cartVouchers);
cart.FUNC_19(LocalDateTime.now());
cart.setUpdatedAt(LocalDateTime.now());
VAR_2.saveAndFlush(VAR_8);
VAR_1.saveAndFlush(cart);
model.addAttribute("cart", VAR_1.FUNC_12());
}
else {
CLASS_9 cart = VAR_1.FUNC_12();
Voucher VAR_8 = VAR_2.getVoucherByName("New user discount");
if (VAR_8.isUserInList(authentication.getName())) {
List<Voucher> cartVouchers = new CLASS_10<Voucher>();
cartVouchers.add(VAR_8);
cart.FUNC_22(cartVouchers);
}
model.addAttribute("cart", cart);
}
}
/**
* Add pages to a view.
*
* @param model - where to pass the attributes.
* @param maxItems - itmes per page.
* @param changePage - page to go to.
* @param newProductList - list divided based on max products.
* @param productsToTransfer - all products based on filters.
*
* @return void
*/
protected void FUNC_23(
CLASS_8 model, CLASS_11 maxItems, CLASS_11 VAR_9,
List<Product> VAR_10, List<Product> VAR_11) {
int VAR_12 = maxItems * VAR_9;
double totalPages = VAR_11.size() / maxItems;
if ((VAR_11.size() % maxItems) > 0 ) {
totalPages = totalPages + 1;
}
model.addAttribute("totalPages" , (int) totalPages);
// When store is at first page
if (VAR_9 == 1) {
for (int VAR_13 = 0; VAR_13 < maxItems; VAR_13++) {
try {
VAR_10.add(VAR_11.FUNC_11(VAR_13));
} catch (CLASS_12 VAR_14) {
break;
}
}
// Avoid showing NEXT when no other pages
if (totalPages != 1 && VAR_10.size() != 0) {
model.addAttribute("showNext", true);
}
}
// When it is not in first page
if (VAR_9 > 1) {
for (int VAR_13 = VAR_12 - maxItems; VAR_13 < VAR_12; VAR_13++) {
try {
VAR_10.add(VAR_11.FUNC_11(VAR_13));
} catch (CLASS_12 VAR_14) {
break;
}
}
if (VAR_10.size() != 0) {
model.addAttribute("showBack", true);
}
// Avoid showing NEXT when at last page
if (VAR_9 != totalPages && VAR_10.size() != 0) {
model.addAttribute("showNext", true);
}
}
// Get next page after running codes
model.addAttribute("newPage", VAR_9 + 1);
}
}
| 0.617625
|
{'CLASS_0': 'ProductRepository', 'VAR_0': 'productRepository', 'CLASS_1': 'CartRepository', 'VAR_1': 'cartRepository', 'CLASS_2': 'VoucherRepository', 'VAR_2': 'voucherRepository', 'CLASS_3': 'CommentRepository', 'VAR_3': 'commentRepository', 'CLASS_4': 'UserService', 'VAR_4': 'userService', 'CLASS_5': 'Authentication', 'FUNC_0': 'getContext', 'FUNC_1': 'getAuthentication', 'CLASS_6': 'AnonymousAuthenticationToken', 'FUNC_2': 'hasRole', 'CLASS_7': 'String', 'VAR_5': 'roleName', 'FUNC_3': 'stream', 'FUNC_4': 'anyMatch', 'VAR_6': 'grantedAuthority', 'FUNC_5': 'equals', 'FUNC_6': 'getUserRole', 'CLASS_8': 'Model', 'FUNC_7': 'toString', 'FUNC_8': 'replaceAll', 'FUNC_9': 'getUserFirstAndLastName', 'VAR_7': 'user', 'FUNC_10': 'getUserByEmail', 'FUNC_11': 'get', 'CLASS_9': 'Cart', 'FUNC_12': 'getCartOfUser', 'FUNC_13': 'getNumberOfProducts', 'FUNC_14': 'createCartAndVoucher', 'VAR_8': 'voucher', 'FUNC_15': 'setVoucherName', 'FUNC_16': 'addUserInList', 'FUNC_17': 'setDescription', 'FUNC_18': 'setDiscount', 'FUNC_19': 'setCreatedAt', 'FUNC_20': 'setExpiryDate', 'FUNC_21': 'setCartOwner', 'CLASS_10': 'ArrayList', 'FUNC_22': 'setVouchers', 'FUNC_23': 'pagination', 'CLASS_11': 'Integer', 'VAR_9': 'changePage', 'VAR_10': 'newProductList', 'VAR_11': 'productsToTransfer', 'VAR_12': 'endOfProducts', 'VAR_13': 'i', 'CLASS_12': 'Exception', 'VAR_14': 'e'}
|
java
|
OOP
|
100.00%
|
package com.example.bikeget;
import java.util.List;
import android.app.Application;
public class BikeList extends Application {
public List<Bike> bikeList = null;
SoapSearchData globalSearchData = null;
public BikeList() {
bikeList = null;
globalSearchData = null;
}
public BikeList(BikeList input, SoapSearchData soapData) {
bikeList = input.bikeList;
globalSearchData = soapData;
}
}
|
package IMPORT_0.example.IMPORT_1;
import java.util.IMPORT_2;
import IMPORT_3.IMPORT_4.Application;
public class CLASS_0 extends Application {
public IMPORT_2<CLASS_1> bikeList = null;
CLASS_2 globalSearchData = null;
public CLASS_0() {
bikeList = null;
globalSearchData = null;
}
public CLASS_0(CLASS_0 VAR_0, CLASS_2 soapData) {
bikeList = VAR_0.bikeList;
globalSearchData = soapData;
}
}
| 0.774953
|
{'IMPORT_0': 'com', 'IMPORT_1': 'bikeget', 'IMPORT_2': 'List', 'IMPORT_3': 'android', 'IMPORT_4': 'app', 'CLASS_0': 'BikeList', 'CLASS_1': 'Bike', 'CLASS_2': 'SoapSearchData', 'VAR_0': 'input'}
|
java
|
OOP
|
100.00%
|
/*
* Copyright 2019 <NAME>
*
* 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.github.vase4kin.teamcityapp.storage;
import androidx.annotation.VisibleForTesting;
import teamcityapp.libraries.storage.models.UserAccount;
/**
* Users factory
*/
public class UsersFactory {
@VisibleForTesting
public static final String GUEST_USER_USER_NAME = "Guest user";
private static final String EMPTY_STRING = "";
static final UserAccount EMPTY_USER = new UserAccount(EMPTY_STRING, EMPTY_STRING, EMPTY_STRING.getBytes(), true, true);
/**
* @return Guest user
*/
static UserAccount guestUser(String serverUrl) {
return new UserAccount(serverUrl, GUEST_USER_USER_NAME, EMPTY_STRING.getBytes(), true, true);
}
/**
* @return Registered user
*/
static UserAccount user(String serverUrl, String userName, byte[] password) {
return new UserAccount(serverUrl, userName, password, false, true);
}
/**
* @return User for equal operations
*/
static UserAccount user(String serverUrl, String userName) {
return new UserAccount(serverUrl, userName, EMPTY_STRING.getBytes(), false, true);
}
/**
* @return Registered user with decrypted password
*/
static UserAccount user(UserAccount userAccount, byte[] decryptedPassword) {
return new UserAccount(
userAccount.getTeamcityUrl(),
userAccount.getUserName(),
decryptedPassword,
userAccount.isGuestUser(),
userAccount.isActive());
}
}
|
/*
* Copyright 2019 <NAME>
*
* 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.github.vase4kin.teamcityapp.storage;
import androidx.annotation.VisibleForTesting;
import teamcityapp.libraries.storage.models.UserAccount;
/**
* Users factory
*/
public class UsersFactory {
@VisibleForTesting
public static final String GUEST_USER_USER_NAME = "Guest user";
private static final String EMPTY_STRING = "";
static final UserAccount EMPTY_USER = new UserAccount(EMPTY_STRING, EMPTY_STRING, EMPTY_STRING.getBytes(), true, true);
/**
* @return Guest user
*/
static UserAccount guestUser(String serverUrl) {
return new UserAccount(serverUrl, GUEST_USER_USER_NAME, EMPTY_STRING.getBytes(), true, true);
}
/**
* @return Registered user
*/
static UserAccount user(String serverUrl, String userName, byte[] password) {
return new UserAccount(serverUrl, userName, password, false, true);
}
/**
* @return User for equal operations
*/
static UserAccount user(String serverUrl, String userName) {
return new UserAccount(serverUrl, userName, EMPTY_STRING.getBytes(), false, true);
}
/**
* @return Registered user with decrypted password
*/
static UserAccount user(UserAccount userAccount, byte[] decryptedPassword) {
return new UserAccount(
userAccount.getTeamcityUrl(),
userAccount.getUserName(),
decryptedPassword,
userAccount.isGuestUser(),
userAccount.isActive());
}
}
| 0.054459
|
{}
|
java
|
Hibrido
|
100.00%
|
package com.yo.algorithm.practise.cig.chapter_02_linkedlist.problem_12_reverseknodeslinkedlist.test;
import com.yo.algorithm.practise.cig.common.entity.SingleNode;
import static com.yo.algorithm.practise.cig.chapter_02_linkedlist.problem_12_reverseknodeslinkedlist.impl.ReverseKNodesLinkedList.reverseKNodes2;
import static com.yo.algorithm.practise.cig.common.util.LinkedListUtil.printLinkedList;
/**
* 测试 - 反转链表中的每k个节点
*/
public class TestReverseKNodesLinkedList {
public static void main(String[] args) {
SingleNode head = null;
int K = 3;
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
System.out.println("=======================");
head = new SingleNode(1);
K = 3;
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
System.out.println("=======================");
head = new SingleNode(1);
head.next = new SingleNode(2);
K = 2;
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
System.out.println("=======================");
head = new SingleNode(1);
head.next = new SingleNode(2);
K = 3;
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
System.out.println("=======================");
head = new SingleNode(1);
head.next = new SingleNode(2);
head.next.next = new SingleNode(3);
head.next.next.next = new SingleNode(4);
K = 2;
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
System.out.println("=======================");
head = new SingleNode(1);
head.next = new SingleNode(2);
head.next.next = new SingleNode(3);
head.next.next.next = new SingleNode(4);
head.next.next.next.next = new SingleNode(5);
head.next.next.next.next.next = new SingleNode(6);
head.next.next.next.next.next.next = new SingleNode(7);
head.next.next.next.next.next.next.next = new SingleNode(8);
K = 3;
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
head = reverseKNodes2(head, K);
printLinkedList(head);
System.out.println("=======================");
}
}
|
package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_6.test;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_7.IMPORT_8.SingleNode;
import static IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.IMPORT_6.IMPORT_9.IMPORT_10.IMPORT_11;
import static IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_7.IMPORT_12.IMPORT_13.printLinkedList;
/**
* 测试 - 反转链表中的每k个节点
*/
public class CLASS_0 {
public static void FUNC_0(CLASS_1[] VAR_0) {
SingleNode VAR_1 = null;
int VAR_2 = 3;
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
System.VAR_3.FUNC_1("=======================");
VAR_1 = new SingleNode(1);
VAR_2 = 3;
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
System.VAR_3.FUNC_1("=======================");
VAR_1 = new SingleNode(1);
VAR_1.VAR_4 = new SingleNode(2);
VAR_2 = 2;
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
System.VAR_3.FUNC_1("=======================");
VAR_1 = new SingleNode(1);
VAR_1.VAR_4 = new SingleNode(2);
VAR_2 = 3;
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
System.VAR_3.FUNC_1("=======================");
VAR_1 = new SingleNode(1);
VAR_1.VAR_4 = new SingleNode(2);
VAR_1.VAR_4.VAR_4 = new SingleNode(3);
VAR_1.VAR_4.VAR_4.VAR_4 = new SingleNode(4);
VAR_2 = 2;
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
System.VAR_3.FUNC_1("=======================");
VAR_1 = new SingleNode(1);
VAR_1.VAR_4 = new SingleNode(2);
VAR_1.VAR_4.VAR_4 = new SingleNode(3);
VAR_1.VAR_4.VAR_4.VAR_4 = new SingleNode(4);
VAR_1.VAR_4.VAR_4.VAR_4.VAR_4 = new SingleNode(5);
VAR_1.VAR_4.VAR_4.VAR_4.VAR_4.VAR_4 = new SingleNode(6);
VAR_1.VAR_4.VAR_4.VAR_4.VAR_4.VAR_4.VAR_4 = new SingleNode(7);
VAR_1.VAR_4.VAR_4.VAR_4.VAR_4.VAR_4.VAR_4.VAR_4 = new SingleNode(8);
VAR_2 = 3;
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
VAR_1 = IMPORT_11(VAR_1, VAR_2);
printLinkedList(VAR_1);
System.VAR_3.FUNC_1("=======================");
}
}
| 0.820093
|
{'IMPORT_0': 'com', 'IMPORT_1': 'yo', 'IMPORT_2': 'algorithm', 'IMPORT_3': 'practise', 'IMPORT_4': 'cig', 'IMPORT_5': 'chapter_02_linkedlist', 'IMPORT_6': 'problem_12_reverseknodeslinkedlist', 'IMPORT_7': 'common', 'IMPORT_8': 'entity', 'IMPORT_9': 'impl', 'IMPORT_10': 'ReverseKNodesLinkedList', 'IMPORT_11': 'reverseKNodes2', 'IMPORT_12': 'util', 'IMPORT_13': 'LinkedListUtil', 'CLASS_0': 'TestReverseKNodesLinkedList', 'FUNC_0': 'main', 'CLASS_1': 'String', 'VAR_0': 'args', 'VAR_1': 'head', 'VAR_2': 'K', 'VAR_3': 'out', 'FUNC_1': 'println', 'VAR_4': 'next'}
|
java
|
OOP
|
100.00%
|
/**
*
* @author Brian S O'Neill
*/
public class NameValuePair<T> implements Comparable<NameValuePair<T>>, java.io.Serializable {
private static final long serialVersionUID = 1L;
private String mName;
private T mValue;
public NameValuePair(String name, T value) {
mName = name;
mValue = value;
}
public NameValuePair(Map.Entry<String, T> entry) {
mName = entry.getKey();
mValue = entry.getValue();
}
public final String getName() {
return mName;
}
public final T getValue() {
return mValue;
}
@SuppressWarnings("rawtypes")
public boolean equals(Object other) {
if (other instanceof NameValuePair) {
NameValuePair<?> pair = (NameValuePair) other;
if (getName() == null) {
if (pair.getName() != null) {
return false;
}
}
else {
if (!getName().equals(pair.getName())) {
return false;
}
}
if (getValue() == null) {
if (pair.getValue() != null) {
return false;
}
}
else {
if (!getValue().equals(pair.getValue())) {
return false;
}
}
return true;
}
return false;
}
public int hashCode() {
return (mName.hashCode() ^ 17) & (mValue.hashCode() ^ 11);
}
public String toString() {
return getName() + '=' + getValue();
}
/**
* Comparison is based on case-insensitive ordering of "name".
*/
public int compareTo(NameValuePair<T> other) {
String otherName = other.mName;
if (mName == null) {
return otherName == null ? 0 : 1;
}
if (otherName == null) {
return -1;
}
return mName.compareToIgnoreCase(otherName);
}
}
|
/**
*
* @author Brian S O'Neill
*/
public class CLASS_0<CLASS_1> implements Comparable<CLASS_0<CLASS_1>>, java.io.Serializable {
private static final long VAR_0 = 1L;
private String mName;
private CLASS_1 mValue;
public CLASS_0(String name, CLASS_1 VAR_1) {
mName = name;
mValue = VAR_1;
}
public CLASS_0(Map.CLASS_2<String, CLASS_1> entry) {
mName = entry.FUNC_0();
mValue = entry.getValue();
}
public final String FUNC_1() {
return mName;
}
public final CLASS_1 getValue() {
return mValue;
}
@SuppressWarnings("rawtypes")
public boolean FUNC_2(Object other) {
if (other instanceof CLASS_0) {
CLASS_0<?> pair = (CLASS_0) other;
if (FUNC_1() == null) {
if (pair.FUNC_1() != null) {
return false;
}
}
else {
if (!FUNC_1().FUNC_2(pair.FUNC_1())) {
return false;
}
}
if (getValue() == null) {
if (pair.getValue() != null) {
return false;
}
}
else {
if (!getValue().FUNC_2(pair.getValue())) {
return false;
}
}
return true;
}
return false;
}
public int hashCode() {
return (mName.hashCode() ^ 17) & (mValue.hashCode() ^ 11);
}
public String toString() {
return FUNC_1() + '=' + getValue();
}
/**
* Comparison is based on case-insensitive ordering of "name".
*/
public int compareTo(CLASS_0<CLASS_1> other) {
String otherName = other.mName;
if (mName == null) {
return otherName == null ? 0 : 1;
}
if (otherName == null) {
return -1;
}
return mName.compareToIgnoreCase(otherName);
}
}
| 0.282591
|
{'CLASS_0': 'NameValuePair', 'CLASS_1': 'T', 'VAR_0': 'serialVersionUID', 'VAR_1': 'value', 'CLASS_2': 'Entry', 'FUNC_0': 'getKey', 'FUNC_1': 'getName', 'FUNC_2': 'equals'}
|
java
|
OOP
|
100.00%
|
// CConfidentialValue size 9, prefixA 8, prefixB 9
protected byte[] readConfidentialValue() {
byte[] versionByte = readBytes(1);
int versionInt = versionByte[0] & 0xFF;
if (versionInt == 1 || versionInt == 0xff) {
return Utils.concatenateArrays(
versionByte,
readBytes(CONFIDENTIAL_VALUE - 1)
);
}
else if (versionInt == 8 || versionInt == 9) {
return Utils.concatenateArrays(
versionByte,
readBytes(CONFIDENTIAL_COMMITMENT - 1)
);
}
return versionByte;
}
|
// CConfidentialValue size 9, prefixA 8, prefixB 9
protected byte[] FUNC_0() {
byte[] VAR_0 = FUNC_1(1);
int versionInt = VAR_0[0] & 0xFF;
if (versionInt == 1 || versionInt == 0xff) {
return VAR_1.FUNC_2(
VAR_0,
FUNC_1(VAR_2 - 1)
);
}
else if (versionInt == 8 || versionInt == 9) {
return VAR_1.FUNC_2(
VAR_0,
FUNC_1(VAR_3 - 1)
);
}
return VAR_0;
}
| 0.774786
|
{'FUNC_0': 'readConfidentialValue', 'VAR_0': 'versionByte', 'FUNC_1': 'readBytes', 'VAR_1': 'Utils', 'FUNC_2': 'concatenateArrays', 'VAR_2': 'CONFIDENTIAL_VALUE', 'VAR_3': 'CONFIDENTIAL_COMMITMENT'}
|
java
|
Procedural
|
100.00%
|
package org.sasanlabs.vulnerabilities.fileupload.service;
import static org.sasanlabs.framework.VulnerableAppConstants.JSP_EXTENSIONS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.sasanlabs.framework.VulnerableAppException;
import org.sasanlabs.framework.i18n.Messages;
import org.sasanlabs.vulnerableapp.facade.schema.Variant;
import org.sasanlabs.vulnerableapp.facade.schema.VulnerabilityLevelDefinition;
import org.sasanlabs.vulnerableapp.facade.schema.VulnerabilityLevelHint;
import org.sasanlabs.vulnerableapp.facade.schema.VulnerabilityType;
public class FileUploadLevel6 extends FileUploadLevel2 {
private static final String LEVEL = "LEVEL_6";
@Override
public VulnerabilityLevelDefinition getVulnerabilityLevelDefinition() {
List<VulnerabilityLevelHint> hints = new ArrayList<VulnerabilityLevelHint>();
hints.add(
new VulnerabilityLevelHint(
Collections.singletonList(
new VulnerabilityType("Custom", "UnrestrictedFileUpload")),
Messages.getMessage("FILE_UPLOAD_VULNERABLE_DOUBLE_EXTENSION")));
return AbstractFileUpload.getFileUploadVulnerabilityLevelDefinition(
LEVEL, "", Variant.UNSECURE, hints);
}
@Override
public boolean validate(FileItem fileItem) throws VulnerableAppException {
String fileName = fileItem.getName();
int index = fileName.indexOf(".");
String extension = fileName.substring(index + 1);
if (JSP_EXTENSIONS.contains(extension)) {
return false;
}
return super.validate(fileItem);
}
}
|
package org.sasanlabs.IMPORT_0.IMPORT_1.IMPORT_2;
import static org.sasanlabs.IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_6.util.IMPORT_7;
import IMPORT_6.util.IMPORT_8;
import IMPORT_6.util.List;
import org.IMPORT_9.IMPORT_10.IMPORT_1.IMPORT_11;
import org.sasanlabs.IMPORT_3.VulnerableAppException;
import org.sasanlabs.IMPORT_3.IMPORT_12.IMPORT_13;
import org.sasanlabs.IMPORT_14.IMPORT_15.IMPORT_16.IMPORT_17;
import org.sasanlabs.IMPORT_14.IMPORT_15.IMPORT_16.IMPORT_18;
import org.sasanlabs.IMPORT_14.IMPORT_15.IMPORT_16.IMPORT_19;
import org.sasanlabs.IMPORT_14.IMPORT_15.IMPORT_16.IMPORT_20;
public class CLASS_0 extends CLASS_1 {
private static final CLASS_2 VAR_0 = "LEVEL_6";
@VAR_1
public IMPORT_18 getVulnerabilityLevelDefinition() {
List<IMPORT_19> VAR_2 = new IMPORT_7<IMPORT_19>();
VAR_2.add(
new IMPORT_19(
IMPORT_8.FUNC_0(
new IMPORT_20("Custom", "UnrestrictedFileUpload")),
IMPORT_13.FUNC_1("FILE_UPLOAD_VULNERABLE_DOUBLE_EXTENSION")));
return VAR_3.FUNC_2(
VAR_0, "", IMPORT_17.VAR_4, VAR_2);
}
@VAR_1
public boolean validate(IMPORT_11 VAR_5) throws VulnerableAppException {
CLASS_2 VAR_6 = VAR_5.FUNC_3();
int VAR_7 = VAR_6.FUNC_4(".");
CLASS_2 VAR_8 = VAR_6.FUNC_5(VAR_7 + 1);
if (IMPORT_5.FUNC_6(VAR_8)) {
return false;
}
return super.validate(VAR_5);
}
}
| 0.755145
|
{'IMPORT_0': 'vulnerabilities', 'IMPORT_1': 'fileupload', 'IMPORT_2': 'service', 'IMPORT_3': 'framework', 'IMPORT_4': 'VulnerableAppConstants', 'IMPORT_5': 'JSP_EXTENSIONS', 'IMPORT_6': 'java', 'IMPORT_7': 'ArrayList', 'IMPORT_8': 'Collections', 'IMPORT_9': 'apache', 'IMPORT_10': 'commons', 'IMPORT_11': 'FileItem', 'IMPORT_12': 'i18n', 'IMPORT_13': 'Messages', 'IMPORT_14': 'vulnerableapp', 'IMPORT_15': 'facade', 'IMPORT_16': 'schema', 'IMPORT_17': 'Variant', 'IMPORT_18': 'VulnerabilityLevelDefinition', 'IMPORT_19': 'VulnerabilityLevelHint', 'IMPORT_20': 'VulnerabilityType', 'CLASS_0': 'FileUploadLevel6', 'CLASS_1': 'FileUploadLevel2', 'CLASS_2': 'String', 'VAR_0': 'LEVEL', 'VAR_1': 'Override', 'VAR_2': 'hints', 'FUNC_0': 'singletonList', 'FUNC_1': 'getMessage', 'VAR_3': 'AbstractFileUpload', 'FUNC_2': 'getFileUploadVulnerabilityLevelDefinition', 'VAR_4': 'UNSECURE', 'VAR_5': 'fileItem', 'VAR_6': 'fileName', 'FUNC_3': 'getName', 'VAR_7': 'index', 'FUNC_4': 'indexOf', 'VAR_8': 'extension', 'FUNC_5': 'substring', 'FUNC_6': 'contains'}
|
java
|
OOP
|
100.00%
|
/**
* This is actually a utility program, rather than a test class.
* It converts BP SQL files and earlier-format Tiger model files
* to latest-format Tiger model files.
* To use this program:
*
* 1) Create a new JUnit plug-in test debug configuration, pointing
* at this class
* 2) Place the files to be converted in the root of the workspace
* you associate with the above debug configuration;
* also, create a folder called "converted" in that root
* 3) Run the debug configuration
*
* The converted model files will be written to the "converted" folder
* in the workspace root.
*
* The JUnit TestCase is employed here merely as a wrapper which
* provides integration with the other plug-ins referenced by this
* class's parent plug-in.
*/
public class ConvertModels extends TestCase
{
@Test
public void testConvertModels() throws Exception
{
//removed after io.sql removal
}
}
|
/**
* This is actually a utility program, rather than a test class.
* It converts BP SQL files and earlier-format Tiger model files
* to latest-format Tiger model files.
* To use this program:
*
* 1) Create a new JUnit plug-in test debug configuration, pointing
* at this class
* 2) Place the files to be converted in the root of the workspace
* you associate with the above debug configuration;
* also, create a folder called "converted" in that root
* 3) Run the debug configuration
*
* The converted model files will be written to the "converted" folder
* in the workspace root.
*
* The JUnit TestCase is employed here merely as a wrapper which
* provides integration with the other plug-ins referenced by this
* class's parent plug-in.
*/
public class ConvertModels extends TestCase
{
@Test
public void testConvertModels() throws Exception
{
//removed after io.sql removal
}
}
| 0.103853
|
{}
|
java
|
OOP
|
23.40%
|
package com.example.test;
import com.alibaba.druid.pool.DruidDataSource;
import com.example.config.SpringConfiguration;
import com.example.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DruidDataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}
|
package com.example.test;
import com.alibaba.druid.pool.DruidDataSource;
import com.example.config.SpringConfiguration;
import com.example.service.UserService;
import org.junit.IMPORT_0;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.IMPORT_1;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration("classpath:applicationContext.xml")
@IMPORT_1(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DruidDataSource VAR_0;
@IMPORT_0
public void test1() throws SQLException {
userService.save();
System.out.println(VAR_0.getConnection());
}
}
| 0.08366
|
{'IMPORT_0': 'Test', 'IMPORT_1': 'ContextConfiguration', 'VAR_0': 'dataSource'}
|
java
|
Procedural
|
54.29%
|
/*
* Copyright 2015-2017 OpenCB
*
* 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.opencb.opencga.core.config;
import java.util.Collections;
import java.util.Map;
/**
* Created by pfurio on 02/09/16.
*/
public class AuthenticationOrigin {
private String id;
private AuthenticationType type;
private String host;
private Map<String, Object> options;
public enum AuthenticationType {
OPENCGA,
LDAP
}
// Possible keys of the options map
public static final String USERS_SEARCH = "usersSearch";
public static final String GROUPS_SEARCH = "groupsSearch";
public AuthenticationOrigin() {
this("internal", AuthenticationType.OPENCGA.name(), "localhost", Collections.emptyMap());
}
public AuthenticationOrigin(String id, String type, String host, Map<String, Object> options) {
this.id = id;
this.type = AuthenticationType.valueOf(type);
this.host = host;
this.options = options;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Auth{");
sb.append("id='").append(id).append('\'');
sb.append(", type='").append(type).append('\'');
sb.append(", host='").append(host).append('\'');
sb.append(", options=").append(options);
sb.append('}');
return sb.toString();
}
public String getId() {
return id;
}
public AuthenticationOrigin setId(String id) {
this.id = id;
return this;
}
public AuthenticationType getType() {
return type;
}
public AuthenticationOrigin setType(AuthenticationType type) {
this.type = type;
return this;
}
public String getHost() {
return host;
}
public AuthenticationOrigin setHost(String host) {
this.host = host;
return this;
}
public Map<String, Object> getOptions() {
return options;
}
public AuthenticationOrigin setOptions(Map<String, Object> options) {
this.options = options;
return this;
}
}
|
/*
* Copyright 2015-2017 OpenCB
*
* 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 IMPORT_0.opencb.opencga.core.config;
import java.util.IMPORT_1;
import java.util.Map;
/**
* Created by pfurio on 02/09/16.
*/
public class AuthenticationOrigin {
private String id;
private AuthenticationType type;
private String host;
private Map<String, CLASS_0> options;
public enum AuthenticationType {
OPENCGA,
LDAP
}
// Possible keys of the options map
public static final String USERS_SEARCH = "usersSearch";
public static final String GROUPS_SEARCH = "groupsSearch";
public AuthenticationOrigin() {
this("internal", AuthenticationType.OPENCGA.name(), "localhost", IMPORT_1.emptyMap());
}
public AuthenticationOrigin(String id, String type, String host, Map<String, CLASS_0> options) {
this.id = id;
this.type = AuthenticationType.valueOf(type);
this.host = host;
this.options = options;
}
@Override
public String toString() {
final StringBuilder VAR_0 = new StringBuilder("Auth{");
VAR_0.FUNC_0("id='").FUNC_0(id).FUNC_0('\'');
VAR_0.FUNC_0(", type='").FUNC_0(type).FUNC_0('\'');
VAR_0.FUNC_0(", host='").FUNC_0(host).FUNC_0('\'');
VAR_0.FUNC_0(", options=").FUNC_0(options);
VAR_0.FUNC_0('}');
return VAR_0.toString();
}
public String getId() {
return id;
}
public AuthenticationOrigin setId(String id) {
this.id = id;
return this;
}
public AuthenticationType getType() {
return type;
}
public AuthenticationOrigin setType(AuthenticationType type) {
this.type = type;
return this;
}
public String getHost() {
return host;
}
public AuthenticationOrigin setHost(String host) {
this.host = host;
return this;
}
public Map<String, CLASS_0> getOptions() {
return options;
}
public AuthenticationOrigin setOptions(Map<String, CLASS_0> options) {
this.options = options;
return this;
}
}
| 0.186824
|
{'IMPORT_0': 'org', 'IMPORT_1': 'Collections', 'CLASS_0': 'Object', 'VAR_0': 'sb', 'FUNC_0': 'append'}
|
java
|
Hibrido
|
70.70%
|
package ru.job4j.threadpool;
/**
* класс для тестирован я класса ThreadPool.
* реализует отдельный поток, котрый выводит свой номер
*/
public class Work implements Runnable {
/**
* номер потока
*/
private int number;
/**
* конструктор
*
* @param number - номер
*/
Work(int number) {
this.number = number;
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
System.out.printf("Поток номер %d начал работу\n", number);
}
}
|
package ru.job4j.threadpool;
/**
* класс для тестирован я класса ThreadPool.
* реализует отдельный поток, котрый выводит свой номер
*/
public class Work implements Runnable {
/**
* номер потока
*/
private int number;
/**
* конструктор
*
* @param number - номер
*/
Work(int number) {
this.number = number;
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
System.out.printf("Поток номер %d начал работу\n", number);
}
}
| 0.002234
|
{}
|
java
|
OOP
|
100.00%
|
package com.coxautodev.graphql.tools.example.types;
public enum Episode {
NEWHOPE,
EMPIRE,
JEDI
}
|
package com.coxautodev.graphql.tools.IMPORT_0.IMPORT_1;
public enum Episode {
VAR_0,
EMPIRE,
VAR_1
}
| 0.372943
|
{'IMPORT_0': 'example', 'IMPORT_1': 'types', 'VAR_0': 'NEWHOPE', 'VAR_1': 'JEDI'}
|
java
|
Texto
|
73.33%
|
/**
* Thread for the connected user.
*/
public class ChatServerThread extends Thread {
public User user;
public ChatServerThread(Socket socket) {
user = new User(socket);
}
public void run() {
try {
// Check if user can join
authenticate();
// Send server info to user
sendMessageToUser("** "+ "Server name: " + ChatServer.serverSettings.getName());
sendMessageToUser("** Server description: "+ChatServer.serverSettings.getDescription());
sendMessageToUser("** Server rules: "+ChatServer.serverSettings.getRules());
sendMessageToUser("** Server message of the day: " + serverSettings.getMotd());
sendMessageToUser("Type /help to see available commands.");
sendMessageToUser(" ");
System.out.println(user.getName()+":"+user.getSocket().getInetAddress().getHostAddress()+" joined the server");
// Start communication loop
while(true) {
if(user.getSocket().isClosed()) {
break;
}
String msg = user.getCommunication().receiveMessage();
if(msg.isEmpty() || msg.equals("\n")) {
continue;
}
//Handle possible command
ICommand cmd = null;
String msgbody = "";
if(msg.charAt(0) == '/') {
String[] splittedMsg = msg.split(" ");
cmd = commands.get(splittedMsg[0]);
int index = msg.indexOf(' ');
if(index != -1) {
msgbody = msg.substring(index+1);
}
if(cmd == null) {
sendMessageToUser("Invalid command!");
continue;
}
} else {
msgbody = msg;
}
// if msg was command, execute it
if(cmd!=null) {
cmd.execute(this,msgbody);
continue;
}
// Cut message if it is too long
if(msgbody.length() > ChatServer.serverSettings.getMaxMessageLength()) {
msgbody = msgbody.substring(0, ChatServer.serverSettings.getMaxMessageLength());
}
// If msg was not command, it is message for other users.
sendMessageToCurrentRoom(msgbody, user.getName());
}
} catch (Exception e) {
System.out.println(e);
} finally {
Room r = user.getCurrentRoom();
if(r != null) {
r.users.remove(user);
user.setCurrentRoom(null);
}
users.remove(user);
System.out.println(user.getName()+":"+user.getSocket().getInetAddress().getHostAddress() + " left the server!");
}
}
/**
* Check if user is allowed to join the server.
* Order: userlimit, username, admin, password, banned
*/
private void authenticate() {
try {
//Check if server is full
if(ChatServer.users.size() >= ChatServer.serverSettings.getMaxUsers()) {
user.getCommunication().sendMessage("Server is full!");
user.getSocket().close();
}
//Username
user.getCommunication().sendMessage("Please give your nickname and the server password (if any)");
String msg = user.getCommunication().receiveMessage();
if(msg.isEmpty()) {
user.getCommunication().sendMessage("Error");
user.getSocket().close();
}
String[] s_msg = msg.split(" ");
user.setName(s_msg[0]);
if(user.getName().equals("SERVER")) {
user.getCommunication().sendMessage("Error");
user.getSocket().close();
}
if(isIllegalName(user.getName())) {
user.getCommunication().sendMessage("Your username contains invalid characters!");
user.getSocket().close();
}
//Check admin
if(s_msg.length > 1) {
String pass = s_msg[1];
if(pass.equals(serverSettings.getServerAdminPassword())) {
System.out.println("Admin user");
sendMessageToUser("You are server admin");
user.setMode(3);
}
}
//Server password if any. Don't check password if user has given admin password
if(serverSettings.getServerPassword() != "" && user.getMode() < 3) {
if(s_msg.length > 1) {
String pass = s_msg[1];
if(!pass.equals(serverSettings.getServerPassword())) {
user.getCommunication().sendMessage("Wrong password");
user.getSocket().close();
}
} else {
user.getCommunication().sendMessage("This server is password protected!");
user.getSocket().close();
}
}
// Check ban
if(isBanned(user.getSocket().getInetAddress().getHostAddress())) {
if(user.getMode() < 3) {
user.getCommunication().sendMessage("You are banned from the server!");
user.getSocket().close();
}
}
//Success, welcome
users.add(user);
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Send message to every user in the room.
* @param msg Message to be sent
* @param MsgSender Who sent the message
*/
public void sendMessageToCurrentRoom(String msg, String MsgSender) {
Room room = user.getCurrentRoom();
if(room == null) {
sendMessageToUser("You are not in room! Use /joinroom to join a room!");
return;
}
try {
if ((MsgSender.equals("SERVER"))) {
System.out.println("Message to be sent: "+msg);
for(User u : room.users) {
u.getCommunication().sendMessage("** " + msg + " **");
}
} else {
// Check if user is muted
if(room.isMuted(user.getSocket().getInetAddress().getHostAddress(), user.getName())) {
// Can't mute room moderator and up
if(user.getMode()<1) {
sendMessageToUser("You are muted");
return;
}
}
LocalDateTime date = new Timestamp(System.currentTimeMillis()).toLocalDateTime();
String timestr = "["+String.format("%02d",date.getHour()) +
":" + String.format("%02d",date.getMinute()) +
":"+ String.format("%02d",date.getSecond())+"] ";
//System.out.println("Message to be sent: "+msg);
for(User u : room.users) {
u.getCommunication().sendMessage(timestr + MsgSender + ": " + msg);
}
}
} catch (Exception e) {
System.out.println("sendMessageToRoom: " + e);
}
}
/**
* Send message directly to the user.
* @param msg Message to be sent
*/
public void sendMessageToUser(String msg) {
try {
user.getCommunication().sendMessage(msg);
} catch (Exception e) {
//TODO: handle exception
}
}
/**
* Send message to everyone with mode minmode in the room.
* @param msg Message to be sent
* @param minMode Mode that someone must have to receive the message
*/
public void sendMessageToModeRoom(String msg, int minMode) {
try {
for(User u : user.getCurrentRoom().users) {
if(u.getMode() >= minMode)
u.getCommunication().sendMessage(msg);
}
} catch (Exception e) {
//TODO: handle exception
}
}
/**
* Send message to everyone with mode minmode in the server.
* @param msg Message to be sent
* @param minMode Mode that someone must have to receive the message
*/
public void sendMessageToModeServer(String msg, int minMode) {
try {
for(User u : ChatServer.users) {
if(u.getMode() >= minMode)
u.getCommunication().sendMessage(msg);
}
} catch (Exception e) {
//TODO: handle exception
}
}
public void sendMessageToAll(String msg) {
try {
for(User u : ChatServer.users) {
u.getCommunication().sendMessage(msg);
}
} catch (Exception e) {
//TODO: handle exception
}
}
/**
* Check if address is banned.
* address:(username):(reason)
* @param address ip address
* @return was the address banned
*/
public boolean isBanned(String address) {
for(String ba : ChatServer.serverSettings.getBannedAddresses()) {
String[] splitted = ba.split(":");
if(splitted[0].equals(address)) {
return true;
}
}
return false;
}
/**
* Check if username does not contain illegal characters.
* @param name Name to be checked for illegal characters
* @return was the name illegal
*/
public boolean isIllegalName(String name) {
String invalidChars = " .:=/\\\'\"";
for(int i=0;i<name.length();i++) {
char c = name.charAt(i);
int index = invalidChars.indexOf(c);
if(index != -1) {
return true;
}
}
return false;
}
}
|
/**
* Thread for the connected user.
*/
public class CLASS_0 extends CLASS_1 {
public User user;
public CLASS_0(CLASS_2 VAR_0) {
user = new User(VAR_0);
}
public void FUNC_0() {
try {
// Check if user can join
authenticate();
// Send server info to user
FUNC_1("** "+ "Server name: " + ChatServer.serverSettings.FUNC_2());
FUNC_1("** Server description: "+ChatServer.serverSettings.FUNC_3());
FUNC_1("** Server rules: "+ChatServer.serverSettings.FUNC_4());
FUNC_1("** Server message of the day: " + serverSettings.getMotd());
FUNC_1("Type /help to see available commands.");
FUNC_1(" ");
System.VAR_1.println(user.FUNC_2()+":"+user.FUNC_5().FUNC_6().FUNC_7()+" joined the server");
// Start communication loop
while(true) {
if(user.FUNC_5().isClosed()) {
break;
}
String VAR_2 = user.FUNC_8().FUNC_9();
if(VAR_2.FUNC_10() || VAR_2.FUNC_11("\n")) {
continue;
}
//Handle possible command
ICommand VAR_3 = null;
String VAR_4 = "";
if(VAR_2.FUNC_12(0) == '/') {
String[] VAR_5 = VAR_2.split(" ");
VAR_3 = VAR_6.FUNC_13(VAR_5[0]);
int VAR_7 = VAR_2.FUNC_14(' ');
if(VAR_7 != -1) {
VAR_4 = VAR_2.substring(VAR_7+1);
}
if(VAR_3 == null) {
FUNC_1("Invalid command!");
continue;
}
} else {
VAR_4 = VAR_2;
}
// if msg was command, execute it
if(VAR_3!=null) {
VAR_3.FUNC_15(this,VAR_4);
continue;
}
// Cut message if it is too long
if(VAR_4.FUNC_16() > ChatServer.serverSettings.FUNC_17()) {
VAR_4 = VAR_4.substring(0, ChatServer.serverSettings.FUNC_17());
}
// If msg was not command, it is message for other users.
sendMessageToCurrentRoom(VAR_4, user.FUNC_2());
}
} catch (CLASS_3 e) {
System.VAR_1.println(e);
} finally {
CLASS_4 VAR_9 = user.getCurrentRoom();
if(VAR_9 != null) {
VAR_9.VAR_10.FUNC_18(user);
user.FUNC_19(null);
}
VAR_10.FUNC_18(user);
System.VAR_1.println(user.FUNC_2()+":"+user.FUNC_5().FUNC_6().FUNC_7() + " left the server!");
}
}
/**
* Check if user is allowed to join the server.
* Order: userlimit, username, admin, password, banned
*/
private void authenticate() {
try {
//Check if server is full
if(ChatServer.VAR_10.FUNC_20() >= ChatServer.serverSettings.getMaxUsers()) {
user.FUNC_8().FUNC_21("Server is full!");
user.FUNC_5().FUNC_22();
}
//Username
user.FUNC_8().FUNC_21("Please give your nickname and the server password (if any)");
String VAR_2 = user.FUNC_8().FUNC_9();
if(VAR_2.FUNC_10()) {
user.FUNC_8().FUNC_21("Error");
user.FUNC_5().FUNC_22();
}
String[] VAR_11 = VAR_2.split(" ");
user.FUNC_23(VAR_11[0]);
if(user.FUNC_2().FUNC_11("SERVER")) {
user.FUNC_8().FUNC_21("Error");
user.FUNC_5().FUNC_22();
}
if(FUNC_24(user.FUNC_2())) {
user.FUNC_8().FUNC_21("Your username contains invalid characters!");
user.FUNC_5().FUNC_22();
}
//Check admin
if(VAR_11.VAR_8 > 1) {
String VAR_12 = VAR_11[1];
if(VAR_12.FUNC_11(serverSettings.FUNC_25())) {
System.VAR_1.println("Admin user");
FUNC_1("You are server admin");
user.FUNC_26(3);
}
}
//Server password if any. Don't check password if user has given admin password
if(serverSettings.getServerPassword() != "" && user.getMode() < 3) {
if(VAR_11.VAR_8 > 1) {
String VAR_12 = VAR_11[1];
if(!VAR_12.FUNC_11(serverSettings.getServerPassword())) {
user.FUNC_8().FUNC_21("Wrong password");
user.FUNC_5().FUNC_22();
}
} else {
user.FUNC_8().FUNC_21("This server is password protected!");
user.FUNC_5().FUNC_22();
}
}
// Check ban
if(FUNC_27(user.FUNC_5().FUNC_6().FUNC_7())) {
if(user.getMode() < 3) {
user.FUNC_8().FUNC_21("You are banned from the server!");
user.FUNC_5().FUNC_22();
}
}
//Success, welcome
VAR_10.add(user);
} catch (CLASS_3 e) {
System.VAR_1.println(e);
}
}
/**
* Send message to every user in the room.
* @param msg Message to be sent
* @param MsgSender Who sent the message
*/
public void sendMessageToCurrentRoom(String VAR_2, String MsgSender) {
CLASS_4 room = user.getCurrentRoom();
if(room == null) {
FUNC_1("You are not in room! Use /joinroom to join a room!");
return;
}
try {
if ((MsgSender.FUNC_11("SERVER"))) {
System.VAR_1.println("Message to be sent: "+VAR_2);
for(User VAR_13 : room.VAR_10) {
VAR_13.FUNC_8().FUNC_21("** " + VAR_2 + " **");
}
} else {
// Check if user is muted
if(room.FUNC_28(user.FUNC_5().FUNC_6().FUNC_7(), user.FUNC_2())) {
// Can't mute room moderator and up
if(user.getMode()<1) {
FUNC_1("You are muted");
return;
}
}
LocalDateTime VAR_14 = new CLASS_5(System.FUNC_29()).FUNC_30();
String VAR_15 = "["+String.FUNC_31("%02d",VAR_14.FUNC_32()) +
":" + String.FUNC_31("%02d",VAR_14.getMinute()) +
":"+ String.FUNC_31("%02d",VAR_14.getSecond())+"] ";
//System.out.println("Message to be sent: "+msg);
for(User VAR_13 : room.VAR_10) {
VAR_13.FUNC_8().FUNC_21(VAR_15 + MsgSender + ": " + VAR_2);
}
}
} catch (CLASS_3 e) {
System.VAR_1.println("sendMessageToRoom: " + e);
}
}
/**
* Send message directly to the user.
* @param msg Message to be sent
*/
public void FUNC_1(String VAR_2) {
try {
user.FUNC_8().FUNC_21(VAR_2);
} catch (CLASS_3 e) {
//TODO: handle exception
}
}
/**
* Send message to everyone with mode minmode in the room.
* @param msg Message to be sent
* @param minMode Mode that someone must have to receive the message
*/
public void FUNC_33(String VAR_2, int VAR_16) {
try {
for(User VAR_13 : user.getCurrentRoom().VAR_10) {
if(VAR_13.getMode() >= VAR_16)
VAR_13.FUNC_8().FUNC_21(VAR_2);
}
} catch (CLASS_3 e) {
//TODO: handle exception
}
}
/**
* Send message to everyone with mode minmode in the server.
* @param msg Message to be sent
* @param minMode Mode that someone must have to receive the message
*/
public void FUNC_34(String VAR_2, int VAR_16) {
try {
for(User VAR_13 : ChatServer.VAR_10) {
if(VAR_13.getMode() >= VAR_16)
VAR_13.FUNC_8().FUNC_21(VAR_2);
}
} catch (CLASS_3 e) {
//TODO: handle exception
}
}
public void FUNC_35(String VAR_2) {
try {
for(User VAR_13 : ChatServer.VAR_10) {
VAR_13.FUNC_8().FUNC_21(VAR_2);
}
} catch (CLASS_3 e) {
//TODO: handle exception
}
}
/**
* Check if address is banned.
* address:(username):(reason)
* @param address ip address
* @return was the address banned
*/
public boolean FUNC_27(String VAR_17) {
for(String VAR_18 : ChatServer.serverSettings.FUNC_36()) {
String[] VAR_19 = VAR_18.split(":");
if(VAR_19[0].FUNC_11(VAR_17)) {
return true;
}
}
return false;
}
/**
* Check if username does not contain illegal characters.
* @param name Name to be checked for illegal characters
* @return was the name illegal
*/
public boolean FUNC_24(String name) {
String invalidChars = " .:=/\\\'\"";
for(int i=0;i<name.FUNC_16();i++) {
char VAR_20 = name.FUNC_12(i);
int VAR_7 = invalidChars.FUNC_14(VAR_20);
if(VAR_7 != -1) {
return true;
}
}
return false;
}
}
| 0.639281
|
{'CLASS_0': 'ChatServerThread', 'CLASS_1': 'Thread', 'CLASS_2': 'Socket', 'VAR_0': 'socket', 'FUNC_0': 'run', 'FUNC_1': 'sendMessageToUser', 'FUNC_2': 'getName', 'FUNC_3': 'getDescription', 'FUNC_4': 'getRules', 'VAR_1': 'out', 'FUNC_5': 'getSocket', 'FUNC_6': 'getInetAddress', 'FUNC_7': 'getHostAddress', 'VAR_2': 'msg', 'FUNC_8': 'getCommunication', 'FUNC_9': 'receiveMessage', 'FUNC_10': 'isEmpty', 'FUNC_11': 'equals', 'VAR_3': 'cmd', 'VAR_4': 'msgbody', 'FUNC_12': 'charAt', 'VAR_5': 'splittedMsg', 'VAR_6': 'commands', 'FUNC_13': 'get', 'VAR_7': 'index', 'FUNC_14': 'indexOf', 'FUNC_15': 'execute', 'FUNC_16': 'length', 'VAR_8': 'length', 'FUNC_17': 'getMaxMessageLength', 'CLASS_3': 'Exception', 'CLASS_4': 'Room', 'VAR_9': 'r', 'VAR_10': 'users', 'FUNC_18': 'remove', 'FUNC_19': 'setCurrentRoom', 'FUNC_20': 'size', 'FUNC_21': 'sendMessage', 'FUNC_22': 'close', 'VAR_11': 's_msg', 'FUNC_23': 'setName', 'FUNC_24': 'isIllegalName', 'VAR_12': 'pass', 'FUNC_25': 'getServerAdminPassword', 'FUNC_26': 'setMode', 'FUNC_27': 'isBanned', 'VAR_13': 'u', 'FUNC_28': 'isMuted', 'VAR_14': 'date', 'CLASS_5': 'Timestamp', 'FUNC_29': 'currentTimeMillis', 'FUNC_30': 'toLocalDateTime', 'VAR_15': 'timestr', 'FUNC_31': 'format', 'FUNC_32': 'getHour', 'FUNC_33': 'sendMessageToModeRoom', 'VAR_16': 'minMode', 'FUNC_34': 'sendMessageToModeServer', 'FUNC_35': 'sendMessageToAll', 'VAR_17': 'address', 'VAR_18': 'ba', 'FUNC_36': 'getBannedAddresses', 'VAR_19': 'splitted', 'VAR_20': 'c'}
|
java
|
OOP
|
100.00%
|
/**
* This is a simple POJO (Plain Old Java Object) that represents the information that is stored
* in the excel workbook located @ src/test/resources/testdata/MyDataFile.xls.
* The class name is intentionally named to match with the worksheet "CustomData" in the above
* mentioned spreadsheet, because that is how {@link com.paypal.selion.platform.dataprovider.SimpleExcelDataProvider}
* will understand as to what sheet to read data from.
*/
public class CustomData {
private String employeeName;
private Country country;
public String getEmployeeName () {
return employeeName;
}
public void setEmployeeName (String employeeName) {
this.employeeName = employeeName;
}
public Country getCountry () {
return country;
}
public void setCountry (Country country) {
this.country = country;
}
@Override
public String toString () {
final StringBuilder sb = new StringBuilder("CustomData{");
sb.append("employeeName='").append(employeeName).append('\'');
sb.append(", country=").append(country);
sb.append('}');
return sb.toString();
}
}
|
/**
* This is a simple POJO (Plain Old Java Object) that represents the information that is stored
* in the excel workbook located @ src/test/resources/testdata/MyDataFile.xls.
* The class name is intentionally named to match with the worksheet "CustomData" in the above
* mentioned spreadsheet, because that is how {@link com.paypal.selion.platform.dataprovider.SimpleExcelDataProvider}
* will understand as to what sheet to read data from.
*/
public class CustomData {
private CLASS_0 VAR_0;
private CLASS_1 VAR_1;
public CLASS_0 getEmployeeName () {
return VAR_0;
}
public void FUNC_0 (CLASS_0 VAR_0) {
this.VAR_0 = VAR_0;
}
public CLASS_1 FUNC_1 () {
return VAR_1;
}
public void FUNC_2 (CLASS_1 VAR_1) {
this.VAR_1 = VAR_1;
}
@VAR_2
public CLASS_0 FUNC_3 () {
final StringBuilder VAR_3 = new StringBuilder("CustomData{");
VAR_3.FUNC_4("employeeName='").FUNC_4(VAR_0).FUNC_4('\'');
VAR_3.FUNC_4(", country=").FUNC_4(VAR_1);
VAR_3.FUNC_4('}');
return VAR_3.FUNC_3();
}
}
| 0.748256
|
{'CLASS_0': 'String', 'VAR_0': 'employeeName', 'CLASS_1': 'Country', 'VAR_1': 'country', 'FUNC_0': 'setEmployeeName', 'FUNC_1': 'getCountry', 'FUNC_2': 'setCountry', 'VAR_2': 'Override', 'FUNC_3': 'toString', 'VAR_3': 'sb', 'FUNC_4': 'append'}
|
java
|
Hibrido
|
95.15%
|
package com.kalessil.phpStorm.phpInspectionsEA.inspectors.strictOperators;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.psi.elements.BinaryExpression;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.strictOperators.util.PhpExpressionTypes;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection;
import org.jetbrains.annotations.NotNull;
public class StrictStringConcatInspector extends BasePhpInspection {
private static final String strProblemDescriptionConcat = "Non string types in string concatenation operation (%t1% . %t2%). Use explicit (string) conversion to convert values to strings.";
@NotNull
public String getShortName() {
return "StrictStringConcatInspection";
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new BasePhpElementVisitor() {
public void visitPhpBinaryExpression(final BinaryExpression expr) {
if (expr.getOperation() == null) {
return;
}
final String operation = expr.getOperation().getText();
if (!operation.equals(".")) {
return;
}
final PhpExpressionTypes leftT = new PhpExpressionTypes(expr.getLeftOperand(), holder);
final PhpExpressionTypes rightT = new PhpExpressionTypes(expr.getRightOperand(), holder);
if (leftT.isString() && rightT.isString()) {
return;
}
final String strWarning = strProblemDescriptionConcat
.replace("%t1%", leftT.toString())
.replace("%t2%", rightT.toString());
holder.registerProblem(expr, strWarning, ProblemHighlightType.WEAK_WARNING);
}
};
}
}
|
package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_0.IMPORT_6.IMPORT_7.ProblemHighlightType;
import IMPORT_0.IMPORT_6.IMPORT_7.IMPORT_8;
import IMPORT_0.IMPORT_6.IMPORT_9.IMPORT_10;
import IMPORT_0.jetbrains.IMPORT_11.IMPORT_12.IMPORT_9.elements.BinaryExpression;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5.util.IMPORT_13;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.openApi.BasePhpElementVisitor;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.openApi.IMPORT_14;
import org.jetbrains.annotations.NotNull;
public class StrictStringConcatInspector extends IMPORT_14 {
private static final CLASS_0 VAR_0 = "Non string types in string concatenation operation (%t1% . %t2%). Use explicit (string) conversion to convert values to strings.";
@NotNull
public CLASS_0 FUNC_0() {
return "StrictStringConcatInspection";
}
@Override
@NotNull
public IMPORT_10 FUNC_1(@NotNull final IMPORT_8 holder, boolean VAR_1) {
return new BasePhpElementVisitor() {
public void FUNC_2(final BinaryExpression expr) {
if (expr.FUNC_3() == null) {
return;
}
final CLASS_0 VAR_2 = expr.FUNC_3().FUNC_4();
if (!VAR_2.FUNC_5(".")) {
return;
}
final IMPORT_13 VAR_3 = new IMPORT_13(expr.getLeftOperand(), holder);
final IMPORT_13 VAR_4 = new IMPORT_13(expr.getRightOperand(), holder);
if (VAR_3.FUNC_6() && VAR_4.FUNC_6()) {
return;
}
final CLASS_0 VAR_5 = VAR_0
.FUNC_7("%t1%", VAR_3.FUNC_8())
.FUNC_7("%t2%", VAR_4.FUNC_8());
holder.registerProblem(expr, VAR_5, ProblemHighlightType.WEAK_WARNING);
}
};
}
}
| 0.575731
|
{'IMPORT_0': 'com', 'IMPORT_1': 'kalessil', 'IMPORT_2': 'phpStorm', 'IMPORT_3': 'phpInspectionsEA', 'IMPORT_4': 'inspectors', 'IMPORT_5': 'strictOperators', 'IMPORT_6': 'intellij', 'IMPORT_7': 'codeInspection', 'IMPORT_8': 'ProblemsHolder', 'IMPORT_9': 'psi', 'IMPORT_10': 'PsiElementVisitor', 'IMPORT_11': 'php', 'IMPORT_12': 'lang', 'IMPORT_13': 'PhpExpressionTypes', 'IMPORT_14': 'BasePhpInspection', 'CLASS_0': 'String', 'VAR_0': 'strProblemDescriptionConcat', 'FUNC_0': 'getShortName', 'FUNC_1': 'buildVisitor', 'VAR_1': 'isOnTheFly', 'FUNC_2': 'visitPhpBinaryExpression', 'FUNC_3': 'getOperation', 'VAR_2': 'operation', 'FUNC_4': 'getText', 'FUNC_5': 'equals', 'VAR_3': 'leftT', 'VAR_4': 'rightT', 'FUNC_6': 'isString', 'VAR_5': 'strWarning', 'FUNC_7': 'replace', 'FUNC_8': 'toString'}
|
java
|
OOP
|
100.00%
|
package team.yingyingmonster.ccbs.database.mapper;
import team.yingyingmonster.ccbs.database.bean.Bill;
import java.util.List;
public interface BillMapper {
Bill selectByPrimaryKey(Long billid);
int deleteByPrimaryKey(Long billid);
int insert(Bill bill);
int insertSelective(Bill bills);
int updateByPrimaryKeySelective(Bill bills);
int updateByPrimaryKey(Bill bill);
}
|
package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_5.IMPORT_6;
import java.util.IMPORT_7;
public interface CLASS_0 {
IMPORT_6 FUNC_0(Long VAR_0);
int FUNC_1(Long VAR_0);
int FUNC_2(IMPORT_6 VAR_1);
int FUNC_3(IMPORT_6 bills);
int updateByPrimaryKeySelective(IMPORT_6 bills);
int FUNC_4(IMPORT_6 VAR_1);
}
| 0.65317
|
{'IMPORT_0': 'team', 'IMPORT_1': 'yingyingmonster', 'IMPORT_2': 'ccbs', 'IMPORT_3': 'database', 'IMPORT_4': 'mapper', 'IMPORT_5': 'bean', 'IMPORT_6': 'Bill', 'IMPORT_7': 'List', 'CLASS_0': 'BillMapper', 'FUNC_0': 'selectByPrimaryKey', 'VAR_0': 'billid', 'FUNC_1': 'deleteByPrimaryKey', 'FUNC_2': 'insert', 'VAR_1': 'bill', 'FUNC_3': 'insertSelective', 'FUNC_4': 'updateByPrimaryKey'}
|
java
|
Texto
|
36.21%
|
/*
* Copyright 2021 <NAME>.
*
* 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 dev.alexengrig.myfe.model;
import dev.alexengrig.myfe.domain.FeFile;
import dev.alexengrig.myfe.model.event.FeFileImageModelEvent;
import dev.alexengrig.myfe.model.event.FeFileImageModelListener;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class FeFileImageModelTest {
final FeFileImageModel model = new FeFileImageModel();
final LinkedList<FeFileImageModelEvent> events = new LinkedList<>();
final FeFileImageModelListener listener = events::add;
@BeforeEach
void beforeEach() {
model.addFeFileImageModelListener(listener);
}
@Test
void should_do_event() {
model.removeFeFileImageModelListener(listener);
model.setFileData(new FeFile("/file.this", "file.this"), new byte[0]);
assertTrue(events.isEmpty(), "There are events");
}
@Test
void should_set_fileData() {
FeFile file = new FeFile("/file.this", "file.this");
byte[] data = {1, 2, 3};
model.setFileData(file, data);
assertEquals(1, events.size(), "Number of events");
FeFileImageModelEvent event = events.get(0);
assertSame(file, event.getFile(), "File");
assertArrayEquals(data, event.getData(), "Data");
}
}
|
/*
* Copyright 2021 <NAME>.
*
* 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 IMPORT_0.alexengrig.myfe.model;
import IMPORT_0.alexengrig.myfe.domain.FeFile;
import IMPORT_0.alexengrig.myfe.model.IMPORT_1.IMPORT_2;
import IMPORT_0.alexengrig.myfe.model.IMPORT_1.IMPORT_3;
import org.junit.IMPORT_4.IMPORT_5.BeforeEach;
import org.junit.IMPORT_4.IMPORT_5.IMPORT_6;
import java.util.IMPORT_7;
import static org.junit.IMPORT_4.IMPORT_5.Assertions.assertArrayEquals;
import static org.junit.IMPORT_4.IMPORT_5.Assertions.assertEquals;
import static org.junit.IMPORT_4.IMPORT_5.Assertions.IMPORT_8;
import static org.junit.IMPORT_4.IMPORT_5.Assertions.assertTrue;
class CLASS_0 {
final FeFileImageModel model = new FeFileImageModel();
final IMPORT_7<IMPORT_2> events = new IMPORT_7<>();
final IMPORT_3 listener = events::add;
@BeforeEach
void FUNC_0() {
model.addFeFileImageModelListener(listener);
}
@IMPORT_6
void should_do_event() {
model.removeFeFileImageModelListener(listener);
model.FUNC_1(new FeFile("/file.this", "file.this"), new byte[0]);
assertTrue(events.FUNC_2(), "There are events");
}
@IMPORT_6
void FUNC_3() {
FeFile VAR_0 = new FeFile("/file.this", "file.this");
byte[] data = {1, 2, 3};
model.FUNC_1(VAR_0, data);
assertEquals(1, events.FUNC_4(), "Number of events");
IMPORT_2 IMPORT_1 = events.FUNC_5(0);
IMPORT_8(VAR_0, IMPORT_1.FUNC_6(), "File");
assertArrayEquals(data, IMPORT_1.FUNC_7(), "Data");
}
}
| 0.53524
|
{'IMPORT_0': 'dev', 'IMPORT_1': 'event', 'IMPORT_2': 'FeFileImageModelEvent', 'IMPORT_3': 'FeFileImageModelListener', 'IMPORT_4': 'jupiter', 'IMPORT_5': 'api', 'IMPORT_6': 'Test', 'IMPORT_7': 'LinkedList', 'IMPORT_8': 'assertSame', 'CLASS_0': 'FeFileImageModelTest', 'FUNC_0': 'beforeEach', 'FUNC_1': 'setFileData', 'FUNC_2': 'isEmpty', 'FUNC_3': 'should_set_fileData', 'VAR_0': 'file', 'FUNC_4': 'size', 'FUNC_5': 'get', 'FUNC_6': 'getFile', 'FUNC_7': 'getData'}
|
java
|
Hibrido
|
100.00%
|
/**
* A class representing the main workbench configuration; parsed from JSON stored in the database.
* See {@link CacheSpringConfiguration}. This should be kept in sync with files in the config/ directory.
*/
public class WorkbenchConfig {
public ServerConfig server;
public static class ServerConfig {
public Boolean debugEndpoints;
public String workbenchApiBaseUrl;
public String publicApiKeyForErrorReports;
public String projectId;
public String gaId;
}
}
|
/**
* A class representing the main workbench configuration; parsed from JSON stored in the database.
* See {@link CacheSpringConfiguration}. This should be kept in sync with files in the config/ directory.
*/
public class WorkbenchConfig {
public CLASS_0 VAR_0;
public static class CLASS_0 {
public CLASS_1 VAR_1;
public CLASS_2 VAR_2;
public CLASS_2 VAR_3;
public CLASS_2 VAR_4;
public CLASS_2 VAR_5;
}
}
| 0.891566
|
{'CLASS_0': 'ServerConfig', 'VAR_0': 'server', 'CLASS_1': 'Boolean', 'VAR_1': 'debugEndpoints', 'CLASS_2': 'String', 'VAR_2': 'workbenchApiBaseUrl', 'VAR_3': 'publicApiKeyForErrorReports', 'VAR_4': 'projectId', 'VAR_5': 'gaId'}
|
java
|
OOP
|
100.00%
|
package com.xunle.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
/**
* @author xunle
* @date 2021/12/16 14:48
*/
public class EchoServer {
private static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);
private final int PORT;
public EchoServer(int port) {
this.PORT = port;
}
public void start() {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
//指定传输Channel
.channel(NioServerSocketChannel.class)
//socket地址使用所选的端口
.localAddress(new InetSocketAddress(PORT))
//添加 EchoServerHandler到 Channel的 ChannelPipeline
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new EchoServerHandler());
}
});
//绑定的服务器,sync 等待服务器关闭
ChannelFuture future = bootstrap.bind().sync();
LOGGER.info(EchoServer.class.getName() + " started and listen on " +
future.channel().localAddress());
//关闭 Channel和块直到它被关闭
future.channel().closeFuture().sync();
} catch (Exception e) {
LOGGER.error("服务端出现异常:{}", e);
try {
group.shutdownGracefully().sync();
} catch (InterruptedException interruptedException) {
LOGGER.error("服务端关闭出现异常:{}", interruptedException);
}
}
}
public static void main(String[] args) {
// 设置端口值
int port = Integer.parseInt("8000");
new EchoServer(port).start();
}
}
|
package com.xunle.IMPORT_0;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.IMPORT_1;
import org.slf4j.LoggerFactory;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
/**
* @author xunle
* @date 2021/12/16 14:48
*/
public class EchoServer {
private static final IMPORT_1 LOGGER = LoggerFactory.getLogger(EchoServer.class);
private final int PORT;
public EchoServer(int port) {
this.PORT = port;
}
public void start() {
NioEventLoopGroup VAR_0 = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.FUNC_0(VAR_0)
//指定传输Channel
.channel(NioServerSocketChannel.class)
//socket地址使用所选的端口
.localAddress(new InetSocketAddress(PORT))
//添加 EchoServerHandler到 Channel的 ChannelPipeline
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new EchoServerHandler());
}
});
//绑定的服务器,sync 等待服务器关闭
ChannelFuture future = bootstrap.bind().sync();
LOGGER.info(EchoServer.class.getName() + " started and listen on " +
future.channel().localAddress());
//关闭 Channel和块直到它被关闭
future.channel().closeFuture().sync();
} catch (Exception e) {
LOGGER.error("服务端出现异常:{}", e);
try {
VAR_0.shutdownGracefully().sync();
} catch (InterruptedException interruptedException) {
LOGGER.error("服务端关闭出现异常:{}", interruptedException);
}
}
}
public static void main(String[] args) {
// 设置端口值
int port = Integer.parseInt("8000");
new EchoServer(port).start();
}
}
| 0.076964
|
{'IMPORT_0': 'server', 'IMPORT_1': 'Logger', 'VAR_0': 'group', 'FUNC_0': 'group'}
|
java
|
OOP
|
30.87%
|
/*
* 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.client.program;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.google.common.base.Preconditions;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobSubmissionResult;
import org.apache.flink.api.common.accumulators.AccumulatorHelper;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.Plan;
import org.apache.flink.optimizer.CompilerException;
import org.apache.flink.optimizer.DataStatistics;
import org.apache.flink.optimizer.Optimizer;
import org.apache.flink.optimizer.costs.DefaultCostEstimator;
import org.apache.flink.optimizer.plan.FlinkPlan;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plan.StreamingPlan;
import org.apache.flink.optimizer.plandump.PlanJSONDumpGenerator;
import org.apache.flink.optimizer.plantranslate.JobGraphGenerator;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.Path;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.client.JobClient;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.instance.ActorGateway;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService;
import org.apache.flink.runtime.messages.accumulators.AccumulatorResultsErroneous;
import org.apache.flink.runtime.messages.accumulators.AccumulatorResultsFound;
import org.apache.flink.runtime.messages.accumulators.RequestAccumulatorResults;
import org.apache.flink.runtime.messages.JobManagerMessages;
import org.apache.flink.runtime.util.LeaderRetrievalUtils;
import org.apache.flink.util.SerializedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
import akka.actor.ActorSystem;
/**
* Encapsulates the functionality necessary to submit a program to a remote cluster.
*/
public class Client {
private static final Logger LOG = LoggerFactory.getLogger(Client.class);
/** The optimizer used in the optimization of batch programs */
final Optimizer compiler;
/** The actor system used to communicate with the JobManager */
private final ActorSystem actorSystem;
/** Configuration of the client */
private final Configuration config;
/** Timeout for futures */
private final FiniteDuration timeout;
/** Lookup timeout for the job manager retrieval service */
private final FiniteDuration lookupTimeout;
/**
* If != -1, this field specifies the total number of available slots on the cluster
* connected to the client.
*/
private final int maxSlots;
/** Flag indicating whether to sysout print execution updates */
private boolean printStatusDuringExecution = true;
/**
* For interactive invocations, the Job ID is only available after the ContextEnvironment has
* been run inside the user JAR. We pass the Client to every instance of the ContextEnvironment
* which lets us access the last JobID here.
*/
private JobID lastJobID;
// ------------------------------------------------------------------------
// Construction
// ------------------------------------------------------------------------
/**
* Creates a instance that submits the programs to the JobManager defined in the
* configuration. This method will try to resolve the JobManager hostname and throw an exception
* if that is not possible.
*
* @param config The config used to obtain the job-manager's address, and used to configure the optimizer.
*
* @throws java.io.IOException Thrown, if the client's actor system could not be started.
* @throws java.net.UnknownHostException Thrown, if the JobManager's hostname could not be resolved.
*/
public Client(Configuration config) throws IOException {
this(config, -1);
}
/**
* Creates a new instance of the class that submits the jobs to a job-manager.
* at the given address using the default port.
*
* @param config The configuration for the client-side processes, like the optimizer.
* @param maxSlots maxSlots The number of maxSlots on the cluster if != -1.
*
* @throws java.io.IOException Thrown, if the client's actor system could not be started.
* @throws java.net.UnknownHostException Thrown, if the JobManager's hostname could not be resolved.
*/
public Client(Configuration config, int maxSlots) throws IOException {
this.config = Preconditions.checkNotNull(config);
this.compiler = new Optimizer(new DataStatistics(), new DefaultCostEstimator(), config);
this.maxSlots = maxSlots;
LOG.info("Starting client actor system");
try {
this.actorSystem = JobClient.startJobClientActorSystem(config);
} catch (Exception e) {
throw new IOException("Could start client actor system.", e);
}
timeout = AkkaUtils.getClientTimeout(config);
lookupTimeout = AkkaUtils.getLookupTimeout(config);
}
// ------------------------------------------------------------------------
// Startup & Shutdown
// ------------------------------------------------------------------------
/**
* Shuts down the client. This stops the internal actor system and actors.
*/
public void shutdown() {
if (!this.actorSystem.isTerminated()) {
this.actorSystem.shutdown();
this.actorSystem.awaitTermination();
}
}
// ------------------------------------------------------------------------
// Configuration
// ------------------------------------------------------------------------
/**
* Configures whether the client should print progress updates during the execution to {@code System.out}.
* All updates are logged via the SLF4J loggers regardless of this setting.
*
* @param print True to print updates to standard out during execution, false to not print them.
*/
public void setPrintStatusDuringExecution(boolean print) {
this.printStatusDuringExecution = print;
}
/**
* @return whether the client will print progress updates during the execution to {@code System.out}
*/
public boolean getPrintStatusDuringExecution() {
return this.printStatusDuringExecution;
}
/**
* @return -1 if unknown. The maximum number of available processing slots at the Flink cluster
* connected to this client.
*/
public int getMaxSlots() {
return this.maxSlots;
}
// ------------------------------------------------------------------------
// Access to the Program's Plan
// ------------------------------------------------------------------------
public static String getOptimizedPlanAsJson(Optimizer compiler, PackagedProgram prog, int parallelism)
throws CompilerException, ProgramInvocationException
{
PlanJSONDumpGenerator jsonGen = new PlanJSONDumpGenerator();
return jsonGen.getOptimizerPlanAsJSON((OptimizedPlan) getOptimizedPlan(compiler, prog, parallelism));
}
public static FlinkPlan getOptimizedPlan(Optimizer compiler, PackagedProgram prog, int parallelism)
throws CompilerException, ProgramInvocationException
{
Thread.currentThread().setContextClassLoader(prog.getUserCodeClassLoader());
if (prog.isUsingProgramEntryPoint()) {
return getOptimizedPlan(compiler, prog.getPlanWithJars(), parallelism);
} else if (prog.isUsingInteractiveMode()) {
// temporary hack to support the optimizer plan preview
OptimizerPlanEnvironment env = new OptimizerPlanEnvironment(compiler);
if (parallelism > 0) {
env.setParallelism(parallelism);
}
return env.getOptimizedPlan(prog);
} else {
throw new RuntimeException("Couldn't determine program mode.");
}
}
public static OptimizedPlan getOptimizedPlan(Optimizer compiler, Plan p, int parallelism) throws CompilerException {
if (parallelism > 0 && p.getDefaultParallelism() <= 0) {
LOG.debug("Changing plan default parallelism from {} to {}", p.getDefaultParallelism(), parallelism);
p.setDefaultParallelism(parallelism);
}
LOG.debug("Set parallelism {}, plan default parallelism {}", parallelism, p.getDefaultParallelism());
return compiler.compile(p);
}
// ------------------------------------------------------------------------
// Program submission / execution
// ------------------------------------------------------------------------
public JobSubmissionResult runBlocking(PackagedProgram prog, int parallelism) throws ProgramInvocationException {
Thread.currentThread().setContextClassLoader(prog.getUserCodeClassLoader());
if (prog.isUsingProgramEntryPoint()) {
return runBlocking(prog.getPlanWithJars(), parallelism, prog.getSavepointPath());
}
else if (prog.isUsingInteractiveMode()) {
LOG.info("Starting program in interactive mode");
ContextEnvironment.setAsContext(new ContextEnvironmentFactory(this, prog.getAllLibraries(),
prog.getClasspaths(), prog.getUserCodeClassLoader(), parallelism, true,
prog.getSavepointPath()));
// invoke here
try {
prog.invokeInteractiveModeForExecution();
}
finally {
ContextEnvironment.unsetContext();
}
return new JobSubmissionResult(lastJobID);
}
else {
throw new RuntimeException();
}
}
public JobSubmissionResult runDetached(PackagedProgram prog, int parallelism)
throws ProgramInvocationException
{
Thread.currentThread().setContextClassLoader(prog.getUserCodeClassLoader());
if (prog.isUsingProgramEntryPoint()) {
return runDetached(prog.getPlanWithJars(), parallelism, prog.getSavepointPath());
}
else if (prog.isUsingInteractiveMode()) {
LOG.info("Starting program in interactive mode");
ContextEnvironmentFactory factory = new ContextEnvironmentFactory(this, prog.getAllLibraries(),
prog.getClasspaths(), prog.getUserCodeClassLoader(), parallelism, false,
prog.getSavepointPath());
ContextEnvironment.setAsContext(factory);
// invoke here
try {
prog.invokeInteractiveModeForExecution();
return ((DetachedEnvironment) factory.getLastEnvCreated()).finalizeExecute();
}
finally {
ContextEnvironment.unsetContext();
}
}
else {
throw new RuntimeException("PackagedProgram does not have a valid invocation mode.");
}
}
public JobExecutionResult runBlocking(JobWithJars program, int parallelism) throws ProgramInvocationException {
return runBlocking(program, parallelism, null);
}
/**
* Runs a program on the Flink cluster to which this client is connected. The call blocks until the
* execution is complete, and returns afterwards.
*
* @param program The program to be executed.
* @param parallelism The default parallelism to use when running the program. The default parallelism is used
* when the program does not set a parallelism by itself.
*
* @throws CompilerException Thrown, if the compiler encounters an illegal situation.
* @throws ProgramInvocationException Thrown, if the program could not be instantiated from its jar file,
* or if the submission failed. That might be either due to an I/O problem,
* i.e. the job-manager is unreachable, or due to the fact that the
* parallel execution failed.
*/
public JobExecutionResult runBlocking(JobWithJars program, int parallelism, String savepointPath)
throws CompilerException, ProgramInvocationException {
ClassLoader classLoader = program.getUserCodeClassLoader();
if (classLoader == null) {
throw new IllegalArgumentException("The given JobWithJars does not provide a usercode class loader.");
}
OptimizedPlan optPlan = getOptimizedPlan(compiler, program, parallelism);
return runBlocking(optPlan, program.getJarFiles(), program.getClasspaths(), classLoader, savepointPath);
}
public JobSubmissionResult runDetached(JobWithJars program, int parallelism) throws ProgramInvocationException {
return runDetached(program, parallelism, null);
}
/**
* Submits a program to the Flink cluster to which this client is connected. The call returns after the
* program was submitted and does not wait for the program to complete.
*
* @param program The program to be executed.
* @param parallelism The default parallelism to use when running the program. The default parallelism is used
* when the program does not set a parallelism by itself.
*
* @throws CompilerException Thrown, if the compiler encounters an illegal situation.
* @throws ProgramInvocationException Thrown, if the program could not be instantiated from its jar file,
* or if the submission failed. That might be either due to an I/O problem,
* i.e. the job-manager is unreachable.
*/
public JobSubmissionResult runDetached(JobWithJars program, int parallelism, String savepointPath)
throws CompilerException, ProgramInvocationException {
ClassLoader classLoader = program.getUserCodeClassLoader();
if (classLoader == null) {
throw new IllegalArgumentException("The given JobWithJars does not provide a usercode class loader.");
}
OptimizedPlan optimizedPlan = getOptimizedPlan(compiler, program, parallelism);
return runDetached(optimizedPlan, program.getJarFiles(), program.getClasspaths(), classLoader, savepointPath);
}
public JobExecutionResult runBlocking(
FlinkPlan compiledPlan, List<URL> libraries, List<URL> classpaths, ClassLoader classLoader) throws ProgramInvocationException {
return runBlocking(compiledPlan, libraries, classpaths, classLoader, null);
}
public JobExecutionResult runBlocking(FlinkPlan compiledPlan, List<URL> libraries, List<URL> classpaths,
ClassLoader classLoader, String savepointPath) throws ProgramInvocationException
{
JobGraph job = getJobGraph(compiledPlan, libraries, classpaths, savepointPath);
return runBlocking(job, classLoader);
}
public JobSubmissionResult runDetached(FlinkPlan compiledPlan, List<URL> libraries, List<URL> classpaths, ClassLoader classLoader) throws ProgramInvocationException {
return runDetached(compiledPlan, libraries, classpaths, classLoader, null);
}
public JobSubmissionResult runDetached(FlinkPlan compiledPlan, List<URL> libraries, List<URL> classpaths,
ClassLoader classLoader, String savepointPath) throws ProgramInvocationException
{
JobGraph job = getJobGraph(compiledPlan, libraries, classpaths, savepointPath);
return runDetached(job, classLoader);
}
public JobExecutionResult runBlocking(JobGraph jobGraph, ClassLoader classLoader) throws ProgramInvocationException {
LeaderRetrievalService leaderRetrievalService;
try {
leaderRetrievalService = LeaderRetrievalUtils.createLeaderRetrievalService(config);
} catch (Exception e) {
throw new ProgramInvocationException("Could not create the leader retrieval service.", e);
}
try {
this.lastJobID = jobGraph.getJobID();
return JobClient.submitJobAndWait(actorSystem, leaderRetrievalService, jobGraph, timeout, printStatusDuringExecution, classLoader);
} catch (JobExecutionException e) {
throw new ProgramInvocationException("The program execution failed: " + e.getMessage(), e);
}
}
public JobSubmissionResult runDetached(JobGraph jobGraph, ClassLoader classLoader) throws ProgramInvocationException {
ActorGateway jobManagerGateway;
try {
jobManagerGateway = getJobManagerGateway();
} catch (Exception e) {
throw new ProgramInvocationException("Failed to retrieve the JobManager gateway.", e);
}
LOG.info("Checking and uploading JAR files");
try {
JobClient.uploadJarFiles(jobGraph, jobManagerGateway, timeout);
}
catch (IOException e) {
throw new ProgramInvocationException("Could not upload the program's JAR files to the JobManager.", e);
}
try {
this.lastJobID = jobGraph.getJobID();
JobClient.submitJobDetached(jobManagerGateway, jobGraph, timeout, classLoader);
return new JobSubmissionResult(jobGraph.getJobID());
} catch (JobExecutionException e) {
throw new ProgramInvocationException("The program execution failed: " + e.getMessage(), e);
}
}
/**
* Cancels a job identified by the job id.
* @param jobId the job id
* @throws Exception In case an error occurred.
*/
public void cancel(JobID jobId) throws Exception {
final ActorGateway jobManagerGateway = getJobManagerGateway();
final Future<Object> response;
try {
response = jobManagerGateway.ask(new JobManagerMessages.CancelJob(jobId), timeout);
} catch (final Exception e) {
throw new ProgramInvocationException("Failed to query the job manager gateway.", e);
}
final Object result = Await.result(response, timeout);
if (result instanceof JobManagerMessages.CancellationSuccess) {
LOG.info("Job cancellation with ID " + jobId + " succeeded.");
} else if (result instanceof JobManagerMessages.CancellationFailure) {
final Throwable t = ((JobManagerMessages.CancellationFailure) result).cause();
LOG.info("Job cancellation with ID " + jobId + " failed.", t);
throw new Exception("Failed to cancel the job because of \n" + t.getMessage());
} else {
throw new Exception("Unknown message received while cancelling: " + result.getClass().getName());
}
}
/**
* Stops a program on Flink cluster whose job-manager is configured in this client's configuration.
* Stopping works only for streaming programs. Be aware, that the program might continue to run for
* a while after sending the stop command, because after sources stopped to emit data all operators
* need to finish processing.
*
* @param jobId
* the job ID of the streaming program to stop
* @throws Exception
* If the job ID is invalid (ie, is unknown or refers to a batch job) or if sending the stop signal
* failed. That might be due to an I/O problem, ie, the job-manager is unreachable.
*/
public void stop(final JobID jobId) throws Exception {
final ActorGateway jobManagerGateway = getJobManagerGateway();
final Future<Object> response;
try {
response = jobManagerGateway.ask(new JobManagerMessages.StopJob(jobId), timeout);
} catch (final Exception e) {
throw new ProgramInvocationException("Failed to query the job manager gateway.", e);
}
final Object result = Await.result(response, timeout);
if (result instanceof JobManagerMessages.StoppingSuccess) {
LOG.info("Job stopping with ID " + jobId + " succeeded.");
} else if (result instanceof JobManagerMessages.StoppingFailure) {
final Throwable t = ((JobManagerMessages.StoppingFailure) result).cause();
LOG.info("Job stopping with ID " + jobId + " failed.", t);
throw new Exception("Failed to stop the job because of \n" + t.getMessage());
} else {
throw new Exception("Unknown message received while stopping: " + result.getClass().getName());
}
}
/**
* Requests and returns the accumulators for the given job identifier. Accumulators can be
* requested while a is running or after it has finished. The default class loader is used
* to deserialize the incoming accumulator results.
* @param jobID The job identifier of a job.
* @return A Map containing the accumulator's name and its value.
*/
public Map<String, Object> getAccumulators(JobID jobID) throws Exception {
return getAccumulators(jobID, ClassLoader.getSystemClassLoader());
}
/**
* Requests and returns the accumulators for the given job identifier. Accumulators can be
* requested while a is running or after it has finished.
* @param jobID The job identifier of a job.
* @param loader The class loader for deserializing the accumulator results.
* @return A Map containing the accumulator's name and its value.
*/
public Map<String, Object> getAccumulators(JobID jobID, ClassLoader loader) throws Exception {
ActorGateway jobManagerGateway = getJobManagerGateway();
Future<Object> response;
try {
response = jobManagerGateway.ask(new RequestAccumulatorResults(jobID), timeout);
} catch (Exception e) {
throw new Exception("Failed to query the job manager gateway for accumulators.", e);
}
Object result = Await.result(response, timeout);
if (result instanceof AccumulatorResultsFound) {
Map<String, SerializedValue<Object>> serializedAccumulators =
((AccumulatorResultsFound) result).result();
return AccumulatorHelper.deserializeAccumulators(serializedAccumulators, loader);
} else if (result instanceof AccumulatorResultsErroneous) {
throw ((AccumulatorResultsErroneous) result).cause();
} else {
throw new Exception("Failed to fetch accumulators for the job " + jobID + ".");
}
}
// ------------------------------------------------------------------------
// Sessions
// ------------------------------------------------------------------------
/**
* Tells the JobManager to finish the session (job) defined by the given ID.
*
* @param jobId The ID that identifies the session.
*/
public void endSession(JobID jobId) throws Exception {
if (jobId == null) {
throw new IllegalArgumentException("The JobID must not be null.");
}
endSessions(Collections.singletonList(jobId));
}
/**
* Tells the JobManager to finish the sessions (jobs) defined by the given IDs.
*
* @param jobIds The IDs that identify the sessions.
*/
public void endSessions(List<JobID> jobIds) throws Exception {
if (jobIds == null) {
throw new IllegalArgumentException("The JobIDs must not be null");
}
ActorGateway jobManagerGateway = getJobManagerGateway();
for (JobID jid : jobIds) {
if (jid != null) {
LOG.info("Telling job manager to end the session {}.", jid);
jobManagerGateway.tell(new JobManagerMessages.RemoveCachedJob(jid));
}
}
}
// ------------------------------------------------------------------------
// Internal translation methods
// ------------------------------------------------------------------------
/**
* Creates the optimized plan for a given program, using this client's compiler.
*
* @param prog The program to be compiled.
* @return The compiled and optimized plan, as returned by the compiler.
* @throws CompilerException Thrown, if the compiler encounters an illegal situation.
* @throws ProgramInvocationException Thrown, if the program could not be instantiated from its jar file.
*/
private static OptimizedPlan getOptimizedPlan(Optimizer compiler, JobWithJars prog, int parallelism)
throws CompilerException, ProgramInvocationException {
return getOptimizedPlan(compiler, prog.getPlan(), parallelism);
}
public JobGraph getJobGraph(PackagedProgram prog, FlinkPlan optPlan) throws ProgramInvocationException {
return getJobGraph(optPlan, prog.getAllLibraries(), prog.getClasspaths(), null);
}
public JobGraph getJobGraph(PackagedProgram prog, FlinkPlan optPlan, String savepointPath) throws ProgramInvocationException {
return getJobGraph(optPlan, prog.getAllLibraries(), prog.getClasspaths(), savepointPath);
}
private JobGraph getJobGraph(FlinkPlan optPlan, List<URL> jarFiles, List<URL> classpaths, String savepointPath) {
JobGraph job;
if (optPlan instanceof StreamingPlan) {
job = ((StreamingPlan) optPlan).getJobGraph();
job.setSavepointPath(savepointPath);
} else {
JobGraphGenerator gen = new JobGraphGenerator(this.config);
job = gen.compileJobGraph((OptimizedPlan) optPlan);
}
for (URL jar : jarFiles) {
try {
job.addJar(new Path(jar.toURI()));
} catch (URISyntaxException e) {
throw new RuntimeException("URL is invalid. This should not happen.", e);
}
}
job.setClasspaths(classpaths);
return job;
}
// ------------------------------------------------------------------------
// Helper methods
// ------------------------------------------------------------------------
/**
* Returns the {@link ActorGateway} of the current job manager leader using
* the {@link LeaderRetrievalService}.
*
* @return ActorGateway of the current job manager leader
* @throws Exception
*/
private ActorGateway getJobManagerGateway() throws Exception {
LOG.info("Looking up JobManager");
LeaderRetrievalService leaderRetrievalService;
leaderRetrievalService = LeaderRetrievalUtils.createLeaderRetrievalService(config);
return LeaderRetrievalUtils.retrieveLeaderGateway(
leaderRetrievalService,
actorSystem,
lookupTimeout);
}
}
|
/*
* 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.IMPORT_0.IMPORT_1.client.program;
import IMPORT_2.io.IMPORT_3;
import IMPORT_2.net.URISyntaxException;
import IMPORT_2.net.IMPORT_4;
import IMPORT_2.IMPORT_5.IMPORT_6;
import IMPORT_2.IMPORT_5.IMPORT_7;
import IMPORT_2.IMPORT_5.IMPORT_8;
import IMPORT_9.google.common.IMPORT_10.Preconditions;
import org.IMPORT_0.IMPORT_1.IMPORT_11.common.IMPORT_12;
import org.IMPORT_0.IMPORT_1.IMPORT_11.common.IMPORT_13;
import org.IMPORT_0.IMPORT_1.IMPORT_11.common.IMPORT_14.IMPORT_15;
import org.IMPORT_0.IMPORT_1.IMPORT_11.common.IMPORT_16;
import org.IMPORT_0.IMPORT_1.IMPORT_11.common.IMPORT_17;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_19;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_20;
import org.IMPORT_0.IMPORT_1.IMPORT_18.Optimizer;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_21.DefaultCostEstimator;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_22.IMPORT_23;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_22.OptimizedPlan;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_22.IMPORT_24;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_25.IMPORT_26;
import org.IMPORT_0.IMPORT_1.IMPORT_18.IMPORT_27.IMPORT_28;
import org.IMPORT_0.IMPORT_1.IMPORT_29.Configuration;
import org.IMPORT_0.IMPORT_1.IMPORT_30.fs.IMPORT_31;
import org.IMPORT_0.IMPORT_1.IMPORT_32.akka.IMPORT_33;
import org.IMPORT_0.IMPORT_1.IMPORT_32.client.IMPORT_34;
import org.IMPORT_0.IMPORT_1.IMPORT_32.client.IMPORT_35;
import org.IMPORT_0.IMPORT_1.IMPORT_32.instance.IMPORT_36;
import org.IMPORT_0.IMPORT_1.IMPORT_32.jobgraph.IMPORT_37;
import org.IMPORT_0.IMPORT_1.IMPORT_32.IMPORT_38.LeaderRetrievalService;
import org.IMPORT_0.IMPORT_1.IMPORT_32.IMPORT_39.IMPORT_14.AccumulatorResultsErroneous;
import org.IMPORT_0.IMPORT_1.IMPORT_32.IMPORT_39.IMPORT_14.AccumulatorResultsFound;
import org.IMPORT_0.IMPORT_1.IMPORT_32.IMPORT_39.IMPORT_14.RequestAccumulatorResults;
import org.IMPORT_0.IMPORT_1.IMPORT_32.IMPORT_39.IMPORT_40;
import org.IMPORT_0.IMPORT_1.IMPORT_32.IMPORT_5.IMPORT_41;
import org.IMPORT_0.IMPORT_1.IMPORT_5.IMPORT_42;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.IMPORT_43.IMPORT_44;
import scala.IMPORT_43.IMPORT_45;
import scala.IMPORT_43.IMPORT_46.FiniteDuration;
import akka.IMPORT_47.IMPORT_48;
/**
* Encapsulates the functionality necessary to submit a program to a remote cluster.
*/
public class CLASS_0 {
private static final Logger VAR_0 = LoggerFactory.getLogger(CLASS_0.class);
/** The optimizer used in the optimization of batch programs */
final Optimizer compiler;
/** The actor system used to communicate with the JobManager */
private final IMPORT_48 actorSystem;
/** Configuration of the client */
private final Configuration VAR_1;
/** Timeout for futures */
private final FiniteDuration VAR_2;
/** Lookup timeout for the job manager retrieval service */
private final FiniteDuration lookupTimeout;
/**
* If != -1, this field specifies the total number of available slots on the cluster
* connected to the client.
*/
private final int VAR_3;
/** Flag indicating whether to sysout print execution updates */
private boolean printStatusDuringExecution = true;
/**
* For interactive invocations, the Job ID is only available after the ContextEnvironment has
* been run inside the user JAR. We pass the Client to every instance of the ContextEnvironment
* which lets us access the last JobID here.
*/
private IMPORT_12 VAR_4;
// ------------------------------------------------------------------------
// Construction
// ------------------------------------------------------------------------
/**
* Creates a instance that submits the programs to the JobManager defined in the
* configuration. This method will try to resolve the JobManager hostname and throw an exception
* if that is not possible.
*
* @param config The config used to obtain the job-manager's address, and used to configure the optimizer.
*
* @throws java.io.IOException Thrown, if the client's actor system could not be started.
* @throws java.net.UnknownHostException Thrown, if the JobManager's hostname could not be resolved.
*/
public CLASS_0(Configuration VAR_1) throws IMPORT_3 {
this(VAR_1, -1);
}
/**
* Creates a new instance of the class that submits the jobs to a job-manager.
* at the given address using the default port.
*
* @param config The configuration for the client-side processes, like the optimizer.
* @param maxSlots maxSlots The number of maxSlots on the cluster if != -1.
*
* @throws java.io.IOException Thrown, if the client's actor system could not be started.
* @throws java.net.UnknownHostException Thrown, if the JobManager's hostname could not be resolved.
*/
public CLASS_0(Configuration VAR_1, int VAR_3) throws IMPORT_3 {
this.VAR_1 = Preconditions.checkNotNull(VAR_1);
this.compiler = new Optimizer(new IMPORT_20(), new DefaultCostEstimator(), VAR_1);
this.VAR_3 = VAR_3;
VAR_0.FUNC_0("Starting client actor system");
try {
this.actorSystem = IMPORT_34.FUNC_1(VAR_1);
} catch (CLASS_1 VAR_5) {
throw new IMPORT_3("Could start client actor system.", VAR_5);
}
VAR_2 = IMPORT_33.FUNC_2(VAR_1);
lookupTimeout = IMPORT_33.getLookupTimeout(VAR_1);
}
// ------------------------------------------------------------------------
// Startup & Shutdown
// ------------------------------------------------------------------------
/**
* Shuts down the client. This stops the internal actor system and actors.
*/
public void shutdown() {
if (!this.actorSystem.FUNC_3()) {
this.actorSystem.shutdown();
this.actorSystem.awaitTermination();
}
}
// ------------------------------------------------------------------------
// Configuration
// ------------------------------------------------------------------------
/**
* Configures whether the client should print progress updates during the execution to {@code System.out}.
* All updates are logged via the SLF4J loggers regardless of this setting.
*
* @param print True to print updates to standard out during execution, false to not print them.
*/
public void FUNC_4(boolean VAR_6) {
this.printStatusDuringExecution = VAR_6;
}
/**
* @return whether the client will print progress updates during the execution to {@code System.out}
*/
public boolean getPrintStatusDuringExecution() {
return this.printStatusDuringExecution;
}
/**
* @return -1 if unknown. The maximum number of available processing slots at the Flink cluster
* connected to this client.
*/
public int getMaxSlots() {
return this.VAR_3;
}
// ------------------------------------------------------------------------
// Access to the Program's Plan
// ------------------------------------------------------------------------
public static CLASS_2 getOptimizedPlanAsJson(Optimizer compiler, CLASS_3 VAR_7, int VAR_8)
throws IMPORT_19, ProgramInvocationException
{
IMPORT_26 VAR_9 = new IMPORT_26();
return VAR_9.getOptimizerPlanAsJSON((OptimizedPlan) FUNC_5(compiler, VAR_7, VAR_8));
}
public static IMPORT_23 FUNC_5(Optimizer compiler, CLASS_3 VAR_7, int VAR_8)
throws IMPORT_19, ProgramInvocationException
{
Thread.FUNC_6().FUNC_7(VAR_7.FUNC_8());
if (VAR_7.isUsingProgramEntryPoint()) {
return FUNC_5(compiler, VAR_7.getPlanWithJars(), VAR_8);
} else if (VAR_7.FUNC_9()) {
// temporary hack to support the optimizer plan preview
OptimizerPlanEnvironment env = new OptimizerPlanEnvironment(compiler);
if (VAR_8 > 0) {
env.FUNC_10(VAR_8);
}
return env.FUNC_5(VAR_7);
} else {
throw new CLASS_4("Couldn't determine program mode.");
}
}
public static OptimizedPlan FUNC_5(Optimizer compiler, IMPORT_17 VAR_10, int VAR_8) throws IMPORT_19 {
if (VAR_8 > 0 && VAR_10.getDefaultParallelism() <= 0) {
VAR_0.FUNC_11("Changing plan default parallelism from {} to {}", VAR_10.getDefaultParallelism(), VAR_8);
VAR_10.setDefaultParallelism(VAR_8);
}
VAR_0.FUNC_11("Set parallelism {}, plan default parallelism {}", VAR_8, VAR_10.getDefaultParallelism());
return compiler.compile(VAR_10);
}
// ------------------------------------------------------------------------
// Program submission / execution
// ------------------------------------------------------------------------
public IMPORT_13 FUNC_12(CLASS_3 VAR_7, int VAR_8) throws ProgramInvocationException {
Thread.FUNC_6().FUNC_7(VAR_7.FUNC_8());
if (VAR_7.isUsingProgramEntryPoint()) {
return FUNC_12(VAR_7.getPlanWithJars(), VAR_8, VAR_7.FUNC_13());
}
else if (VAR_7.FUNC_9()) {
VAR_0.FUNC_0("Starting program in interactive mode");
VAR_11.FUNC_14(new CLASS_5(this, VAR_7.FUNC_15(),
VAR_7.FUNC_16(), VAR_7.FUNC_8(), VAR_8, true,
VAR_7.FUNC_13()));
// invoke here
try {
VAR_7.FUNC_17();
}
finally {
VAR_11.FUNC_18();
}
return new IMPORT_13(VAR_4);
}
else {
throw new CLASS_4();
}
}
public IMPORT_13 FUNC_19(CLASS_3 VAR_7, int VAR_8)
throws ProgramInvocationException
{
Thread.FUNC_6().FUNC_7(VAR_7.FUNC_8());
if (VAR_7.isUsingProgramEntryPoint()) {
return FUNC_19(VAR_7.getPlanWithJars(), VAR_8, VAR_7.FUNC_13());
}
else if (VAR_7.FUNC_9()) {
VAR_0.FUNC_0("Starting program in interactive mode");
CLASS_5 factory = new CLASS_5(this, VAR_7.FUNC_15(),
VAR_7.FUNC_16(), VAR_7.FUNC_8(), VAR_8, false,
VAR_7.FUNC_13());
VAR_11.FUNC_14(factory);
// invoke here
try {
VAR_7.FUNC_17();
return ((DetachedEnvironment) factory.FUNC_20()).FUNC_21();
}
finally {
VAR_11.FUNC_18();
}
}
else {
throw new CLASS_4("PackagedProgram does not have a valid invocation mode.");
}
}
public IMPORT_16 FUNC_12(CLASS_6 program, int VAR_8) throws ProgramInvocationException {
return FUNC_12(program, VAR_8, null);
}
/**
* Runs a program on the Flink cluster to which this client is connected. The call blocks until the
* execution is complete, and returns afterwards.
*
* @param program The program to be executed.
* @param parallelism The default parallelism to use when running the program. The default parallelism is used
* when the program does not set a parallelism by itself.
*
* @throws CompilerException Thrown, if the compiler encounters an illegal situation.
* @throws ProgramInvocationException Thrown, if the program could not be instantiated from its jar file,
* or if the submission failed. That might be either due to an I/O problem,
* i.e. the job-manager is unreachable, or due to the fact that the
* parallel execution failed.
*/
public IMPORT_16 FUNC_12(CLASS_6 program, int VAR_8, CLASS_2 savepointPath)
throws IMPORT_19, ProgramInvocationException {
CLASS_7 VAR_13 = program.FUNC_8();
if (VAR_13 == null) {
throw new CLASS_8("The given JobWithJars does not provide a usercode class loader.");
}
OptimizedPlan VAR_14 = FUNC_5(compiler, program, VAR_8);
return FUNC_12(VAR_14, program.FUNC_22(), program.FUNC_16(), VAR_13, savepointPath);
}
public IMPORT_13 FUNC_19(CLASS_6 program, int VAR_8) throws ProgramInvocationException {
return FUNC_19(program, VAR_8, null);
}
/**
* Submits a program to the Flink cluster to which this client is connected. The call returns after the
* program was submitted and does not wait for the program to complete.
*
* @param program The program to be executed.
* @param parallelism The default parallelism to use when running the program. The default parallelism is used
* when the program does not set a parallelism by itself.
*
* @throws CompilerException Thrown, if the compiler encounters an illegal situation.
* @throws ProgramInvocationException Thrown, if the program could not be instantiated from its jar file,
* or if the submission failed. That might be either due to an I/O problem,
* i.e. the job-manager is unreachable.
*/
public IMPORT_13 FUNC_19(CLASS_6 program, int VAR_8, CLASS_2 savepointPath)
throws IMPORT_19, ProgramInvocationException {
CLASS_7 VAR_13 = program.FUNC_8();
if (VAR_13 == null) {
throw new CLASS_8("The given JobWithJars does not provide a usercode class loader.");
}
OptimizedPlan VAR_15 = FUNC_5(compiler, program, VAR_8);
return FUNC_19(VAR_15, program.FUNC_22(), program.FUNC_16(), VAR_13, savepointPath);
}
public IMPORT_16 FUNC_12(
IMPORT_23 VAR_16, IMPORT_7<IMPORT_4> VAR_17, IMPORT_7<IMPORT_4> VAR_18, CLASS_7 VAR_13) throws ProgramInvocationException {
return FUNC_12(VAR_16, VAR_17, VAR_18, VAR_13, null);
}
public IMPORT_16 FUNC_12(IMPORT_23 VAR_16, IMPORT_7<IMPORT_4> VAR_17, IMPORT_7<IMPORT_4> VAR_18,
CLASS_7 VAR_13, CLASS_2 savepointPath) throws ProgramInvocationException
{
IMPORT_37 VAR_19 = FUNC_23(VAR_16, VAR_17, VAR_18, savepointPath);
return FUNC_12(VAR_19, VAR_13);
}
public IMPORT_13 FUNC_19(IMPORT_23 VAR_16, IMPORT_7<IMPORT_4> VAR_17, IMPORT_7<IMPORT_4> VAR_18, CLASS_7 VAR_13) throws ProgramInvocationException {
return FUNC_19(VAR_16, VAR_17, VAR_18, VAR_13, null);
}
public IMPORT_13 FUNC_19(IMPORT_23 VAR_16, IMPORT_7<IMPORT_4> VAR_17, IMPORT_7<IMPORT_4> VAR_18,
CLASS_7 VAR_13, CLASS_2 savepointPath) throws ProgramInvocationException
{
IMPORT_37 VAR_19 = FUNC_23(VAR_16, VAR_17, VAR_18, savepointPath);
return FUNC_19(VAR_19, VAR_13);
}
public IMPORT_16 FUNC_12(IMPORT_37 VAR_20, CLASS_7 VAR_13) throws ProgramInvocationException {
LeaderRetrievalService VAR_21;
try {
VAR_21 = IMPORT_41.FUNC_24(VAR_1);
} catch (CLASS_1 VAR_5) {
throw new ProgramInvocationException("Could not create the leader retrieval service.", VAR_5);
}
try {
this.VAR_4 = VAR_20.getJobID();
return IMPORT_34.FUNC_25(actorSystem, VAR_21, VAR_20, VAR_2, printStatusDuringExecution, VAR_13);
} catch (IMPORT_35 VAR_5) {
throw new ProgramInvocationException("The program execution failed: " + VAR_5.FUNC_26(), VAR_5);
}
}
public IMPORT_13 FUNC_19(IMPORT_37 VAR_20, CLASS_7 VAR_13) throws ProgramInvocationException {
IMPORT_36 jobManagerGateway;
try {
jobManagerGateway = getJobManagerGateway();
} catch (CLASS_1 VAR_5) {
throw new ProgramInvocationException("Failed to retrieve the JobManager gateway.", VAR_5);
}
VAR_0.FUNC_0("Checking and uploading JAR files");
try {
IMPORT_34.FUNC_27(VAR_20, jobManagerGateway, VAR_2);
}
catch (IMPORT_3 VAR_5) {
throw new ProgramInvocationException("Could not upload the program's JAR files to the JobManager.", VAR_5);
}
try {
this.VAR_4 = VAR_20.getJobID();
IMPORT_34.FUNC_28(jobManagerGateway, VAR_20, VAR_2, VAR_13);
return new IMPORT_13(VAR_20.getJobID());
} catch (IMPORT_35 VAR_5) {
throw new ProgramInvocationException("The program execution failed: " + VAR_5.FUNC_26(), VAR_5);
}
}
/**
* Cancels a job identified by the job id.
* @param jobId the job id
* @throws Exception In case an error occurred.
*/
public void FUNC_29(IMPORT_12 VAR_22) throws CLASS_1 {
final IMPORT_36 jobManagerGateway = getJobManagerGateway();
final IMPORT_45<CLASS_9> VAR_23;
try {
VAR_23 = jobManagerGateway.FUNC_30(new IMPORT_40.CancelJob(VAR_22), VAR_2);
} catch (final CLASS_1 VAR_5) {
throw new ProgramInvocationException("Failed to query the job manager gateway.", VAR_5);
}
final CLASS_9 result = IMPORT_44.result(VAR_23, VAR_2);
if (result instanceof IMPORT_40.CLASS_10) {
VAR_0.FUNC_0("Job cancellation with ID " + VAR_22 + " succeeded.");
} else if (result instanceof IMPORT_40.CLASS_11) {
final CLASS_12 VAR_24 = ((IMPORT_40.CLASS_11) result).FUNC_31();
VAR_0.FUNC_0("Job cancellation with ID " + VAR_22 + " failed.", VAR_24);
throw new CLASS_1("Failed to cancel the job because of \n" + VAR_24.FUNC_26());
} else {
throw new CLASS_1("Unknown message received while cancelling: " + result.FUNC_32().getName());
}
}
/**
* Stops a program on Flink cluster whose job-manager is configured in this client's configuration.
* Stopping works only for streaming programs. Be aware, that the program might continue to run for
* a while after sending the stop command, because after sources stopped to emit data all operators
* need to finish processing.
*
* @param jobId
* the job ID of the streaming program to stop
* @throws Exception
* If the job ID is invalid (ie, is unknown or refers to a batch job) or if sending the stop signal
* failed. That might be due to an I/O problem, ie, the job-manager is unreachable.
*/
public void FUNC_33(final IMPORT_12 VAR_22) throws CLASS_1 {
final IMPORT_36 jobManagerGateway = getJobManagerGateway();
final IMPORT_45<CLASS_9> VAR_23;
try {
VAR_23 = jobManagerGateway.FUNC_30(new IMPORT_40.CLASS_13(VAR_22), VAR_2);
} catch (final CLASS_1 VAR_5) {
throw new ProgramInvocationException("Failed to query the job manager gateway.", VAR_5);
}
final CLASS_9 result = IMPORT_44.result(VAR_23, VAR_2);
if (result instanceof IMPORT_40.CLASS_14) {
VAR_0.FUNC_0("Job stopping with ID " + VAR_22 + " succeeded.");
} else if (result instanceof IMPORT_40.CLASS_15) {
final CLASS_12 VAR_24 = ((IMPORT_40.CLASS_15) result).FUNC_31();
VAR_0.FUNC_0("Job stopping with ID " + VAR_22 + " failed.", VAR_24);
throw new CLASS_1("Failed to stop the job because of \n" + VAR_24.FUNC_26());
} else {
throw new CLASS_1("Unknown message received while stopping: " + result.FUNC_32().getName());
}
}
/**
* Requests and returns the accumulators for the given job identifier. Accumulators can be
* requested while a is running or after it has finished. The default class loader is used
* to deserialize the incoming accumulator results.
* @param jobID The job identifier of a job.
* @return A Map containing the accumulator's name and its value.
*/
public IMPORT_8<CLASS_2, CLASS_9> FUNC_34(IMPORT_12 VAR_25) throws CLASS_1 {
return FUNC_34(VAR_25, VAR_12.FUNC_35());
}
/**
* Requests and returns the accumulators for the given job identifier. Accumulators can be
* requested while a is running or after it has finished.
* @param jobID The job identifier of a job.
* @param loader The class loader for deserializing the accumulator results.
* @return A Map containing the accumulator's name and its value.
*/
public IMPORT_8<CLASS_2, CLASS_9> FUNC_34(IMPORT_12 VAR_25, CLASS_7 loader) throws CLASS_1 {
IMPORT_36 jobManagerGateway = getJobManagerGateway();
IMPORT_45<CLASS_9> VAR_23;
try {
VAR_23 = jobManagerGateway.FUNC_30(new RequestAccumulatorResults(VAR_25), VAR_2);
} catch (CLASS_1 VAR_5) {
throw new CLASS_1("Failed to query the job manager gateway for accumulators.", VAR_5);
}
CLASS_9 result = IMPORT_44.result(VAR_23, VAR_2);
if (result instanceof AccumulatorResultsFound) {
IMPORT_8<CLASS_2, IMPORT_42<CLASS_9>> serializedAccumulators =
((AccumulatorResultsFound) result).result();
return IMPORT_15.FUNC_36(serializedAccumulators, loader);
} else if (result instanceof AccumulatorResultsErroneous) {
throw ((AccumulatorResultsErroneous) result).FUNC_31();
} else {
throw new CLASS_1("Failed to fetch accumulators for the job " + VAR_25 + ".");
}
}
// ------------------------------------------------------------------------
// Sessions
// ------------------------------------------------------------------------
/**
* Tells the JobManager to finish the session (job) defined by the given ID.
*
* @param jobId The ID that identifies the session.
*/
public void FUNC_37(IMPORT_12 VAR_22) throws CLASS_1 {
if (VAR_22 == null) {
throw new CLASS_8("The JobID must not be null.");
}
FUNC_38(IMPORT_6.FUNC_39(VAR_22));
}
/**
* Tells the JobManager to finish the sessions (jobs) defined by the given IDs.
*
* @param jobIds The IDs that identify the sessions.
*/
public void FUNC_38(IMPORT_7<IMPORT_12> VAR_26) throws CLASS_1 {
if (VAR_26 == null) {
throw new CLASS_8("The JobIDs must not be null");
}
IMPORT_36 jobManagerGateway = getJobManagerGateway();
for (IMPORT_12 VAR_27 : VAR_26) {
if (VAR_27 != null) {
VAR_0.FUNC_0("Telling job manager to end the session {}.", VAR_27);
jobManagerGateway.FUNC_40(new IMPORT_40.CLASS_16(VAR_27));
}
}
}
// ------------------------------------------------------------------------
// Internal translation methods
// ------------------------------------------------------------------------
/**
* Creates the optimized plan for a given program, using this client's compiler.
*
* @param prog The program to be compiled.
* @return The compiled and optimized plan, as returned by the compiler.
* @throws CompilerException Thrown, if the compiler encounters an illegal situation.
* @throws ProgramInvocationException Thrown, if the program could not be instantiated from its jar file.
*/
private static OptimizedPlan FUNC_5(Optimizer compiler, CLASS_6 VAR_7, int VAR_8)
throws IMPORT_19, ProgramInvocationException {
return FUNC_5(compiler, VAR_7.FUNC_41(), VAR_8);
}
public IMPORT_37 FUNC_23(CLASS_3 VAR_7, IMPORT_23 VAR_14) throws ProgramInvocationException {
return FUNC_23(VAR_14, VAR_7.FUNC_15(), VAR_7.FUNC_16(), null);
}
public IMPORT_37 FUNC_23(CLASS_3 VAR_7, IMPORT_23 VAR_14, CLASS_2 savepointPath) throws ProgramInvocationException {
return FUNC_23(VAR_14, VAR_7.FUNC_15(), VAR_7.FUNC_16(), savepointPath);
}
private IMPORT_37 FUNC_23(IMPORT_23 VAR_14, IMPORT_7<IMPORT_4> jarFiles, IMPORT_7<IMPORT_4> VAR_18, CLASS_2 savepointPath) {
IMPORT_37 VAR_19;
if (VAR_14 instanceof IMPORT_24) {
VAR_19 = ((IMPORT_24) VAR_14).FUNC_23();
VAR_19.setSavepointPath(savepointPath);
} else {
IMPORT_28 gen = new IMPORT_28(this.VAR_1);
VAR_19 = gen.compileJobGraph((OptimizedPlan) VAR_14);
}
for (IMPORT_4 jar : jarFiles) {
try {
VAR_19.FUNC_42(new IMPORT_31(jar.toURI()));
} catch (URISyntaxException VAR_5) {
throw new CLASS_4("URL is invalid. This should not happen.", VAR_5);
}
}
VAR_19.FUNC_43(VAR_18);
return VAR_19;
}
// ------------------------------------------------------------------------
// Helper methods
// ------------------------------------------------------------------------
/**
* Returns the {@link ActorGateway} of the current job manager leader using
* the {@link LeaderRetrievalService}.
*
* @return ActorGateway of the current job manager leader
* @throws Exception
*/
private IMPORT_36 getJobManagerGateway() throws CLASS_1 {
VAR_0.FUNC_0("Looking up JobManager");
LeaderRetrievalService VAR_21;
VAR_21 = IMPORT_41.FUNC_24(VAR_1);
return IMPORT_41.retrieveLeaderGateway(
VAR_21,
actorSystem,
lookupTimeout);
}
}
| 0.665575
|
{'IMPORT_0': 'apache', 'IMPORT_1': 'flink', 'IMPORT_2': 'java', 'IMPORT_3': 'IOException', 'IMPORT_4': 'URL', 'IMPORT_5': 'util', 'IMPORT_6': 'Collections', 'IMPORT_7': 'List', 'IMPORT_8': 'Map', 'IMPORT_9': 'com', 'IMPORT_10': 'base', 'IMPORT_11': 'api', 'IMPORT_12': 'JobID', 'IMPORT_13': 'JobSubmissionResult', 'IMPORT_14': 'accumulators', 'IMPORT_15': 'AccumulatorHelper', 'IMPORT_16': 'JobExecutionResult', 'IMPORT_17': 'Plan', 'IMPORT_18': 'optimizer', 'IMPORT_19': 'CompilerException', 'IMPORT_20': 'DataStatistics', 'IMPORT_21': 'costs', 'IMPORT_22': 'plan', 'IMPORT_23': 'FlinkPlan', 'IMPORT_24': 'StreamingPlan', 'IMPORT_25': 'plandump', 'IMPORT_26': 'PlanJSONDumpGenerator', 'IMPORT_27': 'plantranslate', 'IMPORT_28': 'JobGraphGenerator', 'IMPORT_29': 'configuration', 'IMPORT_30': 'core', 'IMPORT_31': 'Path', 'IMPORT_32': 'runtime', 'IMPORT_33': 'AkkaUtils', 'IMPORT_34': 'JobClient', 'IMPORT_35': 'JobExecutionException', 'IMPORT_36': 'ActorGateway', 'IMPORT_37': 'JobGraph', 'IMPORT_38': 'leaderretrieval', 'IMPORT_39': 'messages', 'IMPORT_40': 'JobManagerMessages', 'IMPORT_41': 'LeaderRetrievalUtils', 'IMPORT_42': 'SerializedValue', 'IMPORT_43': 'concurrent', 'IMPORT_44': 'Await', 'IMPORT_45': 'Future', 'IMPORT_46': 'duration', 'IMPORT_47': 'actor', 'IMPORT_48': 'ActorSystem', 'CLASS_0': 'Client', 'VAR_0': 'LOG', 'VAR_1': 'config', 'VAR_2': 'timeout', 'VAR_3': 'maxSlots', 'VAR_4': 'lastJobID', 'FUNC_0': 'info', 'FUNC_1': 'startJobClientActorSystem', 'CLASS_1': 'Exception', 'VAR_5': 'e', 'FUNC_2': 'getClientTimeout', 'FUNC_3': 'isTerminated', 'FUNC_4': 'setPrintStatusDuringExecution', 'VAR_6': 'print', 'CLASS_2': 'String', 'CLASS_3': 'PackagedProgram', 'VAR_7': 'prog', 'VAR_8': 'parallelism', 'VAR_9': 'jsonGen', 'FUNC_5': 'getOptimizedPlan', 'FUNC_6': 'currentThread', 'FUNC_7': 'setContextClassLoader', 'FUNC_8': 'getUserCodeClassLoader', 'FUNC_9': 'isUsingInteractiveMode', 'FUNC_10': 'setParallelism', 'CLASS_4': 'RuntimeException', 'VAR_10': 'p', 'FUNC_11': 'debug', 'FUNC_12': 'runBlocking', 'FUNC_13': 'getSavepointPath', 'VAR_11': 'ContextEnvironment', 'FUNC_14': 'setAsContext', 'CLASS_5': 'ContextEnvironmentFactory', 'FUNC_15': 'getAllLibraries', 'FUNC_16': 'getClasspaths', 'FUNC_17': 'invokeInteractiveModeForExecution', 'FUNC_18': 'unsetContext', 'FUNC_19': 'runDetached', 'FUNC_20': 'getLastEnvCreated', 'FUNC_21': 'finalizeExecute', 'CLASS_6': 'JobWithJars', 'CLASS_7': 'ClassLoader', 'VAR_12': 'ClassLoader', 'VAR_13': 'classLoader', 'CLASS_8': 'IllegalArgumentException', 'VAR_14': 'optPlan', 'FUNC_22': 'getJarFiles', 'VAR_15': 'optimizedPlan', 'VAR_16': 'compiledPlan', 'VAR_17': 'libraries', 'VAR_18': 'classpaths', 'VAR_19': 'job', 'FUNC_23': 'getJobGraph', 'VAR_20': 'jobGraph', 'VAR_21': 'leaderRetrievalService', 'FUNC_24': 'createLeaderRetrievalService', 'FUNC_25': 'submitJobAndWait', 'FUNC_26': 'getMessage', 'FUNC_27': 'uploadJarFiles', 'FUNC_28': 'submitJobDetached', 'FUNC_29': 'cancel', 'VAR_22': 'jobId', 'CLASS_9': 'Object', 'VAR_23': 'response', 'FUNC_30': 'ask', 'CLASS_10': 'CancellationSuccess', 'CLASS_11': 'CancellationFailure', 'CLASS_12': 'Throwable', 'VAR_24': 't', 'FUNC_31': 'cause', 'FUNC_32': 'getClass', 'FUNC_33': 'stop', 'CLASS_13': 'StopJob', 'CLASS_14': 'StoppingSuccess', 'CLASS_15': 'StoppingFailure', 'FUNC_34': 'getAccumulators', 'VAR_25': 'jobID', 'FUNC_35': 'getSystemClassLoader', 'FUNC_36': 'deserializeAccumulators', 'FUNC_37': 'endSession', 'FUNC_38': 'endSessions', 'FUNC_39': 'singletonList', 'VAR_26': 'jobIds', 'VAR_27': 'jid', 'FUNC_40': 'tell', 'CLASS_16': 'RemoveCachedJob', 'FUNC_41': 'getPlan', 'FUNC_42': 'addJar', 'FUNC_43': 'setClasspaths'}
|
java
|
Hibrido
|
12.82%
|
/**
* A fake {@link DataSource} capable of simulating various scenarios. It uses a {@link FakeDataSet}
* instance which determines the response to data access calls.
*/
public class FakeDataSource implements DataSource {
/**
* Factory to create a {@link FakeDataSource}.
*/
public static class Factory implements DataSource.Factory {
protected final TransferListener<? super FakeDataSource> transferListener;
protected FakeDataSet fakeDataSet;
public Factory(@Nullable TransferListener<? super FakeDataSource> transferListener) {
this.transferListener = transferListener;
}
public final Factory setFakeDataSet(FakeDataSet fakeDataSet) {
this.fakeDataSet = fakeDataSet;
return this;
}
@Override
public DataSource createDataSource() {
return new FakeDataSource(fakeDataSet, transferListener);
}
}
private final FakeDataSet fakeDataSet;
private final TransferListener<? super FakeDataSource> transferListener;
private final ArrayList<DataSpec> openedDataSpecs;
private Uri uri;
private boolean opened;
private FakeData fakeData;
private int currentSegmentIndex;
private long bytesRemaining;
public FakeDataSource() {
this(new FakeDataSet());
}
public FakeDataSource(FakeDataSet fakeDataSet) {
this(fakeDataSet, null);
}
public FakeDataSource(FakeDataSet fakeDataSet,
@Nullable TransferListener<? super FakeDataSource> transferListener) {
Assertions.checkNotNull(fakeDataSet);
this.fakeDataSet = fakeDataSet;
this.transferListener = transferListener;
this.openedDataSpecs = new ArrayList<>();
}
public final FakeDataSet getDataSet() {
return fakeDataSet;
}
@Override
public final long open(DataSpec dataSpec) throws IOException {
Assertions.checkState(!opened);
// DataSpec requires a matching close call even if open fails.
opened = true;
uri = dataSpec.uri;
openedDataSpecs.add(dataSpec);
fakeData = fakeDataSet.getData(uri.toString());
if (fakeData == null) {
throw new IOException("Data not found: " + dataSpec.uri);
}
long totalLength = 0;
for (Segment segment : fakeData.getSegments()) {
totalLength += segment.length;
}
if (totalLength == 0) {
throw new IOException("Data is empty: " + dataSpec.uri);
}
// If the source knows that the request is unsatisfiable then fail.
if (dataSpec.position >= totalLength || (dataSpec.length != C.LENGTH_UNSET
&& (dataSpec.position + dataSpec.length > totalLength))) {
throw new DataSourceException(DataSourceException.POSITION_OUT_OF_RANGE);
}
// Scan through the segments, configuring them for the current read.
boolean findingCurrentSegmentIndex = true;
currentSegmentIndex = 0;
int scannedLength = 0;
for (Segment segment : fakeData.getSegments()) {
segment.bytesRead =
(int) Math.min(Math.max(0, dataSpec.position - scannedLength), segment.length);
scannedLength += segment.length;
findingCurrentSegmentIndex &= segment.isErrorSegment() ? segment.exceptionCleared
: (!segment.isActionSegment() && segment.bytesRead == segment.length);
if (findingCurrentSegmentIndex) {
currentSegmentIndex++;
}
}
if (transferListener != null) {
transferListener.onTransferStart(this, dataSpec);
}
// Configure bytesRemaining, and return.
if (dataSpec.length == C.LENGTH_UNSET) {
bytesRemaining = totalLength - dataSpec.position;
return fakeData.isSimulatingUnknownLength() ? C.LENGTH_UNSET : bytesRemaining;
} else {
bytesRemaining = dataSpec.length;
return bytesRemaining;
}
}
@Override
public final int read(byte[] buffer, int offset, int readLength) throws IOException {
Assertions.checkState(opened);
while (true) {
if (currentSegmentIndex == fakeData.getSegments().size() || bytesRemaining == 0) {
return C.RESULT_END_OF_INPUT;
}
Segment current = fakeData.getSegments().get(currentSegmentIndex);
if (current.isErrorSegment()) {
if (!current.exceptionCleared) {
current.exceptionThrown = true;
throw (IOException) current.exception.fillInStackTrace();
} else {
currentSegmentIndex++;
}
} else if (current.isActionSegment()) {
currentSegmentIndex++;
current.action.run();
} else {
// Read at most bytesRemaining.
readLength = (int) Math.min(readLength, bytesRemaining);
// Do not allow crossing of the segment boundary.
readLength = Math.min(readLength, current.length - current.bytesRead);
// Perform the read and return.
if (current.data != null) {
System.arraycopy(current.data, current.bytesRead, buffer, offset, readLength);
}
onDataRead(readLength);
if (transferListener != null) {
transferListener.onBytesTransferred(this, readLength);
}
bytesRemaining -= readLength;
current.bytesRead += readLength;
if (current.bytesRead == current.length) {
currentSegmentIndex++;
}
return readLength;
}
}
}
@Override
public final Uri getUri() {
return uri;
}
@Override
public final void close() throws IOException {
Assertions.checkState(opened);
opened = false;
uri = null;
if (fakeData != null && currentSegmentIndex < fakeData.getSegments().size()) {
Segment current = fakeData.getSegments().get(currentSegmentIndex);
if (current.isErrorSegment() && current.exceptionThrown) {
current.exceptionCleared = true;
}
}
if (transferListener != null) {
transferListener.onTransferEnd(this);
}
fakeData = null;
}
/**
* Returns the {@link DataSpec} instances passed to {@link #open(DataSpec)} since the last call to
* this method.
*/
public final DataSpec[] getAndClearOpenedDataSpecs() {
DataSpec[] dataSpecs = new DataSpec[openedDataSpecs.size()];
openedDataSpecs.toArray(dataSpecs);
openedDataSpecs.clear();
return dataSpecs;
}
protected void onDataRead(int bytesRead) {
// Do nothing. Can be overridden.
}
}
|
/**
* A fake {@link DataSource} capable of simulating various scenarios. It uses a {@link FakeDataSet}
* instance which determines the response to data access calls.
*/
public class CLASS_0 implements CLASS_1 {
/**
* Factory to create a {@link FakeDataSource}.
*/
public static class CLASS_2 implements CLASS_1.CLASS_2 {
protected final CLASS_3<? super CLASS_0> VAR_0;
protected CLASS_4 VAR_1;
public CLASS_2(@VAR_2 CLASS_3<? super CLASS_0> VAR_0) {
this.VAR_0 = VAR_0;
}
public final CLASS_2 FUNC_0(CLASS_4 VAR_1) {
this.VAR_1 = VAR_1;
return this;
}
@VAR_3
public CLASS_1 FUNC_1() {
return new CLASS_0(VAR_1, VAR_0);
}
}
private final CLASS_4 VAR_1;
private final CLASS_3<? super CLASS_0> VAR_0;
private final CLASS_5<CLASS_6> VAR_4;
private CLASS_7 VAR_5;
private boolean VAR_6;
private CLASS_8 VAR_7;
private int VAR_8;
private long VAR_9;
public CLASS_0() {
this(new CLASS_4());
}
public CLASS_0(CLASS_4 VAR_1) {
this(VAR_1, null);
}
public CLASS_0(CLASS_4 VAR_1,
@VAR_2 CLASS_3<? super CLASS_0> VAR_0) {
VAR_10.FUNC_2(VAR_1);
this.VAR_1 = VAR_1;
this.VAR_0 = VAR_0;
this.VAR_4 = new CLASS_5<>();
}
public final CLASS_4 FUNC_3() {
return VAR_1;
}
@VAR_3
public final long FUNC_4(CLASS_6 VAR_11) throws CLASS_9 {
VAR_10.FUNC_5(!VAR_6);
// DataSpec requires a matching close call even if open fails.
VAR_6 = true;
VAR_5 = VAR_11.VAR_5;
VAR_4.FUNC_6(VAR_11);
VAR_7 = VAR_1.FUNC_7(VAR_5.FUNC_8());
if (VAR_7 == null) {
throw new CLASS_9("Data not found: " + VAR_11.VAR_5);
}
long VAR_12 = 0;
for (CLASS_10 VAR_13 : VAR_7.FUNC_9()) {
VAR_12 += VAR_13.VAR_14;
}
if (VAR_12 == 0) {
throw new CLASS_9("Data is empty: " + VAR_11.VAR_5);
}
// If the source knows that the request is unsatisfiable then fail.
if (VAR_11.VAR_15 >= VAR_12 || (VAR_11.VAR_14 != VAR_16.VAR_17
&& (VAR_11.VAR_15 + VAR_11.VAR_14 > VAR_12))) {
throw new CLASS_11(VAR_18.VAR_19);
}
// Scan through the segments, configuring them for the current read.
boolean VAR_20 = true;
VAR_8 = 0;
int VAR_21 = 0;
for (CLASS_10 VAR_13 : VAR_7.FUNC_9()) {
VAR_13.VAR_22 =
(int) VAR_23.FUNC_10(VAR_23.FUNC_11(0, VAR_11.VAR_15 - VAR_21), VAR_13.VAR_14);
VAR_21 += VAR_13.VAR_14;
VAR_20 &= VAR_13.FUNC_12() ? VAR_13.VAR_24
: (!VAR_13.FUNC_13() && VAR_13.VAR_22 == VAR_13.VAR_14);
if (VAR_20) {
VAR_8++;
}
}
if (VAR_0 != null) {
VAR_0.FUNC_14(this, VAR_11);
}
// Configure bytesRemaining, and return.
if (VAR_11.VAR_14 == VAR_16.VAR_17) {
VAR_9 = VAR_12 - VAR_11.VAR_15;
return VAR_7.FUNC_15() ? VAR_16.VAR_17 : VAR_9;
} else {
VAR_9 = VAR_11.VAR_14;
return VAR_9;
}
}
@VAR_3
public final int FUNC_16(byte[] VAR_25, int VAR_26, int VAR_27) throws CLASS_9 {
VAR_10.FUNC_5(VAR_6);
while (true) {
if (VAR_8 == VAR_7.FUNC_9().FUNC_17() || VAR_9 == 0) {
return VAR_16.VAR_28;
}
CLASS_10 VAR_29 = VAR_7.FUNC_9().FUNC_18(VAR_8);
if (VAR_29.FUNC_12()) {
if (!VAR_29.VAR_24) {
VAR_29.VAR_30 = true;
throw (CLASS_9) VAR_29.VAR_31.FUNC_19();
} else {
VAR_8++;
}
} else if (VAR_29.FUNC_13()) {
VAR_8++;
VAR_29.VAR_32.FUNC_20();
} else {
// Read at most bytesRemaining.
VAR_27 = (int) VAR_23.FUNC_10(VAR_27, VAR_9);
// Do not allow crossing of the segment boundary.
VAR_27 = VAR_23.FUNC_10(VAR_27, VAR_29.VAR_14 - VAR_29.VAR_22);
// Perform the read and return.
if (VAR_29.VAR_33 != null) {
VAR_34.FUNC_21(VAR_29.VAR_33, VAR_29.VAR_22, VAR_25, VAR_26, VAR_27);
}
FUNC_22(VAR_27);
if (VAR_0 != null) {
VAR_0.FUNC_23(this, VAR_27);
}
VAR_9 -= VAR_27;
VAR_29.VAR_22 += VAR_27;
if (VAR_29.VAR_22 == VAR_29.VAR_14) {
VAR_8++;
}
return VAR_27;
}
}
}
@VAR_3
public final CLASS_7 FUNC_24() {
return VAR_5;
}
@VAR_3
public final void FUNC_25() throws CLASS_9 {
VAR_10.FUNC_5(VAR_6);
VAR_6 = false;
VAR_5 = null;
if (VAR_7 != null && VAR_8 < VAR_7.FUNC_9().FUNC_17()) {
CLASS_10 VAR_29 = VAR_7.FUNC_9().FUNC_18(VAR_8);
if (VAR_29.FUNC_12() && VAR_29.VAR_30) {
VAR_29.VAR_24 = true;
}
}
if (VAR_0 != null) {
VAR_0.FUNC_26(this);
}
VAR_7 = null;
}
/**
* Returns the {@link DataSpec} instances passed to {@link #open(DataSpec)} since the last call to
* this method.
*/
public final CLASS_6[] FUNC_27() {
CLASS_6[] VAR_35 = new CLASS_6[VAR_4.FUNC_17()];
VAR_4.FUNC_28(VAR_35);
VAR_4.FUNC_29();
return VAR_35;
}
protected void FUNC_22(int VAR_22) {
// Do nothing. Can be overridden.
}
}
| 0.998376
|
{'CLASS_0': 'FakeDataSource', 'CLASS_1': 'DataSource', 'CLASS_2': 'Factory', 'CLASS_3': 'TransferListener', 'VAR_0': 'transferListener', 'CLASS_4': 'FakeDataSet', 'VAR_1': 'fakeDataSet', 'VAR_2': 'Nullable', 'FUNC_0': 'setFakeDataSet', 'VAR_3': 'Override', 'FUNC_1': 'createDataSource', 'CLASS_5': 'ArrayList', 'CLASS_6': 'DataSpec', 'VAR_4': 'openedDataSpecs', 'CLASS_7': 'Uri', 'VAR_5': 'uri', 'VAR_6': 'opened', 'CLASS_8': 'FakeData', 'VAR_7': 'fakeData', 'VAR_8': 'currentSegmentIndex', 'VAR_9': 'bytesRemaining', 'VAR_10': 'Assertions', 'FUNC_2': 'checkNotNull', 'FUNC_3': 'getDataSet', 'FUNC_4': 'open', 'VAR_11': 'dataSpec', 'CLASS_9': 'IOException', 'FUNC_5': 'checkState', 'FUNC_6': 'add', 'FUNC_7': 'getData', 'FUNC_8': 'toString', 'VAR_12': 'totalLength', 'CLASS_10': 'Segment', 'VAR_13': 'segment', 'FUNC_9': 'getSegments', 'VAR_14': 'length', 'VAR_15': 'position', 'VAR_16': 'C', 'VAR_17': 'LENGTH_UNSET', 'CLASS_11': 'DataSourceException', 'VAR_18': 'DataSourceException', 'VAR_19': 'POSITION_OUT_OF_RANGE', 'VAR_20': 'findingCurrentSegmentIndex', 'VAR_21': 'scannedLength', 'VAR_22': 'bytesRead', 'VAR_23': 'Math', 'FUNC_10': 'min', 'FUNC_11': 'max', 'FUNC_12': 'isErrorSegment', 'VAR_24': 'exceptionCleared', 'FUNC_13': 'isActionSegment', 'FUNC_14': 'onTransferStart', 'FUNC_15': 'isSimulatingUnknownLength', 'FUNC_16': 'read', 'VAR_25': 'buffer', 'VAR_26': 'offset', 'VAR_27': 'readLength', 'FUNC_17': 'size', 'VAR_28': 'RESULT_END_OF_INPUT', 'VAR_29': 'current', 'FUNC_18': 'get', 'VAR_30': 'exceptionThrown', 'VAR_31': 'exception', 'FUNC_19': 'fillInStackTrace', 'VAR_32': 'action', 'FUNC_20': 'run', 'VAR_33': 'data', 'VAR_34': 'System', 'FUNC_21': 'arraycopy', 'FUNC_22': 'onDataRead', 'FUNC_23': 'onBytesTransferred', 'FUNC_24': 'getUri', 'FUNC_25': 'close', 'FUNC_26': 'onTransferEnd', 'FUNC_27': 'getAndClearOpenedDataSpecs', 'VAR_35': 'dataSpecs', 'FUNC_28': 'toArray', 'FUNC_29': 'clear'}
|
java
|
Texto
|
0.38%
|
/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@WebServlet("/data")
public class DataServlet extends HttpServlet {
private DatastoreService datastore;
private Logger logger;
private UserService userService;
public DataServlet() {
this.datastore = DatastoreServiceFactory.getDatastoreService();
this.logger = LogManager.getLogger("Error");
this.userService = UserServiceFactory.getUserService();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String msgJSON = convertToJSON(getComments(getRequestNum(request), prefersDescending(request)));
response.setContentType("application/json;");
response.getWriter().println(msgJSON);
}
// Retrieves comments from datastore and converts them into Comment objects.
private ArrayList<Comment> getComments(int numRequests, boolean prefersDescending) {
Query query = new Query("Comment");
if (prefersDescending) {
query = query.addSort("timestamp", SortDirection.DESCENDING);
} else {
query = query.addSort("timestamp", SortDirection.ASCENDING);
}
PreparedQuery results = datastore.prepare(query);
Iterator<Entity> resultsItr = results.asIterable().iterator();
ArrayList<Comment> comments = new ArrayList<Comment>();
// Only returns numRequests amount of comments
int i = 0;
String userId = userService.isUserLoggedIn() ? userService.getCurrentUser().getEmail() : null;
while (resultsItr.hasNext() && i < numRequests) {
Entity curEntity = resultsItr.next();
String sender = (String) curEntity.getProperty("sender");
// Display name will be "I" if the current user made the comment
String name = userId != null && sender.equals(userId) ? "I" : (String) curEntity.getProperty("displayName");
String text = (String) curEntity.getProperty("text");
long timestamp = (long) curEntity.getProperty("timestamp");
String imgUrl = (String) curEntity.getProperty("imgUrl");
comments.add(new Comment(text, name, curEntity.getKey().getId(), timestamp, imgUrl));
i++;
}
return comments;
}
//Get request number from query string
private int getRequestNum(HttpServletRequest request) {
String requestString = request.getParameter("request");
int requestNum;
try {
requestNum = Integer.parseInt(requestString);
} catch (NumberFormatException e) {
logger.error("Could not convert to int: " + requestString);
return 10;
}
return requestNum;
}
//Get sorting preference from query string
private boolean prefersDescending(HttpServletRequest request) {
String preference = request.getParameter("sorting");
return preference.equals("newest") ? true : false;
}
// uses Gson library to convert comments list into json string
private String convertToJSON(ArrayList<Comment> comments) {
Gson gson = new Gson();
String json = gson.toJson(comments);
return "{\"comments\": " + json + "}";
}
}
|
/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@VAR_0("/data")
public class DataServlet extends HttpServlet {
private DatastoreService datastore;
private Logger logger;
private UserService userService;
public DataServlet() {
this.datastore = VAR_1.getDatastoreService();
this.logger = LogManager.FUNC_0("Error");
this.userService = VAR_2.getUserService();
}
@Override
public void doGet(CLASS_0 request, HttpServletResponse VAR_3) throws IOException {
String VAR_4 = convertToJSON(getComments(getRequestNum(request), FUNC_1(request)));
VAR_3.setContentType("application/json;");
VAR_3.FUNC_2().println(VAR_4);
}
// Retrieves comments from datastore and converts them into Comment objects.
private ArrayList<Comment> getComments(int numRequests, boolean VAR_5) {
Query VAR_6 = new Query("Comment");
if (VAR_5) {
VAR_6 = VAR_6.FUNC_3("timestamp", SortDirection.DESCENDING);
} else {
VAR_6 = VAR_6.FUNC_3("timestamp", SortDirection.ASCENDING);
}
PreparedQuery results = datastore.prepare(VAR_6);
Iterator<CLASS_1> VAR_7 = results.FUNC_4().iterator();
ArrayList<Comment> comments = new ArrayList<Comment>();
// Only returns numRequests amount of comments
int i = 0;
String userId = userService.isUserLoggedIn() ? userService.getCurrentUser().FUNC_5() : null;
while (VAR_7.hasNext() && i < numRequests) {
CLASS_1 curEntity = VAR_7.next();
String VAR_8 = (String) curEntity.getProperty("sender");
// Display name will be "I" if the current user made the comment
String name = userId != null && VAR_8.equals(userId) ? "I" : (String) curEntity.getProperty("displayName");
String VAR_9 = (String) curEntity.getProperty("text");
long VAR_10 = (long) curEntity.getProperty("timestamp");
String VAR_11 = (String) curEntity.getProperty("imgUrl");
comments.add(new Comment(VAR_9, name, curEntity.getKey().getId(), VAR_10, VAR_11));
i++;
}
return comments;
}
//Get request number from query string
private int getRequestNum(CLASS_0 request) {
String VAR_12 = request.getParameter("request");
int requestNum;
try {
requestNum = Integer.FUNC_6(VAR_12);
} catch (NumberFormatException e) {
logger.error("Could not convert to int: " + VAR_12);
return 10;
}
return requestNum;
}
//Get sorting preference from query string
private boolean FUNC_1(CLASS_0 request) {
String preference = request.getParameter("sorting");
return preference.equals("newest") ? true : false;
}
// uses Gson library to convert comments list into json string
private String convertToJSON(ArrayList<Comment> comments) {
Gson gson = new Gson();
String json = gson.toJson(comments);
return "{\"comments\": " + json + "}";
}
}
| 0.281122
|
{'VAR_0': 'WebServlet', 'VAR_1': 'DatastoreServiceFactory', 'FUNC_0': 'getLogger', 'VAR_2': 'UserServiceFactory', 'CLASS_0': 'HttpServletRequest', 'VAR_3': 'response', 'VAR_4': 'msgJSON', 'FUNC_1': 'prefersDescending', 'VAR_5': 'prefersDescending', 'FUNC_2': 'getWriter', 'VAR_6': 'query', 'FUNC_3': 'addSort', 'CLASS_1': 'Entity', 'VAR_7': 'resultsItr', 'FUNC_4': 'asIterable', 'FUNC_5': 'getEmail', 'VAR_8': 'sender', 'VAR_9': 'text', 'VAR_10': 'timestamp', 'VAR_11': 'imgUrl', 'VAR_12': 'requestString', 'FUNC_6': 'parseInt'}
|
java
|
Hibrido
|
100.00%
|
/*
* Copyright (c) 2017. Team CMPUT301F17T02, CMPUT301, University of Alberta - All Rights Reserved. You may use, distribute, or modify this code under terms and conditions of the Code of Students Behaviour at University of Alberta.
*/
package com.example.baard.Entities;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.zip.DataFormatException;
import io.searchbox.annotations.JestId;
/**
* Class representing a habit
* @since 1.0
* @version 2.0
* @author anarten, bangotti, rderbysh
*/
public class Habit implements Comparable<Habit> {
private String title, reason;
private String startDate;
private ArrayList<Day> frequency;
private HabitEventList events = new HabitEventList();
@JestId
private String id;
private String userId;
/**
* Constructor for Habit
*
* @param title Habit title
* @param reason Habit reason
* @param startDate Habit Start Date
* @param frequency Habit Frequency
* @throws DataFormatException for invalid input
*/
public Habit(String title, String reason, Date startDate, ArrayList<Day> frequency) throws DataFormatException {
if (title.length() <= 20) {
this.title = title;
} else {
throw new DataFormatException("Title over 20 characters.");
}
if (reason.length() <= 30) {
this.reason = reason;
} else {
throw new DataFormatException("Reason over 30 characters.");
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
this.startDate = sdf.format(startDate);
this.frequency = frequency;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Returns title for habit
*
* @return String for title
*/
public String getTitle() {
return title;
}
/**
* Sets title for habit; if over character limit, returns exception
*
* @param title new Habit title
* @throws DataFormatException on invalid input
*/
public void setTitle(String title) throws DataFormatException {
if (title.length() <= 20) {
this.title = title;
} else {
throw new DataFormatException("Title over 20 characters.");
}
}
/**
* Returns reason for habit
*
* @return String for reason
*/
public String getReason() {
return reason;
}
/**
* Sets reason for habit; if over character limit, returns exception
*
* @param reason new Reson String
* @throws DataFormatException for invalid input
*/
public void setReason(String reason) throws DataFormatException {
if (reason.length() <= 30) {
this.reason = reason;
} else {
throw new DataFormatException("Reason over 30 characters.");
}
}
/**
* Returns date for habit
*
* @return Date for habit
*/
public Date getStartDate() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
try {
return sdf.parse(startDate);
} catch (Exception e) {
return null;
}
}
/**
* Sets date for habit
*
* @param startDate new StartDate
*/
public void setStartDate(Date startDate) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
this.startDate = sdf.format(startDate);
}
/**
* Returns frequency for habit
*
* @return Habit Frequency
*/
public ArrayList<Day> getFrequency() {
return frequency;
}
/**
* Sets frequency for habit
*
* @param frequency new Habit frequency
*/
public void setFrequency(ArrayList<Day> frequency) {
this.frequency = frequency;
}
/**
* Returns frequency for habit in the form of a string
*
* @return String for frequency of Habit
*/
public String getFrequencyString() {
String days = "";
for (int i = 0; i < frequency.size(); i++) {
// alternate string replacement
// StringBuilder day = new StringBuilder(frequency.get(i).toString());
// days += day.replace(1, day.length(), day.substring(1).toLowerCase());
days += frequency.get(i).toString().substring(0,1) + frequency.get(i).toString().substring(1,3).toLowerCase();
if (i + 1 < frequency.size())
days += ", ";
}
return days;
}
/**
* Returns habit events for habit
*
* @return Events for this habit
*/
public HabitEventList getEvents() {
return events;
}
/**
* Sets entire list of habit events for habit
*
* @param events new events for this habit
*/
public void setEvents(HabitEventList events) {
this.events = events;
}
/**
* Returns habit in a specific string
*
* @return
*/
public void sendToSharedPreferences(Context context){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(this);
sharedPrefsEditor.putString("currentlyViewingHabit", json);
sharedPrefsEditor.commit();
}
/**
* Determines whether this habit is on a streak and returns the length in number of days
* @return Boolean true if streak is current
*/
public int streak() {
if (events.size() == 0) {
return 0;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE", Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime(getStartDate());
calendar.set(Calendar.DST_OFFSET, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
int streak = 0;
// ensure the current date is checked over
Date date = events.getHabitEvent(events.size()-1).getEventDate();
String dateString = sdf.format(calendar.getTime().getTime()).toUpperCase();
Day dayEnum = Day.valueOf(dateString);
if (date.equals(calendar.getTime()) && frequency.contains(dayEnum)) {
streak++;
}
// while the calendar is not beyond the start date, calculate streak
while ( !calendar.equals(start) ) {
calendar.add(Calendar.DATE, -1);
// check if date is in frequency
dateString = sdf.format(calendar.getTime().getTime()).toUpperCase();
dayEnum = Day.valueOf(dateString);
if (frequency.contains(dayEnum)) {
boolean found = false;
// checking the most recent events first
for (int i = events.size()-1; i >= 0; i--) {
date = events.getHabitEvent(i).getEventDate();
// increase streak if event date and calendar date are aligned
if (date.equals(calendar.getTime())) {
streak++;
found = true;
break;
}
}
if (!found) {
// streak was broken earlier than this point
return streak;
}
}
}
return streak;
}
/**
* Determines if this habit has achieved a milestone of 5, 10, 25, 50, or 100 overall events.
* @return integer representing the last milestone achieved. Otherwise 0.
*/
public int milestone() {
ArrayList<Integer> milestones = new ArrayList<>();
milestones.add(5);
milestones.add(10);
milestones.add(25);
milestones.add(50);
milestones.add(100);
// check for the most reasonable milestone
int toReturn = 0;
int count = events.size();
for (Integer m : milestones) {
if (count < m) {
return toReturn;
} else {
toReturn = m;
}
}
// For milestones greater than 100
while(true) {
if (count > toReturn) {
toReturn += 50;
} else {
return toReturn;
}
}
}
/**
* Compares Habits to each other. Calling Collection.sort will sort them in ascending
* order for display anywhere
* @param habit
* @return
*/
@Override
public int compareTo(Habit habit){
return this.getTitle().toLowerCase().compareTo(habit.getTitle().toLowerCase());
}
/**
* @return String representation of Habit
*/
@Override
public String toString() {
return title;
}
}
|
/*
* Copyright (c) 2017. Team CMPUT301F17T02, CMPUT301, University of Alberta - All Rights Reserved. You may use, distribute, or modify this code under terms and conditions of the Code of Students Behaviour at University of Alberta.
*/
package com.example.baard.IMPORT_0;
import android.IMPORT_1.Context;
import android.IMPORT_1.SharedPreferences;
import android.preference.IMPORT_2;
import com.IMPORT_3.IMPORT_4.Gson;
import java.text.IMPORT_5;
import java.util.IMPORT_6;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.IMPORT_7.IMPORT_8;
import io.searchbox.IMPORT_9.IMPORT_10;
/**
* Class representing a habit
* @since 1.0
* @version 2.0
* @author anarten, bangotti, rderbysh
*/
public class CLASS_0 implements Comparable<CLASS_0> {
private String title, reason;
private String VAR_0;
private IMPORT_6<CLASS_1> frequency;
private HabitEventList events = new HabitEventList();
@IMPORT_10
private String id;
private String userId;
/**
* Constructor for Habit
*
* @param title Habit title
* @param reason Habit reason
* @param startDate Habit Start Date
* @param frequency Habit Frequency
* @throws DataFormatException for invalid input
*/
public CLASS_0(String title, String reason, Date VAR_0, IMPORT_6<CLASS_1> frequency) throws IMPORT_8 {
if (title.FUNC_0() <= 20) {
this.title = title;
} else {
throw new IMPORT_8("Title over 20 characters.");
}
if (reason.FUNC_0() <= 30) {
this.reason = reason;
} else {
throw new IMPORT_8("Reason over 30 characters.");
}
IMPORT_5 VAR_2 = new IMPORT_5("dd/MM/yyyy", Locale.ENGLISH);
this.VAR_0 = VAR_2.FUNC_1(VAR_0);
this.frequency = frequency;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String FUNC_2() {
return userId;
}
public void FUNC_3(String userId) {
this.userId = userId;
}
/**
* Returns title for habit
*
* @return String for title
*/
public String getTitle() {
return title;
}
/**
* Sets title for habit; if over character limit, returns exception
*
* @param title new Habit title
* @throws DataFormatException on invalid input
*/
public void setTitle(String title) throws IMPORT_8 {
if (title.FUNC_0() <= 20) {
this.title = title;
} else {
throw new IMPORT_8("Title over 20 characters.");
}
}
/**
* Returns reason for habit
*
* @return String for reason
*/
public String FUNC_4() {
return reason;
}
/**
* Sets reason for habit; if over character limit, returns exception
*
* @param reason new Reson String
* @throws DataFormatException for invalid input
*/
public void setReason(String reason) throws IMPORT_8 {
if (reason.FUNC_0() <= 30) {
this.reason = reason;
} else {
throw new IMPORT_8("Reason over 30 characters.");
}
}
/**
* Returns date for habit
*
* @return Date for habit
*/
public Date getStartDate() {
IMPORT_5 VAR_2 = new IMPORT_5("dd/MM/yyyy", Locale.ENGLISH);
try {
return VAR_2.parse(VAR_0);
} catch (CLASS_2 e) {
return null;
}
}
/**
* Sets date for habit
*
* @param startDate new StartDate
*/
public void setStartDate(Date VAR_0) {
IMPORT_5 VAR_2 = new IMPORT_5("dd/MM/yyyy", Locale.ENGLISH);
this.VAR_0 = VAR_2.FUNC_1(VAR_0);
}
/**
* Returns frequency for habit
*
* @return Habit Frequency
*/
public IMPORT_6<CLASS_1> FUNC_5() {
return frequency;
}
/**
* Sets frequency for habit
*
* @param frequency new Habit frequency
*/
public void FUNC_6(IMPORT_6<CLASS_1> frequency) {
this.frequency = frequency;
}
/**
* Returns frequency for habit in the form of a string
*
* @return String for frequency of Habit
*/
public String getFrequencyString() {
String days = "";
for (int i = 0; i < frequency.FUNC_7(); i++) {
// alternate string replacement
// StringBuilder day = new StringBuilder(frequency.get(i).toString());
// days += day.replace(1, day.length(), day.substring(1).toLowerCase());
days += frequency.get(i).toString().substring(0,1) + frequency.get(i).toString().substring(1,3).toLowerCase();
if (i + 1 < frequency.FUNC_7())
days += ", ";
}
return days;
}
/**
* Returns habit events for habit
*
* @return Events for this habit
*/
public HabitEventList FUNC_8() {
return events;
}
/**
* Sets entire list of habit events for habit
*
* @param events new events for this habit
*/
public void setEvents(HabitEventList events) {
this.events = events;
}
/**
* Returns habit in a specific string
*
* @return
*/
public void FUNC_9(Context VAR_3){
SharedPreferences VAR_4 = IMPORT_2.FUNC_10(VAR_3);
SharedPreferences.CLASS_3 sharedPrefsEditor = VAR_4.FUNC_11();
Gson IMPORT_4 = new Gson();
String VAR_5 = IMPORT_4.toJson(this);
sharedPrefsEditor.putString("currentlyViewingHabit", VAR_5);
sharedPrefsEditor.commit();
}
/**
* Determines whether this habit is on a streak and returns the length in number of days
* @return Boolean true if streak is current
*/
public int streak() {
if (events.FUNC_7() == 0) {
return 0;
}
IMPORT_5 VAR_2 = new IMPORT_5("EEEE", Locale.ENGLISH);
Calendar VAR_6 = Calendar.FUNC_12();
Calendar VAR_7 = Calendar.FUNC_12();
VAR_7.setTime(getStartDate());
VAR_6.FUNC_13(Calendar.DST_OFFSET, 0);
VAR_6.FUNC_13(Calendar.VAR_8, 0);
VAR_6.FUNC_13(Calendar.HOUR, 0);
VAR_6.FUNC_13(Calendar.AM_PM, 0);
VAR_6.FUNC_13(Calendar.MINUTE, 0);
VAR_6.FUNC_13(Calendar.SECOND, 0);
VAR_6.FUNC_13(Calendar.VAR_9, 0);
int streak = 0;
// ensure the current date is checked over
Date VAR_10 = events.getHabitEvent(events.FUNC_7()-1).FUNC_14();
String VAR_11 = VAR_2.FUNC_1(VAR_6.FUNC_15().FUNC_15()).toUpperCase();
CLASS_1 dayEnum = VAR_1.valueOf(VAR_11);
if (VAR_10.equals(VAR_6.FUNC_15()) && frequency.FUNC_16(dayEnum)) {
streak++;
}
// while the calendar is not beyond the start date, calculate streak
while ( !VAR_6.equals(VAR_7) ) {
VAR_6.FUNC_17(Calendar.DATE, -1);
// check if date is in frequency
VAR_11 = VAR_2.FUNC_1(VAR_6.FUNC_15().FUNC_15()).toUpperCase();
dayEnum = VAR_1.valueOf(VAR_11);
if (frequency.FUNC_16(dayEnum)) {
boolean found = false;
// checking the most recent events first
for (int i = events.FUNC_7()-1; i >= 0; i--) {
VAR_10 = events.getHabitEvent(i).FUNC_14();
// increase streak if event date and calendar date are aligned
if (VAR_10.equals(VAR_6.FUNC_15())) {
streak++;
found = true;
break;
}
}
if (!found) {
// streak was broken earlier than this point
return streak;
}
}
}
return streak;
}
/**
* Determines if this habit has achieved a milestone of 5, 10, 25, 50, or 100 overall events.
* @return integer representing the last milestone achieved. Otherwise 0.
*/
public int milestone() {
IMPORT_6<Integer> milestones = new IMPORT_6<>();
milestones.FUNC_17(5);
milestones.FUNC_17(10);
milestones.FUNC_17(25);
milestones.FUNC_17(50);
milestones.FUNC_17(100);
// check for the most reasonable milestone
int toReturn = 0;
int count = events.FUNC_7();
for (Integer m : milestones) {
if (count < m) {
return toReturn;
} else {
toReturn = m;
}
}
// For milestones greater than 100
while(true) {
if (count > toReturn) {
toReturn += 50;
} else {
return toReturn;
}
}
}
/**
* Compares Habits to each other. Calling Collection.sort will sort them in ascending
* order for display anywhere
* @param habit
* @return
*/
@VAR_12
public int compareTo(CLASS_0 habit){
return this.getTitle().toLowerCase().compareTo(habit.getTitle().toLowerCase());
}
/**
* @return String representation of Habit
*/
@VAR_12
public String toString() {
return title;
}
}
| 0.400568
|
{'IMPORT_0': 'Entities', 'IMPORT_1': 'content', 'IMPORT_2': 'PreferenceManager', 'IMPORT_3': 'google', 'IMPORT_4': 'gson', 'IMPORT_5': 'SimpleDateFormat', 'IMPORT_6': 'ArrayList', 'IMPORT_7': 'zip', 'IMPORT_8': 'DataFormatException', 'IMPORT_9': 'annotations', 'IMPORT_10': 'JestId', 'CLASS_0': 'Habit', 'VAR_0': 'startDate', 'CLASS_1': 'Day', 'VAR_1': 'Day', 'FUNC_0': 'length', 'VAR_2': 'sdf', 'FUNC_1': 'format', 'FUNC_2': 'getUserId', 'FUNC_3': 'setUserId', 'FUNC_4': 'getReason', 'CLASS_2': 'Exception', 'FUNC_5': 'getFrequency', 'FUNC_6': 'setFrequency', 'FUNC_7': 'size', 'FUNC_8': 'getEvents', 'FUNC_9': 'sendToSharedPreferences', 'VAR_3': 'context', 'VAR_4': 'sharedPrefs', 'FUNC_10': 'getDefaultSharedPreferences', 'CLASS_3': 'Editor', 'FUNC_11': 'edit', 'VAR_5': 'json', 'VAR_6': 'calendar', 'FUNC_12': 'getInstance', 'VAR_7': 'start', 'FUNC_13': 'set', 'VAR_8': 'HOUR_OF_DAY', 'VAR_9': 'MILLISECOND', 'VAR_10': 'date', 'FUNC_14': 'getEventDate', 'VAR_11': 'dateString', 'FUNC_15': 'getTime', 'FUNC_16': 'contains', 'FUNC_17': 'add', 'VAR_12': 'Override'}
|
java
|
Hibrido
|
100.00%
|
/**
* desc :
* date : 2020/4/22 10:04 AM
*
* @author : dongSen
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
/**
* 1
* / \
* 2 3
* \ \
* 5 4
*/
static TreeNode obtain() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(4);
return root;
}
/**
* 5
* / \
* 1 10
* / \
* 7 11
*/
static TreeNode obtainBST() {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(1);
root.right = new TreeNode(10);
root.right.left = new TreeNode(7);
root.right.right = new TreeNode(11);
return root;
}
/**
* p
* / \
* l r
*/
static TreeNode obtain(int parent, int left, int right) {
TreeNode root = new TreeNode(parent);
root.left = new TreeNode(left);
root.right = new TreeNode(right);
return root;
}
}
|
/**
* desc :
* date : 2020/4/22 10:04 AM
*
* @author : dongSen
*/
class CLASS_0 {
int VAR_0;
CLASS_0 VAR_1;
CLASS_0 VAR_2;
CLASS_0(int VAR_3) {
VAR_0 = VAR_3;
}
/**
* 1
* / \
* 2 3
* \ \
* 5 4
*/
static CLASS_0 obtain() {
CLASS_0 VAR_4 = new CLASS_0(1);
VAR_4.VAR_1 = new CLASS_0(2);
VAR_4.VAR_2 = new CLASS_0(3);
VAR_4.VAR_1.VAR_2 = new CLASS_0(5);
VAR_4.VAR_2.VAR_2 = new CLASS_0(4);
return VAR_4;
}
/**
* 5
* / \
* 1 10
* / \
* 7 11
*/
static CLASS_0 FUNC_0() {
CLASS_0 VAR_4 = new CLASS_0(5);
VAR_4.VAR_1 = new CLASS_0(1);
VAR_4.VAR_2 = new CLASS_0(10);
VAR_4.VAR_2.VAR_1 = new CLASS_0(7);
VAR_4.VAR_2.VAR_2 = new CLASS_0(11);
return VAR_4;
}
/**
* p
* / \
* l r
*/
static CLASS_0 obtain(int VAR_5, int VAR_1, int VAR_2) {
CLASS_0 VAR_4 = new CLASS_0(VAR_5);
VAR_4.VAR_1 = new CLASS_0(VAR_1);
VAR_4.VAR_2 = new CLASS_0(VAR_2);
return VAR_4;
}
}
| 0.696593
|
{'CLASS_0': 'TreeNode', 'VAR_0': 'val', 'VAR_1': 'left', 'VAR_2': 'right', 'VAR_3': 'x', 'VAR_4': 'root', 'FUNC_0': 'obtainBST', 'VAR_5': 'parent'}
|
java
|
OOP
|
100.00%
|
/**
* Compute an optimal placement.
* <p>
* <table>
* <tr><td><tt> dims </tt></td><td> the number of processes in each
* dimension </tr>
* <tr><td><tt> periods </tt></td><td> <tt>true</tt> if grid is periodic,
* <tt>false</tt> if not, in each
* dimension </tr>
* <tr><td><em> returns: </em></td><td> reordered rank of calling
* process </tr>
* </table>
* <p>
* Java binding of the MPI operation <tt>MPI_CART_MAP</tt>.
* <p>
* The number of dimensions is taken to be size of the <tt>dims</tt> argument.
*/
public int Map(int[] dims, boolean[] periods) throws MPIException {
int procs = 1;
for (int i = 0; i < dims.length; i++) {
if (dims[i] < 0) {
throw new MPIException(" Error in Cartcomm.Map: dims["+i+"] is "+
"less than zero" );
}
procs *= dims[i];
}
int size = this.group.Size();
int rank = this.group.Rank();
if (procs > size) {
throw new MPIException(" Error in Cartcomm.Map: procs <"+procs+"> is "+
"greater than size <"+size+">");
}
return ( (rank < 0) || (rank >= procs)) ? -1 : rank;
}
|
/**
* Compute an optimal placement.
* <p>
* <table>
* <tr><td><tt> dims </tt></td><td> the number of processes in each
* dimension </tr>
* <tr><td><tt> periods </tt></td><td> <tt>true</tt> if grid is periodic,
* <tt>false</tt> if not, in each
* dimension </tr>
* <tr><td><em> returns: </em></td><td> reordered rank of calling
* process </tr>
* </table>
* <p>
* Java binding of the MPI operation <tt>MPI_CART_MAP</tt>.
* <p>
* The number of dimensions is taken to be size of the <tt>dims</tt> argument.
*/
public int FUNC_0(int[] VAR_0, boolean[] VAR_1) throws CLASS_0 {
int VAR_2 = 1;
for (int VAR_3 = 0; VAR_3 < VAR_0.VAR_4; VAR_3++) {
if (VAR_0[VAR_3] < 0) {
throw new CLASS_0(" Error in Cartcomm.Map: dims["+VAR_3+"] is "+
"less than zero" );
}
VAR_2 *= VAR_0[VAR_3];
}
int VAR_5 = this.VAR_6.FUNC_1();
int VAR_7 = this.VAR_6.FUNC_2();
if (VAR_2 > VAR_5) {
throw new CLASS_0(" Error in Cartcomm.Map: procs <"+VAR_2+"> is "+
"greater than size <"+VAR_5+">");
}
return ( (VAR_7 < 0) || (VAR_7 >= VAR_2)) ? -1 : VAR_7;
}
| 0.957408
|
{'FUNC_0': 'Map', 'VAR_0': 'dims', 'VAR_1': 'periods', 'CLASS_0': 'MPIException', 'VAR_2': 'procs', 'VAR_3': 'i', 'VAR_4': 'length', 'VAR_5': 'size', 'VAR_6': 'group', 'FUNC_1': 'Size', 'VAR_7': 'rank', 'FUNC_2': 'Rank'}
|
java
|
Procedural
|
58.18%
|
package org.alexkov.bookservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@EnableEurekaClient
@SpringBootApplication
@RestController
@RequestMapping("/books")
public class BookServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookServiceApplication.class, args);
}
private List<Book> books = Arrays.asList(
new Book(1L, "Baeldung goes to the market", "<NAME>"),
new Book(2L, "Baeldung goes to the park", "Slavisa")
);
@GetMapping("")
public List<Book> findAllBooks() {
return books;
}
@GetMapping("/{bookId}")
public Book findBook(@PathVariable Long bookId) {
return books.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null);
}
}
|
package org.alexkov.IMPORT_0;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.IMPORT_1.SpringBootApplication;
import org.springframework.cloud.IMPORT_2.IMPORT_3.EnableEurekaClient;
import org.springframework.IMPORT_4.bind.annotation.GetMapping;
import org.springframework.IMPORT_4.bind.annotation.PathVariable;
import org.springframework.IMPORT_4.bind.annotation.IMPORT_5;
import org.springframework.IMPORT_4.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@EnableEurekaClient
@SpringBootApplication
@RestController
@IMPORT_5("/books")
public class CLASS_0 {
public static void main(CLASS_1[] args) {
SpringApplication.run(CLASS_0.class, args);
}
private List<CLASS_2> VAR_0 = Arrays.FUNC_0(
new CLASS_2(1L, "Baeldung goes to the market", "<NAME>"),
new CLASS_2(2L, "Baeldung goes to the park", "Slavisa")
);
@GetMapping("")
public List<CLASS_2> findAllBooks() {
return VAR_0;
}
@GetMapping("/{bookId}")
public CLASS_2 FUNC_1(@PathVariable Long bookId) {
return VAR_0.stream().filter(b -> b.FUNC_2().equals(bookId)).findFirst().orElse(null);
}
}
| 0.447105
|
{'IMPORT_0': 'bookservice', 'IMPORT_1': 'autoconfigure', 'IMPORT_2': 'netflix', 'IMPORT_3': 'eureka', 'IMPORT_4': 'web', 'IMPORT_5': 'RequestMapping', 'CLASS_0': 'BookServiceApplication', 'CLASS_1': 'String', 'CLASS_2': 'Book', 'VAR_0': 'books', 'FUNC_0': 'asList', 'FUNC_1': 'findBook', 'FUNC_2': 'getId'}
|
java
|
Hibrido
|
53.25%
|
/**
* Base class for all Barrister IDL entity classes: Enum, Struct, Interface
*/
public abstract class BaseEntity {
protected String name;
protected String comment;
protected Contract contract;
public BaseEntity() {
}
/**
* Extracts 'name' and 'comment' fields from map
*/
public BaseEntity(Map<String, Object> obj) {
if (obj == null) {
throw new IllegalArgumentException("Map cannot be null!");
}
if (obj.containsKey("name")) {
name = (String)obj.get("name");
}
if (obj.containsKey("comment")) {
comment = (String)obj.get("comment");
}
}
/**
* Returns name of entity as defined in IDL
*/
public String getName() {
return name;
}
/**
* Returns name of entity without namespace. If name has no
* namspace, this method returns a value identical to getName()
*/
public String getSimpleName() {
String n = getName();
int pos = n.indexOf(".");
if (pos == -1)
return n;
else
return n.substring(pos+1);
}
/**
* Returns namespace for entity. If entity is not namespaced,
* returns an empty string
*/
public String getNamespace() {
int pos = name.indexOf(".");
if (pos == -1)
return "";
else
return name.substring(0, pos);
}
/**
* Returns name of entity using Java camel case convention.
* For example, name "firstName" becomes "FirstName"
*/
public String getUpperName() {
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
/**
* Returns the comment for this entity as defined in the IDL
*/
public String getComment() {
return comment;
}
/**
* Associates this entity with its Contract
*/
public void setContract(Contract c) {
contract = c;
}
/**
* Returns the Contract associated with this entity
*/
public Contract getContract() {
return contract;
}
}
|
/**
* Base class for all Barrister IDL entity classes: Enum, Struct, Interface
*/
public abstract class BaseEntity {
protected String name;
protected String comment;
protected Contract contract;
public BaseEntity() {
}
/**
* Extracts 'name' and 'comment' fields from map
*/
public BaseEntity(Map<String, Object> obj) {
if (obj == null) {
throw new IllegalArgumentException("Map cannot be null!");
}
if (obj.containsKey("name")) {
name = (String)obj.get("name");
}
if (obj.containsKey("comment")) {
comment = (String)obj.get("comment");
}
}
/**
* Returns name of entity as defined in IDL
*/
public String getName() {
return name;
}
/**
* Returns name of entity without namespace. If name has no
* namspace, this method returns a value identical to getName()
*/
public String getSimpleName() {
String n = getName();
int pos = n.indexOf(".");
if (pos == -1)
return n;
else
return n.substring(pos+1);
}
/**
* Returns namespace for entity. If entity is not namespaced,
* returns an empty string
*/
public String getNamespace() {
int pos = name.indexOf(".");
if (pos == -1)
return "";
else
return name.substring(0, pos);
}
/**
* Returns name of entity using Java camel case convention.
* For example, name "firstName" becomes "FirstName"
*/
public String getUpperName() {
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
/**
* Returns the comment for this entity as defined in the IDL
*/
public String getComment() {
return comment;
}
/**
* Associates this entity with its Contract
*/
public void setContract(Contract c) {
contract = c;
}
/**
* Returns the Contract associated with this entity
*/
public Contract getContract() {
return contract;
}
}
| 0.066302
|
{}
|
java
|
OOP
|
100.00%
|
/**
* A notification sent from the client to the server to signal the change of configuration
* settings.
*
* @see <a
* href="https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeConfiguration">specification</a>
*/
@Override
public void didChangeConfiguration(DidChangeConfigurationParams params) {
logger.info(params.toString());
server.didChangeConfiguration(
gson.fromJson(gson.toJson(params.getSettings()), Settings.class));
}
|
/**
* A notification sent from the client to the server to signal the change of configuration
* settings.
*
* @see <a
* href="https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeConfiguration">specification</a>
*/
@Override
public void FUNC_0(CLASS_0 VAR_0) {
logger.FUNC_1(VAR_0.FUNC_2());
server.FUNC_0(
gson.FUNC_3(gson.toJson(VAR_0.FUNC_4()), Settings.class));
}
| 0.471573
|
{'FUNC_0': 'didChangeConfiguration', 'CLASS_0': 'DidChangeConfigurationParams', 'VAR_0': 'params', 'FUNC_1': 'info', 'FUNC_2': 'toString', 'FUNC_3': 'fromJson', 'FUNC_4': 'getSettings'}
|
java
|
Procedural
|
94.74%
|
package com.reactiveandroid.query.api;
//pull request - bendothall
//Transactions API
import androidx.annotation.NonNull;
import android.util.Log;
import com.reactiveandroid.Model;
import com.reactiveandroid.ReActiveAndroid;
import com.reactiveandroid.annotation.Table;
import com.reactiveandroid.internal.ModelAdapter;
import com.reactiveandroid.internal.database.DatabaseInfo;
import com.reactiveandroid.internal.database.table.TableInfo;
import com.reactiveandroid.query.Insert;
import com.reactiveandroid.query.Select;
import com.reactiveandroid.query.Update;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class Transactions {
public static void BeginTransactions(Class<?> databaseClass) {
if (databaseClass == null) {
throw new IllegalArgumentException("Database Class referenced not found.");
}
ReActiveAndroid.getDatabase(databaseClass).beginTransaction();
}
public static void EndTransactions(Class<?> databaseClass) {
if (databaseClass == null) {
throw new IllegalArgumentException("Database Class referenced not found.");
}
ReActiveAndroid.getDatabase(databaseClass).getWritableDatabase().setTransactionSuccessful();
ReActiveAndroid.getDatabase(databaseClass).endTransaction();
}
public static Boolean BulkCRUDUpdates(Class<?> databaseClass, Class<?> table, List<?> modelData) {
boolean result = true;
if (databaseClass == null) {
throw new IllegalArgumentException("Database Class referenced not found.");
}
if (table == null) {
throw new IllegalArgumentException("Table Class referenced not found.");
}
if (modelData == null) {
throw new IllegalArgumentException("Model Data is Empty");
}
BeginTransactions(databaseClass);
for (Object modelClassDataHolder : modelData) {
for(Field modelClassDataHolderField : modelClassDataHolder.getClass().getDeclaredFields()){
try {
modelClassDataHolderField.setAccessible(true);
Object value = modelClassDataHolderField.get(modelClassDataHolder);
if(Select.from(table).where(modelClassDataHolderField.getName() + " = ?", value.toString()).count() == 1){
//found
//Update.table(table).set(modelClassDataHolderField.getName() + " = ?", value.toString() + " Update via Bulk").where(modelClassDataHolderField.getName() + " = ?", value.toString()).execute();
}else{
//create new
//Insert.into(table).columns(modelClassDataHolderField.getName()).values(value.toString()+ " Insert via Bulk").execute();
}
}catch (Exception error) {
}
}
}
EndTransactions(databaseClass);
return result;
}
}
|
package com.reactiveandroid.query.api;
//pull request - bendothall
//Transactions API
import androidx.annotation.NonNull;
import android.IMPORT_0.IMPORT_1;
import com.reactiveandroid.Model;
import com.reactiveandroid.ReActiveAndroid;
import com.reactiveandroid.annotation.Table;
import com.reactiveandroid.internal.ModelAdapter;
import com.reactiveandroid.internal.database.DatabaseInfo;
import com.reactiveandroid.internal.database.table.TableInfo;
import com.reactiveandroid.query.Insert;
import com.reactiveandroid.query.IMPORT_2;
import com.reactiveandroid.query.Update;
import java.lang.reflect.Field;
import java.IMPORT_0.IMPORT_3;
import java.IMPORT_0.IMPORT_4;
import java.IMPORT_0.Map;
public final class CLASS_0 {
public static void FUNC_0(Class<?> databaseClass) {
if (databaseClass == null) {
throw new IllegalArgumentException("Database Class referenced not found.");
}
ReActiveAndroid.getDatabase(databaseClass).FUNC_1();
}
public static void FUNC_2(Class<?> databaseClass) {
if (databaseClass == null) {
throw new IllegalArgumentException("Database Class referenced not found.");
}
ReActiveAndroid.getDatabase(databaseClass).FUNC_3().setTransactionSuccessful();
ReActiveAndroid.getDatabase(databaseClass).endTransaction();
}
public static Boolean BulkCRUDUpdates(Class<?> databaseClass, Class<?> table, IMPORT_4<?> VAR_0) {
boolean result = true;
if (databaseClass == null) {
throw new IllegalArgumentException("Database Class referenced not found.");
}
if (table == null) {
throw new IllegalArgumentException("Table Class referenced not found.");
}
if (VAR_0 == null) {
throw new IllegalArgumentException("Model Data is Empty");
}
FUNC_0(databaseClass);
for (Object modelClassDataHolder : VAR_0) {
for(Field modelClassDataHolderField : modelClassDataHolder.getClass().getDeclaredFields()){
try {
modelClassDataHolderField.setAccessible(true);
Object value = modelClassDataHolderField.FUNC_4(modelClassDataHolder);
if(IMPORT_2.FUNC_5(table).where(modelClassDataHolderField.getName() + " = ?", value.toString()).FUNC_6() == 1){
//found
//Update.table(table).set(modelClassDataHolderField.getName() + " = ?", value.toString() + " Update via Bulk").where(modelClassDataHolderField.getName() + " = ?", value.toString()).execute();
}else{
//create new
//Insert.into(table).columns(modelClassDataHolderField.getName()).values(value.toString()+ " Insert via Bulk").execute();
}
}catch (Exception error) {
}
}
}
FUNC_2(databaseClass);
return result;
}
}
| 0.279732
|
{'IMPORT_0': 'util', 'IMPORT_1': 'Log', 'IMPORT_2': 'Select', 'IMPORT_3': 'HashMap', 'IMPORT_4': 'List', 'CLASS_0': 'Transactions', 'FUNC_0': 'BeginTransactions', 'FUNC_1': 'beginTransaction', 'FUNC_2': 'EndTransactions', 'FUNC_3': 'getWritableDatabase', 'VAR_0': 'modelData', 'FUNC_4': 'get', 'FUNC_5': 'from', 'FUNC_6': 'count'}
|
java
|
OOP
|
100.00%
|
/**
* Compiles regular expression patterns used in globbing
* @throws JHOVE2Exception Any PatternSyntaxException is thrown as JHOVE2Exception and allowed
* to bubble up to stop processing, as configuration needs fixing
*/
protected void compilePatterns() throws JHOVE2Exception{
try {
this.fileGroupingPattern = Pattern.compile(this.fileGroupingExpr);
}
catch (PatternSyntaxException e){
throw new JHOVE2Exception("Exception thrown compiling fileGroupingToken: "
+ this.fileGroupingExpr, e);
}
if (this.mustHaveExpr != null){
try {
this.mustHavePattern = Pattern.compile(this.mustHaveExpr);
}
catch (PatternSyntaxException e){
throw new JHOVE2Exception("Exception thrown compiling mustHaveToken: "
+ this.mustHaveExpr, e);
}
}
if (this.mayHaveExpr != null){
try {
this.mayHavePattern = Pattern.compile(this.mayHaveExpr);
}
catch (PatternSyntaxException e){
throw new JHOVE2Exception("Exception thrown compiling mayHaveToken: "
+ this.fileGroupingExpr, e);
}
}
return;
}
|
/**
* Compiles regular expression patterns used in globbing
* @throws JHOVE2Exception Any PatternSyntaxException is thrown as JHOVE2Exception and allowed
* to bubble up to stop processing, as configuration needs fixing
*/
protected void FUNC_0() throws CLASS_0{
try {
this.fileGroupingPattern = VAR_0.FUNC_1(this.fileGroupingExpr);
}
catch (CLASS_1 VAR_1){
throw new CLASS_0("Exception thrown compiling fileGroupingToken: "
+ this.fileGroupingExpr, VAR_1);
}
if (this.VAR_2 != null){
try {
this.VAR_3 = VAR_0.FUNC_1(this.VAR_2);
}
catch (CLASS_1 VAR_1){
throw new CLASS_0("Exception thrown compiling mustHaveToken: "
+ this.VAR_2, VAR_1);
}
}
if (this.VAR_4 != null){
try {
this.VAR_5 = VAR_0.FUNC_1(this.VAR_4);
}
catch (CLASS_1 VAR_1){
throw new CLASS_0("Exception thrown compiling mayHaveToken: "
+ this.fileGroupingExpr, VAR_1);
}
}
return;
}
| 0.704723
|
{'FUNC_0': 'compilePatterns', 'CLASS_0': 'JHOVE2Exception', 'VAR_0': 'Pattern', 'FUNC_1': 'compile', 'CLASS_1': 'PatternSyntaxException', 'VAR_1': 'e', 'VAR_2': 'mustHaveExpr', 'VAR_3': 'mustHavePattern', 'VAR_4': 'mayHaveExpr', 'VAR_5': 'mayHavePattern'}
|
java
|
Procedural
|
26.72%
|
/**
* Creates the table for the current clusters and position it below the parent when created.
*
* @param parent the parent
* @return the text window
*/
private static ClusterDataTableModelFrame createClustersTable(ClusterDataTableModelFrame parent) {
return ConcurrencyUtils.refresh(currentClustersTable, JFrame::isShowing, () -> {
final ClusterDataTableModelFrame frame =
new ClusterDataTableModelFrame(new ClusterDataTableModel(true));
frame.setTitle(TITLE + " Current Clusters");
frame.table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (parent != null) {
final Point p = parent.getLocation();
p.y += parent.getHeight();
frame.setLocation(p);
}
frame.setVisible(true);
return frame;
});
}
|
/**
* Creates the table for the current clusters and position it below the parent when created.
*
* @param parent the parent
* @return the text window
*/
private static ClusterDataTableModelFrame createClustersTable(ClusterDataTableModelFrame parent) {
return ConcurrencyUtils.refresh(currentClustersTable, JFrame::isShowing, () -> {
final ClusterDataTableModelFrame frame =
new ClusterDataTableModelFrame(new ClusterDataTableModel(true));
frame.setTitle(TITLE + " Current Clusters");
frame.table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (parent != null) {
final Point p = parent.getLocation();
p.y += parent.getHeight();
frame.setLocation(p);
}
frame.setVisible(true);
return frame;
});
}
| 0.002307
|
{}
|
java
|
Procedural
|
40.38%
|
class Solution {
public String frequencySort(String s) {
// Count
HashMap<Character, Integer> counts = new HashMap<>();
for (char c : s.toCharArray()) {
counts.put(c, counts.getOrDefault(c, 0) + 1);
}
List<Character> characters = new ArrayList<>(counts.keySet());
Collections.sort(characters, (a, b) -> counts.get(b) - counts.get(a));
StringBuilder sb = new StringBuilder();
for (char c : characters) {
int copy = counts.get(c);
for (int i = 0; i < copy; i ++) {
sb.append(c);
}
}
return sb.toString();
}
}
|
class CLASS_0 {
public CLASS_1 FUNC_0(CLASS_1 VAR_0) {
// Count
CLASS_2<CLASS_3, CLASS_4> VAR_1 = new CLASS_2<>();
for (char VAR_2 : VAR_0.FUNC_1()) {
VAR_1.FUNC_2(VAR_2, VAR_1.FUNC_3(VAR_2, 0) + 1);
}
List<CLASS_3> characters = new CLASS_5<>(VAR_1.FUNC_4());
Collections.sort(characters, (VAR_3, VAR_4) -> VAR_1.FUNC_5(VAR_4) - VAR_1.FUNC_5(VAR_3));
CLASS_6 VAR_5 = new CLASS_6();
for (char VAR_2 : characters) {
int VAR_6 = VAR_1.FUNC_5(VAR_2);
for (int VAR_7 = 0; VAR_7 < VAR_6; VAR_7 ++) {
VAR_5.FUNC_6(VAR_2);
}
}
return VAR_5.FUNC_7();
}
}
| 0.791666
|
{'CLASS_0': 'Solution', 'CLASS_1': 'String', 'FUNC_0': 'frequencySort', 'VAR_0': 's', 'CLASS_2': 'HashMap', 'CLASS_3': 'Character', 'CLASS_4': 'Integer', 'VAR_1': 'counts', 'VAR_2': 'c', 'FUNC_1': 'toCharArray', 'FUNC_2': 'put', 'FUNC_3': 'getOrDefault', 'CLASS_5': 'ArrayList', 'FUNC_4': 'keySet', 'VAR_3': 'a', 'VAR_4': 'b', 'FUNC_5': 'get', 'CLASS_6': 'StringBuilder', 'VAR_5': 'sb', 'VAR_6': 'copy', 'VAR_7': 'i', 'FUNC_6': 'append', 'FUNC_7': 'toString'}
|
java
|
OOP
|
100.00%
|
package com.taotao.cloud.java.javaee.s1.c3_mybatis.mybatisadvance.java.dao;
import com.taotao.cloud.java.javaee.s1.c3_mybatis.mybatisadvance.java.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserDAO {
List<User> queryUsers(@Param("rule") String rule);// desc asc
User queryUserById(@Param("id") Integer id);// #{arg0} ${arg0}
User queryUserById2(@Param("id") Integer id);// #{arg0} ${arg0}
List<User> queryUserByUsername(@Param("username") String username);
List<User> queryUserByUsernameorId(User user); // ${username} ${id}
/*@Select("SELECT id,username,password,gender,regist_time FROM t_user")
List<User> queryUsers();
@Select("SELECT id,username,password,gender,regist_time\n" +
" FROM t_user\n" +
" WHERE id = #{id}")
User queryUserById(@Param("id") Integer id);
@Delete("delete from t_user\n" +
" where id=#{id}")
Integer deleteUser(@Param("id") Integer id);
@Update("update t_user\n" +
" set username=#{username},password=#{password},gender=#{gender},regist_time=#{registTime}\n" +
" where id=#{id}")
Integer updateUser(User user);
@Options(useGeneratedKeys = true , keyProperty = "id") // 自增key,主键为id
@Insert("insert into t_user values(#{id},#{username},#{password},#{gender},#{registTime})")
Integer insertUser(User user);*/
}
|
package com.IMPORT_0.cloud.java.IMPORT_1.s1.c3_mybatis.IMPORT_2.java.dao;
import com.IMPORT_0.cloud.java.IMPORT_1.s1.c3_mybatis.IMPORT_2.java.entity.IMPORT_3;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface CLASS_0 {
List<IMPORT_3> FUNC_0(@VAR_0("rule") CLASS_1 rule);// desc asc
IMPORT_3 queryUserById(@VAR_0("id") Integer VAR_1);// #{arg0} ${arg0}
IMPORT_3 FUNC_1(@VAR_0("id") Integer VAR_1);// #{arg0} ${arg0}
List<IMPORT_3> FUNC_2(@VAR_0("username") CLASS_1 VAR_2);
List<IMPORT_3> queryUserByUsernameorId(IMPORT_3 VAR_3); // ${username} ${id}
/*@Select("SELECT id,username,password,gender,regist_time FROM t_user")
List<User> queryUsers();
@Select("SELECT id,username,password,gender,regist_time\n" +
" FROM t_user\n" +
" WHERE id = #{id}")
User queryUserById(@Param("id") Integer id);
@Delete("delete from t_user\n" +
" where id=#{id}")
Integer deleteUser(@Param("id") Integer id);
@Update("update t_user\n" +
" set username=#{username},password=#{password},gender=#{gender},regist_time=#{registTime}\n" +
" where id=#{id}")
Integer updateUser(User user);
@Options(useGeneratedKeys = true , keyProperty = "id") // 自增key,主键为id
@Insert("insert into t_user values(#{id},#{username},#{password},#{gender},#{registTime})")
Integer insertUser(User user);*/
}
| 0.368416
|
{'IMPORT_0': 'taotao', 'IMPORT_1': 'javaee', 'IMPORT_2': 'mybatisadvance', 'IMPORT_3': 'User', 'CLASS_0': 'UserDAO', 'FUNC_0': 'queryUsers', 'VAR_0': 'Param', 'CLASS_1': 'String', 'VAR_1': 'id', 'FUNC_1': 'queryUserById2', 'FUNC_2': 'queryUserByUsername', 'VAR_2': 'username', 'VAR_3': 'user'}
|
java
|
Texto
|
22.50%
|
/**
* Handles nested description tags.
*/
static class DescriptionHandler extends AbstractSimpleElementHandler {
public Description description;
public DescriptionHandler(IssueHandler parent) {
super(parent, "long_desc", DESCRIPTION_SIMPLE_FIELDS);
description = new Description();
}
public void addFieldAndValue(String currentField, String value) {
if(currentField == "who") description.setWho(value);
else if(currentField == "issue_when") description.setWhen(parseLenient(value));
else if(currentField == "thetext") description.setText(value);
else parent.addException(this + " encountered unexpected element " + currentField);
}
}
|
/**
* Handles nested description tags.
*/
static class DescriptionHandler extends CLASS_0 {
public Description description;
public DescriptionHandler(IssueHandler parent) {
super(parent, "long_desc", DESCRIPTION_SIMPLE_FIELDS);
description = new Description();
}
public void addFieldAndValue(String VAR_0, String VAR_1) {
if(VAR_0 == "who") description.setWho(VAR_1);
else if(VAR_0 == "issue_when") description.setWhen(parseLenient(VAR_1));
else if(VAR_0 == "thetext") description.setText(VAR_1);
else parent.addException(this + " encountered unexpected element " + VAR_0);
}
}
| 0.22345
|
{'CLASS_0': 'AbstractSimpleElementHandler', 'VAR_0': 'currentField', 'VAR_1': 'value'}
|
java
|
OOP
|
100.00%
|
package mayfly.sys.module.machine.service;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import mayfly.core.base.service.BaseService;
import mayfly.core.exception.BizAssert;
import mayfly.core.util.IOUtils;
import mayfly.sys.common.utils.ssh.SSHException;
import mayfly.sys.common.utils.ssh.SSHUtils;
import mayfly.sys.common.utils.ssh.SessionInfo;
import mayfly.sys.module.machine.controller.form.MachineForm;
import mayfly.sys.module.machine.entity.MachineDO;
import mayfly.sys.module.machine.service.impl.MachineServiceImpl;
import java.util.Objects;
import java.util.function.Function;
/**
* @author meilin.huang
* @version 1.0
* @date 2019-11-04 3:04 下午
*/
public interface MachineService extends BaseService<Long, MachineDO> {
/**
* 保存新增的机器信息
*
* @param form 机器信息
*/
void create(MachineForm form);
/**
* 执行shell目录下的shell脚本
*
* @param machineId 机器id
* @param shellFileName shell文件名
* @return 执行结果
*/
String runShell(Long machineId, String shellFileName, Object... param);
/**
* 获取top信息
*
* @param machineId 机器id
* @return
*/
MachineServiceImpl.TopInfo getTopInfo(Long machineId);
/**
* 执行指定机器的命令
*
* @param machineId 机器id
* @param cmd 命令
*/
default String exec(Long machineId, String cmd) {
try {
return SSHUtils.exec(getSession(machineId), cmd);
} catch (SSHException e) {
throw BizAssert.newException(e.getMessage());
}
}
/**
* 执行指定机器的命令
*
* @param machineId 机器id
* @param cmd 命令
* @param lineProcessor 行处理器
*/
default void exec(Long machineId, String cmd, IOUtils.LineProcessor lineProcessor) {
try {
SSHUtils.exec(getSession(machineId), cmd, lineProcessor);
} catch (SSHException e) {
throw BizAssert.newException(e.getMessage());
}
}
/**
* 获取sftp 并对channel执行操作
*
* @param machineId 机器id
*/
default <T> T sftpOperate(Long machineId, Function<ChannelSftp, T> function) {
try {
return SSHUtils.sftpOperate(getSession(machineId), function);
} catch (SSHException e) {
throw BizAssert.newException(e.getMessage());
}
}
/**
* 获取指定机器的session
*
* @param machineId 机器id
* @return session
*/
default Session getSession(Long machineId) {
return SSHUtils.getSession(Objects.toString(machineId), () -> {
MachineDO machine = getById(machineId);
BizAssert.notNull(machine, "机器不存在");
return SessionInfo.builder(machine.getIp()).port(machine.getPort())
.password(machine.getPassword()).username(machine.getUsername()).build();
});
}
}
|
package mayfly.IMPORT_0.module.IMPORT_1.service;
import IMPORT_2.jcraft.IMPORT_3.IMPORT_4;
import IMPORT_2.jcraft.IMPORT_3.Session;
import mayfly.IMPORT_5.base.service.IMPORT_6;
import mayfly.IMPORT_5.IMPORT_7.IMPORT_8;
import mayfly.IMPORT_5.IMPORT_9.IMPORT_10;
import mayfly.IMPORT_0.IMPORT_11.IMPORT_12.ssh.SSHException;
import mayfly.IMPORT_0.IMPORT_11.IMPORT_12.ssh.SSHUtils;
import mayfly.IMPORT_0.IMPORT_11.IMPORT_12.ssh.IMPORT_13;
import mayfly.IMPORT_0.module.IMPORT_1.controller.IMPORT_14.IMPORT_15;
import mayfly.IMPORT_0.module.IMPORT_1.IMPORT_16.IMPORT_17;
import mayfly.IMPORT_0.module.IMPORT_1.service.impl.IMPORT_18;
import java.IMPORT_9.IMPORT_19;
import java.IMPORT_9.IMPORT_20.IMPORT_21;
/**
* @author meilin.huang
* @version 1.0
* @date 2019-11-04 3:04 下午
*/
public interface CLASS_0 extends IMPORT_6<CLASS_1, IMPORT_17> {
/**
* 保存新增的机器信息
*
* @param form 机器信息
*/
void FUNC_0(IMPORT_15 IMPORT_14);
/**
* 执行shell目录下的shell脚本
*
* @param machineId 机器id
* @param shellFileName shell文件名
* @return 执行结果
*/
CLASS_2 FUNC_1(CLASS_1 VAR_0, CLASS_2 VAR_1, CLASS_3... VAR_2);
/**
* 获取top信息
*
* @param machineId 机器id
* @return
*/
IMPORT_18.CLASS_4 FUNC_2(CLASS_1 VAR_0);
/**
* 执行指定机器的命令
*
* @param machineId 机器id
* @param cmd 命令
*/
default CLASS_2 exec(CLASS_1 VAR_0, CLASS_2 VAR_3) {
try {
return SSHUtils.exec(FUNC_3(VAR_0), VAR_3);
} catch (SSHException VAR_4) {
throw IMPORT_8.newException(VAR_4.FUNC_4());
}
}
/**
* 执行指定机器的命令
*
* @param machineId 机器id
* @param cmd 命令
* @param lineProcessor 行处理器
*/
default void exec(CLASS_1 VAR_0, CLASS_2 VAR_3, IMPORT_10.CLASS_5 VAR_5) {
try {
SSHUtils.exec(FUNC_3(VAR_0), VAR_3, VAR_5);
} catch (SSHException VAR_4) {
throw IMPORT_8.newException(VAR_4.FUNC_4());
}
}
/**
* 获取sftp 并对channel执行操作
*
* @param machineId 机器id
*/
default <CLASS_6> CLASS_6 sftpOperate(CLASS_1 VAR_0, IMPORT_21<IMPORT_4, CLASS_6> IMPORT_20) {
try {
return SSHUtils.sftpOperate(FUNC_3(VAR_0), IMPORT_20);
} catch (SSHException VAR_4) {
throw IMPORT_8.newException(VAR_4.FUNC_4());
}
}
/**
* 获取指定机器的session
*
* @param machineId 机器id
* @return session
*/
default Session FUNC_3(CLASS_1 VAR_0) {
return SSHUtils.FUNC_3(IMPORT_19.FUNC_5(VAR_0), () -> {
IMPORT_17 IMPORT_1 = FUNC_6(VAR_0);
IMPORT_8.notNull(IMPORT_1, "机器不存在");
return IMPORT_13.FUNC_7(IMPORT_1.getIp()).FUNC_8(IMPORT_1.getPort())
.FUNC_9(IMPORT_1.FUNC_10()).username(IMPORT_1.FUNC_11()).FUNC_12();
});
}
}
| 0.70896
|
{'IMPORT_0': 'sys', 'IMPORT_1': 'machine', 'IMPORT_2': 'com', 'IMPORT_3': 'jsch', 'IMPORT_4': 'ChannelSftp', 'IMPORT_5': 'core', 'IMPORT_6': 'BaseService', 'IMPORT_7': 'exception', 'IMPORT_8': 'BizAssert', 'IMPORT_9': 'util', 'IMPORT_10': 'IOUtils', 'IMPORT_11': 'common', 'IMPORT_12': 'utils', 'IMPORT_13': 'SessionInfo', 'IMPORT_14': 'form', 'IMPORT_15': 'MachineForm', 'IMPORT_16': 'entity', 'IMPORT_17': 'MachineDO', 'IMPORT_18': 'MachineServiceImpl', 'IMPORT_19': 'Objects', 'IMPORT_20': 'function', 'IMPORT_21': 'Function', 'CLASS_0': 'MachineService', 'CLASS_1': 'Long', 'FUNC_0': 'create', 'CLASS_2': 'String', 'FUNC_1': 'runShell', 'VAR_0': 'machineId', 'VAR_1': 'shellFileName', 'CLASS_3': 'Object', 'VAR_2': 'param', 'CLASS_4': 'TopInfo', 'FUNC_2': 'getTopInfo', 'VAR_3': 'cmd', 'FUNC_3': 'getSession', 'VAR_4': 'e', 'FUNC_4': 'getMessage', 'CLASS_5': 'LineProcessor', 'VAR_5': 'lineProcessor', 'CLASS_6': 'T', 'FUNC_5': 'toString', 'FUNC_6': 'getById', 'FUNC_7': 'builder', 'FUNC_8': 'port', 'FUNC_9': 'password', 'FUNC_10': 'getPassword', 'FUNC_11': 'getUsername', 'FUNC_12': 'build'}
|
java
|
Texto
|
31.01%
|
package com.opencdk.util.upgrade;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
import com.opencdk.util.log.Log;
import com.opencdk.core.exception.SdkParseException;
/**
* 版本解析器
*
* @author 笨鸟不乖
* @email <EMAIL>
* @version 1.0.0
*/
public abstract class VersionInfoParser
{
private final String TAG = "VersionInfoParser";
/**
* 解析服务器的版本信息. 如果你自定义服务器版本信息结构, 需要进行重写此类, 同时重写
* {@link VersionInfoParser#parseVersionInfoSelf(String)} 和
* {@link VersionInfoParser#parseVersionInfo(String)} 这两个方法. 此方法不能被重写.
*
* @param versionString
* @return
* @throws SdkParseException
*/
public final VersionInfo parseVersionInfo(String versionString) throws SdkParseException
{
if (!isParseSelf())
{
return parseVersionXml(versionString);
}
return parseVersionInfoSelf(versionString);
}
/**
* 解析自己定义的版本信息结构.
*
* @param versionString
* @return
* @throws SdkParseException
*/
protected abstract VersionInfo parseVersionInfoSelf(String versionString) throws SdkParseException;
/**
* 是否自行处理解析请求.
*
* @return
*/
protected abstract boolean isParseSelf();
/**
* 提供模板的解析方式, 指定服务器的版本信息结构体. 模板如下:</br>
* <hr>
*
* <code>
* <?xml version="1.0" encoding="utf-8"?>
* <version>
* <application>kkdt.apk</application>
* <versionCode>10</versionCode>
* <versionName>2.0.1</versionName>
* <url>https://raw.github.com/benniaobuguai/AppUpdate/master/AppUpdate/apk/xxx.apk</url>
* </version>
* </code>
* <hr>
*
* @param versionXml
* @return
* @throws SdkParseException
*/
private VersionInfo parseVersionXml(String versionXml) throws SdkParseException
{
VersionInfo info = new VersionInfo();
ByteArrayInputStream bais = new ByteArrayInputStream(versionXml.getBytes());
XmlPullParser parser = Xml.newPullParser();
try
{
parser.setInput(bais, "UTF-8");
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
switch (eventType)
{
// At the beginning of document and nothing read yet, do something you want.
case XmlPullParser.START_DOCUMENT:
{
break;
}
case XmlPullParser.START_TAG:
{
String name = parser.getName();
if ("version".equals(name))
{
Log.D(TAG, "start tag.");
}
else if ("application".equals(name))
{
info.setAppName(parser.nextText());
}
else if ("versionCode".equals(name))
{
info.setVersionCode(Integer.valueOf(parser.nextText()));
}
else if ("versionName".equals(name))
{
info.setVersionName(parser.nextText());
}
else if ("url".equals(name))
{
info.setUpdateUrl(parser.nextText());
}
break;
}
case XmlPullParser.END_TAG:
{
String name = parser.getName();
if ("version".equals(name))
{
Log.D(TAG, "end tag.");
return info;
}
break;
}
}
eventType = parser.next();
}
}
catch (XmlPullParserException e)
{
throw new SdkParseException("Parse version info failed./n" + e.toString());
}
catch (IOException e)
{
throw new SdkParseException("Parse version info failed./n" + e.toString());
}
finally
{
if (bais != null)
{
try
{
bais.close();
}
catch (IOException e)
{
throw new SdkParseException("Parse version info failed./n" + e.toString());
}
}
}
return null;
}
}
|
package com.opencdk.util.upgrade;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.IMPORT_0.v1.XmlPullParser;
import org.IMPORT_0.v1.XmlPullParserException;
import android.util.Xml;
import com.opencdk.util.log.Log;
import com.opencdk.core.IMPORT_1.SdkParseException;
/**
* 版本解析器
*
* @author 笨鸟不乖
* @email <EMAIL>
* @version 1.0.0
*/
public abstract class VersionInfoParser
{
private final String TAG = "VersionInfoParser";
/**
* 解析服务器的版本信息. 如果你自定义服务器版本信息结构, 需要进行重写此类, 同时重写
* {@link VersionInfoParser#parseVersionInfoSelf(String)} 和
* {@link VersionInfoParser#parseVersionInfo(String)} 这两个方法. 此方法不能被重写.
*
* @param versionString
* @return
* @throws SdkParseException
*/
public final VersionInfo parseVersionInfo(String versionString) throws SdkParseException
{
if (!isParseSelf())
{
return parseVersionXml(versionString);
}
return parseVersionInfoSelf(versionString);
}
/**
* 解析自己定义的版本信息结构.
*
* @param versionString
* @return
* @throws SdkParseException
*/
protected abstract VersionInfo parseVersionInfoSelf(String versionString) throws SdkParseException;
/**
* 是否自行处理解析请求.
*
* @return
*/
protected abstract boolean isParseSelf();
/**
* 提供模板的解析方式, 指定服务器的版本信息结构体. 模板如下:</br>
* <hr>
*
* <code>
* <?xml version="1.0" encoding="utf-8"?>
* <version>
* <application>kkdt.apk</application>
* <versionCode>10</versionCode>
* <versionName>2.0.1</versionName>
* <url>https://raw.github.com/benniaobuguai/AppUpdate/master/AppUpdate/apk/xxx.apk</url>
* </version>
* </code>
* <hr>
*
* @param versionXml
* @return
* @throws SdkParseException
*/
private VersionInfo parseVersionXml(String VAR_0) throws SdkParseException
{
VersionInfo info = new VersionInfo();
ByteArrayInputStream VAR_1 = new ByteArrayInputStream(VAR_0.getBytes());
XmlPullParser parser = Xml.newPullParser();
try
{
parser.setInput(VAR_1, "UTF-8");
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
switch (eventType)
{
// At the beginning of document and nothing read yet, do something you want.
case XmlPullParser.VAR_2:
{
break;
}
case XmlPullParser.START_TAG:
{
String name = parser.getName();
if ("version".equals(name))
{
Log.D(TAG, "start tag.");
}
else if ("application".equals(name))
{
info.setAppName(parser.nextText());
}
else if ("versionCode".equals(name))
{
info.setVersionCode(Integer.FUNC_0(parser.nextText()));
}
else if ("versionName".equals(name))
{
info.setVersionName(parser.nextText());
}
else if ("url".equals(name))
{
info.setUpdateUrl(parser.nextText());
}
break;
}
case XmlPullParser.END_TAG:
{
String name = parser.getName();
if ("version".equals(name))
{
Log.D(TAG, "end tag.");
return info;
}
break;
}
}
eventType = parser.FUNC_1();
}
}
catch (XmlPullParserException e)
{
throw new SdkParseException("Parse version info failed./n" + e.FUNC_2());
}
catch (IOException e)
{
throw new SdkParseException("Parse version info failed./n" + e.FUNC_2());
}
finally
{
if (VAR_1 != null)
{
try
{
VAR_1.FUNC_3();
}
catch (IOException e)
{
throw new SdkParseException("Parse version info failed./n" + e.FUNC_2());
}
}
}
return null;
}
}
| 0.194395
|
{'IMPORT_0': 'xmlpull', 'IMPORT_1': 'exception', 'VAR_0': 'versionXml', 'VAR_1': 'bais', 'VAR_2': 'START_DOCUMENT', 'FUNC_0': 'valueOf', 'FUNC_1': 'next', 'FUNC_2': 'toString', 'FUNC_3': 'close'}
|
java
|
OOP
|
13.74%
|
/**
* Checks if the player is in the process of hitting a block. <br>
* <i>If the game is played in multiplayer, this should be validated only on client.</i>
*
* @return True if the player is holding mouse left-click and is mousing over a block.
*/
public static boolean isPlayerBreakingBlock()
{
final Minecraft minecraft = Minecraft.getMinecraft();
final RayTraceResult mouseOver = minecraft.objectMouseOver;
boolean isAttackKeyDown = minecraft.gameSettings.keyBindAttack.isKeyDown();
boolean isMouseOverBlock = mouseOver != null && mouseOver.typeOfHit == RayTraceResult.Type.BLOCK;
return isAttackKeyDown && isMouseOverBlock;
}
|
/**
* Checks if the player is in the process of hitting a block. <br>
* <i>If the game is played in multiplayer, this should be validated only on client.</i>
*
* @return True if the player is holding mouse left-click and is mousing over a block.
*/
public static boolean isPlayerBreakingBlock()
{
final Minecraft minecraft = Minecraft.FUNC_0();
final CLASS_0 mouseOver = minecraft.VAR_1;
boolean isAttackKeyDown = minecraft.gameSettings.keyBindAttack.FUNC_1();
boolean isMouseOverBlock = mouseOver != null && mouseOver.typeOfHit == VAR_0.VAR_2.BLOCK;
return isAttackKeyDown && isMouseOverBlock;
}
| 0.377555
|
{'FUNC_0': 'getMinecraft', 'CLASS_0': 'RayTraceResult', 'VAR_0': 'RayTraceResult', 'VAR_1': 'objectMouseOver', 'FUNC_1': 'isKeyDown', 'VAR_2': 'Type'}
|
java
|
Procedural
|
100.00%
|
/*
* Copyright 2017 iserge.
*
* 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.openlayers.ol;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
import org.openlayers.ol.geom.Geometry;
import org.openlayers.ol.options.FeatureOptions;
import org.openlayers.ol.style.Style;
/**
* A vector object for geographic features with a geometry and other attribute properties, similar to the features in
* vector file formats like GeoJSON.
*
* Features can be styled individually with setStyle; otherwise they use the style of their vector layer.
*
* Note that attribute properties are set as ol.Object properties on the feature object, so they are observable,
* and have get/set accessors.
*
* Typically, a feature has a single geometry property. You can set the geometry using the setGeometry method and get it
* with getGeometry. It is possible to store more than one geometry on a feature using attribute properties.
* By default, the geometry used for rendering is identified by the property name geometry. If you want to use another
* geometry property for rendering, use the setGeometryName method to change the attribute property associated with the
* geometry for the feature.
*
* @author <NAME> aka iSergio <<EMAIL>>
*/
@JsType(isNative = true, namespace = "ol", name = "Feature")
public class Feature extends Object {
@JsConstructor
public Feature(Geometry geometry) {}
@JsConstructor
public Feature(FeatureOptions options) {}
/**
* Clone this feature. If the original feature has a geometry it is also cloned. The feature id is not set in the clone.
* @return The clone.
*/
@JsMethod
public native Feature clone();
/**
* Get the feature's default geometry. A feature may have any number of named geometries.
* The "default" geometry (the one that is rendered by default) is set when calling ol.Feature#setGeometry.
* @return The default geometry for the feature.
*/
@JsMethod
public native Geometry getGeometry();
/**
* Get the name of the feature's default geometry. By default, the default geometry is named geometry.
* @return Get the property name associated with the default geometry for this feature.
*/
@JsMethod
public native String getGeometryName();
/**
* Get the feature identifier. This is a stable identifier for the feature and is either set when reading data from a
* remote source or set explicitly by calling ol.Feature#setId.
* @return Id.
*/
@JsMethod
public native String getId();
/**
* Get the feature's style. Will return what was provided to the ol.Feature#setStyle method.
* @return The feature style.
*/
@JsMethod
public native Style getStyle();
/**
* Get the feature's style function.
* @return Return a function representing the current style of this feature.
*/
@JsMethod
public native FeatureStyleFunction getStyleFunction();
/**
* Set the default geometry for the feature. This will update the property with the name returned by {@link #getGeometryName()}.
* @param geometry The new geometry.
*/
@JsMethod
public native void setGeometry(Geometry geometry);
/**
* Set the property name to be used when getting the feature's default geometry. When calling {@link #getGeometry()},
* the value of the property with this name will be returned.
* @param name The property name of the default geometry.
*/
@JsMethod
public native void setGeometryName(String name);
/**
* Set the feature id. The feature id is considered stable and may be used when requesting features or comparing
* identifiers returned from a remote source.
* The feature id can be used with the {@link org.openlayers.ol.source.VectorSource} method.
* @param id The feature id.
*/
@JsMethod
public native void setId(String id);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@JsMethod
public native void setStyle(Style style);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@JsMethod
public native void setStyle(Style[] style);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@JsMethod
public native void setStyle(FeatureStyleFunction style);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@JsMethod
public native void setStyle(StyleFunction style);
}
|
/*
* Copyright 2017 iserge.
*
* 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.openlayers.ol;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.IMPORT_0;
import jsinterop.annotations.JsType;
import org.openlayers.ol.geom.Geometry;
import org.openlayers.ol.IMPORT_1.FeatureOptions;
import org.openlayers.ol.style.IMPORT_2;
/**
* A vector object for geographic features with a geometry and other attribute properties, similar to the features in
* vector file formats like GeoJSON.
*
* Features can be styled individually with setStyle; otherwise they use the style of their vector layer.
*
* Note that attribute properties are set as ol.Object properties on the feature object, so they are observable,
* and have get/set accessors.
*
* Typically, a feature has a single geometry property. You can set the geometry using the setGeometry method and get it
* with getGeometry. It is possible to store more than one geometry on a feature using attribute properties.
* By default, the geometry used for rendering is identified by the property name geometry. If you want to use another
* geometry property for rendering, use the setGeometryName method to change the attribute property associated with the
* geometry for the feature.
*
* @author <NAME> aka iSergio <<EMAIL>>
*/
@JsType(isNative = true, namespace = "ol", name = "Feature")
public class Feature extends CLASS_0 {
@JsConstructor
public Feature(Geometry geometry) {}
@JsConstructor
public Feature(FeatureOptions IMPORT_1) {}
/**
* Clone this feature. If the original feature has a geometry it is also cloned. The feature id is not set in the clone.
* @return The clone.
*/
@IMPORT_0
public native Feature clone();
/**
* Get the feature's default geometry. A feature may have any number of named geometries.
* The "default" geometry (the one that is rendered by default) is set when calling ol.Feature#setGeometry.
* @return The default geometry for the feature.
*/
@IMPORT_0
public native Geometry getGeometry();
/**
* Get the name of the feature's default geometry. By default, the default geometry is named geometry.
* @return Get the property name associated with the default geometry for this feature.
*/
@IMPORT_0
public native String FUNC_0();
/**
* Get the feature identifier. This is a stable identifier for the feature and is either set when reading data from a
* remote source or set explicitly by calling ol.Feature#setId.
* @return Id.
*/
@IMPORT_0
public native String getId();
/**
* Get the feature's style. Will return what was provided to the ol.Feature#setStyle method.
* @return The feature style.
*/
@IMPORT_0
public native IMPORT_2 FUNC_1();
/**
* Get the feature's style function.
* @return Return a function representing the current style of this feature.
*/
@IMPORT_0
public native FeatureStyleFunction getStyleFunction();
/**
* Set the default geometry for the feature. This will update the property with the name returned by {@link #getGeometryName()}.
* @param geometry The new geometry.
*/
@IMPORT_0
public native void setGeometry(Geometry geometry);
/**
* Set the property name to be used when getting the feature's default geometry. When calling {@link #getGeometry()},
* the value of the property with this name will be returned.
* @param name The property name of the default geometry.
*/
@IMPORT_0
public native void setGeometryName(String name);
/**
* Set the feature id. The feature id is considered stable and may be used when requesting features or comparing
* identifiers returned from a remote source.
* The feature id can be used with the {@link org.openlayers.ol.source.VectorSource} method.
* @param id The feature id.
*/
@IMPORT_0
public native void FUNC_2(String id);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@IMPORT_0
public native void FUNC_3(IMPORT_2 style);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@IMPORT_0
public native void FUNC_3(IMPORT_2[] style);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@IMPORT_0
public native void FUNC_3(FeatureStyleFunction style);
/**
* Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a
* resolution and returns an array of styles. If it is null the feature has no style (a null style).
* @param style Style for this feature.
*/
@IMPORT_0
public native void FUNC_3(CLASS_1 style);
}
| 0.325003
|
{'IMPORT_0': 'JsMethod', 'IMPORT_1': 'options', 'IMPORT_2': 'Style', 'CLASS_0': 'Object', 'FUNC_0': 'getGeometryName', 'FUNC_1': 'getStyle', 'FUNC_2': 'setId', 'FUNC_3': 'setStyle', 'CLASS_1': 'StyleFunction'}
|
java
|
Hibrido
|
100.00%
|
/**
* Root Method that will drop everything in all inventory slots minus fuel
*/
protected void noInventoryModuleDropItems()
{
if(this.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_LESSER.getMetadata()
|| this.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata()
|| this.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_GREATER.getMetadata())
{
canDrop = true;
}
if(this.getModuleVariantSlot1() != EnumsVC.ModuleType.STORAGE_LESSER.getMetadata()
&& this.getModuleVariantSlot1() != EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata()
&& this.getModuleVariantSlot1() != EnumsVC.ModuleType.STORAGE_GREATER.getMetadata()
&& canDrop)
{
this.dropInventoryItemStorageOnly();
canDrop = false;
}
}
|
/**
* Root Method that will drop everything in all inventory slots minus fuel
*/
protected void noInventoryModuleDropItems()
{
if(this.getModuleVariantSlot1() == EnumsVC.ModuleType.VAR_0.getMetadata()
|| this.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata()
|| this.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_GREATER.getMetadata())
{
canDrop = true;
}
if(this.getModuleVariantSlot1() != EnumsVC.ModuleType.VAR_0.getMetadata()
&& this.getModuleVariantSlot1() != EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata()
&& this.getModuleVariantSlot1() != EnumsVC.ModuleType.STORAGE_GREATER.getMetadata()
&& canDrop)
{
this.dropInventoryItemStorageOnly();
canDrop = false;
}
}
| 0.119262
|
{'VAR_0': 'STORAGE_LESSER'}
|
java
|
Procedural
|
100.00%
|
package com.crud.hotels.backend.controller;
import com.crud.hotels.backend.dto.HotelDto;
import com.crud.hotels.backend.service.HotelService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/v1/hotels")
public class HotelController {
private final HotelService hotelService;
private final ModelMapper modelMapper;
@Autowired
public HotelController(HotelService hotelService, ModelMapper modelMapper) {
this.hotelService = hotelService;
this.modelMapper = modelMapper;
}
@GetMapping
public List<HotelDto> getHotels() {
return hotelService.getAllHotels();
}
@GetMapping(value = "/{hotelId}")
public HotelDto getHotel(@PathVariable Long hotelId) {
return modelMapper.map(hotelService.getHotelById(hotelId), HotelDto.class);
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(code = HttpStatus.CREATED)
public void createHotel(@Valid @RequestBody HotelDto hotelDto) {
hotelService.createHotel(hotelDto);
}
@PutMapping(path = "/{hotelId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public HotelDto editHotel(@Valid @RequestBody HotelDto hotelDto, @PathVariable Long hotelId) {
return modelMapper.map(hotelService.editHotel(hotelId, hotelDto), HotelDto.class);
}
@DeleteMapping(path = "/{hotelId}")
public void deleteHotel(@PathVariable Long hotelId) {
hotelService.deleteHotel(hotelId);
}
@GetMapping(path = "/available")
public List<HotelDto> getHotelsWithAvailableRooms() {
return hotelService.getAllHotelsWithFreeRooms()
.stream()
.map(hotel -> modelMapper.map(hotel, HotelDto.class))
.collect(Collectors.toList());
}
@GetMapping(path = "/owned/{user}")
public List<HotelDto> getHotelsOwnedByUser(@PathVariable String user, @RequestParam String name, @RequestParam String city,
@RequestParam String country) {
return hotelService.getHotelsOwnedByUser(user, name, city, country);
}
}
|
package com.crud.hotels.backend.controller;
import com.crud.hotels.backend.dto.HotelDto;
import com.crud.hotels.backend.service.HotelService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.IMPORT_0.Valid;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/v1/hotels")
public class HotelController {
private final HotelService VAR_0;
private final ModelMapper modelMapper;
@Autowired
public HotelController(HotelService VAR_0, ModelMapper modelMapper) {
this.VAR_0 = VAR_0;
this.modelMapper = modelMapper;
}
@GetMapping
public List<HotelDto> getHotels() {
return VAR_0.getAllHotels();
}
@GetMapping(value = "/{hotelId}")
public HotelDto getHotel(@PathVariable Long hotelId) {
return modelMapper.map(VAR_0.getHotelById(hotelId), HotelDto.class);
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(code = HttpStatus.VAR_1)
public void createHotel(@Valid @RequestBody HotelDto hotelDto) {
VAR_0.createHotel(hotelDto);
}
@PutMapping(path = "/{hotelId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public HotelDto editHotel(@Valid @RequestBody HotelDto hotelDto, @PathVariable Long hotelId) {
return modelMapper.map(VAR_0.editHotel(hotelId, hotelDto), HotelDto.class);
}
@DeleteMapping(path = "/{hotelId}")
public void deleteHotel(@PathVariable Long hotelId) {
VAR_0.deleteHotel(hotelId);
}
@GetMapping(path = "/available")
public List<HotelDto> getHotelsWithAvailableRooms() {
return VAR_0.getAllHotelsWithFreeRooms()
.stream()
.map(hotel -> modelMapper.map(hotel, HotelDto.class))
.collect(Collectors.toList());
}
@GetMapping(path = "/owned/{user}")
public List<HotelDto> getHotelsOwnedByUser(@PathVariable String user, @RequestParam String name, @RequestParam String city,
@RequestParam String country) {
return VAR_0.getHotelsOwnedByUser(user, name, city, country);
}
}
| 0.070216
|
{'IMPORT_0': 'validation', 'VAR_0': 'hotelService', 'VAR_1': 'CREATED'}
|
java
|
Hibrido
|
46.55%
|
package fr.sii.atlantique.fusiion.fusiion_gestion_competences.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import fr.sii.atlantique.fusiion.fusiion_gestion_competences.models.statistiques.ActionStatistique;
import fr.sii.atlantique.fusiion.fusiion_gestion_competences.services.CompetenceService;
/**
*
* Classe permettant de traiter la réalisation d'une action demandée par le service statistique
*
* @author <NAME>, <NAME>, <NAME>, <NAME>
*/
@Component
public class TraitementStatistiques {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private TopicExchange topicExchange;
private static final Logger LOGGER = LoggerFactory.getLogger(TraitementStatistiques.class);
private final ObjectMapper mapper = new ObjectMapper();
private final String STATISTIQUE_ENREGISTRER_QUEUE = "Statistique.enregistrer";
@Autowired
private CompetenceService competenceService;
/**
* Constructeur vide
*
*/
public TraitementStatistiques() {
super();
}
/**
* permet de traiter les différentes action demandé par le service statistiques
*
* @throws JsonProcessingException
*/
public void receiveAction(ActionStatistique action) throws JsonProcessingException {
switch(action.getTypeAction()) {
case "Actualiser" :
competenceService.actualiserStatistique(action.getAkStatistique());
break;
default :
LOGGER.info("WARN: TraitementStatistiques[receiveActionSucces] - {} , {} ", "Action non traitée ", action);
break;
}
}
}
|
package IMPORT_0.IMPORT_1.atlantique.fusiion.IMPORT_2.listener;
import IMPORT_3.slf4j.Logger;
import IMPORT_3.slf4j.IMPORT_4;
import IMPORT_3.IMPORT_5.IMPORT_6.core.TopicExchange;
import IMPORT_3.IMPORT_5.IMPORT_6.IMPORT_7.core.RabbitTemplate;
import IMPORT_3.IMPORT_5.beans.IMPORT_8.annotation.IMPORT_9;
import IMPORT_3.IMPORT_5.IMPORT_10.IMPORT_11;
import IMPORT_12.IMPORT_13.IMPORT_14.core.JsonProcessingException;
import IMPORT_12.IMPORT_13.IMPORT_14.databind.IMPORT_15;
import IMPORT_0.IMPORT_1.atlantique.fusiion.IMPORT_2.IMPORT_16.statistiques.ActionStatistique;
import IMPORT_0.IMPORT_1.atlantique.fusiion.IMPORT_2.IMPORT_17.IMPORT_18;
/**
*
* Classe permettant de traiter la réalisation d'une action demandée par le service statistique
*
* @author <NAME>, <NAME>, <NAME>, <NAME>
*/
@IMPORT_11
public class CLASS_0 {
@IMPORT_9
private RabbitTemplate VAR_0;
@IMPORT_9
private TopicExchange VAR_1;
private static final Logger LOGGER = IMPORT_4.getLogger(CLASS_0.class);
private final IMPORT_15 VAR_2 = new IMPORT_15();
private final CLASS_1 VAR_3 = "Statistique.enregistrer";
@IMPORT_9
private IMPORT_18 competenceService;
/**
* Constructeur vide
*
*/
public CLASS_0() {
super();
}
/**
* permet de traiter les différentes action demandé par le service statistiques
*
* @throws JsonProcessingException
*/
public void FUNC_0(ActionStatistique action) throws JsonProcessingException {
switch(action.FUNC_1()) {
case "Actualiser" :
competenceService.FUNC_2(action.FUNC_3());
break;
default :
LOGGER.info("WARN: TraitementStatistiques[receiveActionSucces] - {} , {} ", "Action non traitée ", aVAR_4;
break;
}
}
}
| 0.734172
|
{'IMPORT_0': 'fr', 'IMPORT_1': 'sii', 'IMPORT_2': 'fusiion_gestion_competences', 'IMPORT_3': 'org', 'IMPORT_4': 'LoggerFactory', 'IMPORT_5': 'springframework', 'IMPORT_6': 'amqp', 'IMPORT_7': 'rabbit', 'IMPORT_8': 'factory', 'IMPORT_9': 'Autowired', 'IMPORT_10': 'stereotype', 'IMPORT_11': 'Component', 'IMPORT_12': 'com', 'IMPORT_13': 'fasterxml', 'IMPORT_14': 'jackson', 'IMPORT_15': 'ObjectMapper', 'IMPORT_16': 'models', 'IMPORT_17': 'services', 'IMPORT_18': 'CompetenceService', 'CLASS_0': 'TraitementStatistiques', 'VAR_0': 'rabbitTemplate', 'VAR_1': 'topicExchange', 'VAR_2': 'mapper', 'CLASS_1': 'String', 'VAR_3': 'STATISTIQUE_ENREGISTRER_QUEUE', 'FUNC_0': 'receiveAction', 'FUNC_1': 'getTypeAction', 'FUNC_2': 'actualiserStatistique', 'FUNC_3': 'getAkStatistique', 'VAR_4': 'ction)'}
|
java
|
OOP
|
60.11%
|
package Model.Main;
import Model.Library.ConnectDatabase;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
class ReactStoryDB {
static LinkedList<ReactStory> getReacts(String sid) {
LinkedList<ReactStory> reacts = new LinkedList<>();
PreparedStatement ps = ConnectDatabase.preparedStatement("{CALL getReactStories(?)}");
assert ps != null;
try {
ps.setString(1, sid);
ps.execute();
ResultSet rs = ps.getResultSet();
while (rs.next()) {
String userID = rs.getString("UserID");
String name = rs.getString("Name");
String avatar = rs.getString("Avatar");
String type = rs.getString("Type");
reacts.add(new ReactStory(userID, name, avatar, type));
}
return reacts;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
static void newReactStory(String sid, String uid, String t) {
PreparedStatement ps = ConnectDatabase.preparedStatement("{CALL newReactStory(?,?,?)}");
try {
assert ps != null;
ps.setString(1, sid);
ps.setString(2, uid);
ps.setString(3, t);
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package Model.IMPORT_0;
import Model.IMPORT_1.IMPORT_2;
import IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_3.IMPORT_4.IMPORT_6;
import IMPORT_3.IMPORT_4.IMPORT_7;
import IMPORT_3.IMPORT_8.IMPORT_9;
class CLASS_0 {
static IMPORT_9<CLASS_1> FUNC_0(CLASS_2 VAR_0) {
IMPORT_9<CLASS_1> reacts = new IMPORT_9<>();
IMPORT_5 VAR_1 = IMPORT_2.FUNC_1("{CALL getReactStories(?)}");
assert VAR_1 != null;
try {
VAR_1.FUNC_2(1, VAR_0);
VAR_1.FUNC_3();
IMPORT_6 VAR_2 = VAR_1.FUNC_4();
while (VAR_2.FUNC_5()) {
CLASS_2 VAR_3 = VAR_2.getString("UserID");
CLASS_2 name = VAR_2.getString("Name");
CLASS_2 VAR_4 = VAR_2.getString("Avatar");
CLASS_2 type = VAR_2.getString("Type");
reacts.FUNC_6(new CLASS_1(VAR_3, name, VAR_4, type));
}
return reacts;
} catch (IMPORT_7 VAR_5) {
VAR_5.printStackTrace();
}
return null;
}
static void FUNC_7(CLASS_2 VAR_0, CLASS_2 VAR_6, CLASS_2 VAR_7) {
IMPORT_5 VAR_1 = IMPORT_2.FUNC_1("{CALL newReactStory(?,?,?)}");
try {
assert VAR_1 != null;
VAR_1.FUNC_2(1, VAR_0);
VAR_1.FUNC_2(2, VAR_6);
VAR_1.FUNC_2(3, VAR_7);
VAR_1.FUNC_3();
} catch (IMPORT_7 VAR_5) {
VAR_5.printStackTrace();
}
}
}
| 0.827725
|
{'IMPORT_0': 'Main', 'IMPORT_1': 'Library', 'IMPORT_2': 'ConnectDatabase', 'IMPORT_3': 'java', 'IMPORT_4': 'sql', 'IMPORT_5': 'PreparedStatement', 'IMPORT_6': 'ResultSet', 'IMPORT_7': 'SQLException', 'IMPORT_8': 'util', 'IMPORT_9': 'LinkedList', 'CLASS_0': 'ReactStoryDB', 'CLASS_1': 'ReactStory', 'FUNC_0': 'getReacts', 'CLASS_2': 'String', 'VAR_0': 'sid', 'VAR_1': 'ps', 'FUNC_1': 'preparedStatement', 'FUNC_2': 'setString', 'FUNC_3': 'execute', 'VAR_2': 'rs', 'FUNC_4': 'getResultSet', 'FUNC_5': 'next', 'VAR_3': 'userID', 'VAR_4': 'avatar', 'FUNC_6': 'add', 'VAR_5': 'e', 'FUNC_7': 'newReactStory', 'VAR_6': 'uid', 'VAR_7': 't'}
|
java
|
OOP
|
100.00%
|
/**
* Inventory implementation for casings, having six slots for modules, one per face.
*/
public final class CasingInventory extends Inventory implements ISidedInventory {
private final CasingTileEntity tileEntity;
public CasingInventory(final CasingTileEntity tileEntity) {
super(Face.VALUES.length);
this.tileEntity = tileEntity;
}
// Copy-paste of parent setInventorySlotContents, but allows passing along module facing.
public void setInventorySlotContents(final int index, final ItemStack stack, final Port facing) {
if (items[index] == stack) {
return;
}
if (!items[index].isEmpty()) {
onItemRemoved(index);
}
items[index] = stack;
if (!items[index].isEmpty()) {
onItemAdded(index, facing);
}
setChanged();
}
// --------------------------------------------------------------------- //
// IInventory
@Override
public int getMaxStackSize() {
return 1;
}
@Override
public void setChanged() {
tileEntity.setChanged();
final World world = tileEntity.getBlockEntityWorld();
if (!world.isClientSide()) {
BlockState state = tileEntity.getBlockState();
for (final Face face : Face.VALUES) {
final BooleanProperty property = CasingBlock.FACE_TO_PROPERTY.get(face);
state = state.setValue(property, !items[face.ordinal()].isEmpty());
}
world.setBlockAndUpdate(tileEntity.getBlockPos(), state);
}
}
// --------------------------------------------------------------------- //
// ISidedInventory
@Override
public int[] getSlotsForFace(final Direction side) {
return new int[side.ordinal()];
}
@Override
public boolean canPlaceItemThroughFace(final int index, final ItemStack stack, @Nullable final Direction side) {
return side != null && side.ordinal() == index &&
getItem(index).isEmpty() &&
tileEntity.getModule(Face.fromDirection(side)) == null && // Handles virtual modules.
canInstall(stack, Face.fromDirection(side));
}
@Override
public boolean canTakeItemThroughFace(final int index, final ItemStack stack, final Direction side) {
return side.ordinal() == index && stack == getItem(index);
}
private boolean canInstall(final ItemStack stack, final Face face) {
return ModuleProviders.getProviderFor(stack, tileEntity, face).isPresent();
}
// --------------------------------------------------------------------- //
// Inventory
@Override
protected void onItemAdded(final int index) {
onItemAdded(index, Port.UP);
}
private void onItemAdded(final int index, final Port facing) {
final ItemStack stack = getItem(index);
if (stack.isEmpty()) {
return;
}
final Face face = Face.VALUES[index];
final Optional<ModuleProvider> provider = ModuleProviders.getProviderFor(stack, tileEntity, face);
if (!provider.isPresent()) {
return;
}
final Module module = provider.get().createModule(stack, tileEntity, face);
if (module instanceof ModuleWithRotation) {
((ModuleWithRotation) module).setFacing(facing);
}
if (!tileEntity.getCasingLevel().isClientSide()) {
// Grab module data from newly created module, if any, don't rely on stack.
// Rationale: module may initialize data from stack while contents of stack
// are not synchronized to client, or do some fancy server-side only setup
// based on the stack. The possibilities are endless. This is robust.
final CompoundNBT moduleData;
if (module != null) {
module.onInstalled(stack);
module.save(moduleData = new CompoundNBT());
} else {
moduleData = null;
}
final CasingInventoryMessage message = new CasingInventoryMessage(tileEntity, index, stack, moduleData);
Network.INSTANCE.send(Network.getTracking(tileEntity), message);
}
tileEntity.setModule(Face.VALUES[index], module);
}
@Override
protected void onItemRemoved(final int index) {
final Face face = Face.VALUES[index];
final Module module = tileEntity.getModule(face);
tileEntity.setModule(face, null);
if (!tileEntity.getCasingLevel().isClientSide()) {
if (module != null) {
module.onUninstalled(getItem(index));
module.onDisposed();
}
final CasingInventoryMessage message = new CasingInventoryMessage(tileEntity, index, ItemStack.EMPTY, null);
Network.INSTANCE.send(Network.getTracking(tileEntity), message);
}
}
}
|
/**
* Inventory implementation for casings, having six slots for modules, one per face.
*/
public final class CLASS_0 extends CLASS_1 implements ISidedInventory {
private final CasingTileEntity VAR_0;
public CLASS_0(final CasingTileEntity VAR_0) {
super(VAR_1.VAR_2.VAR_3);
this.VAR_0 = VAR_0;
}
// Copy-paste of parent setInventorySlotContents, but allows passing along module facing.
public void setInventorySlotContents(final int VAR_4, final ItemStack stack, final Port facing) {
if (VAR_5[VAR_4] == stack) {
return;
}
if (!VAR_5[VAR_4].FUNC_0()) {
FUNC_1(VAR_4);
}
VAR_5[VAR_4] = stack;
if (!VAR_5[VAR_4].FUNC_0()) {
onItemAdded(VAR_4, facing);
}
setChanged();
}
// --------------------------------------------------------------------- //
// IInventory
@Override
public int getMaxStackSize() {
return 1;
}
@Override
public void setChanged() {
VAR_0.setChanged();
final CLASS_3 world = VAR_0.getBlockEntityWorld();
if (!world.isClientSide()) {
CLASS_4 state = VAR_0.getBlockState();
for (final CLASS_2 VAR_6 : VAR_1.VAR_2) {
final CLASS_5 VAR_7 = CasingBlock.FACE_TO_PROPERTY.FUNC_2(VAR_6);
state = state.setValue(VAR_7, !VAR_5[VAR_6.FUNC_3()].FUNC_0());
}
world.FUNC_4(VAR_0.FUNC_5(), state);
}
}
// --------------------------------------------------------------------- //
// ISidedInventory
@Override
public int[] getSlotsForFace(final CLASS_6 side) {
return new int[side.FUNC_3()];
}
@Override
public boolean canPlaceItemThroughFace(final int VAR_4, final ItemStack stack, @VAR_8 final CLASS_6 side) {
return side != null && side.FUNC_3() == VAR_4 &&
getItem(VAR_4).FUNC_0() &&
VAR_0.getModule(VAR_1.FUNC_6(side)) == null && // Handles virtual modules.
canInstall(stack, VAR_1.FUNC_6(side));
}
@Override
public boolean canTakeItemThroughFace(final int VAR_4, final ItemStack stack, final CLASS_6 side) {
return side.FUNC_3() == VAR_4 && stack == getItem(VAR_4);
}
private boolean canInstall(final ItemStack stack, final CLASS_2 VAR_6) {
return ModuleProviders.getProviderFor(stack, VAR_0, VAR_6).FUNC_7();
}
// --------------------------------------------------------------------- //
// Inventory
@Override
protected void onItemAdded(final int VAR_4) {
onItemAdded(VAR_4, Port.UP);
}
private void onItemAdded(final int VAR_4, final Port facing) {
final ItemStack stack = getItem(VAR_4);
if (stack.FUNC_0()) {
return;
}
final CLASS_2 VAR_6 = VAR_1.VAR_2[VAR_4];
final CLASS_7<CLASS_8> provider = ModuleProviders.getProviderFor(stack, VAR_0, VAR_6);
if (!provider.FUNC_7()) {
return;
}
final CLASS_9 VAR_9 = provider.FUNC_2().FUNC_8(stack, VAR_0, VAR_6);
if (VAR_9 instanceof ModuleWithRotation) {
((ModuleWithRotation) VAR_9).setFacing(facing);
}
if (!VAR_0.FUNC_9().isClientSide()) {
// Grab module data from newly created module, if any, don't rely on stack.
// Rationale: module may initialize data from stack while contents of stack
// are not synchronized to client, or do some fancy server-side only setup
// based on the stack. The possibilities are endless. This is robust.
final CompoundNBT moduleData;
if (VAR_9 != null) {
VAR_9.onInstalled(stack);
VAR_9.FUNC_10(moduleData = new CompoundNBT());
} else {
moduleData = null;
}
final CasingInventoryMessage VAR_10 = new CasingInventoryMessage(VAR_0, VAR_4, stack, moduleData);
Network.VAR_11.FUNC_11(Network.FUNC_12(VAR_0), VAR_10);
}
VAR_0.FUNC_13(VAR_1.VAR_2[VAR_4], VAR_9);
}
@Override
protected void FUNC_1(final int VAR_4) {
final CLASS_2 VAR_6 = VAR_1.VAR_2[VAR_4];
final CLASS_9 VAR_9 = VAR_0.getModule(VAR_6);
VAR_0.FUNC_13(VAR_6, null);
if (!VAR_0.FUNC_9().isClientSide()) {
if (VAR_9 != null) {
VAR_9.FUNC_14(getItem(VAR_4));
VAR_9.FUNC_15();
}
final CasingInventoryMessage VAR_10 = new CasingInventoryMessage(VAR_0, VAR_4, ItemStack.VAR_12, null);
Network.VAR_11.FUNC_11(Network.FUNC_12(VAR_0), VAR_10);
}
}
}
| 0.491244
|
{'CLASS_0': 'CasingInventory', 'CLASS_1': 'Inventory', 'VAR_0': 'tileEntity', 'VAR_1': 'Face', 'CLASS_2': 'Face', 'VAR_2': 'VALUES', 'VAR_3': 'length', 'VAR_4': 'index', 'VAR_5': 'items', 'FUNC_0': 'isEmpty', 'FUNC_1': 'onItemRemoved', 'CLASS_3': 'World', 'CLASS_4': 'BlockState', 'VAR_6': 'face', 'CLASS_5': 'BooleanProperty', 'VAR_7': 'property', 'FUNC_2': 'get', 'FUNC_3': 'ordinal', 'FUNC_4': 'setBlockAndUpdate', 'FUNC_5': 'getBlockPos', 'CLASS_6': 'Direction', 'VAR_8': 'Nullable', 'FUNC_6': 'fromDirection', 'FUNC_7': 'isPresent', 'CLASS_7': 'Optional', 'CLASS_8': 'ModuleProvider', 'CLASS_9': 'Module', 'VAR_9': 'module', 'FUNC_8': 'createModule', 'FUNC_9': 'getCasingLevel', 'FUNC_10': 'save', 'VAR_10': 'message', 'VAR_11': 'INSTANCE', 'FUNC_11': 'send', 'FUNC_12': 'getTracking', 'FUNC_13': 'setModule', 'FUNC_14': 'onUninstalled', 'FUNC_15': 'onDisposed', 'VAR_12': 'EMPTY'}
|
java
|
OOP
|
100.00%
|
/** Feature is average within-class similarity. Also add feature that
* is Node's similarity to the Prototype of this cluster, where the
* Prototype is defined as the node that has the highest similarity to
* all other nodes in the cluster. */
public class ClusterHomogeneity extends Pipe
{
Classifier classifier;
public ClusterHomogeneity (Classifier _classifier) {
this.classifier = _classifier;
}
public Instance pipe (Instance carrier) {
NodeClusterPair pair = (NodeClusterPair)carrier.getData();
Collection cluster = (Collection)pair.getCluster();
Citation[] nodes = (Citation[])cluster.toArray (new Citation[] {});
double[][] similarity = new double[nodes.length][nodes.length];
if (cluster.size() > 1) { // don't include feature for singleton clusters
for (int i=0; i < nodes.length; i++) {
Citation ci = nodes[i];
similarity[i][i] = 1.0;
for (int j=i+1; j < nodes.length; j++) {
Citation cj = nodes[j];
similarity[i][j] = similarity[j][i] = getSimilarity (ci, cj);
}
}
double avgSimilarity = getAverage (similarity, nodes.length);
Citation prototype = getCitationClosestToAll (nodes, similarity);
Citation node = (Citation)pair.getNode();
double prototypeSimilarity = getSimilarity (prototype, node);
if (prototypeSimilarity > 0.9)
pair.setFeatureValue ("CH_PrototypeNodeSimilarityHigh", 1.0);
else if (prototypeSimilarity > 0.75)
pair.setFeatureValue ("CH_PrototypeNodeSimilarityMed", 1.0);
else if (prototypeSimilarity > 0.5)
pair.setFeatureValue ("CH_PrototypeNodeSimilarityWeak", 1.0);
else if (prototypeSimilarity > 0.3)
pair.setFeatureValue ("CH_PrototypeNodeSimilarityMin", 1.0);
else
pair.setFeatureValue ("CH_PrototypeNodeSimilarityNone", 1.0);
if (avgSimilarity > 0.9)
pair.setFeatureValue ("WithinClusterSimilarityHigh", 1.0);
else if (avgSimilarity > 0.75)
pair.setFeatureValue ("WithinClusterSimilarityMed", 1.0);
else if (avgSimilarity > 0.5)
pair.setFeatureValue ("WithinClusterSimilarityWeak", 1.0);
else if (avgSimilarity > 0.3)
pair.setFeatureValue ("WithinClusterSimilarityMin", 1.0);
else
pair.setFeatureValue ("WithinClusterSimilarityNone", 1.0);
}
return carrier;
}
private double getAverage (double[][] m, int len) {
double sum = 0.0;
for (int i=0; i < len; i++) {
for (int j=0; j < len; j++) {
sum += m[i][j];
}
}
return sum / ((double)len*len);
}
private double getSimilarity (Citation ci, Citation cj) {
NodePair np = new NodePair (ci, cj);
Instance inst = new Instance (np, "unknown", null, np, classifier.getInstancePipe());
Labeling labeling = classifier.classify(inst).getLabeling();
double val = 0.0;
if (labeling.labelAtLocation(0).toString().equals("no"))
val = labeling.valueAtLocation(1)-labeling.valueAtLocation(0);
else
val = labeling.valueAtLocation(0)-labeling.valueAtLocation(1);
return val;
}
/** Finds the citation that has the highest similarity to all other citations*/
private Citation getCitationClosestToAll (Citation[] nodes, double[][] similarity) {
double maxSim = -9999999.9;
int maxIndex = -1;
for (int i=0; i < nodes.length; i++) {
double sim = 0.0;
for (int j=0; j < nodes.length; j++) {
sim += similarity[i][j];
}
if (sim > maxSim) {
maxSim = sim;
maxIndex = i;
}
}
return nodes[maxIndex];
}
}
|
/** Feature is average within-class similarity. Also add feature that
* is Node's similarity to the Prototype of this cluster, where the
* Prototype is defined as the node that has the highest similarity to
* all other nodes in the cluster. */
public class CLASS_0 extends Pipe
{
CLASS_1 classifier;
public CLASS_0 (CLASS_1 VAR_0) {
this.classifier = VAR_0;
}
public CLASS_2 FUNC_0 (CLASS_2 carrier) {
CLASS_3 VAR_1 = (CLASS_3)carrier.FUNC_1();
CLASS_4 VAR_2 = (CLASS_4)VAR_1.FUNC_2();
CLASS_5[] VAR_3 = (CLASS_5[])VAR_2.toArray (new CLASS_5[] {});
double[][] VAR_4 = new double[VAR_3.VAR_5][VAR_3.VAR_5];
if (VAR_2.size() > 1) { // don't include feature for singleton clusters
for (int i=0; i < VAR_3.VAR_5; i++) {
CLASS_5 VAR_6 = VAR_3[i];
VAR_4[i][i] = 1.0;
for (int VAR_7=i+1; VAR_7 < VAR_3.VAR_5; VAR_7++) {
CLASS_5 VAR_8 = VAR_3[VAR_7];
VAR_4[i][VAR_7] = VAR_4[VAR_7][i] = FUNC_3 (VAR_6, VAR_8);
}
}
double VAR_9 = FUNC_4 (VAR_4, VAR_3.VAR_5);
CLASS_5 VAR_10 = FUNC_5 (VAR_3, VAR_4);
CLASS_5 VAR_11 = (CLASS_5)VAR_1.FUNC_6();
double VAR_12 = FUNC_3 (VAR_10, VAR_11);
if (VAR_12 > 0.9)
VAR_1.FUNC_7 ("CH_PrototypeNodeSimilarityHigh", 1.0);
else if (VAR_12 > 0.75)
VAR_1.FUNC_7 ("CH_PrototypeNodeSimilarityMed", 1.0);
else if (VAR_12 > 0.5)
VAR_1.FUNC_7 ("CH_PrototypeNodeSimilarityWeak", 1.0);
else if (VAR_12 > 0.3)
VAR_1.FUNC_7 ("CH_PrototypeNodeSimilarityMin", 1.0);
else
VAR_1.FUNC_7 ("CH_PrototypeNodeSimilarityNone", 1.0);
if (VAR_9 > 0.9)
VAR_1.FUNC_7 ("WithinClusterSimilarityHigh", 1.0);
else if (VAR_9 > 0.75)
VAR_1.FUNC_7 ("WithinClusterSimilarityMed", 1.0);
else if (VAR_9 > 0.5)
VAR_1.FUNC_7 ("WithinClusterSimilarityWeak", 1.0);
else if (VAR_9 > 0.3)
VAR_1.FUNC_7 ("WithinClusterSimilarityMin", 1.0);
else
VAR_1.FUNC_7 ("WithinClusterSimilarityNone", 1.0);
}
return carrier;
}
private double FUNC_4 (double[][] VAR_13, int VAR_14) {
double VAR_15 = 0.0;
for (int i=0; i < VAR_14; i++) {
for (int VAR_7=0; VAR_7 < VAR_14; VAR_7++) {
VAR_15 += VAR_13[i][VAR_7];
}
}
return VAR_15 / ((double)VAR_14*VAR_14);
}
private double FUNC_3 (CLASS_5 VAR_6, CLASS_5 VAR_8) {
CLASS_6 VAR_16 = new CLASS_6 (VAR_6, VAR_8);
CLASS_2 VAR_17 = new CLASS_2 (VAR_16, "unknown", null, VAR_16, classifier.FUNC_8());
CLASS_7 VAR_18 = classifier.FUNC_9(VAR_17).FUNC_10();
double VAR_19 = 0.0;
if (VAR_18.FUNC_11(0).FUNC_12().FUNC_13("no"))
VAR_19 = VAR_18.FUNC_14(1)-VAR_18.FUNC_14(0);
else
VAR_19 = VAR_18.FUNC_14(0)-VAR_18.FUNC_14(1);
return VAR_19;
}
/** Finds the citation that has the highest similarity to all other citations*/
private CLASS_5 FUNC_5 (CLASS_5[] VAR_3, double[][] VAR_4) {
double VAR_20 = -9999999.9;
int maxIndex = -1;
for (int i=0; i < VAR_3.VAR_5; i++) {
double VAR_21 = 0.0;
for (int VAR_7=0; VAR_7 < VAR_3.VAR_5; VAR_7++) {
VAR_21 += VAR_4[i][VAR_7];
}
if (VAR_21 > VAR_20) {
VAR_20 = VAR_21;
maxIndex = i;
}
}
return VAR_3[maxIndex];
}
}
| 0.917959
|
{'CLASS_0': 'ClusterHomogeneity', 'CLASS_1': 'Classifier', 'VAR_0': '_classifier', 'CLASS_2': 'Instance', 'FUNC_0': 'pipe', 'CLASS_3': 'NodeClusterPair', 'VAR_1': 'pair', 'FUNC_1': 'getData', 'CLASS_4': 'Collection', 'VAR_2': 'cluster', 'FUNC_2': 'getCluster', 'CLASS_5': 'Citation', 'VAR_3': 'nodes', 'VAR_4': 'similarity', 'VAR_5': 'length', 'VAR_6': 'ci', 'VAR_7': 'j', 'VAR_8': 'cj', 'FUNC_3': 'getSimilarity', 'VAR_9': 'avgSimilarity', 'FUNC_4': 'getAverage', 'VAR_10': 'prototype', 'FUNC_5': 'getCitationClosestToAll', 'VAR_11': 'node', 'FUNC_6': 'getNode', 'VAR_12': 'prototypeSimilarity', 'FUNC_7': 'setFeatureValue', 'VAR_13': 'm', 'VAR_14': 'len', 'VAR_15': 'sum', 'CLASS_6': 'NodePair', 'VAR_16': 'np', 'VAR_17': 'inst', 'FUNC_8': 'getInstancePipe', 'CLASS_7': 'Labeling', 'VAR_18': 'labeling', 'FUNC_9': 'classify', 'FUNC_10': 'getLabeling', 'VAR_19': 'val', 'FUNC_11': 'labelAtLocation', 'FUNC_12': 'toString', 'FUNC_13': 'equals', 'FUNC_14': 'valueAtLocation', 'VAR_20': 'maxSim', 'VAR_21': 'sim'}
|
java
|
OOP
|
20.21%
|
// This method will be showed when player wins game
private void winningMessage(int point) {
GLabel win = new GLabel("You are winner");
win.setFont("Helvetica-30");
win.setColor(Color.RED);
GLabel score = new GLabel("Your point is " + point);
score.setFont("Helvetica-22");
score.setColor(Color.BLUE);
double winWidth = win.getWidth();
double scoreWidth = score.getWidth();
double scoreAscent = score.getAscent();
win.setLocation((WIDTH - winWidth) / 2, HEIGHT / 2 - MESSAGE_SEP / 2);
score.setLocation((WIDTH - scoreWidth) / 2, HEIGHT / 2 + scoreAscent + MESSAGE_SEP / 2);
add(win);
add(score);
}
|
// This method will be showed when player wins game
private void FUNC_0(int VAR_0) {
GLabel win = new GLabel("You are winner");
win.FUNC_1("Helvetica-30");
win.setColor(Color.RED);
GLabel VAR_1 = new GLabel("Your point is " + VAR_0);
VAR_1.FUNC_1("Helvetica-22");
VAR_1.setColor(Color.BLUE);
double winWidth = win.FUNC_2();
double VAR_2 = VAR_1.FUNC_2();
double scoreAscent = VAR_1.FUNC_3();
win.FUNC_4((VAR_3 - winWidth) / 2, VAR_4 / 2 - VAR_5 / 2);
VAR_1.FUNC_4((VAR_3 - VAR_2) / 2, VAR_4 / 2 + scoreAscent + VAR_5 / 2);
add(win);
add(VAR_1);
}
| 0.590946
|
{'FUNC_0': 'winningMessage', 'VAR_0': 'point', 'FUNC_1': 'setFont', 'VAR_1': 'score', 'FUNC_2': 'getWidth', 'VAR_2': 'scoreWidth', 'FUNC_3': 'getAscent', 'FUNC_4': 'setLocation', 'VAR_3': 'WIDTH', 'VAR_4': 'HEIGHT', 'VAR_5': 'MESSAGE_SEP'}
|
java
|
Procedural
|
100.00%
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.jetbrains.plugins.groovy.codeInspection.control.finalVar;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiVariable;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.DFAEngine;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.DfaInstance;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.Semilattice;
import org.jetbrains.plugins.groovy.util.LightCacheKey;
import java.util.List;
import java.util.Map;
/**
* @author <NAME>
*/
public class VariableInitializationChecker {
private static final LightCacheKey<Map<GroovyPsiElement, Boolean>> KEY = LightCacheKey.createByFileModificationCount();
public static boolean isVariableDefinitelyInitialized(@NotNull String varName, @NotNull Instruction[] controlFlow) {
DFAEngine<Data> engine = new DFAEngine<>(controlFlow, new MyDfaInstance(varName), new MySemilattice());
final List<Data> result = engine.performDFAWithTimeout();
if (result == null) return false;
return result.get(controlFlow.length - 1).get();
}
public static boolean isVariableDefinitelyInitializedCached(@NotNull PsiVariable var,
@NotNull GroovyPsiElement context,
@NotNull Instruction[] controlFlow) {
Map<GroovyPsiElement, Boolean> map = KEY.getCachedValue(var);
if (map == null) {
map = ContainerUtil.newHashMap();
KEY.putCachedValue(var, map);
}
final Boolean cached = map.get(context);
if (cached != null) return cached.booleanValue();
final boolean result = isVariableDefinitelyInitialized(var.getName(), controlFlow);
map.put(context, result);
return result;
}
private static class MyDfaInstance implements DfaInstance<Data> {
public MyDfaInstance(String var) {
myVar = var;
}
@Override
public void fun(@NotNull Data e, @NotNull Instruction instruction) {
if (instruction instanceof ReadWriteVariableInstruction &&
((ReadWriteVariableInstruction)instruction).getVariableName().equals(myVar)) {
e.set(true);
}
}
@NotNull
@Override
public Data initial() {
return new Data(false);
}
private final String myVar;
}
private static class MySemilattice implements Semilattice<Data> {
@NotNull
@Override
public Data join(@NotNull List<Data> ins) {
if (ins.isEmpty()) return new Data(false);
boolean b = true;
for (Data data : ins) {
b &= data.get().booleanValue();
}
return new Data(b);
}
@Override
public boolean eq(@NotNull Data e1, @NotNull Data e2) {
return e1.get().booleanValue() == e2.get().booleanValue();
}
}
private static class Data extends Ref<Boolean> {
public Data(Boolean value) {
super(value);
}
}
}
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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 IMPORT_0.IMPORT_1.plugins.IMPORT_2.codeInspection.control.IMPORT_3;
import IMPORT_4.intellij.IMPORT_5.util.IMPORT_6;
import IMPORT_4.intellij.psi.IMPORT_7;
import IMPORT_4.intellij.util.IMPORT_8.IMPORT_9;
import IMPORT_0.IMPORT_1.IMPORT_10.IMPORT_11;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.lang.psi.IMPORT_12;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.lang.psi.controlFlow.Instruction;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.lang.psi.controlFlow.ReadWriteVariableInstruction;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.lang.psi.IMPORT_13.IMPORT_14;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.lang.psi.IMPORT_13.DfaInstance;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.lang.psi.IMPORT_13.IMPORT_15;
import IMPORT_0.IMPORT_1.plugins.IMPORT_2.util.IMPORT_16;
import IMPORT_17.util.IMPORT_18;
import IMPORT_17.util.IMPORT_19;
/**
* @author <NAME>
*/
public class CLASS_0 {
private static final IMPORT_16<IMPORT_19<IMPORT_12, CLASS_1>> VAR_0 = IMPORT_16.FUNC_0();
public static boolean isVariableDefinitelyInitialized(@IMPORT_11 CLASS_2 VAR_1, @IMPORT_11 Instruction[] controlFlow) {
IMPORT_14<Data> VAR_2 = new IMPORT_14<>(controlFlow, new MyDfaInstance(VAR_1), new MySemilattice());
final IMPORT_18<Data> VAR_3 = VAR_2.performDFAWithTimeout();
if (VAR_3 == null) return false;
return VAR_3.FUNC_1(controlFlow.VAR_4 - 1).FUNC_1();
}
public static boolean FUNC_2(@IMPORT_11 IMPORT_7 VAR_5,
@IMPORT_11 IMPORT_12 context,
@IMPORT_11 Instruction[] controlFlow) {
IMPORT_19<IMPORT_12, CLASS_1> map = VAR_0.FUNC_3(VAR_5);
if (map == null) {
map = IMPORT_9.FUNC_4();
VAR_0.FUNC_5(VAR_5, map);
}
final CLASS_1 cached = map.FUNC_1(context);
if (cached != null) return cached.FUNC_6();
final boolean VAR_3 = isVariableDefinitelyInitialized(VAR_5.FUNC_7(), controlFlow);
map.put(context, VAR_3);
return VAR_3;
}
private static class MyDfaInstance implements DfaInstance<Data> {
public MyDfaInstance(CLASS_2 VAR_5) {
myVar = VAR_5;
}
@Override
public void FUNC_8(@IMPORT_11 Data e, @IMPORT_11 Instruction instruction) {
if (instruction instanceof ReadWriteVariableInstruction &&
((ReadWriteVariableInstruction)instruction).FUNC_9().FUNC_10(myVar)) {
e.set(true);
}
}
@IMPORT_11
@Override
public Data initial() {
return new Data(false);
}
private final CLASS_2 myVar;
}
private static class MySemilattice implements IMPORT_15<Data> {
@IMPORT_11
@Override
public Data join(@IMPORT_11 IMPORT_18<Data> VAR_6) {
if (VAR_6.FUNC_11()) return new Data(false);
boolean b = true;
for (Data data : VAR_6) {
b &= data.FUNC_1().FUNC_6();
}
return new Data(b);
}
@Override
public boolean eq(@IMPORT_11 Data VAR_7, @IMPORT_11 Data e2) {
return VAR_7.FUNC_1().FUNC_6() == e2.FUNC_1().FUNC_6();
}
}
private static class Data extends IMPORT_6<CLASS_1> {
public Data(CLASS_1 VAR_8) {
super(VAR_8);
}
}
}
| 0.521935
|
{'IMPORT_0': 'org', 'IMPORT_1': 'jetbrains', 'IMPORT_2': 'groovy', 'IMPORT_3': 'finalVar', 'IMPORT_4': 'com', 'IMPORT_5': 'openapi', 'IMPORT_6': 'Ref', 'IMPORT_7': 'PsiVariable', 'IMPORT_8': 'containers', 'IMPORT_9': 'ContainerUtil', 'IMPORT_10': 'annotations', 'IMPORT_11': 'NotNull', 'IMPORT_12': 'GroovyPsiElement', 'IMPORT_13': 'dataFlow', 'IMPORT_14': 'DFAEngine', 'IMPORT_15': 'Semilattice', 'IMPORT_16': 'LightCacheKey', 'IMPORT_17': 'java', 'IMPORT_18': 'List', 'IMPORT_19': 'Map', 'CLASS_0': 'VariableInitializationChecker', 'CLASS_1': 'Boolean', 'VAR_0': 'KEY', 'FUNC_0': 'createByFileModificationCount', 'CLASS_2': 'String', 'VAR_1': 'varName', 'VAR_2': 'engine', 'VAR_3': 'result', 'FUNC_1': 'get', 'VAR_4': 'length', 'FUNC_2': 'isVariableDefinitelyInitializedCached', 'VAR_5': 'var', 'FUNC_3': 'getCachedValue', 'FUNC_4': 'newHashMap', 'FUNC_5': 'putCachedValue', 'FUNC_6': 'booleanValue', 'FUNC_7': 'getName', 'FUNC_8': 'fun', 'FUNC_9': 'getVariableName', 'FUNC_10': 'equals', 'VAR_6': 'ins', 'FUNC_11': 'isEmpty', 'VAR_7': 'e1', 'VAR_8': 'value'}
|
java
|
Hibrido
|
100.00%
|
package com.checkoutcrypto.display;
public class TransList {
}
|
package com.checkoutcrypto.display;
public class TransList {
}
| 0.050606
|
{}
|
java
|
OOP
|
100.00%
|
package org.elasticsearch.plugin.head;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.plugin.head.action.ResourceRestAction;
import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
/**
* head插件
* @author yupd
*/
public class HeadPlugin extends Plugin implements ActionPlugin {
@Override
public List<RestHandler> getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings,
IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster) {
List<RestHandler> handlers = new ArrayList<>();
handlers.addAll(Arrays.asList(
new ResourceRestAction()
));
return handlers;
}
}
|
package IMPORT_0.elasticsearch.IMPORT_1.head;
import IMPORT_0.elasticsearch.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_0.elasticsearch.IMPORT_2.IMPORT_5.IMPORT_6;
import IMPORT_0.elasticsearch.IMPORT_7.IMPORT_8.IMPORT_9;
import IMPORT_0.elasticsearch.IMPORT_7.IMPORT_8.IndexScopedSettings;
import IMPORT_0.elasticsearch.IMPORT_7.IMPORT_8.IMPORT_10;
import IMPORT_0.elasticsearch.IMPORT_7.IMPORT_8.IMPORT_11;
import IMPORT_0.elasticsearch.IMPORT_1.head.IMPORT_12.ResourceRestAction;
import IMPORT_0.elasticsearch.plugins.IMPORT_13;
import IMPORT_0.elasticsearch.plugins.IMPORT_14;
import IMPORT_0.elasticsearch.rest.IMPORT_15;
import IMPORT_0.elasticsearch.rest.IMPORT_16;
import IMPORT_17.util.IMPORT_18;
import IMPORT_17.util.IMPORT_19;
import IMPORT_17.util.IMPORT_20;
import IMPORT_17.util.function.Supplier;
/**
* head插件
* @author yupd
*/
public class HeadPlugin extends IMPORT_14 implements IMPORT_13 {
@VAR_0
public IMPORT_20<IMPORT_16> getRestHandlers(IMPORT_10 IMPORT_8, IMPORT_15 VAR_1, IMPORT_9 VAR_2,
IndexScopedSettings VAR_3, IMPORT_11 VAR_4, IMPORT_4 VAR_5,
Supplier<IMPORT_6> nodesInCluster) {
IMPORT_20<IMPORT_16> VAR_6 = new IMPORT_18<>();
VAR_6.FUNC_0(IMPORT_19.FUNC_1(
new ResourceRestAction()
));
return VAR_6;
}
}
| 0.578805
|
{'IMPORT_0': 'org', 'IMPORT_1': 'plugin', 'IMPORT_2': 'cluster', 'IMPORT_3': 'metadata', 'IMPORT_4': 'IndexNameExpressionResolver', 'IMPORT_5': 'node', 'IMPORT_6': 'DiscoveryNodes', 'IMPORT_7': 'common', 'IMPORT_8': 'settings', 'IMPORT_9': 'ClusterSettings', 'IMPORT_10': 'Settings', 'IMPORT_11': 'SettingsFilter', 'IMPORT_12': 'action', 'IMPORT_13': 'ActionPlugin', 'IMPORT_14': 'Plugin', 'IMPORT_15': 'RestController', 'IMPORT_16': 'RestHandler', 'IMPORT_17': 'java', 'IMPORT_18': 'ArrayList', 'IMPORT_19': 'Arrays', 'IMPORT_20': 'List', 'VAR_0': 'Override', 'VAR_1': 'restController', 'VAR_2': 'clusterSettings', 'VAR_3': 'indexScopedSettings', 'VAR_4': 'settingsFilter', 'VAR_5': 'indexNameExpressionResolver', 'VAR_6': 'handlers', 'FUNC_0': 'addAll', 'FUNC_1': 'asList'}
|
java
|
OOP
|
100.00%
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.qpid.server.bytebuffer;
import io.netty.channel.ChannelHandlerContext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
public interface QpidByteBuffer extends AutoCloseable
{
static QpidByteBuffer allocate(boolean direct, int size)
{
return QpidByteBufferFactory.allocate(direct, size);
}
static QpidByteBuffer allocate(int size)
{
return QpidByteBufferFactory.allocate(size);
}
static QpidByteBuffer allocateDirect(int size)
{
return QpidByteBufferFactory.allocateDirect(size);
}
static QpidByteBuffer asQpidByteBuffer(InputStream stream) throws IOException
{
return QpidByteBufferFactory.asQpidByteBuffer(stream);
}
static SSLEngineResult encryptSSL(SSLEngine engine,
Collection<QpidByteBuffer> buffers,
QpidByteBuffer dest) throws SSLException
{
return QpidByteBufferFactory.encryptSSL(engine, buffers, dest);
}
static SSLEngineResult decryptSSL(SSLEngine engine, QpidByteBuffer src, QpidByteBuffer dst) throws SSLException
{
return QpidByteBufferFactory.decryptSSL(engine, src, dst);
}
static QpidByteBuffer inflate(QpidByteBuffer compressedBuffer) throws IOException
{
return QpidByteBufferFactory.inflate(compressedBuffer);
}
static QpidByteBuffer deflate(QpidByteBuffer uncompressedBuffer) throws IOException
{
return QpidByteBufferFactory.deflate(uncompressedBuffer);
}
static long write(GatheringByteChannel channel, Collection<QpidByteBuffer> qpidByteBuffers)
throws IOException
{
return QpidByteBufferFactory.write(channel, qpidByteBuffers);
}
static long write(ChannelHandlerContext channelHandlerContext, Collection<QpidByteBuffer> qpidByteBuffers)
throws IOException {
return QpidByteBufferFactory.write(channelHandlerContext, qpidByteBuffers);
}
static long write(ChannelHandlerContext channelHandlerContext, QpidByteBuffer qpidByteBuffer) throws IOException {
return QpidByteBufferFactory.write(channelHandlerContext, qpidByteBuffer);
}
static QpidByteBuffer wrap(ByteBuffer wrap)
{
return QpidByteBufferFactory.wrap(wrap);
}
static QpidByteBuffer wrap(byte[] data)
{
return QpidByteBufferFactory.wrap(data);
}
static QpidByteBuffer wrap(byte[] data, int offset, int length)
{
return QpidByteBufferFactory.wrap(data, offset, length);
}
static void initialisePool(int bufferSize, int maxPoolSize, double sparsityFraction)
{
QpidByteBufferFactory.initialisePool(bufferSize, maxPoolSize, sparsityFraction);
}
/**
* Test use only
*/
static void deinitialisePool()
{
QpidByteBufferFactory.deinitialisePool();
}
static void returnToPool(ByteBuffer buffer)
{
QpidByteBufferFactory.returnToPool(buffer);
}
static int getPooledBufferSize()
{
return QpidByteBufferFactory.getPooledBufferSize();
}
static long getAllocatedDirectMemorySize()
{
return QpidByteBufferFactory.getAllocatedDirectMemorySize();
}
static int getNumberOfBuffersInUse()
{
return QpidByteBufferFactory.getNumberOfBuffersInUse();
}
static int getNumberOfBuffersInPool()
{
return QpidByteBufferFactory.getNumberOfBuffersInPool();
}
static long getPooledBufferDisposalCounter()
{
return QpidByteBufferFactory.getPooledBufferDisposalCounter();
}
static QpidByteBuffer reallocateIfNecessary(QpidByteBuffer data)
{
return QpidByteBufferFactory.reallocateIfNecessary(data);
}
static QpidByteBuffer concatenate(List<QpidByteBuffer> buffers)
{
return QpidByteBufferFactory.concatenate(buffers);
}
static QpidByteBuffer concatenate(QpidByteBuffer... buffers)
{
return QpidByteBufferFactory.concatenate(buffers);
}
static QpidByteBuffer emptyQpidByteBuffer()
{
return QpidByteBufferFactory.emptyQpidByteBuffer();
}
static ThreadFactory createQpidByteBufferTrackingThreadFactory(ThreadFactory factory)
{
return QpidByteBufferFactory.createQpidByteBufferTrackingThreadFactory(factory);
}
@Override
void close();
QpidByteBuffer put(int index, byte b);
QpidByteBuffer putShort(int index, short value);
QpidByteBuffer putChar(int index, char value);
QpidByteBuffer putInt(int index, int value);
QpidByteBuffer putLong(int index, long value);
QpidByteBuffer putFloat(int index, float value);
QpidByteBuffer putDouble(int index, double value);
QpidByteBuffer put(byte b);
QpidByteBuffer putUnsignedByte(short s);
QpidByteBuffer putShort(short value);
QpidByteBuffer putUnsignedShort(int i);
QpidByteBuffer putChar(char value);
QpidByteBuffer putInt(int value);
QpidByteBuffer putUnsignedInt(long value);
QpidByteBuffer putLong(long value);
QpidByteBuffer putFloat(float value);
QpidByteBuffer putDouble(double value);
QpidByteBuffer put(byte[] src);
QpidByteBuffer put(byte[] src, int offset, int length);
QpidByteBuffer put(ByteBuffer src);
QpidByteBuffer put(QpidByteBuffer src);
byte get(int index);
short getShort(int index);
int getUnsignedShort(int index);
char getChar(int index);
int getInt(int index);
long getLong(int index);
float getFloat(int index);
double getDouble(int index);
byte get();
short getUnsignedByte();
short getShort();
int getUnsignedShort();
char getChar();
int getInt();
long getUnsignedInt();
long getLong();
float getFloat();
double getDouble();
QpidByteBuffer get(byte[] dst);
QpidByteBuffer get(byte[] dst, int offset, int length);
void copyTo(byte[] dst);
void copyTo(ByteBuffer dst);
void putCopyOf(QpidByteBuffer source);
boolean isDirect();
void dispose();
InputStream asInputStream();
long read(ScatteringByteChannel channel) throws IOException;
QpidByteBuffer reset();
QpidByteBuffer rewind();
boolean hasArray();
byte[] array();
QpidByteBuffer clear();
QpidByteBuffer compact();
int position();
QpidByteBuffer position(int newPosition);
int limit();
QpidByteBuffer limit(int newLimit);
QpidByteBuffer mark();
int remaining();
boolean hasRemaining();
boolean hasRemaining(int atLeast);
QpidByteBuffer flip();
int capacity();
QpidByteBuffer duplicate();
QpidByteBuffer slice();
QpidByteBuffer view(int offset, int length);
boolean isSparse();
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.qpid.server.bytebuffer;
import io.netty.IMPORT_0.ChannelHandlerContext;
import IMPORT_1.io.IOException;
import IMPORT_1.io.InputStream;
import IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_1.IMPORT_2.channels.GatheringByteChannel;
import IMPORT_1.IMPORT_2.channels.ScatteringByteChannel;
import IMPORT_1.util.IMPORT_4;
import IMPORT_1.util.List;
import IMPORT_1.util.concurrent.ThreadFactory;
import javax.net.ssl.IMPORT_5;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
public interface QpidByteBuffer extends AutoCloseable
{
static QpidByteBuffer allocate(boolean VAR_0, int size)
{
return QpidByteBufferFactory.allocate(VAR_0, size);
}
static QpidByteBuffer allocate(int size)
{
return QpidByteBufferFactory.allocate(size);
}
static QpidByteBuffer allocateDirect(int size)
{
return QpidByteBufferFactory.allocateDirect(size);
}
static QpidByteBuffer FUNC_0(InputStream stream) throws IOException
{
return QpidByteBufferFactory.FUNC_0(stream);
}
static SSLEngineResult encryptSSL(IMPORT_5 engine,
IMPORT_4<QpidByteBuffer> buffers,
QpidByteBuffer dest) throws SSLException
{
return QpidByteBufferFactory.encryptSSL(engine, buffers, dest);
}
static SSLEngineResult FUNC_1(IMPORT_5 engine, QpidByteBuffer src, QpidByteBuffer dst) throws SSLException
{
return QpidByteBufferFactory.FUNC_1(engine, src, dst);
}
static QpidByteBuffer inflate(QpidByteBuffer compressedBuffer) throws IOException
{
return QpidByteBufferFactory.inflate(compressedBuffer);
}
static QpidByteBuffer deflate(QpidByteBuffer uncompressedBuffer) throws IOException
{
return QpidByteBufferFactory.deflate(uncompressedBuffer);
}
static long FUNC_2(GatheringByteChannel IMPORT_0, IMPORT_4<QpidByteBuffer> qpidByteBuffers)
throws IOException
{
return QpidByteBufferFactory.FUNC_2(IMPORT_0, qpidByteBuffers);
}
static long FUNC_2(ChannelHandlerContext channelHandlerContext, IMPORT_4<QpidByteBuffer> qpidByteBuffers)
throws IOException {
return QpidByteBufferFactory.FUNC_2(channelHandlerContext, qpidByteBuffers);
}
static long FUNC_2(ChannelHandlerContext channelHandlerContext, QpidByteBuffer VAR_1) throws IOException {
return QpidByteBufferFactory.FUNC_2(channelHandlerContext, VAR_1);
}
static QpidByteBuffer FUNC_3(IMPORT_3 VAR_2)
{
return QpidByteBufferFactory.FUNC_3(VAR_2);
}
static QpidByteBuffer FUNC_3(byte[] data)
{
return QpidByteBufferFactory.FUNC_3(data);
}
static QpidByteBuffer FUNC_3(byte[] data, int offset, int length)
{
return QpidByteBufferFactory.FUNC_3(data, offset, length);
}
static void initialisePool(int bufferSize, int maxPoolSize, double VAR_3)
{
QpidByteBufferFactory.initialisePool(bufferSize, maxPoolSize, VAR_3);
}
/**
* Test use only
*/
static void FUNC_4()
{
QpidByteBufferFactory.FUNC_4();
}
static void returnToPool(IMPORT_3 buffer)
{
QpidByteBufferFactory.returnToPool(buffer);
}
static int FUNC_5()
{
return QpidByteBufferFactory.FUNC_5();
}
static long getAllocatedDirectMemorySize()
{
return QpidByteBufferFactory.getAllocatedDirectMemorySize();
}
static int FUNC_6()
{
return QpidByteBufferFactory.FUNC_6();
}
static int FUNC_7()
{
return QpidByteBufferFactory.FUNC_7();
}
static long getPooledBufferDisposalCounter()
{
return QpidByteBufferFactory.getPooledBufferDisposalCounter();
}
static QpidByteBuffer reallocateIfNecessary(QpidByteBuffer data)
{
return QpidByteBufferFactory.reallocateIfNecessary(data);
}
static QpidByteBuffer FUNC_8(List<QpidByteBuffer> buffers)
{
return QpidByteBufferFactory.FUNC_8(buffers);
}
static QpidByteBuffer FUNC_8(QpidByteBuffer... buffers)
{
return QpidByteBufferFactory.FUNC_8(buffers);
}
static QpidByteBuffer emptyQpidByteBuffer()
{
return QpidByteBufferFactory.emptyQpidByteBuffer();
}
static ThreadFactory createQpidByteBufferTrackingThreadFactory(ThreadFactory factory)
{
return QpidByteBufferFactory.createQpidByteBufferTrackingThreadFactory(factory);
}
@VAR_4
void close();
QpidByteBuffer put(int index, byte b);
QpidByteBuffer FUNC_9(int index, short value);
QpidByteBuffer putChar(int index, char value);
QpidByteBuffer putInt(int index, int value);
QpidByteBuffer putLong(int index, long value);
QpidByteBuffer FUNC_10(int index, float value);
QpidByteBuffer putDouble(int index, double value);
QpidByteBuffer put(byte b);
QpidByteBuffer putUnsignedByte(short s);
QpidByteBuffer FUNC_9(short value);
QpidByteBuffer putUnsignedShort(int i);
QpidByteBuffer putChar(char value);
QpidByteBuffer putInt(int value);
QpidByteBuffer putUnsignedInt(long value);
QpidByteBuffer putLong(long value);
QpidByteBuffer FUNC_10(float value);
QpidByteBuffer putDouble(double value);
QpidByteBuffer put(byte[] src);
QpidByteBuffer put(byte[] src, int offset, int length);
QpidByteBuffer put(IMPORT_3 src);
QpidByteBuffer put(QpidByteBuffer src);
byte get(int index);
short getShort(int index);
int FUNC_11(int index);
char getChar(int index);
int getInt(int index);
long getLong(int index);
float getFloat(int index);
double getDouble(int index);
byte get();
short getUnsignedByte();
short getShort();
int FUNC_11();
char getChar();
int getInt();
long getUnsignedInt();
long getLong();
float getFloat();
double getDouble();
QpidByteBuffer get(byte[] dst);
QpidByteBuffer get(byte[] dst, int offset, int length);
void copyTo(byte[] dst);
void copyTo(IMPORT_3 dst);
void putCopyOf(QpidByteBuffer VAR_5);
boolean isDirect();
void dispose();
InputStream asInputStream();
long read(ScatteringByteChannel IMPORT_0) throws IOException;
QpidByteBuffer reset();
QpidByteBuffer rewind();
boolean hasArray();
byte[] array();
QpidByteBuffer clear();
QpidByteBuffer compact();
int FUNC_12();
QpidByteBuffer FUNC_12(int newPosition);
int FUNC_13();
QpidByteBuffer FUNC_13(int newLimit);
QpidByteBuffer FUNC_14();
int remaining();
boolean hasRemaining();
boolean hasRemaining(int atLeast);
QpidByteBuffer FUNC_15();
int capacity();
QpidByteBuffer duplicate();
QpidByteBuffer slice();
QpidByteBuffer view(int offset, int length);
boolean isSparse();
}
| 0.155379
|
{'IMPORT_0': 'channel', 'IMPORT_1': 'java', 'IMPORT_2': 'nio', 'IMPORT_3': 'ByteBuffer', 'IMPORT_4': 'Collection', 'IMPORT_5': 'SSLEngine', 'VAR_0': 'direct', 'FUNC_0': 'asQpidByteBuffer', 'FUNC_1': 'decryptSSL', 'FUNC_2': 'write', 'VAR_1': 'qpidByteBuffer', 'FUNC_3': 'wrap', 'VAR_2': 'wrap', 'VAR_3': 'sparsityFraction', 'FUNC_4': 'deinitialisePool', 'FUNC_5': 'getPooledBufferSize', 'FUNC_6': 'getNumberOfBuffersInUse', 'FUNC_7': 'getNumberOfBuffersInPool', 'FUNC_8': 'concatenate', 'VAR_4': 'Override', 'FUNC_9': 'putShort', 'FUNC_10': 'putFloat', 'FUNC_11': 'getUnsignedShort', 'VAR_5': 'source', 'FUNC_12': 'position', 'FUNC_13': 'limit', 'FUNC_14': 'mark', 'FUNC_15': 'flip'}
|
java
|
Procedural
|
15.26%
|
/*******************************************************************************
* Copyright 2012,2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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.dkpro.bigdata.io.hadoop;
import static org.apache.uima.fit.factory.TypeSystemDescriptionFactory.createTypeSystemDescription;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.uima.cas.CAS;
import org.apache.uima.util.CasCreationUtils;
import org.dkpro.bigdata.io.hadoop.CASWritable;
import org.junit.Test;
public class CASWritableTest
{
private static final String testString = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.";
protected Class<? extends CASWritable> writable = CASWritable.class;
@Test
public void testCASWritable()
throws InstantiationException, IllegalAccessException
{
CASWritable casWritable = writable.newInstance();
assertNotNull(casWritable.getCAS());
}
@Test
public void testReadWriteFields()
{
try {
CAS cas = CasCreationUtils.createCas(createTypeSystemDescription(), null, null);
cas.setDocumentText(testString);
CASWritable casWritable = writable.newInstance();
casWritable.setCAS(cas);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
casWritable.write(oos);
oos.close();
casWritable = writable.newInstance();
ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
casWritable.readFields(ois);
assertEquals(casWritable.getCAS().getDocumentText(), testString);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
|
/*******************************************************************************
* Copyright 2012,2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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.IMPORT_0.bigdata.io.hadoop;
import static org.apache.uima.fit.factory.TypeSystemDescriptionFactory.createTypeSystemDescription;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IMPORT_1;
import java.io.ObjectOutputStream;
import org.apache.uima.cas.CAS;
import org.apache.uima.util.CasCreationUtils;
import org.IMPORT_0.bigdata.io.hadoop.CASWritable;
import org.junit.Test;
public class CASWritableTest
{
private static final String testString = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.";
protected Class<? extends CASWritable> writable = CASWritable.class;
@Test
public void testCASWritable()
throws InstantiationException, IllegalAccessException
{
CASWritable casWritable = writable.FUNC_0();
assertNotNull(casWritable.getCAS());
}
@Test
public void testReadWriteFields()
{
try {
CAS cas = CasCreationUtils.createCas(createTypeSystemDescription(), null, null);
cas.setDocumentText(testString);
CASWritable casWritable = writable.FUNC_0();
casWritable.setCAS(cas);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
casWritable.write(oos);
oos.close();
casWritable = writable.FUNC_0();
ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray());
IMPORT_1 ois = new IMPORT_1(bis);
casWritable.readFields(ois);
assertEquals(casWritable.getCAS().getDocumentText(), testString);
}
catch (Exception e) {
e.FUNC_1();
fail(e.getMessage());
}
}
}
| 0.122509
|
{'IMPORT_0': 'dkpro', 'IMPORT_1': 'ObjectInputStream', 'FUNC_0': 'newInstance', 'FUNC_1': 'printStackTrace'}
|
java
|
Hibrido
|
100.00%
|
package com.baoyongan.java.eg.base.class_ch.enums;
public enum MyEnum {
ZERO(1),
FIRST(2);
private int code;
MyEnum(int i) {
this.code=i;
}
public void loop(){
System.out.println(this.ordinal());
}
public static void main(String[] args) {
MyEnum.ZERO.loop();
MyEnum.FIRST.loop();
}
}
|
package IMPORT_0.IMPORT_1.java.eg.base.IMPORT_2.enums;
public enum MyEnum {
VAR_0(1),
VAR_1(2);
private int VAR_2;
MyEnum(int i) {
this.VAR_2=i;
}
public void FUNC_0(){
System.VAR_3.FUNC_1(this.ordinal());
}
public static void FUNC_2(CLASS_0[] VAR_4) {
MyEnum.VAR_0.FUNC_0();
MyEnum.VAR_1.FUNC_0();
}
}
| 0.53396
|
{'IMPORT_0': 'com', 'IMPORT_1': 'baoyongan', 'IMPORT_2': 'class_ch', 'VAR_0': 'ZERO', 'VAR_1': 'FIRST', 'VAR_2': 'code', 'FUNC_0': 'loop', 'VAR_3': 'out', 'FUNC_1': 'println', 'FUNC_2': 'main', 'CLASS_0': 'String', 'VAR_4': 'args'}
|
java
|
Texto
|
17.65%
|
package com.refinitiv.eta.json.converter;
import com.refinitiv.eta.codec.DataDictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
class JsonConverterBuilderImpl implements JsonConverterBuilder {
private Map<Integer, Object> propertiesMap = new HashMap<>();
private ServiceNameIdConverter serviceNameIdConverter;
private DataDictionary dataDictionary;
@Override
public JsonConverterBuilder setProperties(Map<Integer, Object> properties) {
propertiesMap.putAll(properties);
return this;
}
@Override
public JsonConverterBuilder setProperty(int propertyId, boolean enabled) {
propertiesMap.put(propertyId, enabled);
return this;
}
@Override
public JsonConverterBuilder setProperty(int propertyId, int intValue) {
propertiesMap.put(propertyId, intValue);
return this;
}
@Override
public JsonConverterBuilder setServiceConverter(ServiceNameIdConverter serviceNameIdConverter) {
this.serviceNameIdConverter = serviceNameIdConverter;
return this;
}
@Override
public JsonConverterBuilder setDictionary(DataDictionary dataDictionary) {
this.dataDictionary = dataDictionary;
return this;
}
@Override
public JsonConverter build(JsonConverterError error) {
switch (getProtocolVer()) {
case JsonProtocol.JSON_JPT_JSON2:
return createJsonConverter(error);
default:
error.setError(JsonConverterErrorCodes.JSON_ERROR_UNSUPPORTED_PROTOCOL, String.valueOf(getProtocolVer()));
return null;
}
}
@Override
public void clear() {
propertiesMap.clear();
serviceNameIdConverter = null;
if (Objects.nonNull(dataDictionary)) {
dataDictionary = null;
}
}
private int getProtocolVer() {
if (!propertiesMap.containsKey(JsonConverterProperties.JSON_CPC_PROTOCOL_VERSION))
propertiesMap.put(JsonConverterProperties.JSON_CPC_PROTOCOL_VERSION, JsonProtocol.JSON_JPT_JSON2);
return (int) propertiesMap.get(JsonConverterProperties.JSON_CPC_PROTOCOL_VERSION);
}
private JsonConverter createJsonConverter(JsonConverterError error) {
JsonConverterBaseImpl result = new JsonConverterBaseImpl();
for (Map.Entry<Integer, Object> entry : propertiesMap.entrySet()) {
Integer propertyId = entry.getKey();
switch (propertyId) {
case JsonConverterProperties.JSON_CPC_CATCH_UNKNOWN_JSON_KEYS:
if (checkBoolean(entry, error)) {
result.catchUnexpectedKeys((Boolean) entry.getValue());
} else {
return null;
}
break;
case JsonConverterProperties.JSON_CPC_CATCH_UNKNOWN_JSON_FIDS:
if (checkBoolean(entry, error)) {
result.catchUnexpectedFids((Boolean) entry.getValue());
} else {
return null;
}
break;
case JsonConverterProperties.JSON_CPC_ALLOW_ENUM_DISPLAY_STRINGS:
if (checkBoolean(entry, error)) {
result.allowEnumDisplayStrings((Boolean) entry.getValue());
} else {
return null;
}
break;
case JsonConverterProperties.JSON_CPC_USE_DEFAULT_DYNAMIC_QOS:
if (checkBoolean(entry, error)) {
result.useDefaultDynamicQoS((Boolean) entry.getValue());
} else {
return null;
}
break;
case JsonConverterProperties.JSON_CPC_EXPAND_ENUM_FIELDS:
if (checkBoolean(entry, error)) {
result.expandEnumFields((Boolean) entry.getValue());
} else {
return null;
}
break;
case JsonConverterProperties.JSON_CPC_DEFAULT_SERVICE_ID:
if (checkInteger(entry, error)) {
result.setDefaultServiceId((Integer) entry.getValue());
result.setHasDefaultServiceId(true);
} else {
return null;
}
break;
case JsonConverterProperties.JSON_CPC_PROTOCOL_VERSION:
break;
default:
error.setError(JsonConverterErrorCodes.JSON_ERROR_UNKNOWN_PROPERTY, entry.toString() + " properties: " + propertiesMap.toString());
}
}
result.setDictionary(dataDictionary);
result.setServiceNameIdConverter(serviceNameIdConverter);
return result;
}
private boolean checkBoolean(Map.Entry<Integer, Object> entry, JsonConverterError error) {
if (!(entry.getValue() instanceof Boolean)) {
error.setError(JsonConverterErrorCodes.JSON_ERROR_UNKNOWN_PROPERTY, entry.getKey() + " expected boolean");
return false;
}
return true;
}
private boolean checkInteger(Map.Entry<Integer, Object> entry, JsonConverterError error) {
if (!(entry.getValue() instanceof Integer)) {
error.setError(JsonConverterErrorCodes.JSON_ERROR_UNKNOWN_PROPERTY, entry.getKey() + " expected integer");
return false;
}
return true;
}
}
|
package IMPORT_0.refinitiv.IMPORT_1.IMPORT_2.IMPORT_3;
import IMPORT_0.refinitiv.IMPORT_1.codec.DataDictionary;
import IMPORT_4.IMPORT_5.IMPORT_6;
import IMPORT_4.IMPORT_5.IMPORT_7;
import IMPORT_4.IMPORT_5.Objects;
class JsonConverterBuilderImpl implements CLASS_0 {
private IMPORT_7<Integer, CLASS_1> VAR_0 = new IMPORT_6<>();
private CLASS_2 VAR_1;
private DataDictionary dataDictionary;
@VAR_2
public CLASS_0 setProperties(IMPORT_7<Integer, CLASS_1> VAR_3) {
VAR_0.putAll(VAR_3);
return this;
}
@VAR_2
public CLASS_0 FUNC_0(int VAR_4, boolean VAR_5) {
VAR_0.FUNC_1(VAR_4, VAR_5);
return this;
}
@VAR_2
public CLASS_0 FUNC_0(int VAR_4, int VAR_6) {
VAR_0.FUNC_1(VAR_4, VAR_6);
return this;
}
@VAR_2
public CLASS_0 FUNC_2(CLASS_2 VAR_1) {
this.VAR_1 = VAR_1;
return this;
}
@VAR_2
public CLASS_0 setDictionary(DataDictionary dataDictionary) {
this.dataDictionary = dataDictionary;
return this;
}
@VAR_2
public CLASS_3 FUNC_3(CLASS_4 VAR_7) {
switch (getProtocolVer()) {
case VAR_8.VAR_9:
return FUNC_4(VAR_7);
default:
VAR_7.FUNC_5(VAR_10.VAR_11, VAR_12.valueOf(getProtocolVer()));
return null;
}
}
@VAR_2
public void FUNC_6() {
VAR_0.FUNC_6();
VAR_1 = null;
if (Objects.FUNC_7(dataDictionary)) {
dataDictionary = null;
}
}
private int getProtocolVer() {
if (!VAR_0.FUNC_8(VAR_13.JSON_CPC_PROTOCOL_VERSION))
VAR_0.FUNC_1(VAR_13.JSON_CPC_PROTOCOL_VERSION, VAR_8.VAR_9);
return (int) VAR_0.get(VAR_13.JSON_CPC_PROTOCOL_VERSION);
}
private CLASS_3 FUNC_4(CLASS_4 VAR_7) {
CLASS_5 result = new CLASS_5();
for (IMPORT_7.Entry<Integer, CLASS_1> VAR_14 : VAR_0.FUNC_9()) {
Integer VAR_4 = VAR_14.getKey();
switch (VAR_4) {
case VAR_13.VAR_15:
if (FUNC_10(VAR_14, VAR_7)) {
result.catchUnexpectedKeys((CLASS_6) VAR_14.FUNC_11());
} else {
return null;
}
break;
case VAR_13.VAR_16:
if (FUNC_10(VAR_14, VAR_7)) {
result.FUNC_12((CLASS_6) VAR_14.FUNC_11());
} else {
return null;
}
break;
case VAR_13.JSON_CPC_ALLOW_ENUM_DISPLAY_STRINGS:
if (FUNC_10(VAR_14, VAR_7)) {
result.FUNC_13((CLASS_6) VAR_14.FUNC_11());
} else {
return null;
}
break;
case VAR_13.JSON_CPC_USE_DEFAULT_DYNAMIC_QOS:
if (FUNC_10(VAR_14, VAR_7)) {
result.FUNC_14((CLASS_6) VAR_14.FUNC_11());
} else {
return null;
}
break;
case VAR_13.JSON_CPC_EXPAND_ENUM_FIELDS:
if (FUNC_10(VAR_14, VAR_7)) {
result.FUNC_15((CLASS_6) VAR_14.FUNC_11());
} else {
return null;
}
break;
case VAR_13.VAR_17:
if (checkInteger(VAR_14, VAR_7)) {
result.setDefaultServiceId((Integer) VAR_14.FUNC_11());
result.setHasDefaultServiceId(true);
} else {
return null;
}
break;
case VAR_13.JSON_CPC_PROTOCOL_VERSION:
break;
default:
VAR_7.FUNC_5(VAR_10.VAR_18, VAR_14.FUNC_16() + " properties: " + VAR_0.FUNC_16());
}
}
result.setDictionary(dataDictionary);
result.setServiceNameIdConverter(VAR_1);
return result;
}
private boolean FUNC_10(IMPORT_7.Entry<Integer, CLASS_1> VAR_14, CLASS_4 VAR_7) {
if (!(VAR_14.FUNC_11() instanceof CLASS_6)) {
VAR_7.FUNC_5(VAR_10.VAR_18, VAR_14.getKey() + " expected boolean");
return false;
}
return true;
}
private boolean checkInteger(IMPORT_7.Entry<Integer, CLASS_1> VAR_14, CLASS_4 VAR_7) {
if (!(VAR_14.FUNC_11() instanceof Integer)) {
VAR_7.FUNC_5(VAR_10.VAR_18, VAR_14.getKey() + " expected integer");
return false;
}
return true;
}
}
| 0.624492
|
{'IMPORT_0': 'com', 'IMPORT_1': 'eta', 'IMPORT_2': 'json', 'IMPORT_3': 'converter', 'IMPORT_4': 'java', 'IMPORT_5': 'util', 'IMPORT_6': 'HashMap', 'IMPORT_7': 'Map', 'CLASS_0': 'JsonConverterBuilder', 'CLASS_1': 'Object', 'VAR_0': 'propertiesMap', 'CLASS_2': 'ServiceNameIdConverter', 'VAR_1': 'serviceNameIdConverter', 'VAR_2': 'Override', 'VAR_3': 'properties', 'FUNC_0': 'setProperty', 'VAR_4': 'propertyId', 'VAR_5': 'enabled', 'FUNC_1': 'put', 'VAR_6': 'intValue', 'FUNC_2': 'setServiceConverter', 'CLASS_3': 'JsonConverter', 'FUNC_3': 'build', 'CLASS_4': 'JsonConverterError', 'VAR_7': 'error', 'VAR_8': 'JsonProtocol', 'VAR_9': 'JSON_JPT_JSON2', 'FUNC_4': 'createJsonConverter', 'FUNC_5': 'setError', 'VAR_10': 'JsonConverterErrorCodes', 'VAR_11': 'JSON_ERROR_UNSUPPORTED_PROTOCOL', 'VAR_12': 'String', 'FUNC_6': 'clear', 'FUNC_7': 'nonNull', 'FUNC_8': 'containsKey', 'VAR_13': 'JsonConverterProperties', 'CLASS_5': 'JsonConverterBaseImpl', 'VAR_14': 'entry', 'FUNC_9': 'entrySet', 'VAR_15': 'JSON_CPC_CATCH_UNKNOWN_JSON_KEYS', 'FUNC_10': 'checkBoolean', 'CLASS_6': 'Boolean', 'FUNC_11': 'getValue', 'VAR_16': 'JSON_CPC_CATCH_UNKNOWN_JSON_FIDS', 'FUNC_12': 'catchUnexpectedFids', 'FUNC_13': 'allowEnumDisplayStrings', 'FUNC_14': 'useDefaultDynamicQoS', 'FUNC_15': 'expandEnumFields', 'VAR_17': 'JSON_CPC_DEFAULT_SERVICE_ID', 'VAR_18': 'JSON_ERROR_UNKNOWN_PROPERTY', 'FUNC_16': 'toString'}
|
java
|
OOP
|
100.00%
|
/**
* for user setting audio prescale
*
* @param sourceId
* @return
*/
public int queryAudioPrescale()
{
String audioPrescale = new String("0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,");
int value = 0;
Cursor cursor = getContentResolver().query(Uri.parse("content://mstar.tv.usersetting/soundsetting"),
null, null, null, null);
if (cursor.moveToFirst())
{
audioPrescale = cursor.getString(cursor.getColumnIndex("SpeakerPreScale"));
String[] array = audioPrescale.split(",");
int iSource = queryCurInputSrc();
String str = array[iSource];
String substr = str.substring(0);
int prevalue = 0;
if (substr.contains("0x"))
{
substr = substr.substring(2);
prevalue = Integer.parseInt(substr, 16);
}
else
prevalue = Integer.parseInt(substr, 10);
value = prevalue/10*16+prevalue%10;
}
cursor.close();
return value;
}
|
/**
* for user setting audio prescale
*
* @param sourceId
* @return
*/
public int FUNC_0()
{
String audioPrescale = new String("0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,");
int VAR_0 = 0;
Cursor VAR_1 = FUNC_1().query(VAR_2.FUNC_2("content://mstar.tv.usersetting/soundsetting"),
null, null, null, null);
if (VAR_1.FUNC_3())
{
audioPrescale = VAR_1.getString(VAR_1.getColumnIndex("SpeakerPreScale"));
String[] VAR_3 = audioPrescale.FUNC_4(",");
int iSource = queryCurInputSrc();
String str = VAR_3[iSource];
String substr = str.FUNC_5(0);
int prevalue = 0;
if (substr.contains("0x"))
{
substr = substr.FUNC_5(2);
prevalue = VAR_4.FUNC_6(substr, 16);
}
else
prevalue = VAR_4.FUNC_6(substr, 10);
VAR_0 = prevalue/10*16+prevalue%10;
}
VAR_1.close();
return VAR_0;
}
| 0.713224
|
{'FUNC_0': 'queryAudioPrescale', 'VAR_0': 'value', 'VAR_1': 'cursor', 'FUNC_1': 'getContentResolver', 'VAR_2': 'Uri', 'FUNC_2': 'parse', 'FUNC_3': 'moveToFirst', 'VAR_3': 'array', 'FUNC_4': 'split', 'FUNC_5': 'substring', 'VAR_4': 'Integer', 'FUNC_6': 'parseInt'}
|
java
|
Procedural
|
100.00%
|
/**
* A utility class to help with building ExerciseList objects.
* Example usage: <br>
* {@code ExerciseList exerciseList =
* new ExerciseListBuilder().withExercise(new Exercise(...)).build();}
*/
public class ExerciseListBuilder {
private ExerciseList exerciseList;
public ExerciseListBuilder() {
exerciseList = new ExerciseList();
}
public ExerciseListBuilder(ExerciseList exerciseList) {
this.exerciseList = exerciseList;
}
/**
* Adds a new {@code Exercise} to the {@code ExerciseList} that we are building.
*/
public ExerciseListBuilder withExercise(Exercise exercise) {
exerciseList.addExercise(exercise);
return this;
}
public ExerciseList build() {
return exerciseList;
}
}
|
/**
* A utility class to help with building ExerciseList objects.
* Example usage: <br>
* {@code ExerciseList exerciseList =
* new ExerciseListBuilder().withExercise(new Exercise(...)).build();}
*/
public class CLASS_0 {
private CLASS_1 VAR_0;
public CLASS_0() {
VAR_0 = new CLASS_1();
}
public CLASS_0(CLASS_1 VAR_0) {
this.VAR_0 = VAR_0;
}
/**
* Adds a new {@code Exercise} to the {@code ExerciseList} that we are building.
*/
public CLASS_0 FUNC_0(CLASS_2 VAR_1) {
VAR_0.FUNC_1(VAR_1);
return this;
}
public CLASS_1 FUNC_2() {
return VAR_0;
}
}
| 0.915435
|
{'CLASS_0': 'ExerciseListBuilder', 'CLASS_1': 'ExerciseList', 'VAR_0': 'exerciseList', 'FUNC_0': 'withExercise', 'CLASS_2': 'Exercise', 'VAR_1': 'exercise', 'FUNC_1': 'addExercise', 'FUNC_2': 'build'}
|
java
|
OOP
|
100.00%
|
/*
* Copyright 2020 <NAME>
*
* 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.kovacs;
import com.ibm.icu.text.Normalizer2;
import com.ibm.icu.text.SpoofChecker;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.kovacs.commandclient.CustomClientBuilder;
import com.kovacs.commands.generic.*;
import com.jagrosh.jdautilities.command.CommandClient;
import com.kovacs.commands.config.*;
import com.kovacs.commands.moderation.*;
import com.kovacs.commands.notes.CheckNotes;
import com.kovacs.commands.owner.ReloadConfig;
import com.kovacs.commands.owner.Shutdown;
import com.kovacs.commands.owner.Test;
import com.kovacs.commands.toolbox.GenerateInvite;
import com.kovacs.database.GuildConfigManager;
import com.kovacs.listeners.*;
import com.kovacs.tools.BotConfig;
import com.kovacs.tools.Unicode;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginException;
import java.io.*;
import java.util.Collection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import static net.dv8tion.jda.api.entities.Activity.*;
public class Kovacs {
final static Logger logger = LoggerFactory.getLogger(Kovacs.class);
public static JSONObject config;
public static JDA bot;
public static EventWaiter waiter;
private static ScheduledExecutorService eventWaiterScheduler = Executors.newScheduledThreadPool(1);
public static CommandClient commandClient;
public static String[] autoMod = new String[]{"bos", "mos", "dos", "dehoist",
"normalize", "janitor", "invites", "duplicates"};
//todo migrate to non-deprecated mongo functions
public static void main(String[] args) throws LoginException, IOException {
config = BotConfig.open();
waiter = new EventWaiter(eventWaiterScheduler, false);
SpoofChecker checker = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build();
Unicode.setNormalizer(Normalizer2.getNFKCInstance());
Unicode.setSpoofChecker(checker);
commandClient = getCommandClient();
bot = new JDABuilder(AccountType.BOT)
.addEventListeners(commandClient, new EventListener(), new GuildEventListener(), new MessageEventListener(), new NameEventListener(), waiter)
.setToken(config.getString("token"))
.setGuildSubscriptionsEnabled(true)
.build();
}
public static CommandClient getCommandClient(){
Command[] configCommands = new Command[]{new AddBOS(), new AddDOS(), new AddMOS(), new Sudo(),
new RemoveBOS(), new Blacklist(), new WhitelistChannels(), new BlacklistChannels(), new AutoMod(), new SetAuditChannel(),
new RemoveSudo(), new SetMutedRole(), new ShowConfig(), new Whitelist(), new Sync(),
new Automod(), new SetDuplicateThreshold(), new RemoveDOS(), new RemoveMOS(), new Prefix(),
new WhitelistInvites(), new BlackistInvites(), new SetFallbackName(), new SetInviteName()};
Command[] moderation = new Command[]{new Ban(), new Mute(), new Unban(), new UnMute(), new Prune(),
new ManageNicks()};
Command[] generic = new Command[]{new Ping(), new Normalize(), new Help(), new BotInfo(), new UserInfo()};
Command[] owner = new Command[]{new Shutdown(), new ReloadConfig(), new Test()};
Command[] notes = new Command[]{new CheckNotes()};
Command[] toolbox = new Command[]{new GenerateInvite()};
return new CustomClientBuilder()
.setOwnerId(config.getString("botOwner"))
.setCoOwnerIds(config.getJSONArray("coOwners").toList().toArray(new String[]{}))
.setAlternativePrefix("@mention")
.addCommands(configCommands)
.setGuildSettingsManager(new GuildConfigManager())
.addCommands(moderation)
.addCommands(generic)
.addCommands(owner)
.addCommands(notes)
.addCommands(toolbox)
.setActivity(Activity.of(ActivityType.valueOf(ActivityType.class, config.getString("activityType")),
config.getString("activityMessage")))
.useHelpBuilder(false)
.build();
}
public static void addIfMissing(Collection<String> target, Collection<String> toAdd){
toAdd.stream().distinct().forEach(string -> {
if(!target.contains(string)){
target.add(string);
}
});
}
}
|
/*
* Copyright 2020 <NAME>
*
* 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.kovacs;
import com.ibm.icu.text.Normalizer2;
import com.ibm.icu.text.SpoofChecker;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.kovacs.commandclient.CustomClientBuilder;
import com.kovacs.commands.generic.*;
import com.jagrosh.jdautilities.command.CommandClient;
import com.kovacs.commands.config.*;
import com.kovacs.commands.moderation.*;
import com.kovacs.commands.notes.CheckNotes;
import com.kovacs.commands.owner.ReloadConfig;
import com.kovacs.commands.owner.Shutdown;
import com.kovacs.commands.owner.Test;
import com.kovacs.commands.toolbox.GenerateInvite;
import com.kovacs.database.GuildConfigManager;
import com.kovacs.listeners.*;
import com.kovacs.tools.BotConfig;
import com.kovacs.tools.Unicode;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import org.json.JSONObject;
import org.IMPORT_0.Logger;
import org.IMPORT_0.LoggerFactory;
import javax.security.auth.login.LoginException;
import java.io.*;
import java.util.Collection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import static net.dv8tion.jda.api.entities.Activity.*;
public class Kovacs {
final static Logger VAR_0 = LoggerFactory.getLogger(Kovacs.class);
public static JSONObject config;
public static JDA bot;
public static EventWaiter waiter;
private static ScheduledExecutorService eventWaiterScheduler = Executors.newScheduledThreadPool(1);
public static CommandClient commandClient;
public static String[] autoMod = new String[]{"bos", "mos", "dos", "dehoist",
"normalize", "janitor", "invites", "duplicates"};
//todo migrate to non-deprecated mongo functions
public static void main(String[] args) throws LoginException, IOException {
config = BotConfig.open();
waiter = new EventWaiter(eventWaiterScheduler, false);
SpoofChecker checker = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build();
Unicode.setNormalizer(Normalizer2.getNFKCInstance());
Unicode.setSpoofChecker(checker);
commandClient = getCommandClient();
bot = new JDABuilder(AccountType.BOT)
.addEventListeners(commandClient, new EventListener(), new GuildEventListener(), new MessageEventListener(), new NameEventListener(), waiter)
.setToken(config.getString("token"))
.setGuildSubscriptionsEnabled(true)
.build();
}
public static CommandClient getCommandClient(){
Command[] configCommands = new Command[]{new AddBOS(), new AddDOS(), new AddMOS(), new Sudo(),
new RemoveBOS(), new Blacklist(), new WhitelistChannels(), new BlacklistChannels(), new AutoMod(), new SetAuditChannel(),
new RemoveSudo(), new SetMutedRole(), new ShowConfig(), new Whitelist(), new Sync(),
new Automod(), new SetDuplicateThreshold(), new RemoveDOS(), new RemoveMOS(), new Prefix(),
new WhitelistInvites(), new BlackistInvites(), new SetFallbackName(), new SetInviteName()};
Command[] moderation = new Command[]{new Ban(), new Mute(), new Unban(), new UnMute(), new Prune(),
new ManageNicks()};
Command[] generic = new Command[]{new Ping(), new Normalize(), new CLASS_0(), new BotInfo(), new UserInfo()};
Command[] owner = new Command[]{new Shutdown(), new ReloadConfig(), new Test()};
Command[] notes = new Command[]{new CheckNotes()};
Command[] toolbox = new Command[]{new GenerateInvite()};
return new CustomClientBuilder()
.setOwnerId(config.getString("botOwner"))
.setCoOwnerIds(config.getJSONArray("coOwners").toList().toArray(new String[]{}))
.setAlternativePrefix("@mention")
.addCommands(configCommands)
.setGuildSettingsManager(new GuildConfigManager())
.addCommands(moderation)
.addCommands(generic)
.addCommands(owner)
.addCommands(notes)
.addCommands(toolbox)
.setActivity(Activity.of(ActivityType.valueOf(ActivityType.class, config.getString("activityType")),
config.getString("activityMessage")))
.useHelpBuilder(false)
.build();
}
public static void addIfMissing(Collection<String> target, Collection<String> toAdd){
toAdd.stream().distinct().forEach(string -> {
if(!target.contains(string)){
target.add(string);
}
});
}
}
| 0.033545
|
{'IMPORT_0': 'slf4j', 'VAR_0': 'logger', 'CLASS_0': 'Help'}
|
java
|
Hibrido
|
41.52%
|
/**
* Evaluation context allows us to define how pipeline instructions.
*/
public class EvaluationContext implements EvaluationResult {
private final JavaSparkContext jsc;
private final Pipeline pipeline;
private final SparkRuntimeContext runtime;
private final Map<PValue, RDDHolder<?>> pcollections = new LinkedHashMap<>();
private final Set<RDDHolder<?>> leafRdds = new LinkedHashSet<>();
private final Set<PValue> multireads = new LinkedHashSet<>();
private final Map<PValue, Object> pobjects = new LinkedHashMap<>();
private final Map<PValue, Iterable<? extends WindowedValue<?>>> pview = new LinkedHashMap<>();
protected AppliedPTransform<?, ?, ?> currentTransform;
public EvaluationContext(JavaSparkContext jsc, Pipeline pipeline) {
this.jsc = jsc;
this.pipeline = pipeline;
this.runtime = new SparkRuntimeContext(jsc, pipeline);
}
/**
* Holds an RDD or values for deferred conversion to an RDD if needed. PCollections are
* sometimes created from a collection of objects (using RDD parallelize) and then
* only used to create View objects; in which case they do not need to be
* converted to bytes since they are not transferred across the network until they are
* broadcast.
*/
private class RDDHolder<T> {
private Iterable<WindowedValue<T>> windowedValues;
private Coder<T> coder;
private JavaRDDLike<WindowedValue<T>, ?> rdd;
RDDHolder(Iterable<T> values, Coder<T> coder) {
this.windowedValues =
Iterables.transform(values, WindowingHelpers.<T>windowValueFunction());
this.coder = coder;
}
RDDHolder(JavaRDDLike<WindowedValue<T>, ?> rdd) {
this.rdd = rdd;
}
JavaRDDLike<WindowedValue<T>, ?> getRDD() {
if (rdd == null) {
WindowedValue.ValueOnlyWindowedValueCoder<T> windowCoder =
WindowedValue.getValueOnlyCoder(coder);
rdd = jsc.parallelize(CoderHelpers.toByteArrays(windowedValues, windowCoder))
.map(CoderHelpers.fromByteFunction(windowCoder));
}
return rdd;
}
Iterable<WindowedValue<T>> getValues(PCollection<T> pcollection) {
if (windowedValues == null) {
WindowFn<?, ?> windowFn =
pcollection.getWindowingStrategy().getWindowFn();
Coder<? extends BoundedWindow> windowCoder = windowFn.windowCoder();
final WindowedValue.WindowedValueCoder<T> windowedValueCoder;
if (windowFn instanceof GlobalWindows) {
windowedValueCoder =
WindowedValue.ValueOnlyWindowedValueCoder.of(pcollection.getCoder());
} else {
windowedValueCoder =
WindowedValue.FullWindowedValueCoder.of(pcollection.getCoder(), windowCoder);
}
JavaRDDLike<byte[], ?> bytesRDD =
rdd.map(CoderHelpers.toByteFunction(windowedValueCoder));
List<byte[]> clientBytes = bytesRDD.collect();
windowedValues = Iterables.transform(clientBytes,
new Function<byte[], WindowedValue<T>>() {
@Override
public WindowedValue<T> apply(byte[] bytes) {
return CoderHelpers.fromByteArray(bytes, windowedValueCoder);
}
});
}
return windowedValues;
}
}
protected JavaSparkContext getSparkContext() {
return jsc;
}
protected Pipeline getPipeline() {
return pipeline;
}
protected SparkRuntimeContext getRuntimeContext() {
return runtime;
}
protected void setCurrentTransform(AppliedPTransform<?, ?, ?> transform) {
this.currentTransform = transform;
}
protected AppliedPTransform<?, ?, ?> getCurrentTransform() {
return currentTransform;
}
protected <T extends PInput> T getInput(PTransform<T, ?> transform) {
checkArgument(currentTransform != null && currentTransform.getTransform() == transform,
"can only be called with current transform");
@SuppressWarnings("unchecked")
T input = (T) currentTransform.getInput();
return input;
}
protected <T extends POutput> T getOutput(PTransform<?, T> transform) {
checkArgument(currentTransform != null && currentTransform.getTransform() == transform,
"can only be called with current transform");
@SuppressWarnings("unchecked")
T output = (T) currentTransform.getOutput();
return output;
}
protected <T> void setOutputRDD(PTransform<?, ?> transform,
JavaRDDLike<WindowedValue<T>, ?> rdd) {
setRDD((PValue) getOutput(transform), rdd);
}
protected <T> void setOutputRDDFromValues(PTransform<?, ?> transform, Iterable<T> values,
Coder<T> coder) {
pcollections.put((PValue) getOutput(transform), new RDDHolder<>(values, coder));
}
void setPView(PValue view, Iterable<? extends WindowedValue<?>> value) {
pview.put(view, value);
}
protected boolean hasOutputRDD(PTransform<? extends PInput, ?> transform) {
PValue pvalue = (PValue) getOutput(transform);
return pcollections.containsKey(pvalue);
}
protected JavaRDDLike<?, ?> getRDD(PValue pvalue) {
RDDHolder<?> rddHolder = pcollections.get(pvalue);
JavaRDDLike<?, ?> rdd = rddHolder.getRDD();
leafRdds.remove(rddHolder);
if (multireads.contains(pvalue)) {
// Ensure the RDD is marked as cached
rdd.rdd().cache();
} else {
multireads.add(pvalue);
}
return rdd;
}
protected <T> void setRDD(PValue pvalue, JavaRDDLike<WindowedValue<T>, ?> rdd) {
try {
rdd.rdd().setName(pvalue.getName());
} catch (IllegalStateException e) {
// name not set, ignore
}
RDDHolder<T> rddHolder = new RDDHolder<>(rdd);
pcollections.put(pvalue, rddHolder);
leafRdds.add(rddHolder);
}
JavaRDDLike<?, ?> getInputRDD(PTransform<? extends PInput, ?> transform) {
return getRDD((PValue) getInput(transform));
}
<T> Iterable<? extends WindowedValue<?>> getPCollectionView(PCollectionView<T> view) {
return pview.get(view);
}
/**
* Computes the outputs for all RDDs that are leaves in the DAG and do not have any
* actions (like saving to a file) registered on them (i.e. they are performed for side
* effects).
*/
public void computeOutputs() {
for (RDDHolder<?> rddHolder : leafRdds) {
JavaRDDLike<?, ?> rdd = rddHolder.getRDD();
rdd.rdd().cache(); // cache so that any subsequent get() is cheap
rdd.count(); // force the RDD to be computed
}
}
@Override
public <T> T get(PValue value) {
if (pobjects.containsKey(value)) {
@SuppressWarnings("unchecked")
T result = (T) pobjects.get(value);
return result;
}
if (pcollections.containsKey(value)) {
JavaRDDLike<?, ?> rdd = pcollections.get(value).getRDD();
@SuppressWarnings("unchecked")
T res = (T) Iterables.getOnlyElement(rdd.collect());
pobjects.put(value, res);
return res;
}
throw new IllegalStateException("Cannot resolve un-known PObject: " + value);
}
@Override
public <T> T getAggregatorValue(String named, Class<T> resultType) {
return runtime.getAggregatorValue(named, resultType);
}
@Override
public <T> AggregatorValues<T> getAggregatorValues(Aggregator<?, T> aggregator)
throws AggregatorRetrievalException {
return runtime.getAggregatorValues(aggregator);
}
@Override
public <T> Iterable<T> get(PCollection<T> pcollection) {
@SuppressWarnings("unchecked")
RDDHolder<T> rddHolder = (RDDHolder<T>) pcollections.get(pcollection);
Iterable<WindowedValue<T>> windowedValues = rddHolder.getValues(pcollection);
return Iterables.transform(windowedValues, WindowingHelpers.<T>unwindowValueFunction());
}
<T> Iterable<WindowedValue<T>> getWindowedValues(PCollection<T> pcollection) {
@SuppressWarnings("unchecked")
RDDHolder<T> rddHolder = (RDDHolder<T>) pcollections.get(pcollection);
return rddHolder.getValues(pcollection);
}
@Override
public void close() {
SparkContextFactory.stopSparkContext(jsc);
}
/** The runner is blocking. */
@Override
public State getState() {
return State.DONE;
}
@Override
public State cancel() throws IOException {
throw new UnsupportedOperationException(
"Spark runner EvaluationContext does not support cancel.");
}
@Override
public State waitUntilFinish()
throws IOException, InterruptedException {
return waitUntilFinish(Duration.millis(-1));
}
@Override
public State waitUntilFinish(Duration duration)
throws IOException, InterruptedException {
throw new UnsupportedOperationException(
"Spark runner EvaluationContext does not support waitUntilFinish.");
}
}
|
/**
* Evaluation context allows us to define how pipeline instructions.
*/
public class CLASS_0 implements CLASS_1 {
private final JavaSparkContext jsc;
private final Pipeline pipeline;
private final CLASS_2 VAR_0;
private final Map<PValue, CLASS_3<?>> pcollections = new LinkedHashMap<>();
private final CLASS_4<CLASS_3<?>> leafRdds = new CLASS_5<>();
private final CLASS_4<PValue> VAR_1 = new CLASS_5<>();
private final Map<PValue, Object> pobjects = new LinkedHashMap<>();
private final Map<PValue, CLASS_6<? extends CLASS_7<?>>> VAR_3 = new LinkedHashMap<>();
protected AppliedPTransform<?, ?, ?> currentTransform;
public CLASS_0(JavaSparkContext jsc, Pipeline pipeline) {
this.jsc = jsc;
this.pipeline = pipeline;
this.VAR_0 = new CLASS_2(jsc, pipeline);
}
/**
* Holds an RDD or values for deferred conversion to an RDD if needed. PCollections are
* sometimes created from a collection of objects (using RDD parallelize) and then
* only used to create View objects; in which case they do not need to be
* converted to bytes since they are not transferred across the network until they are
* broadcast.
*/
private class CLASS_3<CLASS_8> {
private CLASS_6<CLASS_7<CLASS_8>> windowedValues;
private CLASS_9<CLASS_8> coder;
private JavaRDDLike<CLASS_7<CLASS_8>, ?> VAR_4;
CLASS_3(CLASS_6<CLASS_8> VAR_5, CLASS_9<CLASS_8> coder) {
this.windowedValues =
Iterables.FUNC_1(VAR_5, WindowingHelpers.<CLASS_8>windowValueFunction());
this.coder = coder;
}
CLASS_3(JavaRDDLike<CLASS_7<CLASS_8>, ?> VAR_4) {
this.VAR_4 = VAR_4;
}
JavaRDDLike<CLASS_7<CLASS_8>, ?> FUNC_2() {
if (VAR_4 == null) {
CLASS_7.CLASS_10<CLASS_8> windowCoder =
VAR_2.FUNC_3(coder);
VAR_4 = jsc.parallelize(VAR_8.FUNC_4(windowedValues, windowCoder))
.map(VAR_8.FUNC_5(windowCoder));
}
return VAR_4;
}
CLASS_6<CLASS_7<CLASS_8>> FUNC_6(PCollection<CLASS_8> pcollection) {
if (windowedValues == null) {
CLASS_11<?, ?> VAR_9 =
pcollection.getWindowingStrategy().getWindowFn();
CLASS_9<? extends BoundedWindow> windowCoder = VAR_9.windowCoder();
final CLASS_7.WindowedValueCoder<CLASS_8> VAR_10;
if (VAR_9 instanceof CLASS_12) {
VAR_10 =
VAR_2.VAR_7.of(pcollection.getCoder());
} else {
VAR_10 =
VAR_2.FullWindowedValueCoder.of(pcollection.getCoder(), windowCoder);
}
JavaRDDLike<byte[], ?> VAR_11 =
VAR_4.map(VAR_8.toByteFunction(VAR_10));
List<byte[]> clientBytes = VAR_11.collect();
windowedValues = Iterables.FUNC_1(clientBytes,
new CLASS_13<byte[], CLASS_7<CLASS_8>>() {
@Override
public CLASS_7<CLASS_8> FUNC_7(byte[] bytes) {
return VAR_8.FUNC_8(bytes, VAR_10);
}
});
}
return windowedValues;
}
}
protected JavaSparkContext FUNC_9() {
return jsc;
}
protected Pipeline FUNC_10() {
return pipeline;
}
protected CLASS_2 getRuntimeContext() {
return VAR_0;
}
protected void setCurrentTransform(AppliedPTransform<?, ?, ?> VAR_6) {
this.currentTransform = VAR_6;
}
protected AppliedPTransform<?, ?, ?> FUNC_11() {
return currentTransform;
}
protected <CLASS_8 extends CLASS_14> CLASS_8 FUNC_12(CLASS_15<CLASS_8, ?> VAR_6) {
checkArgument(currentTransform != null && currentTransform.getTransform() == VAR_6,
"can only be called with current transform");
@VAR_12("unchecked")
CLASS_8 input = (CLASS_8) currentTransform.FUNC_12();
return input;
}
protected <CLASS_8 extends CLASS_16> CLASS_8 getOutput(CLASS_15<?, CLASS_8> VAR_6) {
checkArgument(currentTransform != null && currentTransform.getTransform() == VAR_6,
"can only be called with current transform");
@VAR_12("unchecked")
CLASS_8 output = (CLASS_8) currentTransform.getOutput();
return output;
}
protected <CLASS_8> void FUNC_13(CLASS_15<?, ?> VAR_6,
JavaRDDLike<CLASS_7<CLASS_8>, ?> VAR_4) {
setRDD((PValue) getOutput(VAR_6), VAR_4);
}
protected <CLASS_8> void FUNC_14(CLASS_15<?, ?> VAR_6, CLASS_6<CLASS_8> VAR_5,
CLASS_9<CLASS_8> coder) {
pcollections.FUNC_15((PValue) getOutput(VAR_6), new CLASS_3<>(VAR_5, coder));
}
void setPView(PValue VAR_13, CLASS_6<? extends CLASS_7<?>> VAR_14) {
VAR_3.FUNC_15(VAR_13, VAR_14);
}
protected boolean FUNC_16(CLASS_15<? extends CLASS_14, ?> VAR_6) {
PValue pvalue = (PValue) getOutput(VAR_6);
return pcollections.containsKey(pvalue);
}
protected JavaRDDLike<?, ?> FUNC_2(PValue pvalue) {
CLASS_3<?> rddHolder = pcollections.get(pvalue);
JavaRDDLike<?, ?> VAR_4 = rddHolder.FUNC_2();
leafRdds.FUNC_17(rddHolder);
if (VAR_1.contains(pvalue)) {
// Ensure the RDD is marked as cached
VAR_4.FUNC_0().FUNC_18();
} else {
VAR_1.FUNC_19(pvalue);
}
return VAR_4;
}
protected <CLASS_8> void setRDD(PValue pvalue, JavaRDDLike<CLASS_7<CLASS_8>, ?> VAR_4) {
try {
VAR_4.FUNC_0().setName(pvalue.getName());
} catch (IllegalStateException e) {
// name not set, ignore
}
CLASS_3<CLASS_8> rddHolder = new CLASS_3<>(VAR_4);
pcollections.FUNC_15(pvalue, rddHolder);
leafRdds.FUNC_19(rddHolder);
}
JavaRDDLike<?, ?> getInputRDD(CLASS_15<? extends CLASS_14, ?> VAR_6) {
return FUNC_2((PValue) FUNC_12(VAR_6));
}
<CLASS_8> CLASS_6<? extends CLASS_7<?>> FUNC_20(CLASS_17<CLASS_8> VAR_13) {
return VAR_3.get(VAR_13);
}
/**
* Computes the outputs for all RDDs that are leaves in the DAG and do not have any
* actions (like saving to a file) registered on them (i.e. they are performed for side
* effects).
*/
public void computeOutputs() {
for (CLASS_3<?> rddHolder : leafRdds) {
JavaRDDLike<?, ?> VAR_4 = rddHolder.FUNC_2();
VAR_4.FUNC_0().FUNC_18(); // cache so that any subsequent get() is cheap
VAR_4.FUNC_21(); // force the RDD to be computed
}
}
@Override
public <CLASS_8> CLASS_8 get(PValue VAR_14) {
if (pobjects.containsKey(VAR_14)) {
@VAR_12("unchecked")
CLASS_8 result = (CLASS_8) pobjects.get(VAR_14);
return result;
}
if (pcollections.containsKey(VAR_14)) {
JavaRDDLike<?, ?> VAR_4 = pcollections.get(VAR_14).FUNC_2();
@VAR_12("unchecked")
CLASS_8 VAR_15 = (CLASS_8) Iterables.FUNC_22(VAR_4.collect());
pobjects.FUNC_15(VAR_14, VAR_15);
return VAR_15;
}
throw new IllegalStateException("Cannot resolve un-known PObject: " + VAR_14);
}
@Override
public <CLASS_8> CLASS_8 getAggregatorValue(String named, CLASS_18<CLASS_8> VAR_16) {
return VAR_0.getAggregatorValue(named, VAR_16);
}
@Override
public <CLASS_8> CLASS_19<CLASS_8> FUNC_23(Aggregator<?, CLASS_8> VAR_17)
throws AggregatorRetrievalException {
return VAR_0.FUNC_23(VAR_17);
}
@Override
public <CLASS_8> CLASS_6<CLASS_8> get(PCollection<CLASS_8> pcollection) {
@VAR_12("unchecked")
CLASS_3<CLASS_8> rddHolder = (CLASS_3<CLASS_8>) pcollections.get(pcollection);
CLASS_6<CLASS_7<CLASS_8>> windowedValues = rddHolder.FUNC_6(pcollection);
return Iterables.FUNC_1(windowedValues, WindowingHelpers.<CLASS_8>unwindowValueFunction());
}
<CLASS_8> CLASS_6<CLASS_7<CLASS_8>> FUNC_24(PCollection<CLASS_8> pcollection) {
@VAR_12("unchecked")
CLASS_3<CLASS_8> rddHolder = (CLASS_3<CLASS_8>) pcollections.get(pcollection);
return rddHolder.FUNC_6(pcollection);
}
@Override
public void close() {
SparkContextFactory.FUNC_25(jsc);
}
/** The runner is blocking. */
@Override
public State FUNC_26() {
return State.VAR_18;
}
@Override
public State cancel() throws CLASS_20 {
throw new CLASS_21(
"Spark runner EvaluationContext does not support cancel.");
}
@Override
public State FUNC_27()
throws CLASS_20, CLASS_22 {
return FUNC_27(VAR_19.millis(-1));
}
@Override
public State FUNC_27(CLASS_23 VAR_20)
throws CLASS_20, CLASS_22 {
throw new CLASS_21(
"Spark runner EvaluationContext does not support waitUntilFinish.");
}
}
| 0.516952
|
{'CLASS_0': 'EvaluationContext', 'CLASS_1': 'EvaluationResult', 'CLASS_2': 'SparkRuntimeContext', 'VAR_0': 'runtime', 'CLASS_3': 'RDDHolder', 'CLASS_4': 'Set', 'CLASS_5': 'LinkedHashSet', 'VAR_1': 'multireads', 'CLASS_6': 'Iterable', 'CLASS_7': 'WindowedValue', 'VAR_2': 'WindowedValue', 'VAR_3': 'pview', 'CLASS_8': 'T', 'CLASS_9': 'Coder', 'VAR_4': 'rdd', 'FUNC_0': 'rdd', 'VAR_5': 'values', 'FUNC_1': 'transform', 'VAR_6': 'transform', 'FUNC_2': 'getRDD', 'CLASS_10': 'ValueOnlyWindowedValueCoder', 'VAR_7': 'ValueOnlyWindowedValueCoder', 'FUNC_3': 'getValueOnlyCoder', 'VAR_8': 'CoderHelpers', 'FUNC_4': 'toByteArrays', 'FUNC_5': 'fromByteFunction', 'FUNC_6': 'getValues', 'CLASS_11': 'WindowFn', 'VAR_9': 'windowFn', 'VAR_10': 'windowedValueCoder', 'CLASS_12': 'GlobalWindows', 'VAR_11': 'bytesRDD', 'CLASS_13': 'Function', 'FUNC_7': 'apply', 'FUNC_8': 'fromByteArray', 'FUNC_9': 'getSparkContext', 'FUNC_10': 'getPipeline', 'FUNC_11': 'getCurrentTransform', 'CLASS_14': 'PInput', 'FUNC_12': 'getInput', 'CLASS_15': 'PTransform', 'VAR_12': 'SuppressWarnings', 'CLASS_16': 'POutput', 'FUNC_13': 'setOutputRDD', 'FUNC_14': 'setOutputRDDFromValues', 'FUNC_15': 'put', 'VAR_13': 'view', 'VAR_14': 'value', 'FUNC_16': 'hasOutputRDD', 'FUNC_17': 'remove', 'FUNC_18': 'cache', 'FUNC_19': 'add', 'FUNC_20': 'getPCollectionView', 'CLASS_17': 'PCollectionView', 'FUNC_21': 'count', 'VAR_15': 'res', 'FUNC_22': 'getOnlyElement', 'CLASS_18': 'Class', 'VAR_16': 'resultType', 'CLASS_19': 'AggregatorValues', 'FUNC_23': 'getAggregatorValues', 'VAR_17': 'aggregator', 'FUNC_24': 'getWindowedValues', 'FUNC_25': 'stopSparkContext', 'FUNC_26': 'getState', 'VAR_18': 'DONE', 'CLASS_20': 'IOException', 'CLASS_21': 'UnsupportedOperationException', 'FUNC_27': 'waitUntilFinish', 'CLASS_22': 'InterruptedException', 'VAR_19': 'Duration', 'CLASS_23': 'Duration', 'VAR_20': 'duration'}
|
java
|
OOP
|
31.91%
|
package io.ona.rdt.repository;
import android.content.Context;
import net.sqlcipher.database.SQLiteDatabase;
import org.smartregister.AllConstants;
import org.smartregister.repository.EventClientRepository;
import org.smartregister.repository.LocationRepository;
import org.smartregister.repository.PlanDefinitionRepository;
import org.smartregister.repository.PlanDefinitionSearchRepository;
import org.smartregister.repository.Repository;
import org.smartregister.repository.SettingsRepository;
import org.smartregister.repository.StructureRepository;
import org.smartregister.repository.TaskRepository;
import org.smartregister.repository.UniqueIdRepository;
import timber.log.Timber;
/**
* Created by <NAME> on 07/06/2019
*/
public class RDTRepository extends Repository {
protected SQLiteDatabase readableDatabase;
protected SQLiteDatabase writableDatabase;
public RDTRepository(Context context, org.smartregister.Context openSRPContext) {
super(context, AllConstants.DATABASE_NAME, 1, openSRPContext.session(), openSRPContext.commonFtsObject(), openSRPContext.sharedRepositoriesArray());
}
@Override
public void onCreate(SQLiteDatabase database) {
super.onCreate(database);
EventClientRepository.createTable(database, EventClientRepository.Table.client, EventClientRepository.client_column.values());
EventClientRepository.createTable(database, EventClientRepository.Table.event, EventClientRepository.event_column.values());
UniqueIdRepository.createTable(database);
SettingsRepository.onUpgrade(database);
RDTTestsRepository.createIndexes(database);
ParasiteProfileRepository.createIndexes(database);
LocationRepository.createTable(database);
TaskRepository.createTable(database);
StructureRepository.createTable(database);
PlanDefinitionRepository.createTable(database);
PlanDefinitionSearchRepository.createTable(database);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
Timber.w("Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
int upgradeTo = oldVersion + 1;
while (upgradeTo <= newVersion) {
switch (upgradeTo) {
default:
break;
}
upgradeTo++;
}
}
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
if (readableDatabase == null || !readableDatabase.isOpen()) {
readableDatabase = super.getReadableDatabase();
}
return readableDatabase;
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
if (writableDatabase == null || !writableDatabase.isOpen()) {
writableDatabase = super.getWritableDatabase();
}
return writableDatabase;
}
}
|
package io.ona.rdt.repository;
import IMPORT_0.content.Context;
import net.sqlcipher.database.IMPORT_1;
import org.IMPORT_2.AllConstants;
import org.IMPORT_2.repository.IMPORT_3;
import org.IMPORT_2.repository.LocationRepository;
import org.IMPORT_2.repository.IMPORT_4;
import org.IMPORT_2.repository.PlanDefinitionSearchRepository;
import org.IMPORT_2.repository.IMPORT_5;
import org.IMPORT_2.repository.IMPORT_6;
import org.IMPORT_2.repository.IMPORT_7;
import org.IMPORT_2.repository.IMPORT_8;
import org.IMPORT_2.repository.IMPORT_9;
import timber.log.Timber;
/**
* Created by <NAME> on 07/06/2019
*/
public class RDTRepository extends IMPORT_5 {
protected IMPORT_1 readableDatabase;
protected IMPORT_1 VAR_0;
public RDTRepository(Context context, org.IMPORT_2.Context VAR_1) {
super(context, AllConstants.DATABASE_NAME, 1, VAR_1.FUNC_0(), VAR_1.FUNC_1(), VAR_1.sharedRepositoriesArray());
}
@VAR_2
public void onCreate(IMPORT_1 database) {
super.onCreate(database);
IMPORT_3.createTable(database, IMPORT_3.Table.VAR_3, IMPORT_3.VAR_4.values());
IMPORT_3.createTable(database, IMPORT_3.Table.VAR_5, IMPORT_3.VAR_6.values());
IMPORT_9.createTable(database);
IMPORT_6.onUpgrade(database);
VAR_7.FUNC_2(database);
VAR_8.FUNC_2(database);
LocationRepository.createTable(database);
IMPORT_8.createTable(database);
IMPORT_7.createTable(database);
IMPORT_4.createTable(database);
PlanDefinitionSearchRepository.createTable(database);
}
@VAR_2
public void onUpgrade(IMPORT_1 sqLiteDatabase, int oldVersion, int VAR_9) {
Timber.w("Upgrading database from version " + oldVersion + " to "
+ VAR_9 + ", which will destroy all old data");
int upgradeTo = oldVersion + 1;
while (upgradeTo <= VAR_9) {
switch (upgradeTo) {
default:
break;
}
upgradeTo++;
}
}
@VAR_2
public synchronized IMPORT_1 getReadableDatabase() {
if (readableDatabase == null || !readableDatabase.FUNC_3()) {
readableDatabase = super.getReadableDatabase();
}
return readableDatabase;
}
@VAR_2
public synchronized IMPORT_1 getWritableDatabase() {
if (VAR_0 == null || !VAR_0.FUNC_3()) {
VAR_0 = super.getWritableDatabase();
}
return VAR_0;
}
}
| 0.474824
|
{'IMPORT_0': 'android', 'IMPORT_1': 'SQLiteDatabase', 'IMPORT_2': 'smartregister', 'IMPORT_3': 'EventClientRepository', 'IMPORT_4': 'PlanDefinitionRepository', 'IMPORT_5': 'Repository', 'IMPORT_6': 'SettingsRepository', 'IMPORT_7': 'StructureRepository', 'IMPORT_8': 'TaskRepository', 'IMPORT_9': 'UniqueIdRepository', 'VAR_0': 'writableDatabase', 'VAR_1': 'openSRPContext', 'FUNC_0': 'session', 'FUNC_1': 'commonFtsObject', 'VAR_2': 'Override', 'VAR_3': 'client', 'VAR_4': 'client_column', 'VAR_5': 'event', 'VAR_6': 'event_column', 'VAR_7': 'RDTTestsRepository', 'FUNC_2': 'createIndexes', 'VAR_8': 'ParasiteProfileRepository', 'VAR_9': 'newVersion', 'FUNC_3': 'isOpen'}
|
java
|
OOP
|
100.00%
|
/**
* Anonymously register the current application/device with the Token Vending Machine.
*/
public Response anonymousRegister() {
Response response = Response.SUCCESSFUL;
if ( AmazonSharedPreferencesWrapper.getUidForDevice( this.sharedPreferences ) == null ) {
String uid = this.generateRandomString();
String key = this.generateRandomString();
RegisterDeviceRequest registerDeviceRequest = new RegisterDeviceRequest( this.endpoint, this.useSSL, uid, key );
ResponseHandler handler = new ResponseHandler();
response = this.processRequest( registerDeviceRequest, handler );
if ( response.requestWasSuccessful() ) {
AmazonSharedPreferencesWrapper.registerDeviceId( this.sharedPreferences, uid, key );
}
}
return response;
}
|
/**
* Anonymously register the current application/device with the Token Vending Machine.
*/
public CLASS_0 FUNC_0() {
CLASS_0 VAR_1 = VAR_0.VAR_2;
if ( VAR_3.FUNC_1( this.VAR_4 ) == null ) {
CLASS_1 VAR_5 = this.FUNC_2();
CLASS_1 VAR_6 = this.FUNC_2();
RegisterDeviceRequest VAR_7 = new RegisterDeviceRequest( this.VAR_8, this.VAR_9, VAR_5, VAR_6 );
CLASS_2 handler = new CLASS_2();
VAR_1 = this.FUNC_3( VAR_7, handler );
if ( VAR_1.requestWasSuccessful() ) {
VAR_3.registerDeviceId( this.VAR_4, VAR_5, VAR_6 );
}
}
return VAR_1;
}
| 0.579339
|
{'CLASS_0': 'Response', 'VAR_0': 'Response', 'FUNC_0': 'anonymousRegister', 'VAR_1': 'response', 'VAR_2': 'SUCCESSFUL', 'VAR_3': 'AmazonSharedPreferencesWrapper', 'FUNC_1': 'getUidForDevice', 'VAR_4': 'sharedPreferences', 'CLASS_1': 'String', 'VAR_5': 'uid', 'FUNC_2': 'generateRandomString', 'VAR_6': 'key', 'VAR_7': 'registerDeviceRequest', 'VAR_8': 'endpoint', 'VAR_9': 'useSSL', 'CLASS_2': 'ResponseHandler', 'FUNC_3': 'processRequest'}
|
java
|
Procedural
|
100.00%
|
/**
* Helper factory for crating CSVParser objects
* @param year year identitying the file
* @return CSVParser from file
*/
private CSVParser parserFactory(int year) {
final String path = "C:/Users/pd/Documents/Coursera/duke-java-1/BabyNames/data/us_babynames_by_year/";
String fileName = path+"yob"+year+".csv";
FileResource fr = new FileResource(fileName);
return fr.getCSVParser(false);
}
|
/**
* Helper factory for crating CSVParser objects
* @param year year identitying the file
* @return CSVParser from file
*/
private CSVParser FUNC_0(int year) {
final String path = "C:/Users/pd/Documents/Coursera/duke-java-1/BabyNames/data/us_babynames_by_year/";
String fileName = path+"yob"+year+".csv";
CLASS_0 fr = new CLASS_0(fileName);
return fr.getCSVParser(false);
}
| 0.157259
|
{'FUNC_0': 'parserFactory', 'CLASS_0': 'FileResource'}
|
java
|
Procedural
|
100.00%
|
/**
* TODO - GS1 Datamatrix
*
* @author Michiel Drost - Nullpointer Works
* @see The CAB Programming Manual x4 - page 287
*/
public class GS1Datamatrix implements BarcodeType
{
@Override
public String getText()
{
return null;
}
}
|
/**
* TODO - GS1 Datamatrix
*
* @author Michiel Drost - Nullpointer Works
* @see The CAB Programming Manual x4 - page 287
*/
public class GS1Datamatrix implements BarcodeType
{
@VAR_0
public String getText()
{
return null;
}
}
| 0.323927
|
{'VAR_0': 'Override'}
|
java
|
OOP
|
100.00%
|
/***
* A contract showing various options on the request side, including use
* of path and header parameters, regex path matching and overloading.
* @author Joseph Molnar
*
*/
@ResourceContract( name="com.tales.request_contract", versions={ "20140124" } )
public class RequestResource {
/**
* This method shows a simple hard fixed path.
*/
@ResourceOperation( name="overlap1", path="GET : overlap/element_one" )
public String overlapFixedPath1( ) {
return "overlap with fixed path value 'element_one'";
}
/**
* This method shows a path where a string parameter can be in the path.
*/
@ResourceOperation( name="overlap2", path="GET : overlap/{value}" )
public String overlapOneStringPathParameter( @PathParam(name = "value") String theValue ) {
return "overlap with one string path parameter: " + theValue;
}
/**
* This method shows a path where a parameter can be in the path and will match based on a regular expression.
* Even the the 'overlapOnePathParameter' overlaps, if the value that comes in is a number with 3 to 4 digits
* this method will be called. This also shows the type of the parameter being something other than a string.
* In this case, an int.
*/
@ResourceOperation( name="overlap3", path="GET : overlap/{value:[0-9]{3,4}}" )
public String overlapRegexPathParameter( @PathParam(name = "value") int theValue ) {
return "overlap with regex int path path parameter: " + theValue;
}
/**
* This method shows a path where a string parameter can be in the path and will match based on a regular expression.
* Even the the 'overlapOnePathParameter' overlaps this will still be used.
*/
@ResourceOperation( name="overlap4", path="GET : overlap/element_two" )
public String overlapFixedPath2( ) {
return "overlap with fixed path value 'element_two'";
}
/**
* This method shows a path with two values and while it can overlap with the above, having
* additional path elements will ensure this gets called.
*/
@ResourceOperation( name="overlap5", path="GET : overlap/{value_one}/{value_two}" )
public String overlapTwoStringPathParameter( @PathParam(name = "value_one") String theValueOne, @PathParam(name = "value_two") String theValueTwo ) {
return "overlap with two string path parameters: " + theValueOne + " | " + theValueTwo;
}
/**
* This demonstrates getting a header as a parameter.
*/
@ResourceOperation( name="get_header", path="GET : get_header" )
public String getHeader( @HeaderParam( name="Accept-Language" )String theLanguage ) {
return theLanguage;
}
}
|
/***
* A contract showing various options on the request side, including use
* of path and header parameters, regex path matching and overloading.
* @author Joseph Molnar
*
*/
@ResourceContract( name="com.tales.request_contract", versions={ "20140124" } )
public class RequestResource {
/**
* This method shows a simple hard fixed path.
*/
@ResourceOperation( name="overlap1", path="GET : overlap/element_one" )
public String overlapFixedPath1( ) {
return "overlap with fixed path value 'element_one'";
}
/**
* This method shows a path where a string parameter can be in the path.
*/
@ResourceOperation( name="overlap2", path="GET : overlap/{value}" )
public String overlapOneStringPathParameter( @PathParam(name = "value") String theValue ) {
return "overlap with one string path parameter: " + theValue;
}
/**
* This method shows a path where a parameter can be in the path and will match based on a regular expression.
* Even the the 'overlapOnePathParameter' overlaps, if the value that comes in is a number with 3 to 4 digits
* this method will be called. This also shows the type of the parameter being something other than a string.
* In this case, an int.
*/
@ResourceOperation( name="overlap3", path="GET : overlap/{value:[0-9]{3,4}}" )
public String overlapRegexPathParameter( @PathParam(name = "value") int theValue ) {
return "overlap with regex int path path parameter: " + theValue;
}
/**
* This method shows a path where a string parameter can be in the path and will match based on a regular expression.
* Even the the 'overlapOnePathParameter' overlaps this will still be used.
*/
@ResourceOperation( name="overlap4", path="GET : overlap/element_two" )
public String overlapFixedPath2( ) {
return "overlap with fixed path value 'element_two'";
}
/**
* This method shows a path with two values and while it can overlap with the above, having
* additional path elements will ensure this gets called.
*/
@ResourceOperation( name="overlap5", path="GET : overlap/{value_one}/{value_two}" )
public String overlapTwoStringPathParameter( @PathParam(name = "value_one") String theValueOne, @PathParam(name = "value_two") String theValueTwo ) {
return "overlap with two string path parameters: " + theValueOne + " | " + theValueTwo;
}
/**
* This demonstrates getting a header as a parameter.
*/
@ResourceOperation( name="get_header", path="GET : get_header" )
public String getHeader( @HeaderParam( name="Accept-Language" )String theLanguage ) {
return theLanguage;
}
}
| 0.023797
|
{}
|
java
|
Procedural
|
9.73%
|
/**
* This is a utility class that is used to collect all the declared tag in a Slam system.
*/
public class MessageRepository {
private final Map<String, MessageTag> tags;
/**
* Creates an empty message repository.
*/
public MessageRepository() {
this.tags = new TreeMap<>();
}
/**
* Returns a new tag having the given name that is associated with content of the given type. An {@link IllegalArgumentException}
* is thrown if a tag with the same name already exists in this repository.
*
* @param tagName tag name.
* @param content type of message content.
* @return the new created tag.
*/
public synchronized MessageTag addTag(String tagName, SlamType[] content) {
if (tags.containsKey(tagName)) {
throw new IllegalArgumentException();
}
MessageTag tag = new MessageTag(tags.size(), tagName, content);
tags.put(tagName, tag);
return tag;
}
/**
* Returns the tag associated with the given name if it exists in this repository.
*
* @param tagName tag name
* @return the tag associated with the given name if it exists in this repository.
*/
public synchronized MessageTag getTag(String tagName) {
return tags.get(tagName);
}
/**
* Returns true if a tag with the given name is stored in this repository.
*
* @param tagName tag name.
* @return true if a tag with the given name is stored in this repository.
*/
public boolean exists(String tagName) {
return tags.containsKey(tagName);
}
}
|
/**
* This is a utility class that is used to collect all the declared tag in a Slam system.
*/
public class CLASS_0 {
private final CLASS_1<String, MessageTag> VAR_0;
/**
* Creates an empty message repository.
*/
public CLASS_0() {
this.VAR_0 = new TreeMap<>();
}
/**
* Returns a new tag having the given name that is associated with content of the given type. An {@link IllegalArgumentException}
* is thrown if a tag with the same name already exists in this repository.
*
* @param tagName tag name.
* @param content type of message content.
* @return the new created tag.
*/
public synchronized MessageTag FUNC_0(String VAR_1, CLASS_2[] VAR_2) {
if (VAR_0.FUNC_1(VAR_1)) {
throw new IllegalArgumentException();
}
MessageTag tag = new MessageTag(VAR_0.FUNC_2(), VAR_1, VAR_2);
VAR_0.put(VAR_1, tag);
return tag;
}
/**
* Returns the tag associated with the given name if it exists in this repository.
*
* @param tagName tag name
* @return the tag associated with the given name if it exists in this repository.
*/
public synchronized MessageTag FUNC_3(String VAR_1) {
return VAR_0.get(VAR_1);
}
/**
* Returns true if a tag with the given name is stored in this repository.
*
* @param tagName tag name.
* @return true if a tag with the given name is stored in this repository.
*/
public boolean exists(String VAR_1) {
return VAR_0.FUNC_1(VAR_1);
}
}
| 0.474929
|
{'CLASS_0': 'MessageRepository', 'CLASS_1': 'Map', 'VAR_0': 'tags', 'FUNC_0': 'addTag', 'VAR_1': 'tagName', 'CLASS_2': 'SlamType', 'VAR_2': 'content', 'FUNC_1': 'containsKey', 'FUNC_2': 'size', 'FUNC_3': 'getTag'}
|
java
|
OOP
|
100.00%
|
package com.xiyoulinux.utils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @Title: Redis 工具类
*/
@Component
public class RedisOperator {
// @Autowired
// private RedisTemplate<String, Object> redisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;
// Key(键),简单的key-value操作
/**
* 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)。
*
* @param key
* @return
*/
public long ttl(String key) {
return stringRedisTemplate.getExpire(key);
}
/**
* 实现命令:expire 设置过期时间,单位秒
*
* @param key
* @return
*/
public void expire(String key, long timeout) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:INCR key,增加key一次
*
* @param key
* @return
*/
public long incr(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
/**
* 实现命令:decr key,减少key一次
*
* @param key
* @return
*/
public long decr(String key, long delta) {
return stringRedisTemplate.opsForValue().decrement(key, delta);
}
/**
* 实现命令:scan pattern,查找所有符合给定模式 pattern的 key
*/
public Set<String> scan(String pattern) {
return stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keysTmp = new HashSet<>();
Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(pattern).count(1000).build());
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
return keysTmp;
});
}
/**
* 实现命令:DEL key,删除一个key
*
* @param key
*/
public void delOne(String key) {
stringRedisTemplate.delete(key);
}
/**
* 实现命令:DEL some key,删除多个key
*
* @param key
*/
public void delCollect(Collection<String> key) {
stringRedisTemplate.delete(key);
}
// String(字符串)
/**
* 实现命令:SET key value,设置一个key-value(将字符串值 value关联到 key)
*
* @param key
* @param value
*/
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
/**
* 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
*
* @param key
* @param value
* @param timeout (以秒为单位)
*/
public void set(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:GET key,返回 key所关联的字符串值。
*
* @param key
* @return value
*/
public String get(String key) {
return (String) stringRedisTemplate.opsForValue().get(key);
}
/**
* 批量查询,对应mget
*
* @param keys
* @return
*/
public List<String> mget(List<String> keys) {
return stringRedisTemplate.opsForValue().multiGet(keys);
}
/**
* 批量查询,管道pipeline
*
* @param keys
* @return
*/
public List<Object> batchGet(List<String> keys) {
// nginx -> keepalive
// redis -> pipeline
List<Object> result = stringRedisTemplate.executePipelined(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection src = (StringRedisConnection) connection;
for (String k : keys) {
src.get(k);
}
return null;
}
});
return result;
}
// Hash(哈希表)
/**
* 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
*
* @param key
* @param field
* @param value
*/
public void hset(String key, String field, Object value) {
stringRedisTemplate.opsForHash().put(key, field, value);
}
/**
* 实现命令:HGET key field,返回哈希表 key中给定域 field的值
*
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
return (String) stringRedisTemplate.opsForHash().get(key, field);
}
/**
* 实现命令:HDEL key field [field ...],删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param fields
*/
public void hdel(String key, Object... fields) {
stringRedisTemplate.opsForHash().delete(key, fields);
}
/**
* 实现命令:HGETALL key,返回哈希表 key中,所有的域和值。
*
* @param key
* @return
*/
public Map<Object, Object> hgetall(String key) {
return stringRedisTemplate.opsForHash().entries(key);
}
// List(列表)
/**
* 实现命令:LPUSH key value,将一个值 value插入到列表 key的表头
*
* @param key
* @param value
* @return 执行 LPUSH命令后,列表的长度。
*/
public long lpush(String key, String value) {
return stringRedisTemplate.opsForList().leftPush(key, value);
}
/**
* 实现命令:LPOP key,移除并返回列表 key的头元素。
*
* @param key
* @return 列表key的头元素。
*/
public String lpop(String key) {
return (String) stringRedisTemplate.opsForList().leftPop(key);
}
/**
* 实现命令:RPUSH key value,将一个值 value插入到列表 key的表尾(最右边)。
*
* @param key
* @param value
* @return 执行 LPUSH命令后,列表的长度。
*/
public long rpush(String key, String value) {
return stringRedisTemplate.opsForList().rightPush(key, value);
}
}
|
package com.xiyoulinux.utils;
import IMPORT_0.IMPORT_1.dao.DataAccessException;
import IMPORT_0.IMPORT_1.data.IMPORT_2.IMPORT_3.IMPORT_4;
import IMPORT_0.IMPORT_1.data.IMPORT_2.IMPORT_3.IMPORT_5;
import IMPORT_0.IMPORT_1.data.IMPORT_2.IMPORT_6.IMPORT_7;
import IMPORT_0.IMPORT_1.data.IMPORT_2.IMPORT_6.IMPORT_8;
import IMPORT_0.IMPORT_1.data.IMPORT_2.IMPORT_6.IMPORT_9;
import IMPORT_0.IMPORT_1.data.IMPORT_2.IMPORT_6.IMPORT_10;
import IMPORT_0.IMPORT_1.IMPORT_11.IMPORT_12;
import IMPORT_13.IMPORT_14.IMPORT_15;
import IMPORT_16.util.*;
import IMPORT_16.util.IMPORT_17.TimeUnit;
/**
* @Title: Redis 工具类
*/
@IMPORT_12
public class CLASS_0 {
// @Autowired
// private RedisTemplate<String, Object> redisTemplate;
@IMPORT_15
private IMPORT_10 VAR_0;
// Key(键),简单的key-value操作
/**
* 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)。
*
* @param key
* @return
*/
public long FUNC_0(CLASS_1 key) {
return VAR_0.getExpire(key);
}
/**
* 实现命令:expire 设置过期时间,单位秒
*
* @param key
* @return
*/
public void FUNC_1(CLASS_1 key, long VAR_1) {
VAR_0.FUNC_1(key, VAR_1, TimeUnit.VAR_2);
}
/**
* 实现命令:INCR key,增加key一次
*
* @param key
* @return
*/
public long FUNC_2(CLASS_1 key, long delta) {
return VAR_0.FUNC_3().FUNC_4(key, delta);
}
/**
* 实现命令:decr key,减少key一次
*
* @param key
* @return
*/
public long decr(CLASS_1 key, long delta) {
return VAR_0.FUNC_3().FUNC_5(key, delta);
}
/**
* 实现命令:scan pattern,查找所有符合给定模式 pattern的 key
*/
public Set<CLASS_1> FUNC_6(CLASS_1 pattern) {
return VAR_0.FUNC_7((IMPORT_8<Set<CLASS_1>>) IMPORT_3 -> {
Set<CLASS_1> keysTmp = new CLASS_2<>();
IMPORT_7<byte[]> VAR_3 = IMPORT_3.FUNC_6(new IMPORT_9.CLASS_3().FUNC_8(pattern).FUNC_9(1000).FUNC_10());
while (VAR_3.FUNC_11()) {
keysTmp.FUNC_12(new CLASS_1(VAR_3.next()));
}
return keysTmp;
});
}
/**
* 实现命令:DEL key,删除一个key
*
* @param key
*/
public void FUNC_13(CLASS_1 key) {
VAR_0.FUNC_14(key);
}
/**
* 实现命令:DEL some key,删除多个key
*
* @param key
*/
public void FUNC_15(CLASS_4<CLASS_1> key) {
VAR_0.FUNC_14(key);
}
// String(字符串)
/**
* 实现命令:SET key value,设置一个key-value(将字符串值 value关联到 key)
*
* @param key
* @param value
*/
public void FUNC_16(CLASS_1 key, CLASS_1 value) {
VAR_0.FUNC_3().FUNC_16(key, value);
}
/**
* 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
*
* @param key
* @param value
* @param timeout (以秒为单位)
*/
public void FUNC_16(CLASS_1 key, CLASS_1 value, long VAR_1) {
VAR_0.FUNC_3().FUNC_16(key, value, VAR_1, TimeUnit.VAR_2);
}
/**
* 实现命令:GET key,返回 key所关联的字符串值。
*
* @param key
* @return value
*/
public CLASS_1 get(CLASS_1 key) {
return (CLASS_1) VAR_0.FUNC_3().get(key);
}
/**
* 批量查询,对应mget
*
* @param keys
* @return
*/
public CLASS_5<CLASS_1> FUNC_17(CLASS_5<CLASS_1> VAR_4) {
return VAR_0.FUNC_3().multiGet(VAR_4);
}
/**
* 批量查询,管道pipeline
*
* @param keys
* @return
*/
public CLASS_5<Object> FUNC_18(CLASS_5<CLASS_1> VAR_4) {
// nginx -> keepalive
// redis -> pipeline
CLASS_5<Object> VAR_5 = VAR_0.FUNC_19(new IMPORT_8<CLASS_1>() {
@Override
public CLASS_1 FUNC_20(IMPORT_4 IMPORT_3) throws DataAccessException {
IMPORT_5 src = (IMPORT_5) IMPORT_3;
for (CLASS_1 VAR_6 : VAR_4) {
src.get(VAR_6);
}
return null;
}
});
return VAR_5;
}
// Hash(哈希表)
/**
* 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
*
* @param key
* @param field
* @param value
*/
public void hset(CLASS_1 key, CLASS_1 VAR_7, Object value) {
VAR_0.FUNC_21().FUNC_22(key, VAR_7, value);
}
/**
* 实现命令:HGET key field,返回哈希表 key中给定域 field的值
*
* @param key
* @param field
* @return
*/
public CLASS_1 FUNC_23(CLASS_1 key, CLASS_1 VAR_7) {
return (CLASS_1) VAR_0.FUNC_21().get(key, VAR_7);
}
/**
* 实现命令:HDEL key field [field ...],删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param fields
*/
public void FUNC_24(CLASS_1 key, Object... VAR_8) {
VAR_0.FUNC_21().FUNC_14(key, VAR_8);
}
/**
* 实现命令:HGETALL key,返回哈希表 key中,所有的域和值。
*
* @param key
* @return
*/
public CLASS_6<Object, Object> hgetall(CLASS_1 key) {
return VAR_0.FUNC_21().entries(key);
}
// List(列表)
/**
* 实现命令:LPUSH key value,将一个值 value插入到列表 key的表头
*
* @param key
* @param value
* @return 执行 LPUSH命令后,列表的长度。
*/
public long lpush(CLASS_1 key, CLASS_1 value) {
return VAR_0.FUNC_25().FUNC_26(key, value);
}
/**
* 实现命令:LPOP key,移除并返回列表 key的头元素。
*
* @param key
* @return 列表key的头元素。
*/
public CLASS_1 lpop(CLASS_1 key) {
return (CLASS_1) VAR_0.FUNC_25().FUNC_27(key);
}
/**
* 实现命令:RPUSH key value,将一个值 value插入到列表 key的表尾(最右边)。
*
* @param key
* @param value
* @return 执行 LPUSH命令后,列表的长度。
*/
public long FUNC_28(CLASS_1 key, CLASS_1 value) {
return VAR_0.FUNC_25().FUNC_29(key, value);
}
}
| 0.766067
|
{'IMPORT_0': 'org', 'IMPORT_1': 'springframework', 'IMPORT_2': 'redis', 'IMPORT_3': 'connection', 'IMPORT_4': 'RedisConnection', 'IMPORT_5': 'StringRedisConnection', 'IMPORT_6': 'core', 'IMPORT_7': 'Cursor', 'IMPORT_8': 'RedisCallback', 'IMPORT_9': 'ScanOptions', 'IMPORT_10': 'StringRedisTemplate', 'IMPORT_11': 'stereotype', 'IMPORT_12': 'Component', 'IMPORT_13': 'javax', 'IMPORT_14': 'annotation', 'IMPORT_15': 'Resource', 'IMPORT_16': 'java', 'IMPORT_17': 'concurrent', 'CLASS_0': 'RedisOperator', 'VAR_0': 'stringRedisTemplate', 'FUNC_0': 'ttl', 'CLASS_1': 'String', 'FUNC_1': 'expire', 'VAR_1': 'timeout', 'VAR_2': 'SECONDS', 'FUNC_2': 'incr', 'FUNC_3': 'opsForValue', 'FUNC_4': 'increment', 'FUNC_5': 'decrement', 'FUNC_6': 'scan', 'FUNC_7': 'execute', 'CLASS_2': 'HashSet', 'VAR_3': 'cursor', 'CLASS_3': 'ScanOptionsBuilder', 'FUNC_8': 'match', 'FUNC_9': 'count', 'FUNC_10': 'build', 'FUNC_11': 'hasNext', 'FUNC_12': 'add', 'FUNC_13': 'delOne', 'FUNC_14': 'delete', 'FUNC_15': 'delCollect', 'CLASS_4': 'Collection', 'FUNC_16': 'set', 'CLASS_5': 'List', 'FUNC_17': 'mget', 'VAR_4': 'keys', 'FUNC_18': 'batchGet', 'VAR_5': 'result', 'FUNC_19': 'executePipelined', 'FUNC_20': 'doInRedis', 'VAR_6': 'k', 'VAR_7': 'field', 'FUNC_21': 'opsForHash', 'FUNC_22': 'put', 'FUNC_23': 'hget', 'FUNC_24': 'hdel', 'VAR_8': 'fields', 'CLASS_6': 'Map', 'FUNC_25': 'opsForList', 'FUNC_26': 'leftPush', 'FUNC_27': 'leftPop', 'FUNC_28': 'rpush', 'FUNC_29': 'rightPush'}
|
java
|
OOP
|
29.88%
|
package com.h8.nh.nhoodengine.core.impl;
import com.h8.nh.nhoodengine.core.DataFinderAbstractTest;
import com.h8.nh.nhoodengine.core.DataFinderTestContext;
import com.h8.nh.nhoodengine.core.DataResourceKey;
class DataScoreComputationEngineTest extends DataFinderAbstractTest<DataResourceKey, Object> {
@Override
protected DataFinderTestContext<DataResourceKey, Object> initializeContext() {
return new DataScoreComputationEngineTestContext();
}
}
|
package IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_5;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_6;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_7;
import IMPORT_0.IMPORT_1.IMPORT_2.IMPORT_3.IMPORT_4.IMPORT_8;
class CLASS_0 extends IMPORT_6<IMPORT_8, CLASS_1> {
@VAR_0
protected IMPORT_7<IMPORT_8, CLASS_1> FUNC_0() {
return new CLASS_2();
}
}
| 0.943417
|
{'IMPORT_0': 'com', 'IMPORT_1': 'h8', 'IMPORT_2': 'nh', 'IMPORT_3': 'nhoodengine', 'IMPORT_4': 'core', 'IMPORT_5': 'impl', 'IMPORT_6': 'DataFinderAbstractTest', 'IMPORT_7': 'DataFinderTestContext', 'IMPORT_8': 'DataResourceKey', 'CLASS_0': 'DataScoreComputationEngineTest', 'CLASS_1': 'Object', 'VAR_0': 'Override', 'FUNC_0': 'initializeContext', 'CLASS_2': 'DataScoreComputationEngineTestContext'}
|
java
|
OOP
|
100.00%
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.