method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
016cd5b5-b51f-43ce-bd64-f3ac2afc16ab
| 3
|
public void close() {
if (State.CLOSED == getState()) return;
setState(State.CLOSED);
RotateTransition rotate = new RotateTransition();
rotate.setNode(cross);
rotate.setToAngle(0);
rotate.setDuration(Duration.millis(200));
rotate.setInterpolator(Interpolator.EASE_BOTH);
rotate.play();
closeTimeLines[closeTimeLines.length - 1].setOnFinished(actionEvent -> {
FadeTransition buttonFadeOut = new FadeTransition();
buttonFadeOut.setNode(mainMenuButton);
buttonFadeOut.setDuration(Duration.millis(100));
buttonFadeOut.setToValue(options.getButtonAlpha());
buttonFadeOut.play();
buttonFadeOut.setOnFinished(event -> {
if (options.isButtonHideOnClose()) hide();
fireMenuEvent(new MenuEvent(this, null, MenuEvent.MENU_CLOSE_FINISHED));
});
});
for (int i = 0 ; i < closeTimeLines.length ; i++) {
closeTimeLines[i].play();
}
fireMenuEvent(new MenuEvent(this, null, MenuEvent.MENU_CLOSE_STARTED));
}
|
44b24e68-78ff-47e9-b53a-1d70cb48f741
| 8
|
public Set<Light> getLights(int[][] board) {
lights = new HashSet<Light>();
objective = new HashMap<Integer,Tuple<Integer,Integer>>();
lightArr = new Light[numLights];
sectors = getSectors();
for( int i=0; i<numLights; i++)
{
int x = 0;
int y = 0;
double theta = i*(360/numLights) + (360/numLights)/2;
log.trace("i" + i + " - theta:" + theta);
double slope = Math.tan(Math.toRadians(theta));
int xf = 1;
int yf = 1;
if ( theta > 90 && theta < 270 ) {
xf = -1;
}
// Placement should be more precise...this is very lazy
// Special case: vertical lines
if ( theta == 90 || theta == 270 ) {
while ( Math.abs(y) < 50 ) {
y++;
}
} else {
while ( Math.abs(x)<30 && Math.abs(y)<30 ) {
x=x+xf;
y=(int) Math.floor(slope*x);
y = (int) (slope*x);
log.trace(i+":(x,y):"+x+","+y+"slope"+slope);
}
}
lastLight = new Point2D.Double(x+50, y+50);
MoveableLight l = new MoveableLight(lastLight.getX(),lastLight.getY(), true);
log.trace("Positioned a light at (" + lastLight.getX() + ", " + lastLight.getY() + ")");
lights.add(l);
lightArr[i]=l;
objective.put(i, null);
}
return lights;
}
|
1d76ce18-3b52-46c3-bfad-f722c6f9b922
| 6
|
public void move() {
if (!inTarget) {
double a = Math.round(Math.cos(angle) * speed);
curPosX += (int)a;
double b = Math.round(Math.sin(angle) * speed);
curPosY -= (int)b;
if(curPosX <= 0 || curPosX >= rightBorder || curPosY <= 0 || curPosY >= downBorder) {
needsDelete = true;
}
}
else {
if(imgCounter < TEXTURES_COUNT - 1) {
imgCounter++;
rocketImage = textures[imgCounter];
}
else {
needsDelete = true;
}
}
}
|
622b9640-b60d-40aa-9e2e-fd7827d2d606
| 0
|
@Override
public String toString() {
return "First State";
}
|
76a66b08-b25c-4c85-aeba-1a2900d3375a
| 4
|
public static int[] connections(int from) {
int[] count = new int[nNodes];
Queue<Point> q = new LinkedList<Point>();
BitSet vis = new BitSet(nNodes + 1);
Point e = new Point(from, -1);
int next = 0;
q.add(e);
vis.set(from, true);
while (!q.isEmpty()) {
e = q.poll();
if (e.y != -1)
count[e.y]++;
for (int i = 0; i < ady[e.x].size(); i++) {
next = ady[e.x].get(i);
if (!vis.get(next)) {
q.add(new Point(next, e.y + 1));
vis.set(next, true);
}
}
}
return count;
}
|
8228d761-b853-4b70-8c67-08ea3a18efe2
| 7
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Border))
return false;
Border other = (Border) obj;
if (neighbour == null) {
if (other.neighbour != null)
return false;
} else if (!neighbour.equals(other.neighbour))
return false;
if (type != other.type)
return false;
return true;
}
|
04edef5b-8b34-45ae-affa-aefb09313b78
| 1
|
public void testSetMilliOfSecond_int2() {
MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8);
try {
test.setMillisOfSecond(1000);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals("2002-06-09T05:06:07.008+01:00", test.toString());
}
|
c972cdc7-7166-42a2-a2cb-15d74ad9a7a1
| 8
|
@Override
public SingleObjectiveSolution run() {
int outer = schedule.getOuterLoopCounter();
int inner = schedule.getInnerLoopCounter();
double temp = schedule.getNextTemperature();
T omega = startWith;
omega.value = function.valueAt(decoder.decode(omega));
omega.fitness = minimize ? -omega.value : omega.value;
T max = omega;
for (int i = 0; i < outer; i++) {
for (int j = 0; j < inner; j++) {
T omegaNew = neighborhood.randomNeighbor(omega);
omegaNew.value = function.valueAt(decoder.decode(omegaNew));
omegaNew.fitness = minimize ? -omegaNew.value : omegaNew.value;
double delta = omegaNew.value - omega.value;
if (!minimize) {
delta = -delta;
}
if (delta <= 0) {
omega = omegaNew;
} else {
double p = Math.exp(-delta / temp);
if (rand.nextDouble() <= p) {
omega = omegaNew;
}
}
if (omega.compareTo(max) < 0) {
max = omega;
}
}
// System.out.println(max);
temp = schedule.getNextTemperature();
}
return max;
}
|
d4f7d539-23b7-4eb2-b3e9-36ea896b75e8
| 2
|
private static final void traverse( final File file, final String path,
final Collection<ClassPathHandler> handlers, final ClassLoader classLoader,
final ErrorHandler errorHandler )
{
if ( file.isDirectory() )
{
for ( File child : file.listFiles() )
{
traverse( child, path, handlers, classLoader, errorHandler );
}
return;
}
handleEntry( file.getAbsolutePath().substring( path.length() + 1 ), path, handlers, classLoader, errorHandler );
}
|
9082d95b-e061-44be-ac65-c5bf317deeb3
| 2
|
public void mostrarProcesos(){
//mbLog.setBounds(1, 81, 485,347);
//mbLog.setVisible(true);
NodosListaProceso aux = this.PrimerNodo;
int i = 0;
while (aux.siguiente!=null && i<cant) {
//aux.proceso.setVisible(true);
i++;
aux=aux.siguiente;
}
//aux.proceso.setVisible(true);
}
|
a3ed65e1-9ee6-4e3f-a2dd-3690fa09053d
| 4
|
@Override
public int getMetricInternal() {
int add = curGb.step(Move.A,curGb.pokemon.owPlayerInputCheckAAddress); // after IsSpriteOrSignInFrontOfPlayer call
if(add == 0) {
System.out.println("OverworldInteract: IsSpriteOrSignInFrontOfPlayer call not found");
return 0;
}
int id = curGb.readMemory(curGb.pokemon.owInteractionTargetAddress); // text ID of entity talked to
if(textID != -1 && textID != id) {
System.out.println("WARNING: text ID "+id+" does not match expected ID "+textID);
return 0;
}
add = Util.runToAddressLimit(0, Move.A, 500, curGb.pokemon.owInteractionSuccessfulAddress, curGb.pokemon.owLoopAddress); // before DisplayTextID call
//add = State.step(Move.A,0x496); // before DisplayTextID call
if(add != curGb.pokemon.owInteractionSuccessfulAddress) {
System.out.println("ERROR: talking to "+textID+" failed");
return 0;
}
return 1;
}
|
28eb5e08-7ea6-4a76-9851-53915c941bc3
| 6
|
private void initFileMenu(JMenuBar menuBar) {
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem = new JMenuItem("Load RDC data...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Bring up the Load File dialog
browseDialog.setAcceptAllFileFilterUsed(true);
int returnVal = browseDialog.showOpenDialog(mainFrame);
if(returnVal != JFileChooser.APPROVE_OPTION) return; // Stop if no selection was made
File file = browseDialog.getSelectedFile();
readRDCInput(file);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Save state...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Bring up the Save File dialog
browseDialog.setAcceptAllFileFilterUsed(false);
browseDialog.addChoosableFileFilter(stateFilter);
int returnVal = browseDialog.showSaveDialog(mainFrame);
if(returnVal != JFileChooser.APPROVE_OPTION) { // Stop if no selection was made
browseDialog.removeChoosableFileFilter(stateFilter); // Clean up for the next use
return;
}
File file = browseDialog.getSelectedFile();
browseDialog.removeChoosableFileFilter(stateFilter); // Clean up for the next use
saveState(file);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Load state...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Bring up the Open File dialog
browseDialog.setAcceptAllFileFilterUsed(false);
browseDialog.addChoosableFileFilter(stateFilter);
int returnVal = browseDialog.showOpenDialog(mainFrame);
if(returnVal != JFileChooser.APPROVE_OPTION) { // Stop if no selection was made
browseDialog.removeChoosableFileFilter(stateFilter); // Clean up for the next use
return;
}
File file = browseDialog.getSelectedFile();
browseDialog.removeChoosableFileFilter(stateFilter); // Clean up for the next use
loadState(file);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Save data in DC format");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AlignmentMedium selectedMedium;
if(media.size() > 1) { // Only ask to select medium if there are more than one
RDCOutputSelectDialog dialog = new RDCOutputSelectDialog(mainFrame, media);
dialog.setVisible(true);
if(dialog.selectionWasMade())
selectedMedium = media.get(dialog.getSelectedMedium());
else
return; // If no selection was made then stop here
} else
selectedMedium = media.get(0);
// Bring up the Save File dialog
int returnVal = browseDialog.showSaveDialog(mainFrame);
if(returnVal != JFileChooser.APPROVE_OPTION) return; // Stop if no selection was made
File file = browseDialog.getSelectedFile();
exportInDCFormat(file, selectedMedium);
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Quit");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainFrame.dispose();
}
});
menu.add(menuItem);
}
|
b52a0f76-3589-460a-b96f-1fcf142d8e70
| 3
|
public TrackingWnd(int direction, int delta, int a1, int a2) {
super(new Coord(100,100), Coord.z, UI.instance.root, "Direction");
this.a1 = a1;
this.a2 = a2;
justclose = true;
new Label(Coord.z, this, "Direction: "+direction+"o, delta: "+delta+"o");
pack();
Gob pl;
if((ui.mapview.playergob >= 0) && ((pl = ui.sess.glob.oc.getgob(ui.mapview.playergob)) != null) && (pl.sc != null)) {
pos = pl.position();
}
instances.add(this);
}
|
726ef414-bd48-4146-9fb8-d5b63f85cd44
| 7
|
public double propositionWeight(Proposition proposition) {
{ WhynotPartialMatch self = this;
if (proposition == null) {
return (1.0);
}
else if (proposition.kind == Logic.KWD_ISA) {
return (0.25);
}
else if ((proposition.kind == Logic.KWD_NOT) &&
(((Proposition)((proposition.arguments.theArray)[0])).kind == Logic.KWD_EQUIVALENT)) {
return (0.1);
}
else if (Proposition.auxiliaryEquivalencePropositionP(proposition)) {
return (0.0);
}
else if (((FloatWrapper)(KeyValueList.dynamicSlotValue(proposition.dynamicSlots, Logic.SYM_LOGIC_WEIGHT, Stella.NULL_FLOAT_WRAPPER))).wrapperValue != Stella.NULL_FLOAT) {
return (((FloatWrapper)(KeyValueList.dynamicSlotValue(proposition.dynamicSlots, Logic.SYM_LOGIC_WEIGHT, Stella.NULL_FLOAT_WRAPPER))).wrapperValue);
}
else if (((TruthValue)(Stella_Object.accessInContext(proposition.truthValue, proposition.homeContext, false))) != null) {
return (((TruthValue)(Stella_Object.accessInContext(proposition.truthValue, proposition.homeContext, false))).positiveScore);
}
else {
return (1.0);
}
}
}
|
e4da0d49-779c-4278-a312-01675788f5db
| 5
|
public static void solveNearestNeighbor()
{
//Parse file
Parser p = new Parser();
p.parse();
long startTime = System.nanoTime();
Graph g = new Graph();
//All cities
g.cities = p.out;
//Copy of cities
LinkedList<Double[]> linkCities = new LinkedList<Double[]>();
g.bestTour = null;
g.bestCost = Integer.MAX_VALUE;
for(int i = 0; i < g.cities.size(); i++){
//Add all cities to copy
for(int j = 0; j < g.cities.size(); j++)
linkCities.add(g.cities.get(j));
//Save and remove starting city
Double[] start = g.cities.get(i);
linkCities.remove(start);
//Calculate tour cost
Tour t1 = g.tourCalc(start, linkCities, start);
//Compare to best cost found
if(t1.cost < g.bestCost){
g.bestCost = t1.cost;
g.bestTourString = t1.tour;
}
}
// By nature, starting city was at the end of bestTourString
// This places the starting city at the beginning instead
String lastNum = g.bestTourString.substring(g.bestTourString.lastIndexOf(","));
g.bestTourString = (lastNum + "," + g.bestTourString.substring(0, g.bestTourString.length()-lastNum.length())).substring(1);
System.out.println(g.bestCost);
System.out.println(g.bestTourString);
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
try{
generateTourFile(p, g, endTime-startTime);
}
catch(FileNotFoundException FNFE)
{
System.err.println("Caught FileNotFoundException: " + FNFE.getMessage());
System.out.println();
}
catch(UnsupportedEncodingException UEE)
{
System.err.println("Caught UnsupportedEncodingException: " + UEE.getMessage());
System.out.println();
}
}
|
824ea22b-5557-4e94-99af-744c98d9aca1
| 0
|
public UsuarioFacade() {
super(Usuario.class);
}
|
973cd731-729e-4802-95bd-3bfb6a065790
| 1
|
public void Remove(Tick t) {
synchronized(ticks) {
if (ticks.contains(t))
ticks.remove(t);
}
}
|
8e7d08d1-5d51-4f03-85ab-c5f52a7178d9
| 0
|
public int hashCode() {
return (String.valueOf(String.valueOf(Arrays.hashCode(currentCells))
+ String.valueOf(intelligentX) + String.valueOf(intelligentY)))
.hashCode();
}
|
6116182d-b040-4fe8-a289-3acc1eec38c1
| 5
|
public PolyLinje generateRandomPolylinje()
{
// Antalet horn på linjen
int antalPunkter = 2;
// Skapar en Punkt vektor som håller Punkterna
Punkt[] punktVektor = new Punkt[antalPunkter];
for(int i = 0; i < antalPunkter; i++)
{
// X koordinat för Punkten
int x = new Random().nextInt(10) + 1;
// Y koordinat för Punkten
int y = new Random().nextInt(10) + 1;
// Antal bokstäver i linjens namn
int bokstaver = new Random().nextInt(5) + 1;
StringBuilder sBuilder = new StringBuilder();
for(int i2 = 0; i2 < bokstaver; i2++)
{
sBuilder.append((char) (new Random().nextInt(25) + 65));
}
punktVektor[i] = new Punkt(sBuilder.toString(), x, y);
}
int fargKod = 0;
String farg = "";
switch(fargKod)
{
case 0:
farg = "gul";
break;
case 1:
farg = "röd";
break;
case 2:
farg = "blå";
break;
}
return new PolyLinje(punktVektor, farg);
}
|
d8b81198-06e3-47f2-a586-e40bdc44cdec
| 2
|
public synchronized boolean seatPlayer(Player player, int index)
throws IndexOutOfBoundsException {
if (index > players.length)
throw new IndexOutOfBoundsException(
"The max number of players is four.");
if (this.players[index] == null)
this.players[index] = player;
else
return false;
return true;
}
|
c359d6db-a45f-4137-80fa-0edd20dbe290
| 1
|
public static void loadProperties() {
try {
PropertiesLoader.getInstance();
} catch (IOException e) {
logger.error(e.getMessage(),e);
System.err.println(e.getMessage());
}
}
|
480b178e-5faf-4b3c-99b4-f45e852888b2
| 5
|
public boolean accept(File file) {
if (file.isDirectory()) {
return false;
}
String name = file.getName();
// find the last
int index = name.lastIndexOf(".");
if (index == -1) {
return false;
} else if (index == name.length() - 1) {
return false;
} else{
for(int i=0;i<extension.length;i++){
boolean b=extension[i].equals(
name.substring(index + 1).toLowerCase());
if(b){
return true;
}
}
return false;
}
}
|
b39cd38a-3c64-4322-b518-4afd7f2d9082
| 3
|
public void run(){
ReadingMessages serverReder;
try {
while(true) {
SOCKET = serverSocket.accept();
System.out.println("New connection accepted...");
serverReder = new ReadingMessages(SOCKET, LOCAL_IP);
serverReder.start();
}
}catch (IOException ioe){
System.out.println("<ERROR> Cuased by:" + ioe);
} catch (Exception e) {
e.printStackTrace();
}
}
|
83115578-0e37-4e47-8a44-82b4910b6cb8
| 9
|
private OperationSignature(String opName, MBeanParameterInfo...infos) {
this.opName = opName;
List<Class<?>> sig = new ArrayList<Class<?>>(infos==null ? 0 : infos.length);
List<String> strSig = new ArrayList<String>(infos==null ? 0 : infos.length);
if(infos!=null) {
for(MBeanParameterInfo pinfo: infos) {
String className = pinfo.getType();
strSig.add(className);
if(Primitive.isPrimitiveName(className)) {
sig.add(Primitive.getPrimitive(className).getPclazz());
} else {
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (Exception e) {
clazz = UnknownClass.class;
}
sig.add(clazz);
}
}
}
signature = sig.toArray(new Class[sig.size()]);
strSignature = strSig.toArray(new String[strSig.size()]);
}
|
731a91fd-41d8-4736-a0a4-38077bf040d4
| 7
|
public void insert(Collidable c) {
if (nodes.get(0) != null) {
int index = getIndex(c);
if (index != -1) {
nodes.get(index).insert(c);
return;
}
}
stuff.add(c);
if (stuff.size() > MAX_OBJECTS && level < MAX_LEVELS) {
if (nodes.get(0) == null) {
split();
}
int i = 0;
while (i < stuff.size()) {
int index = getIndex(stuff.get(i));
if (index != -1) {
nodes.get(index).insert(stuff.remove(i));
} else {
i++;
}
}
}
}
|
2f8fc16f-59dd-4524-b59c-1bfa812f67fd
| 8
|
@Override
public boolean setHelm(Wearable helm) throws NoSuchItemException, WrongItemTypeException {
if (helm != null) {
if (helm instanceof Helm) {
if (helm.getLevelRequirement() > level || helm.getStrengthRequirement() > stats[0]
|| helm.getDexterityRequirement() > stats[1] || helm.getMagicRequirement() > stats[2]) {
return false;
}
if (inventory.remove(helm)) {
if (onPerson[0] != null) {
removeItem(0);
}
putOnItem(helm, 0);
return true;
} else {
throw new NoSuchItemException();
}
}
throw new WrongItemTypeException();
} else {
removeItem(0);
return true;
}
}
|
a86b306c-77f5-4b3a-b785-e4e8a9565a80
| 2
|
public void test_06() {
String seqStr[] = { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }; // Two almost equal sequences (first one is longer)
SuffixIndexerNmer<DnaSequence> seqIndex = new SuffixIndexerNmer<DnaSequence>(new DnaSubsequenceComparator<DnaSequence>(true, 0), NMER_SIZE);
for( int i = 0; i < seqStr.length; i++ ) {
DnaSequence bseq = new DnaSequence(seqStr[i]);
if( !seqIndex.overlap(bseq) ) seqIndex.add(bseq); // Add or overlap
}
assertEquals(seqStr[0], seqIndex.get(1).getSequence());
}
|
64d3a1c2-fbdf-4f15-b1ec-443afdd62340
| 4
|
public static void main(String[] args) {
SpiralIterator sp = new SpiralIterator();
int nums = 0, primes = 0;
while (true) {
nums++;
int n = sp.next();
if (isPrime(n)) {
primes++;
}
if (nums > 10 && primes * 1.0 / nums < 0.1) {
//One of the next 4 diagonals is going to be a perfect square... So why not print them all?
System.out.println(Math.sqrt(n));
System.out.println(Math.sqrt(sp.next()));
System.out.println(Math.sqrt(sp.next()));
System.out.println(Math.sqrt(sp.next()));
return;
}
}
}
|
fdc688a0-3abc-439c-b28d-3698e5c1fba2
| 8
|
public void readNeuron (LineNumberReader inputFile, boolean readInterConnections) {
String inputLine,paramString,toNetName;
StringTokenizer tokenizedLine;
int testID=-1;
double Weight = 0.0;
int toNeuronID = 0;
int axonsToRead=0;
Double tempDouble;
//read the neuron ID
try {
inputLine = inputFile.readLine();
tokenizedLine = new StringTokenizer(inputLine);
// System.out.println(inputLine);
paramString=tokenizedLine.nextToken();
testID = Integer.parseInt(paramString);
}
catch (IOException e) {
System.err.println("Bad Neuron Read" + e.toString());
System.exit(1);
}
//assert(testID == ID); // 8/12/02
//read the number of axons
try {
inputLine = inputFile.readLine();
tokenizedLine = new StringTokenizer(inputLine);
// System.out.println(inputLine);
paramString=tokenizedLine.nextToken();
axonsToRead = Integer.parseInt(paramString);
}
catch (IOException e) {
System.err.println("Bad Neuron Read Axon" + e.toString());
System.exit(1);
}
//read in the axons.
for (int cAxons = 0; cAxons < axonsToRead; cAxons++) {
try {
inputLine = inputFile.readLine();
tokenizedLine = new StringTokenizer(inputLine);
toNetName=tokenizedLine.nextToken();
if (parentNet.getName().compareTo(toNetName) != 0)
{
//System.out.println(testID + " " + toNetName + " " + parentNet.getName());
if (readInterConnections)
System.out.println("reading multiple nets not yet supported");
}
else {
paramString=tokenizedLine.nextToken();
toNeuronID = Integer.parseInt(paramString);
paramString=tokenizedLine.nextToken();
tempDouble = new Double(paramString);
Weight = tempDouble.doubleValue();
}
}
catch (IOException e) {
System.err.println("Bad Axon Read" + e.toString());
System.exit(1);
}
//set the inhibitory neural value based on the first value
if (cAxons == 0)
if (Weight < 0) isInhibitory = true;
else isInhibitory = false;
addConnection(parentNet.neurons[toNeuronID],Weight);
}
}
|
c0215950-9cd5-425c-9a5c-809419c27892
| 6
|
@Override
protected void paintSafely(Graphics g) {
super.paintSafely(g);
JTextComponent comp = getComponent();
if(fontOriginal==null){
fontOriginal=comp.getFont();
hintFont = new Font(fontOriginal.getName(), fontOriginal.getStyle() | Font.ITALIC, fontOriginal.getSize());
}
if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
if(color != null) {
g.setColor(color);
} else {
g.setColor(comp.getForeground().brighter().brighter().brighter());
}
int padding = (comp.getHeight() - comp.getFont().getSize())/2;
comp.setFont(hintFont);
g.drawString(hint, 8, comp.getHeight()-padding-1);
}else{
comp.setFont(fontOriginal);
}
}
|
d97013b3-2ed7-4266-acce-d8959830c7c5
| 4
|
public StructuredBlock prevCase(StructuredBlock block) {
for (int i = caseBlocks.length - 1; i >= 0; i--) {
if (caseBlocks[i].subBlock == block) {
for (i--; i >= 0; i--) {
if (caseBlocks[i].subBlock != null)
return caseBlocks[i].subBlock;
}
}
}
return null;
}
|
5480f942-1e41-4aa3-af2b-66619bb2a911
| 8
|
public double energy() {
double d = 0.0;
if (hasCharge_i && hasCharge_j)
d += cou_ij;
if (hasDipole_i && hasDipole_j)
d += dipoleDipoleEnergy();
if (hasCharge_i && hasDipole_j)
d += pjqi * rijuj;
if (hasDipole_i && hasCharge_j)
d += piqj * rijui;
return d * rCD;
}
|
c6351d93-a378-4996-a8e1-a3c58a56d94b
| 5
|
@Override
public void run() {
if (args.length == 2) {
try {
if (args[1].equalsIgnoreCase("all")) {
int j = 0;
ArrayList<String> cs = api.getCoupons();
for (String i : cs) {
api.removeCouponFromDatabase(i);
j++;
}
sender.sendMessage(ChatColor.GREEN+"A total of "+ChatColor.GOLD+j+ChatColor.GREEN+" coupons have been removed.");
return;
}
if (!api.couponExists(args[1])) {
sender.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return;
}
api.removeCouponFromDatabase(api.createNewItemCoupon(args[1], 0, -1, null, null));
sender.sendMessage(ChatColor.GREEN+"The coupon "+ChatColor.GOLD+args[1]+ChatColor.GREEN+" has been removed.");
return;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while removing coupon from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return;
}
} else {
sender.sendMessage(CommandUsage.C_REMOVE.toString());
return;
}
}
|
87d62e1b-e22f-46de-aceb-ae4be1c6f166
| 1
|
public ArrayList<User> getUsers() {
ArrayList<User> userList = new ArrayList<User>();
for(int i = 0; i < serviceList.size(); i++) {
userList.add(serviceList.get(i).getUser());
}
return userList;
}
|
877eb613-5136-43d8-bbd4-9cdbe539976e
| 6
|
@Override
public void connect() throws NotConnectedException, IOException,
AuthenticationNotSupportedException, FtpIOException,
FtpWorkflowException {
setConnectionStatusLock(FTPConnection.CSL_INDIRECT_CALL);
socketProvider = new SocketProvider();
try {
socketProvider.socket().setSoTimeout(getTimeout());
socketProvider.connect(getAddress(), getProxy(),
getDownloadBandwidth(), getUploadBandwidth());
log.debug("connected to:" + getAddress().getHostName() + ":"
+ getAddress().getPort());
socketProvider.socket().setKeepAlive(true);
} catch (IOException ioe) {
String error = "Error connection to:" + getAddress().getHostName() + ":"
+ getAddress().getPort();
log.error(error, ioe);
throw new NotConnectedException(error);
}
// Till here the connection is not encrypted!!
if (this.getConnectionType() == FTPConnection.IMPLICIT_SSL_FTP_CONNECTION
|| this.getConnectionType() == FTPConnection.IMPLICIT_TLS_FTP_CONNECTION
|| this.getConnectionType() == FTPConnection.IMPLICIT_SSL_WITH_CRYPTED_DATA_FTP_CONNECTION
|| this.getConnectionType() == FTPConnection.IMPLICIT_TLS_WITH_CRYPTED_DATA_FTP_CONNECTION) {
negotiateAndLogin(null);
} else {
Reply connectReply = ReplyWorker.readReply(this.socketProvider);
if (connectReply != null)
this.fireReplyMessageArrived(new FTPEvent(this, this.getConnectionStatus(), connectReply));
connectReply.dumpReply();
negotiateAndLogin(getAuthString());
}
checkFeatures();
this.setConnectionStatus(FTPConnection.CONNECTED);
this.setConnectionStatus(FTPConnection.IDLE);
checkSystem();
setConnectionStatusLock(FTPConnection.CSL_DIRECT_CALL);
}
|
48093db3-0701-43c0-9af7-d99c0a50ed42
| 0
|
@Override
public TKey getKey() {
return this._key;
}
|
42c4ed73-4f1c-4b9e-a606-46f3099785d0
| 8
|
* @param aspect der Aspekt
* @param usage die Verwendung der Attributgruppenverwendung
* @param isExplicitDefined gibt an, ob die Verwendung explizit vorgegeben sein muss
*
* @throws ConfigurationChangeException Falls der konfigurierende Datensatz nicht am Objekt gespeichert werden konnte.
*/
private void setAttributeGroupUsageProperties(
AttributeGroupUsage atgUsage, AttributeGroup attributeGroup, Aspect aspect, AttributeGroupUsage.Usage usage, boolean isExplicitDefined
) throws ConfigurationChangeException {
final AttributeGroup atg = _dataModel.getAttributeGroup("atg.attributgruppenVerwendung");
Data data = AttributeBaseValueDataFactory.createAdapter(atg, AttributeHelper.getAttributesValues(atg));
data.getReferenceValue("Attributgruppe").setSystemObject(attributeGroup);
data.getReferenceValue("Aspekt").setSystemObject(aspect);
// beim Import werden nur solche Attributgruppenverwendungen erstellt, die explizit in der Versorgungsdatei angegeben wurden
data.getUnscaledValue("VerwendungExplizitVorgegeben").set((isExplicitDefined ? 1 : 0));
int usageNumber;
switch(usage) {
case RequiredConfigurationData:
usageNumber = 1;
break;
case ChangeableRequiredConfigurationData:
usageNumber = 2;
break;
case OptionalConfigurationData:
usageNumber = 3;
break;
case ChangeableOptionalConfigurationData:
usageNumber = 4;
break;
case OnlineDataAsSourceReceiver:
usageNumber = 5;
break;
case OnlineDataAsSenderDrain:
usageNumber = 6;
break;
case OnlineDataAsSourceReceiverOrSenderDrain:
usageNumber = 7;
break;
default:
throw new IllegalStateException("Diese AttributgruppenVerwendung '" + usage + "' wird beim Import noch nicht unterstützt.");
}
data.getUnscaledValue("DatensatzVerwendung").set(usageNumber);
atgUsage.setConfigurationData(atg, data);
}
|
1df715a3-94c2-4df6-b213-4833d5047805
| 3
|
@Override
public void init(GameContainer gc) {
if(_spriteSheet == null) {
try {
_spriteSheet = new SpriteSheet("res/sprites/followers.png", 32, 32, new Color(160, 176, 128));
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
_animation = new Animation[4];
_animation[Direction.NORTH] = new Animation(_spriteSheet, 4, 0, 7, 0, true, 150, true);
_animation[Direction.EAST] = new Animation(_spriteSheet, 4, 3, 5, 3, true, 150, true);
_animation[Direction.SOUTH] = new Animation(_spriteSheet, 4, 1, 7, 1, true, 150, true);
_animation[Direction.WEST] = new Animation(_spriteSheet, 4, 2, 7, 2, true, 150, true);
for(int i = 0; i <= _animation.length - 1; i++) {
_animation[i].setPingPong(true);
_animation[i].setCurrentFrame(0);
}
_animation[facing].setAutoUpdate(true);
}
|
45bc58e8-4abc-416e-97ef-244d5f8edd19
| 6
|
public void dumpSource(TabbedPrintWriter writer) throws java.io.IOException {
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_LOCALS) != 0) {
if (declare != null)
writer.println("declaring: " + declare);
if (done != null)
writer.println("done: " + done);
writer.println("using: " + used);
}
if (declare != null) {
Iterator iter = declare.iterator();
while (iter.hasNext()) {
Declarable decl = (Declarable) iter.next();
decl.dumpDeclaration(writer);
writer.println(";");
}
}
dumpInstruction(writer);
if (jump != null)
jump.dumpSource(writer);
}
|
bdc7637b-5f0b-4d16-a7d4-2e2045a76429
| 6
|
private List<String> scanLocal(File file) {
List<String> messages = new ArrayList<String>();
InputStream stream = null;
BufferedReader reader = null;
String line;
try {
stream = new FileInputStream(file);
reader = new BufferedReader(
new InputStreamReader(stream));
while ((line = reader.readLine()) != null) {
messages.add(line);
}
} catch (IOException e) {
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return messages;
}
|
21e762b5-a480-461d-8905-f5a12c7f26cc
| 1
|
public void connectDb() {
startSQL();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
|
ae26e9e3-ecd2-4c48-a60c-a7d2a7ea9979
| 5
|
@EventHandler
public void OnPlayerDeath(PlayerDeathEvent event)
{
if (plugin.GameStarted == true)
{
Player p = event.getEntity();
if (plugin.sbHandler.goodTeam.getPlayers().size() >= 1)
{
if (plugin.sbHandler.goodTeam.hasPlayer(p))
{
for(String str : plugin.PlayersInGame){
Bukkit.getPlayer(str).sendMessage("A good guy has been killed!");
}
plugin.sbHandler.goodTeam.removePlayer(p);
plugin.sbHandler.badTeam.addPlayer(p);
if (plugin.sbHandler.goodTeam.getPlayers().size() == 0)
{
GameEndEvent e = new GameEndEvent(plugin.PlayersInGame);
plugin.getServer().getPluginManager().callEvent(e);
}
}
}
else
{
GameEndEvent e = new GameEndEvent(plugin.PlayersInGame);
plugin.getServer().getPluginManager().callEvent(e);
}
}
}
|
200edf33-3569-4afd-bd80-aa946bb4c671
| 4
|
public static void sqlQuery(String csvName,String characterSet,String valSeparator,String strSql)
{
Logger logger = Logger.getLogger(ProcessData.class);
try
{
logger.info("Main Start");
String currentPath = System.getProperty("user.dir");
logger.info("GET Porperties File:\"" + currentPath + File.separator + "configdb.properties\"");
logger.debug("Call: ComJdbc.connection Start");
ComJdbc.connection( currentPath + File.separator + "configdb.properties");
logger.debug("Call: ComJdbc.connection End");
// logger.info("Get Sql From :" + currentPath + File.separator + "selectSql.ddl " + "Start");
//
// ConfigGetDb getsql = new ConfigGetDb(currentPath + File.separator + "selectSql.ddl");
//
// String strSql = getsql.execSql;
logger.info("Exec Query Sql :\"" + strSql + "\"");
logger.debug("Call : ComJdbc.execQuery() Start");
ResultSet rs = ComJdbc.execQuery(strSql);
logger.debug("Call : ComJdbc.execQuery() End");
ResultSetMetaData metaDate = rs.getMetaData();
int columnCount = metaDate.getColumnCount();
logger.info("Geted The Table Number Of Columns :" + columnCount);
List exportData = new ArrayList();
Map row1 = null;
while (rs.next())
{
row1 = new LinkedHashMap();
for (int i = 1; i <= columnCount; i++)
{
row1.put(new Integer(i), rs.getString(i));
}
exportData.add(row1);
}
LinkedHashMap map = new LinkedHashMap();
for (int i = 1; i <= columnCount; i++)
{
map.put(new Integer(i), metaDate.getColumnName(i));
}
logger.info("Exec Query End");
logger.info("Call createCSVFile Start");
CsvUtil.createCSVFile(exportData, map, currentPath + File.separator, csvName,valSeparator,characterSet);
logger.info("Call createCSVFile End");
SuccessFrame sf = new SuccessFrame();
sf.setTitle("Successful!");
sf.setDefaultCloseOperation(SuccessFrame.EXIT_ON_CLOSE);
sf.getContentPane().setPreferredSize(null);
sf.setLocationRelativeTo(null);
sf.pack();
sf.setVisible(true);
} catch (SQLException e)
{
SqlErrorFrame sef = new SqlErrorFrame();
sef.setDefaultCloseOperation(SqlErrorFrame.EXIT_ON_CLOSE);
sef.getContentPane().setPreferredSize(null);
sef.pack();
sef.setLocationRelativeTo(null);
sef.setVisible(true);
logger.fatal(e);
e.printStackTrace();
} finally
{
ComJdbc.close();
}
}
|
f5b80d64-eca0-40cf-a8d5-e9532d1b35ce
| 0
|
public int size() {
return this.list.size();
}
|
799e1147-4112-4379-8ec1-459b0293a904
| 2
|
public void guardar() {
try {
if (!fichero.contains(".chp")) {
fichero = fichero + ".chp";
}
FileOutputStream fs = new FileOutputStream(fichero);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(principal);
os.close();
principal.guardado = true;
} catch (HeadlessException | IOException e) {
JOptionPane.showMessageDialog(null,
"Error al guardar el archivo",
"Aviso",
JOptionPane.ERROR_MESSAGE);
}
}
|
d58fb351-1d42-4e33-9e88-a3b17fe4dee8
| 6
|
private void ReadData() throws Exception
{
//As an exception could occur in the loading process, an exception handler is used.
String key="", value="";
try
{
Scanner sc;
InputStream stream = getClass().getClassLoader().getResourceAsStream(this._exceptionFileName);
if (stream != null) {
sc = new Scanner(stream);
} else {
sc = new Scanner(new File("dist/PhoneticTranscriber/" + this._exceptionFileName));
}
while (sc.hasNext())
{
key=sc.next();
if(key.contains("_"))
{
throw new Exception("Invalid key - "+key);
}
value=sc.next();
if (key!="" && key!="\0")
{
_exceptions.Insert(key, value);
}
}
sc.close();
}
catch(Exception e)
{
throw new Exception(e.getMessage());
}
}
|
dde0ba4d-051e-436b-8c25-92f561823e7d
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.idUsuario == null && other.idUsuario != null) || (this.idUsuario != null && !this.idUsuario.equals(other.idUsuario))) {
return false;
}
return true;
}
|
19cfb3f2-79e1-45ba-a5a2-d65aea4c011e
| 2
|
public int getInt(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number ? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not an int.");
}
}
|
ec17da21-781c-4537-89bd-4a53050ac0f2
| 2
|
private void checkState() {
if (!start) {
throw new IllegalStateException(
"Cannot visit member before visit has been called.");
}
if (end) {
throw new IllegalStateException(
"Cannot visit member after visitEnd has been called.");
}
}
|
69ff6faf-610f-4848-8679-fc09b0805876
| 3
|
public EnumRemoteScriptErrorType isBuildFileValid() throws Throwable
{
List<String> lines = Files.readAllLines(Paths.get(new File("build.hoppix").toURI()), Charsets.ISO_8859_1);
String line = lines.get(0);
if (line.startsWith("error"))
{
int indexOfSeparator = line.indexOf("|");
String errorMsg = line.substring(0, indexOfSeparator).trim();
switch (errorMsg)
{
case "error.FileNotFound":
return EnumRemoteScriptErrorType.FILE_NOT_FOUND;
case "error.AccessDenied":
return EnumRemoteScriptErrorType.ACCESS_DENIED;
default:
return EnumRemoteScriptErrorType.UNKNOWN_ERROR;
}
}
return null;
}
|
69c9f1de-f8b4-45fc-801d-8c7edddd9fc1
| 3
|
@Override
public void deserialize(Buffer buf) {
super.deserialize(buf);
int limit = buf.readUShort();
spellCooldowns = new GameFightSpellCooldown[limit];
for (int i = 0; i < limit; i++) {
spellCooldowns[i] = new GameFightSpellCooldown();
spellCooldowns[i].deserialize(buf);
}
summonCount = buf.readByte();
if (summonCount < 0)
throw new RuntimeException("Forbidden value on summonCount = " + summonCount + ", it doesn't respect the following condition : summonCount < 0");
bombCount = buf.readByte();
if (bombCount < 0)
throw new RuntimeException("Forbidden value on bombCount = " + bombCount + ", it doesn't respect the following condition : bombCount < 0");
}
|
0946a13b-20a6-405c-95b0-94418fbb6273
| 3
|
private void _getLock() throws WriterException {
try {
this.file = new RandomAccessFile(ConfigurationManager.read.getConfigFile(), "rw");
this.channel = this.file.getChannel();
try {
this.lock = this.channel.tryLock();
} catch (OverlappingFileLockException e) {
throw new WriterException(lockException);
}
} catch (FileNotFoundException e) {
throw new WriterException("Configuration file was not found at provided location");
} catch (IOException e) {
throw new WriterException(e.getMessage());
}
}
|
8cce013f-f38d-48c0-ab57-e70e7a4af9b5
| 7
|
public double getMeanofDuration(RequestType type)
{
long sum = 0;
int cnt = 0;
switch (type) {
case ONDEMAND:
for(OndemandRequest on: getOndemand())
{
long duration=on.getDuration();
sum+=duration;
cnt++;
}
break;
case SPOT:
for(SpotRequest on: getSpot())
{
long duration=on.getDuration();
sum+=duration;
cnt++;
}
break;
case RESERVED:
for(ReservedRequest on: getReserved())
{
long duration=on.getDuration();
sum+=duration;
cnt++;
}
break;
}
if (cnt > 0)
return sum / (double) cnt;
return -1;
}
|
0e39fd8d-a547-463e-aeef-22624755206b
| 5
|
final public Value getValue() throws ParseException {
Attribute.Type type;
String val;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case INT_LITERAL:
jj_consume_token(INT_LITERAL);
type = Attribute.Type.INT;
val = token.image;
break;
case DECIMAL_LITERAL:
jj_consume_token(DECIMAL_LITERAL);
type = Attribute.Type.DECIMAL;
val = token.image;
break;
case STRING_LITERAL:
jj_consume_token(STRING_LITERAL);
type = Attribute.Type.CHAR;
val = token.image;
break;
default:
jj_la1[20] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return new Value(type, val);}
throw new Error("Missing return statement in function");
}
|
be46beec-fc4a-4bef-bce2-4f7c66a6f5ca
| 0
|
@Override
public void startSetup(Attributes atts) {
Outliner.menuBar = this;
Outliner.outliner.setJMenuBar(this);
}
|
2b16d26e-bdbc-47ab-92b3-0ae879749461
| 9
|
static public int[] InitialSolutionFromFile(int noOfPeaks, int noOfAA){
int[] initialSol= new int[noOfAA+1];
boolean[] aaCheck= new boolean[noOfAA+1];
try {
BufferedReader br_solution;
br_solution = new BufferedReader(new FileReader("initialsolution.txt"));
for(int i=1;i<=noOfPeaks;i++){
String Line_solution = br_solution.readLine();
String[] values_solution = Line_solution.split(" ");
int peak= Integer.parseInt(values_solution[0]);
int aa=Integer.parseInt(values_solution[1]);
initialSol[peak]=aa;
//System.out.println("initialSol"+initialSol[peak]+" "+aa);
}
br_solution.close();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(noOfAA>noOfPeaks){
for(int i=1;i<=noOfPeaks;i++){
aaCheck[initialSol[i]]=true;
}
}
if(noOfAA>noOfPeaks){
int temp=1;
for(int i=1;i<=noOfAA;i++){
if(!aaCheck[i]){
initialSol[noOfPeaks+temp]=i;
temp++;
}
}
}
//System.out.println("the aa assigned to peak 53: "+initialSol[53]+"and it is "+aaCheck[initialSol[53]]);
/*System.out.println("=================");
for(int i=1;i<=noOfAA;i++){
if(!aaCheck[i]){
System.out.println(aaCheck[i]);
initialSol[i+noOfPeaks]=i;
}
}*/
return initialSol;
}
|
0f958c32-3d5b-4636-9c31-202de022ae23
| 1
|
@SuppressWarnings("deprecation")
public synchronized void flush(String tableName) throws IOException {
HTableInterface hTable = tablePool.getTable(tableName);
try {
hTable.flushCommits();
} finally {
if (hTable != null) {
tablePool.putTable(hTable);
}
}
}
|
63ca0f35-73ca-43a8-8e30-d5ea22eca409
| 2
|
@Override
public void itemStateChanged(ItemEvent event) {
Object object = event.getSource();
if (object == portComboBox) {
portComboBox_itemStateChanged(event);
}
else if (object == baudComboBox) {
baudComboBox_itemStateChanged(event);
}
sendText.requestFocus();
}
|
0291c174-cfa6-4bcd-be3b-f47215472190
| 7
|
public ArrayList<String> letterCombinations(String digits) {
String[] digitalMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ArrayList<String> result = new ArrayList<String>();
if (digits.length() == 0) {
result.add("");
return result;
}
if (digits.charAt(0) == '0' || digits.charAt(0) == '1') {
return letterCombinations(digits.substring(1));
}
if (digits.length() == 1) {
for (char c : digitalMap[digits.charAt(0) - '0'].toCharArray()) {
result.add(c + "");
}
return result;
}
for (char c : digitalMap[digits.charAt(0) - '0'].toCharArray()) {
for (String s : letterCombinations(digits.substring(1))) {
result.add(c + s);
}
}
return result;
}
|
ef73f3ee-4328-4d40-8ed5-cca1c837bcd0
| 3
|
public static final long hash(byte[] b, long m) {
long h = 1125899906842597L; // prime
for (int i = 0; i < b.length; i++) h = 31*h + b[i];
return (h & 0x7fffffffffffffffL) % (m > 0 && m < p ? m : p);
}
|
ca4618bd-6e77-462d-864a-314808b06f40
| 3
|
public void run()
{
try
{
this.MPrio.acquire();
this.MReading.acquire();
if(this.counter == 0)
this.MWriting.acquire();
this.counter++;
this.MReading.release();
System.out.println("Lecture");
Thread.sleep(100);
this.MReading.acquire();
this.counter--;
if(this.counter == 0)
this.MWriting.release();
this.MReading.release();
this.MPrio.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
|
cda53385-f230-4218-90d2-124101a16095
| 8
|
public static void readFile(String filePath) {
int lineFlag = 0;
int caseCounter = 0;
int vectorLength = 0;
try {
FileInputStream fstream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String[] strVector1 = null;
String[] strVector2 = null;
while ((strLine = br.readLine()) != null) {
if (noOfCases == 0) {
noOfCases = Integer.parseInt(strLine);
} else if (lineFlag == 0) {
vectorLength = Integer.parseInt(strLine);
lineFlag = 1;
} else if (lineFlag == 1) {
strVector1 = strLine.split(" ");
vector1 = new int[strVector1.length];
for (int i = 0; i < strVector1.length; i++) {
vector1[i] = Integer.parseInt(strVector1[i]);
}
lineFlag = 2;
caseCounter++;
} else if (lineFlag == 2) {
strVector2 = strLine.split(" ");
vector2 = new int[strVector2.length];
for (int i = 0; i < strVector2.length; i++) {
vector2[i] = Integer.parseInt(strVector2[i]);
}
lineFlag = 0;
solve(vector1, vector2, caseCounter, vectorLength);
}
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
|
fc2d035c-df66-4bbe-b463-aa92eb771191
| 3
|
public static void putf(String format, Object... items) {
if (format == null)
throw new IllegalArgumentException("Null format string in TextIO.putf() method.");
try {
out.printf(format,items);
}
catch (IllegalFormatException e) {
throw new IllegalArgumentException("Illegal format string in TextIO.putf() method.");
}
out.flush();
if (out.checkError())
outputError("Error while writing output.");
}
|
370e38fa-463a-4e5b-9923-6474c7cd666f
| 9
|
void performTest(int mask, boolean watchSubtree, ArrayList<Command> commands,
ArrayList<Event> expectedEvents) throws IOException
{
System.out.println("JUnit : -------------- performTest -------------- :");
String rootDir = "$$$_TEST_$$$/";
File testRoot = new File(rootDir).getAbsoluteFile();
// make sure the dir is empty.
deleteDirectory(testRoot);
testRoot.mkdirs();
int wd2 = -1;
try
{
final ArrayList<Event> actualEvents = new ArrayList<Event>();
wd2 = JNotify.addWatch(testRoot.getName(), mask, watchSubtree, createListener(actualEvents));
// sleep(500);
System.out.println("JUnit : Executing commands...");
for (int i = 0; i < commands.size(); i++)
{
Command command = commands.get(i);
try
{
System.out.println("JUnit : Action " + command);
boolean perform = command.perform(testRoot);
assertTrue("Error performing command " + command, perform);
}
catch (IOException e)
{
System.out.println("JUnit : Error performing:");
System.out.println(command);
e.printStackTrace();
throw e;
}
}
System.out.println("JUnit : Done, waiting for events to settle...");
sleep(1000);
System.out.println("JUnit : Done, analyzing events");
int expectedIndex = 0, actualIndex = 0;
for (; expectedIndex < expectedEvents.size();)
{
Event expected = expectedEvents.get(expectedIndex);
Event actual = actualEvents.get(actualIndex);
// On windows, the sysetm sends both modified and deleted
// in response to file deletion or file rename.
// skip modified.
if (_isWindows && (expected.isDeleted() || expected.isRenamed()) && actual.isModified())
{
// skip actual event
actualIndex++;
continue;
}
actualIndex++;
expectedIndex++;
assertMatch(expected, actual);
}
}
catch (Error e)
{
e.printStackTrace();
throw e;
}
finally
{
System.out.println("JUnit : Removing watch " + wd2);
boolean res = JNotify.removeWatch(wd2);
//sleep(500000); // hack
if (!res)
{
System.out.println("JUnit: Warning, failed to remove watch");
}
System.out.println("JUnit : Deleting directory " + testRoot);
deleteDirectory(testRoot);
}
}
|
3ef7f9a7-6612-406a-b6ba-af51f433edba
| 7
|
public static String encrypt(String input, String key){
int inputLength = input.length();
char[] out = new char[inputLength];
int code = key.hashCode();
Character[] mapping = randomizeArray(getMasterMapping(), code);
for(int i = 0; i < inputLength; i++){
char x = input.charAt(i);
if(x < 32 && x != 9 && x != 10 || x > 255 || x > 126 && x < 160){
throw new IllegalArgumentException("Illegal Input Character " + (int)x);
}
int y = convert(x);
char z = mapping[y];
out[i] = z;
}
return new String(out);
}
|
1b17ad29-2ec8-483c-9f18-d8cf753290f4
| 3
|
public void resetTableau (){
for (int i=0; i<this.getRowCount()+hauteurZoneFantome;i++){
for (int j=0;j<this.getColumnCount(); j++){
images[i][j]=frame;
if (i>=hauteurZoneFantome){
this.setValueAt(images[i][j], i-hauteurZoneFantome, j);
}
}
}
}
|
282e101e-3adb-4da2-8417-b576518fbdc9
| 9
|
private void temporalProcessing(){
System.out.println("Rate of non null results: " + pitches.length/nonNullPitches);
System.out.println("Results under examination: " + postModeNotes.length);
System.out.println("Pitch per Second: " + (float) (AudioData.SAMPLE_RATE/(pitches.length/pitchSampleGroup.length)));
System.out.println("Audio Length: " + ((float) postDetect.getNumberOfSamples())/ ((float) AudioData.SAMPLE_RATE) + " seconds");
//reusing the sample array from the previous methods
pitchSampleGroup = new double[10];
double timeRecorder = 0;
double changeNoteTime = 0;
Note changeNote = new Note("A2");//this is an arbitrary starting point, I'll need to change this
Note finalNote;
Note currentNote = postModeNotes[0];
finalGenerationNotes = new Note[noteTimer.length];
int a = 0;//the index counter for final generation notes.
for(int i = 0; i < noteTimer.length; i++){//calculation of time each note should be played for
if(postModeNotes[i]==(null)){//end of viable notes
break;
}
if(postModeNotes[i].getPitch().equals(currentNote.getPitch()))//if the note at i is the same as the currently selected note
{
timeRecorder+= noteTimer[i];
}
else if(postModeNotes[i].getPitch().equals(changeNote.getPitch()))
{
changeNoteTime += noteTimer[i];
timeRecorder += noteTimer[i];
if(changeNoteTime > 0.2){//this number represents the cut off for a pitches representation
System.out.println("adding new final Note: " + currentNote);
System.out.println("final note time: " + timeRecorder);
finalNote = currentNote;
finalNote.setTime(timeRecorder);
finalGenerationNotes[a] = finalNote;
a++;
timeRecorder = noteTimer[i];
currentNote = changeNote;
changeNote = new Note("A2");
changeNoteTime = 0;
}
} else {
changeNote = postModeNotes[i];
changeNoteTime = noteTimer[i];
timeRecorder += noteTimer[i];
}
}
System.out.println("adding new final Note: " + currentNote);
finalNote = currentNote;
finalNote.setTime(timeRecorder);
finalGenerationNotes[a] = finalNote;
int i = 0;
System.out.println("");
while(finalGenerationNotes[i]!= null){
System.out.print("Pitch: " + finalGenerationNotes[i].getPitch() + ", ");
System.out.println("Duration: " + finalGenerationNotes[i].getTime() + " seconds");
i++;
}
synth = new SynthModule();
int s = 0;
int t = 0;
for(int j = 0; i < postModeNotes.length; i++){
if(postModeNotes[j] != null){
s++;
}
if(finalGenerationNotes[j]!= null){
t++;
}
}
System.out.println("average notes: " + s);
System.out.println("Final Generation Notes: " + t);
System.out.println("Pitches: " + pitches.length);
synthFile = synth.generateChords(scale, finalGenerationNotes, postDetect.getFileName());
System.out.println("I got here!");
WavHandler combiner = new WavHandler();
combiner.wavCombiner(synthFile, inputFile);
}
|
93d154b6-5370-4fa2-bdb2-c6183799282b
| 0
|
@Override
public String toString() {
return getDescription();
}
|
2d89c8c4-3268-4a9f-8486-787aaddc4627
| 7
|
private void wordSelectHandler(Page currentPage, Point mouseLocation) {
if (currentPage != null &&
currentPage.isInitiated()) {
// get page text
PageText pageText = currentPage.getViewText();
if (pageText != null) {
// clear the currently selected state, ignore highlighted.
currentPage.getViewText().clearSelected();
// get page transform, same for all calculations
AffineTransform pageTransform = currentPage.getPageTransform(
Page.BOUNDARY_CROPBOX,
documentViewModel.getViewRotation(),
documentViewModel.getViewZoom());
Point2D.Float pageMouseLocation =
convertMouseToPageSpace(mouseLocation, pageTransform);
ArrayList<LineText> pageLines = pageText.getPageLines();
for (LineText pageLine : pageLines) {
// check for containment, if so break into words.
if (pageLine.getBounds().contains(pageMouseLocation)) {
pageLine.setHasSelected(true);
ArrayList<WordText> lineWords = pageLine.getWords();
for (WordText word : lineWords) {
// if (word.contains(pageTransform, mouseLocation)) {
if (word.getBounds().contains(pageMouseLocation)) {
word.selectAll();
pageViewComponent.repaint();
break;
}
}
}
}
}
}
}
|
8e1f80fd-3b51-47f1-9f66-227f5e7618ea
| 1
|
public void addAccount(BankAccount account) throws IllegalArgumentException {
if (! canHaveAsAccount(account))
throw new IllegalArgumentException();
accounts.add(account);
}
|
b570e3d6-3a41-4bf2-b9d2-f6cf589ea0f4
| 3
|
public void randomDeck(ArrayList<Card> cards) {
Random r = new Random();
r.setSeed(System.currentTimeMillis());
do {
int numLands = r.nextInt(15) + 15;
for (int i = 0; i < (60 - numLands)/4; i++){
Card c = cards.remove(r.nextInt(cards.size() - 1));
for(int j = 0; j < 4; j++)
this.cardList.add(c);
}
this.addBasicLands();
} while (!this.isValid());
}
|
e2f63fb8-f9e7-4a46-9f85-6a1062ad1544
| 2
|
public void getInitialLocation(SensorInterface si) {
if (si == null) {
return;
}
if (!hasSentInitialLocation) {
hasSentInitialLocation = true;
si.startingXCoord = floorPlan.getInitialX();
si.startingYCoord = floorPlan.getInitialY();
} else {
si.startingXCoord = Integer.MAX_VALUE;
si.startingYCoord = Integer.MAX_VALUE;
}
}
|
c3517744-ddd7-459f-9dd5-9e9c9f986d07
| 8
|
public static long to_long(String aString) {
if (aString.equalsIgnoreCase("")) {
// Default noDataValue
return Long.MIN_VALUE;
}
try {
return new BigInteger(aString).longValue();
} catch (NumberFormatException aNumberFormatException) {
String[] aStringSplit = null;
if (aString.contains("e".subSequence(0, 1))) {
aStringSplit = aString.split("e");
}
if (aString.contains("E".subSequence(0, 1))) {
aStringSplit = aString.split("E");
}
boolean isNegative = false;
if (aStringSplit[1].startsWith("-")) {
isNegative = true;
aStringSplit[1] = aStringSplit[1].substring(1, aStringSplit[1].length());
} else {
if (aStringSplit[1].startsWith("+")) {
aStringSplit[1] = aStringSplit[1].substring(1,
aStringSplit[1].length());
}
}
while (aStringSplit[1].startsWith("0")) {
aStringSplit[1] = aStringSplit[1].substring(1, aStringSplit[1].length());
}
int power = to_int(aStringSplit[1]);
if (isNegative) {
power = power * -1;
}
BigDecimal aBigDecimal = new BigDecimal(aStringSplit[0]).multiply(BigDecimal.TEN.pow(power));
return aBigDecimal.longValue();
}
}
|
bb04fb43-46ca-4568-ae4a-a4202e3c2a3e
| 6
|
public TestInfo runInTheCloud(String userKey, String testId) {
TestInfo testInfo = null;
String error = null;
if (userKey == null || userKey.trim().isEmpty()) {
error = "Test cannot be started in the cloud, userKey is empty";
BmLog.debug(error);
testInfo = new TestInfo();
testInfo.setError(error);
return testInfo;
}
if (testId == null || testId.trim().isEmpty()) {
error = "Test cannot be started in the cloud, testId is empty";
BmLog.debug(error);
testInfo = new TestInfo();
testInfo.setError(error);
return testInfo;
}
String url = this.urlManager.testStart(Constants.APP_KEY, userKey, testId);
JSONObject jo = getJson(Methods.POST, url, null);
testInfo = TestInfoProcessor.parseTestInfo(jo);
try {
testInfo.setStatus(jo.getInt("response_code") == 200 ? TestStatus.Running : TestStatus.NotRunning);
} catch (JSONException je) {
BmLog.debug("Failed to set test status: " + je.getMessage());
}
return testInfo;
}
|
6fae3fc5-2779-422e-8a87-388741332d08
| 1
|
public List<String> getArgs(){
ArrayList<String> args = new ArrayList<String>();
for (int i = 1; i < command.size(); i++)
args.add(command.get(i));
return args;
}
|
adb7683e-1a5c-4268-affe-e846063d4cbd
| 8
|
private void cftrec4_th(final int n, final float[] a, final int offa, final int nw, final float[] w) {
int idiv4, m, nthread;
int idx = 0;
nthread = 2;
idiv4 = 0;
m = n >> 1;
if (n > ConcurrencyUtils.getThreadsBeginN_1D_FFT_4Threads()) {
nthread = 4;
idiv4 = 1;
m >>= 1;
}
Future<?>[] futures = new Future[nthread];
final int mf = m;
for (int i = 0; i < nthread; i++) {
final int firstIdx = offa + i * m;
if (i != idiv4) {
futures[idx++] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
int isplt, k, m;
int idx1 = firstIdx + mf;
m = n;
while (m > 512) {
m >>= 2;
cftmdl1(m, a, idx1 - m, w, nw - (m >> 1));
}
cftleaf(m, 1, a, idx1 - m, nw, w);
k = 0;
int idx2 = firstIdx - m;
for (int j = mf - m; j > 0; j -= m) {
k++;
isplt = cfttree(m, j, k, a, firstIdx, nw, w);
cftleaf(m, isplt, a, idx2 + j, nw, w);
}
}
});
} else {
futures[idx++] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
int isplt, k, m;
int idx1 = firstIdx + mf;
k = 1;
m = n;
while (m > 512) {
m >>= 2;
k <<= 2;
cftmdl2(m, a, idx1 - m, w, nw - m);
}
cftleaf(m, 0, a, idx1 - m, nw, w);
k >>= 1;
int idx2 = firstIdx - m;
for (int j = mf - m; j > 0; j -= m) {
k++;
isplt = cfttree(m, j, k, a, firstIdx, nw, w);
cftleaf(m, isplt, a, idx2 + j, nw, w);
}
}
});
}
}
ConcurrencyUtils.waitForCompletion(futures);
}
|
e7f1b0c3-891a-42c6-8f61-a4a128b57895
| 9
|
private void processCyclisedChain(Element chainGroup, Element cycloEl) throws ComponentGenerationException {
String smiles=chainGroup.getAttributeValue(VALUE_ATR);
int chainlen =0;
for (int i = smiles.length() -1 ; i >=0; i--) {
if (Character.isUpperCase(smiles.charAt(i)) && smiles.charAt(i) !='H'){
chainlen++;
}
}
if (chainlen < 3){
throw new ComponentGenerationException("Heteroatom chain too small to create a ring: " + chainlen);
}
smiles+="1";
if (smiles.charAt(0)=='['){
int closeBracketIndex = smiles.indexOf(']');
smiles= smiles.substring(0, closeBracketIndex +1) +"1" + smiles.substring(closeBracketIndex +1);
}
else{
if (Character.getType(smiles.charAt(1)) == Character.LOWERCASE_LETTER){//element is 2 letters long
smiles= smiles.substring(0,2) +"1" + smiles.substring(2);
}
else{
smiles= smiles.substring(0,1) +"1" + smiles.substring(1);
}
}
chainGroup.getAttribute(VALUE_ATR).setValue(smiles);
if (chainlen==6){//6 membered rings have ortho/meta/para positions
if (chainGroup.getAttribute(LABELS_ATR)!=null){
chainGroup.getAttribute(LABELS_ATR).setValue("1/2,ortho/3,meta/4,para/5/6");
}
else{
chainGroup.addAttribute(new Attribute(LABELS_ATR, "1/2,ortho/3,meta/4,para/5/6"));
}
}
chainGroup.getAttribute(TYPE_ATR).setValue(RING_TYPE_VAL);
if (chainGroup.getAttribute(USABLEASJOINER_ATR) !=null){
chainGroup.removeAttribute(chainGroup.getAttribute(USABLEASJOINER_ATR));
}
cycloEl.detach();
}
|
2f8b933d-1dec-410a-9f65-779bf51b3715
| 8
|
public void put(String atrName, Object val) {
if (atrName.equals(LABEL)) {
g.setLabel((String) val);
} else if (atrName.equals(ZOOM)) {
g.setZoom((ArrayX<String>) val);
} else if (atrName.equals(FONT)) {
g.setFont((Font) val);
} else if (atrName.equals(DRAW_VERTEX_LABELS)) {
g.setDrawVertexLabels((Boolean) val);
} else if (atrName.equals(IS_EDGES_CURVED)) {
g.setIsEdgesCurved((Boolean) val);
} else if (atrName.equals(BACKGROUND_IMAGE)) {
g.setBackgroundImageFile((File) val);
} else if (atrName.equals(Allow_Loops)) {
g.setAllowLoops((Boolean) val);
} else if (atrName.equals(DRAW_EDGE_LABELS)) {
g.setDrawEdgeLabels((Boolean) val);
} else {
g.setUserDefinedAttribute(atrName, val);
}
}
|
5fafe750-ba43-4d66-9d03-c2e3fd7cffb5
| 3
|
public void run() {
if (Fenetre._list_birds.size() != 0)
Fenetre._fenster.changeBird(Fenetre._list_birds.get(0));
while (Fenetre._state == StateFen.Level) {
this.printObj();
try {
Thread.sleep(_REFRESH_AFF);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
db93a24a-ca08-460f-a893-ad493bf35572
| 4
|
public void mouseClicked(MouseEvent me) {
int clickCount = me.getClickCount();
int button = me.getButton();
if (popup != null) {
popup.setVisible(false);
if (clickCount == 2) {
if (journals != null) AccountDetails.getAccountDetails(selectedAccount, journals, journalInputGUI);
} else if (button == 3) {
Point location = me.getLocationOnScreen();
popup.show(null, location.x, location.y);
}
}
}
|
9da56008-f82a-455c-8bd6-4ebce3c8e5ed
| 5
|
private static double[] getSupportPoints(int lineNumber, double[] lowPrices) {
double[] sPoints = new double[lineNumber];
for(int i =0;i<lineNumber-1;i++){
double price = 999999999;
for(int j=-5;j<=0;j++){
if((i+j>=0) && (i+j<lineNumber-1) && lowPrices[i+j]<price){
price =lowPrices[i+j];
sPoints[i]=price;
}
}
}
return sPoints;
}
|
142f968a-2b8f-42b0-9e0d-bee99f32b6ea
| 8
|
@Test
public void removeAt() {
RandomAccessDoubleLinkedList test = new RandomAccessDoubleLinkedList();
try {
test.removeAt(2); // empty list
fail("ValueException");
} catch (InvalidAccessException e) {
} catch (Exception e) {
fail("Unexpected Exception");
}
try {
test.insertAt(2, 3);
test.insertAt(7, 2);
test.insertAt(5, 3);
} catch (Exception e) {
fail("Unexpected Exception");
}
try {
assertEquals(false, test.removeAt(-2)); // index smaller than 1 is
// not
fail("InvalidAccessException");
} catch (InvalidAccessException e) {
// possible
} catch (Exception e) {
fail("Unexpected Exception");
}
try {
assertEquals(false, test.removeAt(8));
fail("InvaidAccessExeption"); // index bigger than list is not
} catch (InvalidAccessException e) {
} catch (Exception e) {
fail("Unexpected Exception");
}
try { // possible
assertEquals(true, test.removeAt(7));
assertEquals(true, test.removeAt(2));
assertEquals(true, test.removeAt(5));
assertEquals(true, test.removeAt(4));
} catch (Exception E) {
fail("Unexpected Exception");
}
}
|
1c6690ec-4069-4a45-bcb4-a7d20d400a8e
| 7
|
public void RSAEncrypt(int length, int modulus_size)
throws RdesktopException {
byte[] inr = new byte[length];
// int outlength = 0;
BigInteger mod = null;
BigInteger exp = null;
BigInteger x = null;
this.reverse(this.exponent);
this.reverse(this.modulus);
System.arraycopy(this.client_random, 0, inr, 0, length);
this.reverse(inr);
if ((this.modulus[0] & 0x80) != 0) {
byte[] temp = new byte[this.modulus.length + 1];
System.arraycopy(this.modulus, 0, temp, 1, this.modulus.length);
temp[0] = 0;
mod = new BigInteger(temp);
} else {
mod = new BigInteger(this.modulus);
}
if ((this.exponent[0] & 0x80) != 0) {
byte[] temp = new byte[this.exponent.length + 1];
System.arraycopy(this.exponent, 0, temp, 1, this.exponent.length);
temp[0] = 0;
exp = new BigInteger(temp);
} else {
exp = new BigInteger(this.exponent);
}
if ((inr[0] & 0x80) != 0) {
byte[] temp = new byte[inr.length + 1];
System.arraycopy(inr, 0, temp, 1, inr.length);
temp[0] = 0;
x = new BigInteger(temp);
} else {
x = new BigInteger(inr);
}
BigInteger y = x.modPow(exp, mod);
this.sec_crypted_random = y.toByteArray();
if ((this.sec_crypted_random[0] & 0x80) != 0) {
throw new RdesktopException(
"Wrong Sign! Expected positive Integer!");
}
if (this.sec_crypted_random.length > SEC_MAX_MODULUS_SIZE) {
logger.warn("sec_crypted_random too big!"); /* FIXME */
}
this.reverse(this.sec_crypted_random);
byte[] temp = new byte[SEC_MAX_MODULUS_SIZE];
if (this.sec_crypted_random.length < modulus_size) {
System.arraycopy(this.sec_crypted_random, 0, temp, 0,
this.sec_crypted_random.length);
for (int i = this.sec_crypted_random.length; i < temp.length; i++) {
temp[i] = 0;
}
this.sec_crypted_random = temp;
}
}
|
d6998da9-dfee-408f-9366-8cf1cfeb4d05
| 4
|
@Override
protected final void finalize() throws Throwable {
synchronized (Path.finalizerMonitor) {
final Set<PathReference> ss = new HashSet<>(
this.successors.values());
for (final WeakReference<Path> s : ss) {
if (!s.isEnqueued()) {
s.get().finalize();
}
}
if (this.parent != null) {
if (this.parent.successors.remove(this.filename) != null) {
Path.reusableHashes.push(Integer.valueOf(this.hash));
}
} else {
Path.reusableHashes.push(Integer.valueOf(this.hash));
}
}
}
|
156e19e4-a940-4c99-90ed-15a2d5063df3
| 3
|
private Sprite getClosestTarget(LinkedList<Sprite>targets){
Sprite closestTarget = null;
if(targets == null){
closestTarget = null;
}else{
closestTarget = targets.get(0);
for(int i = 0; i < targets.size(); i++){
if(distanceBetween(this, closestTarget) > distanceBetween(this, targets.get(i))){
closestTarget = targets.get(i);
}
}
}
return closestTarget;
}
|
9b886a77-38ca-43bf-8813-9f464d85aeeb
| 2
|
public List<WorldName> sendRequest(String lang) {
List<WorldName> result = new ArrayList<WorldName>();
RestTemplate rest = new RestTemplate();
String json = rest.getForObject("https://api.guildwars2.com/v1/world_names.json?lang="+lang, String.class);
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode node = mapper.readTree(json);
result = mapper.readValue(node.traverse(), new TypeReference<List<WorldName>>() {
});
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
|
7c8b718e-fe3f-4223-b1ec-bcd1c0eda15d
| 7
|
public boolean canBuild(Player player, Block block)
{
// Default FALSE return unless conditions are true
boolean canwg = false;
boolean canps = false;
if (pstones != null)
{
if (PreciousStones.API().canBreak(player, block.getLocation()))
canps = true;
DebugMode.log("ps:" + canps);
}
else
canps = true;
if (WorldGuard != null)
{
// Check if WorldGuard prohibits player
if (getWorldGuard().canBuild(player, block) || !getWorldGuard().isEnabled())
{
canwg = true;
}
DebugMode.log("wg:" + canwg);
}
else
canwg = true;
if (canps && canwg)
return true;
return false;
}
|
8a55e7f1-6085-4d2d-8f5b-dac098901e86
| 8
|
@Override
public String toString()
{
if (symbol >= '1' && symbol <= '9')
{
return "Character " + symbol;
}
else if (symbol == 'N')
{
return "North Wind";
}
else if (symbol == 'E')
{
return "East Wind";
}
else if (symbol == 'W')
{
return "West Wind";
}
else if (symbol == 'S')
{
return "South Wind";
}
else if (symbol == 'C')
{
return "Red Dragon";
}
else if (symbol == 'F')
{
return "Green Dragon";
}
else
{
return "Invalid Character symbol";
}
}
|
7a8ea4b1-0e28-4dbb-84ff-0b30f43d17e2
| 0
|
public boolean isObfuscated() {
return isObfuscated;
}
|
0483478b-a229-4425-bd61-c4263075e333
| 7
|
public static ArrayList getSerialResumo(String arg_serial) throws SQLException, ClassNotFoundException {
SimpleDateFormat sdf3 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
ArrayList<ja_jdbc_plpgsql.bean.bRegistro> aobj = new ArrayList<ja_jdbc_plpgsql.bean.bRegistro>();
ArrayList<ja_jdbc_plpgsql.bean.bDefeito> aobjDef = new ArrayList<ja_jdbc_plpgsql.bean.bDefeito>();
// jItm jItm = new jItm();
ArrayList<String> arra = new ArrayList<String>();
if(arg_serial.length() > 6 ){
arg_serial = arg_serial.substring(arg_serial.length() - 6);
}
aobj = jItm.PesquisaFun(arg_serial);
if (aobj.isEmpty()) {
arra.add(" ---> Não há registros deste Número de Série.");
} else {
// arra.add(" --> Teste Funcional:");
// arra.add(" ");
for (ja_jdbc_plpgsql.bean.bRegistro c : aobj) {
arra.add(
c.getCod_prod() + " "
+ c.getSerial() + " "
+ c.getCod_statusS() + " "
+ c.getPosto_gmp() + " "
+ sdf3.format(c.getDatah()) + " "
+ c.getStr_nome() + " "
+ c.getComplemento());
}
}
aobjDef = jItm.getDefeitos(arg_serial);
if (aobjDef.isEmpty()) {
//
} else {
arra.add(" ");
arra.add(" --> Reparos:");
arra.add(" ");
for (ja_jdbc_plpgsql.bean.bDefeito c : aobjDef) {
arra.add(
c.getCod_prod() + " "
+ c.getSerial() + " "
+ c.getStr_tp_defeito() + " "
+ c.getCod_comp() + c.getPos_comp() + " "
+ sdf3.format(c.getDatahora()) + " "
+ c.getStr_cr_operador() + " "
+ c.getTipo_montagem());
}
}
// Assistec:
ArrayList<ja_jdbc_plpgsql.bean.bAssistecConsulta> ar_ob = new ArrayList<ja_jdbc_plpgsql.bean.bAssistecConsulta>();
ar_ob = jAssistec2.getSintomas(arg_serial);
if (ar_ob.isEmpty()) {
//
} else {
SimpleDateFormat formatt1 = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
arra.add(" ");
arra.add(" --> Assistec:");
arra.add(" ");
for (ja_jdbc_plpgsql.bean.bAssistecConsulta c : ar_ob) {
arra.add(
c.getSerial() + " "
+ c.getStr_sintoma() + " "
+ c.getTipo_montagem() + ": " + c.getCod_comp() + c.getPos_comp() + " "
+ c.getStr_tp_defeito() + " "
+ formatt1.format(c.getDatahora()) + " "
+ c.getStr_cr_operador() + " "
+ c.getCod_deposito() + " "
+ c.getObs() + " "
+ c.getStr_sa());
}
}
return arra;
}
|
c153dd0a-8bc7-4f96-bff4-3b0ced5b5cd8
| 1
|
public static void registerSignal(Signal signal) throws SignalNameInUseException
{
if (linker.containsKey(signal.getSignalName()))
{
throw new SignalNameInUseException("Error: This signal name is currently in use");
}
SignalStructure struct = new SignalStructure(signal.getParams(), new ArrayList<Slot>(), signal.getReturnParam());
linker.put(signal.getSignalName(), struct);
}
|
f26ad49e-4767-46e1-bbf1-239255b9955c
| 0
|
public int getRemotePort() {
return remotePort;
}
|
a601b76f-c218-4091-8b2f-9a6b2364dddb
| 1
|
public static void main(String[] args) {
try {
AppGameContainer app = new AppGameContainer(new Game("Forgotten Space"));
app.setDisplayMode(640, 480, false);
app.setTargetFrameRate(60);
app.start();
}
catch (SlickException e) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, e);
}
}
|
638dd5fc-53fe-4e0d-ac5a-97c918677508
| 7
|
@Override
public void undo() {
// Find the node we will change focus too, note may end up null
Node youngestNode = ((PrimitiveUndoableInsert) primitives.get(primitives.size() - 1)).getNode();
Node newSelectedNode = youngestNode.prev();
// Shorthand
JoeTree tree = youngestNode.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
// Delete Everything
for (int i = 0, limit = primitives.size(); i < limit; i++) {
primitives.get(i).undo();
}
if ((newSelectedNode == youngestNode.getParent()) && !newSelectedNode.isLeaf()) {
newSelectedNode = newSelectedNode.getFirstChild();
}
// If the newSelectedNode is null, then select the first node in the tree
if (newSelectedNode == null || newSelectedNode.isRoot()) {
tree.setSelectedNodesParent(tree.getRootNode());
newSelectedNode = tree.getRootNode().getFirstChild();
tree.addNodeToSelection(newSelectedNode);
} else {
tree.setSelectedNodesParent(newSelectedNode.getParent());
tree.addNodeToSelection(newSelectedNode);
}
// Record the EditingNode
tree.setEditingNode(newSelectedNode);
tree.setComponentFocus(OutlineLayoutManager.ICON);
// Redraw and Set Focus
// First make sure the node to draw from wasn't removed, it will be root since it is orphaned.
// If so, we need to set the new one before trying to redraw.
if (layout.getNodeToDrawFrom().isRoot()) {
layout.setNodeToDrawFrom(newSelectedNode, tree.getVisibleNodes().indexOf(newSelectedNode));
}
if (!newSelectedNode.isVisible()) {
tree.insertNode(newSelectedNode); // Just to make it visible
}
layout.draw(newSelectedNode, OutlineLayoutManager.ICON);
}
|
29e5e44b-45de-4eb5-9b59-860a7f70dfc2
| 5
|
public String printAST()
{
StringBuilder ret = new StringBuilder();
int len = rhs.size();
for(int i=0; i < len; i++){
if(rhs.get(0) instanceof Expr && i > 0) ret.append(" ");
if(rhs.get(i) instanceof Terminal){
ret.append(((Terminal)rhs.get(i)).printAST());
}else if(rhs.get(i) instanceof Call){
ret.append(((Call)rhs.get(i)).printAST());
}else{
ret.append(((Expr)rhs.get(i)).printAST());
}
}
return ret.toString();
}
|
20cea4d4-0e2d-4def-ab33-c36f28c4b388
| 7
|
public void resolveCollision(int ix, int jx, Player player, boolean isHorizontal) {
// First resolve in y
// move upward until not touching
Rectangle tileRec = new Rectangle(ix * tileSizeX, jx * tileSizeY, tileSizeX, tileSizeY);
// Rectangle playerRec = p1.getBounds();
double tileRectangleMaxY = tileRec.getMaxY();
double tileRectangleMinY = tileRec.getMinY();
double tileRectangleMaxX = tileRec.getMaxX();
double tileRectangleMinX = tileRec.getMinX();
double playerNewX = player.getX();
double playerNewY = player.getY();
double playerOldX = player.getOldX();
double playerOldY = player.getOldY();
double playerWidth = player.getTileSizeX();
double playerHeight = player.getTileSizeY();
//System.out.println(pX + " " + pXOld);
//System.out.println( (pX+pWX) + " " + (pXOld+pWX));
//System.out.println( tileRectangleMinX);
// if player entered tile from left -> move left..
if (isHorizontal) {
//System.out.println("I'm trying!");
if (playerNewX + playerWidth >= tileRectangleMinX && playerOldX + playerWidth <= tileRectangleMinX) {
player.setX(tileRectangleMinX - playerWidth - 1);
//player.setVx(0.0f);
//double VxOld=player.getVx();
player.setVx(-player.getVx());
} else if (playerNewX <= tileRectangleMaxX && playerOldX >= tileRectangleMaxX) {
player.setX(tileRectangleMaxX + 1);
//player.setVx(0.0f);
player.setVx(-player.getVx());
}
} else {
// if player entered tile from top -> move up..
if (playerNewY + playerHeight >= tileRectangleMinY && playerOldY + playerHeight <= tileRectangleMinY) {
player.setY(tileRectangleMinY - playerHeight);
player.setVy(0.0f);
//player.setVy(-player.getVy());
player.setTouchGround(true);
}
//else if (playerNewY <= tileRectangleMaxY && playerOldY >= tileRectangleMaxY) {
// player.setY(tileRectangleMaxX + 1);
// player.setVy(0.0f);
//player.setVy(-player.getVy());
//player.setTouchGround(true);
//}
}
}
|
f3bbeaee-b7e9-49f4-ba89-fd4b82b71f9b
| 9
|
public PreferencesDialog(Frame owner) {
super(owner, "Recipe Preferences", true);
opts = Options.getInstance();
sb = owner;
Enumeration<NetworkInterface> interfaces;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()){
NetworkInterface current = interfaces.nextElement();
try {
if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()){
InetAddress current_addr = addresses.nextElement();
System.out.println("Found an address " + current_addr);
if (current_addr.isLoopbackAddress()) continue;
if (current_addr instanceof Inet4Address) {
lblIPAddr.setText("IP Address is: " + current_addr.getHostAddress().toString());
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
layoutUi();
setLocation(owner.getLocation());
setOptions();
}
|
f699c196-8b15-44c0-ae0a-1674010a02f0
| 4
|
private void addFriend(String friend) {
if (currentProfile != null) {
if (!friend.equals(currentProfile.getName())) {
if (database.containsProfile(friend)) {
if (currentProfile.addFriend(friend)) {
database.getProfile(friend).addFriend(currentProfile.getName());
canvas.displayProfile(currentProfile);
canvas.showMessage(friend + " added as a friend");
} else {
canvas.showMessage(currentProfile.getName() + " already has " + friend + " as a friend");
}
} else {
canvas.showMessage(friend + " does not exist");
}
}
} else {
canvas.showMessage("Please select a profile to add friend");
}
}
|
e76f2c59-5ff2-4a53-a548-a9b89356ec68
| 0
|
@Override public void finishPopulate()
{
setBbox(new double[]{getCoordinates().getLongitude(), getCoordinates().getLongitude(), getCoordinates().getLatitude(), getCoordinates().getLatitude()});
}
|
7444fa59-75d0-4fa7-bf03-30934a35f633
| 9
|
private byte[] buildMultipartBody(Map<String, String> params, byte[] photoData, String boundary) throws JinxException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
String filename = params.get("filename");
if (JinxUtils.isNullOrEmpty(filename)) {
filename = "image.jpg";
}
String fileMimeType = params.get("filemimetype");
if (JinxUtils.isNullOrEmpty(fileMimeType)) {
fileMimeType = "image/jpeg";
}
buffer.write(("--" + boundary + "\r\n").getBytes(JinxConstants.UTF8));
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
if (!key.equals("filename") && !key.equals("filemimetype")) {
buffer.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n").getBytes(JinxConstants.UTF8));
buffer.write((entry.getValue()).getBytes(JinxConstants.UTF8));
buffer.write(("\r\n" + "--" + boundary + "\r\n").getBytes(JinxConstants.UTF8));
}
}
buffer.write(("Content-Disposition: form-data; name=\"photo\"; filename=\"" + filename + "\";\r\n").getBytes(JinxConstants.UTF8));
buffer.write(("Content-Type: " + fileMimeType + "\r\n\r\n").getBytes(JinxConstants.UTF8));
buffer.write(photoData);
buffer.write(("\r\n" + "--" + boundary + "--\r\n").getBytes(JinxConstants.UTF8)); // NOTE: last boundary has -- suffix
} catch (Exception e) {
throw new JinxException("Unable to build multipart body.", e);
}
if (this.isVerboseLogging()) {
String logMpBody = System.getProperty(JinxConstants.JINX_LOG_MULTIPART);
if (!JinxUtils.isNullOrEmpty(logMpBody) && logMpBody.equals("true")) {
JinxLogger.getLogger().log("Multipart body: " + buffer.toString());
}
}
return buffer.toByteArray();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.