method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
8aa65098-e445-4860-b3f3-9e83192e32e9 | 2 | public JSONArray names() {
JSONArray ja = new JSONArray();
Iterator keys = this.keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
return ja.length() == 0 ? null : ja;
} |
79d06b78-b800-4883-9b07-b2f4fd287136 | 2 | private String AddByBit(String str1, String str2)
{
StringBuffer sumBuffer = new StringBuffer();
for(int i = 0; i < str1.length(); ++i)
{
if(str1.charAt(i) == str2.charAt(i))
{
sumBuffer.append("0");
}
else
{
sumBuffer.append("1");
}
}
return sumBuffer.toString();
} |
33cf01e0-8ca1-42f6-89d4-5266d6911ebe | 3 | public void printMetadataInfo() throws IOException {
if (flac instanceof FlacOggFile) {
FlacOggFile ogg = (FlacOggFile)flac;
System.out.println("FLAC-in-Ogg, in stream " + ogg.getSid());
} else {
System.out.println("FLAC Native");
}
// Output The information
FlacInfo info = flac.getInfo();
System.out.println(INDENT1 + "Min Block Size=" + info.getMinimumBlockSize());
System.out.println(INDENT1 + "Max Block Size=" + info.getMaximumBlockSize());
System.out.println(INDENT1 + "Min Frame Size=" + info.getMinimumFrameSize());
System.out.println(INDENT1 + "Max Frame Size=" + info.getMaximumFrameSize());
System.out.println(INDENT1 + "Num Channels=" + info.getNumChannels());
System.out.println(INDENT1 + "Bits Per Sample=" + info.getBitsPerSample());
System.out.println(INDENT1 + "Sample Rate=" + info.getSampleRate());
System.out.println(INDENT1 + "Num Samples=" + info.getNumberOfSamples());
System.out.println(INDENT1 + "Pre Skip=" + info.getPreSkip());
// Output a comments summary
FlacTags tags = flac.getTags();
System.out.println(tags.getAllComments().size() + " Comments:");
for (String tag : tags.getAllComments().keySet()) {
System.out.println(INDENT1 + tag);
for (String value : tags.getAllComments().get(tag)) {
System.out.println(INDENT2 + value);
}
}
System.out.println();
} |
e48790d4-195b-4b2c-821d-5a270792696f | 3 | public static void toggleMoveableInheritance(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
JoeNodeList nodeList = tree.getSelectedNodes();
for (int i = 0, limit = nodeList.size(); i < limit; i++) {
toggleMoveableInheritanceForSingleNode(nodeList.get(i), undoable);
}
if (!undoable.isEmpty()) {
if (undoable.getPrimitiveCount() == 1) {
undoable.setName("Toggle Moveability Inheritance for Node");
} else {
undoable.setName(new StringBuffer().append("Toggle Moveability Inheritance for ").append(undoable.getPrimitiveCount()).append(" Nodes").toString());
}
tree.getDocument().getUndoQueue().add(undoable);
}
layout.draw(currentNode, OutlineLayoutManager.ICON);
} |
27b93586-ce56-40a8-a0e9-5b66ffb6de78 | 8 | Point3f[] getFaceVertices(byte face) {
if (faceVertices == null) {
faceVertices = new Point3f[4];
for (int i = 0; i < 4; i++)
faceVertices[i] = new Point3f();
}
float x = Math.abs(corner.x);
float y = Math.abs(corner.y);
float z = Math.abs(corner.z);
switch (face) {
case FRONT:
faceVertices[0].set(center.x + x, center.y + y, center.z + z);
faceVertices[1].set(center.x - x, center.y + y, center.z + z);
faceVertices[2].set(center.x - x, center.y - y, center.z + z);
faceVertices[3].set(center.x + x, center.y - y, center.z + z);
return faceVertices;
case REAR:
faceVertices[0].set(center.x + x, center.y + y, center.z - z);
faceVertices[1].set(center.x - x, center.y + y, center.z - z);
faceVertices[2].set(center.x - x, center.y - y, center.z - z);
faceVertices[3].set(center.x + x, center.y - y, center.z - z);
return faceVertices;
case TOP:
faceVertices[0].set(center.x + x, center.y + y, center.z + z);
faceVertices[1].set(center.x - x, center.y + y, center.z + z);
faceVertices[2].set(center.x - x, center.y + y, center.z - z);
faceVertices[3].set(center.x + x, center.y + y, center.z - z);
return faceVertices;
case BOTTOM:
faceVertices[0].set(center.x + x, center.y - y, center.z + z);
faceVertices[1].set(center.x - x, center.y - y, center.z + z);
faceVertices[2].set(center.x - x, center.y - y, center.z - z);
faceVertices[3].set(center.x + x, center.y - y, center.z - z);
return faceVertices;
case RIGHT:
faceVertices[0].set(center.x + x, center.y + y, center.z + z);
faceVertices[1].set(center.x + x, center.y - y, center.z + z);
faceVertices[2].set(center.x + x, center.y - y, center.z - z);
faceVertices[3].set(center.x + x, center.y + y, center.z - z);
return faceVertices;
case LEFT:
faceVertices[0].set(center.x - x, center.y + y, center.z + z);
faceVertices[1].set(center.x - x, center.y - y, center.z + z);
faceVertices[2].set(center.x - x, center.y - y, center.z - z);
faceVertices[3].set(center.x - x, center.y + y, center.z - z);
return faceVertices;
}
return null;
} |
5abc8056-171c-430e-89d0-114d04344c22 | 5 | public SecuredMessageTriggerBean execute(SecuredMessageTriggerBean message) throws GranException {
ArrayList<String> possibleHandlers = new ArrayList<String>();
List<String> users = KernelManager.getStep().getHandlerList(message.getMstatusId(), message.getTaskId());
for (String userId : users) {
ArrayList<String> statuses = KernelManager.getAcl().getEffectiveStatuses(message.getTaskId(), userId);
if (statuses.contains(SECOND_LINE_ROLE_ID) && !statuses.contains(ESCALATOR_BOT_ROLE)) {
possibleHandlers.add(userId);
}
if (statuses.contains(THIRD_LINE_ROLE_ID) && !statuses.contains(ESCALATOR_BOT_ROLE)) {
possibleHandlers.add(userId);
}
}
PeekAssigneeStrategy generator = new RandomAssignee(possibleHandlers, message.getHandlerUser());
// message.setHandlerUserId(generator.peek().toString());
// message.setHandlerGroupId(null);
return message;
} |
be5c05fe-6922-4f40-a2b9-022a88ed5899 | 6 | public MapObject[] getCollisionObject(Rectangle rect) {
List<MapObject> objects = new ArrayList<MapObject>();
// Iterate through the layers
for (int i = 0; i < layers.size(); i++) {
// Get the layer
Layer layer = layers.get(i);
// Is it an object group?
if (layer instanceof ObjectGroup) {
// We want all the objects
MapObject[] layerObjects = ((ObjectGroup) layer).getObjects();
for (int j = 0; j < layerObjects.length; j++) {
MapObject object = layerObjects[j];
// Does it have a GID?
if (object.hasGID()) {
// We need the tile width/height
Tileset tileset = getTilesetByGID(object.getGID());
int tilewidth = tileset.getTileWidth();
int tileheight = tileset.getTileHeight();
int objectx1 = object.getX();
int objecty1 = object.getY();
int objectx2 = tilewidth;
int objecty2 = tileheight;
Rectangle rectangle = new Rectangle(objectx1, objecty1, objectx2, objecty2);
if (rect.intersects(rectangle)) {
objects.add(object);
}
} else {
int objectx1 = object.getX();
int objecty1 = object.getY();
int objectx2 = object.getWidth();
int objecty2 = object.getHeight();
Rectangle rectangle = new Rectangle(objectx1, objecty1, objectx2, objecty2);
if (rect.intersects(rectangle)) {
objects.add(object);
}
}
}
}
}
return objects.toArray(new MapObject[objects.size()]);
} |
b070acbd-3561-42bb-92f4-5a15e88e9a8f | 5 | public void analyzeInnerClasses(ProgressListener pl, double done,
double scale) {
double subScale = scale / innerComplexity;
// If output should be immediate, we delay analyzation to output.
// Note that this may break anonymous classes, but the user
// has been warned.
if ((Options.options & Options.OPTION_IMMEDIATE) != 0)
return;
// Now analyze the inner classes.
for (int j = 0; j < inners.length; j++) {
if (pl != null) {
double innerCompl = inners[j].getComplexity() * subScale;
if (innerCompl > STEP_COMPLEXITY) {
double innerscale = subScale * inners[j].methodComplexity;
inners[j].analyze(pl, done, innerscale);
inners[j].analyzeInnerClasses(null, done + innerscale,
innerCompl - innerscale);
} else {
pl.updateProgress(done, inners[j].name);
inners[j].analyze(null, 0.0, 0.0);
inners[j].analyzeInnerClasses(null, 0.0, 0.0);
}
done += innerCompl;
} else {
inners[j].analyze(null, 0.0, 0.0);
inners[j].analyzeInnerClasses(null, 0.0, 0.0);
}
}
// Now analyze the method scoped classes.
for (int j = 0; j < methods.length; j++)
methods[j].analyzeInnerClasses();
} |
19ee5783-6b63-49ca-aae7-2ff70620e094 | 7 | public static Rule_dirMethod parse(ParserContext context)
{
context.push("dirMethod");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal_StringValue.parse(context, ".method");
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule_dirMethod(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("dirMethod", parsed);
return (Rule_dirMethod)rule;
} |
246ef2a4-c010-4186-9624-9a82a04c31fd | 7 | @Override
public void insert(String key) {
totOps++;
if (find(key))
return;
if (isOverLoaded(numElements + 1))
increaseTable();// Increase table size if table will be overloaded.
int hCode = hashCode.giveCode(key);
int compKey = compressKey(hCode);
totProb++;
if (table[compKey] == null || table[compKey].equals(AVAILABLE)) {
numElements++;
table[compKey] = key;
return;
}
int doubleCode = compressDoubleHash(hCode);
for (int j = 1; j < table.length - 1; j++) {
totProb++;
int dCompress = doubleHash(compKey, doubleCode, j);
if (table[dCompress] == null || table[dCompress].equals(AVAILABLE)) {
numElements++;
table[dCompress] = key;
return;
}
}
} |
5efca507-6905-45eb-9f57-64ea7210afbf | 9 | private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
JButton button = (JButton) evt.getSource();
if ("启动评价".equals(button.getText())) {
jButton4.setText("暂停评价");
flagComment = true;
new Thread() {
public void run() {
while (flagComment && brush.getLists().size() > 0) {
//评价
ResourceInfo info = brush.getLists().get(0);
boolean ret = brush.commentById(info.getUrl());
if (ret) {
//action = Action.WORK_LOG;
message = info.getName() + "已经被评价啦。";
//成功了就删掉列表
brush.getLists().remove(0);
// System.out.println(message);
updateLog(message);
resource_time_label.setText("70");
jList1.setListData(brush.getLists().toArray());
resource_count_label.setText(brush.getLists().size() + "个");
jList1.invalidate();
//action = Action.NOTING;
} else {
updateLog(info.getName() + " 评价的时候出现错误!!");
resource_time_label.setText("70");
//错了继续再来。
}
try {
while (true) {
message = (Integer.parseInt(resource_time_label.getText()) - 1) + "";
Thread.sleep(1000);
resource_time_label.setText(message);
if (Integer.parseInt(message) <= 0 || !flagComment) {
break;
}
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (flagComment == true) {
updateLog("已经没有东西好评价的啦。");
}
jButton4.setText("启动评价");
}
}.start();
} else {
flagComment = false;
jButton4.setText("启动评价");
updateLog("已经停止评价。可能需要等上60秒再开始操作啦。");
}
}//GEN-LAST:event_jButton4ActionPerformed |
598fa46c-1251-42cd-a524-310dcd415016 | 6 | public void setSelectedItem(Object element) {
if (element == null) {
if (elementIndex != -1) {
elementIndex = -1;
fireContentsChanged(this, -1, -1);
}
} else if (element instanceof String) {
for (int i=0; i<elementTypeStrings.length; i++) {
if (elementTypeStrings[i].equals((String)element)) {
if (elementIndex != i) {
elementIndex = i;
fireContentsChanged(this, -1, -1);
}
break;
}
}
}
} |
d76ce37e-d36f-4e3b-84c7-a97d80bc4aa9 | 9 | public void getTaskData(int pos, TaskDesc td, Task task) {
if (task.taskMD.parent != null && task.numParentDataRecv < task.taskMD.parent.size()) {
String data = requestData(task.taskId, task.taskMD.parent.get(pos), td,
task.taskMD.dataSize.get(pos), task.taskMD.dataNameList.get(pos));
while (data != null && pos < task.taskMD.parent.size()
|| task.taskMD.dataSize.get(pos) == 0) {
if (task.taskMD.dataSize.get(pos) > 0)
localTime += Library.procTimePerKVSRequest;
task.numParentDataRecv++;
pos++;
task.data += data;
if (pos == task.taskMD.parent.size())
break;
data = requestData(task.taskId, task.taskMD.parent.get(pos), td,
task.taskMD.dataSize.get(pos), task.taskMD.dataNameList.get(pos));
}
}
if (task.taskMD.parent == null || task.numParentDataRecv == task.taskMD.parent.size())
actExecuteTask(td);
Library.globalTaskHM.put(task.taskId, task);
} |
a406f48d-b3e2-409c-a9cd-48c4001924ed | 9 | private void removeOldChildren()
{
Map<String, Object> attributes = component.getAttributes();
List<String> currentComponents = createdComponents;
// Get the old list of created component ids and update the current list as a
// component attribute
Object oldValue;
if (currentComponents != null)
{
oldValue = attributes.put(JSP_CREATED_COMPONENT_IDS, currentComponents);
createdComponents = null;
}
else
{
oldValue = attributes.remove(JSP_CREATED_COMPONENT_IDS);
}
// Remove old children that are no longer present
if (oldValue != null)
{
List<String> oldList = TypedCollections.dynamicallyCastList((List)oldValue, String.class);
int oldCount = oldList.size();
if (oldCount > 0)
{
if (currentComponents != null)
{
int currStartIndex = 0;
for (int oldIndex = 0; oldIndex < oldCount; oldIndex++)
{
String oldId = oldList.get(oldIndex);
int foundIndex = _indexOfStartingFrom(currentComponents, currStartIndex, oldId);
if (foundIndex != -1)
{
currStartIndex = foundIndex + 1;
}
else
{
UIComponent child = component.findComponent(oldId);
// if a component is marked transient, it would have
// been already removed from the child list, but the
// oldList would still have it. In addition, the component
// might have manually been removed. So, if findComponent
// isn't successful, don't call remove child (it will NPE)
if ( child != null)
{
component.getChildren().remove(child);
}
}
}
}
else
{
List<UIComponent> children = component.getChildren();
// All old components need to be removed
for (String oldId : oldList)
{
UIComponent child = component.findComponent(oldId);
if (child != null)
{
children.remove(child);
}
}
}
}
}
} |
ef6e291e-33a9-456b-9c9c-765c5255456d | 8 | public void addNotification(String[][] map, TrayPlugin trayplugin, int delay) {
String title = "", subtitle = "", message = "", time = "", icon = "";
for(String[] values: map) {
if(values[0].equals("title")) {
title = values[1];
} else if(values[0].equals("subtitle")) {
subtitle = values[1];
} else if(values[0].equals("message")) {
message = values[1];
} else if(values[0].equals("time")) {
time = values[1];
} else if(values[0].equals("icon")) {
icon = values[1];
}
}
Pattern p = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); // RegEx Bedinung
Matcher m = p.matcher(message);
while (m.find()) { message = message.replace(m.group(0), "<span style='color:darkred'>[LINK]</span>"); }
logo = Utils.getImage(icon, 50, 50, false);
NMessage td = new NMessage(title, subtitle, message, time, logo, pin, unpin, this, delay);
add(td, 0);
if(trayplugin.shoudPlaySound()) { playSound(); }
resetTo(getHeight() +td.getPreferredSize().height +5);
validate();
} |
fcc1f271-ccab-4c0a-8781-cb3f55341f97 | 9 | public int update() throws SQLException {
StringBuilder sb = new StringBuilder();
if (commentLine != null) {
sb.append("/* ").append(commentLine).append(" */");
}
sb.append("update " + TABLENAME + " set ");
int i = 1;
List<Object> list = new ArrayList<Object>();
for (Fields hf : fieldValueMap.keySet()) {
list.add(fieldValueMap.get(hf));
sb.append(hf.getFieldName()).append("=?");
if (i < fieldValueMap.size()) {
sb.append(",");
}
i++;
}
if (whereMap.size() > 0) {
StringBuilder sbWhere = new StringBuilder();
for (String str : whereMap.keySet()) {
sbWhere.append(str);
Object o = whereMap.get(str);
if (o != null)
if (o instanceof Array) {
getArrayObj(list, (Array) o);
} else {
list.add(o);
}
}
sb.append(sbWhere.toString().replaceFirst(AND, " where "));
}
String sql = sb.toString();
Object[] values = new Object[list.size()];
list.toArray(values);
if (this.isloggerOn) {
StringBuilder s = new StringBuilder();
for (Object o : values) {
s.append(o).append(",");
}
logger.log("[UPDATE SQL][" + sql + "][" + s.toString().substring(0, s.length() - 1) + "]");
}
return jdao.executeUpdate(sql, list.toArray(values));
} |
d38566d5-edf5-406f-be03-edde2752d8de | 7 | @Override
public void paint(Graphics g) {
Color colores[] = new Color[6];
colores[0] = Constantes.COLOR_CIC_0;
colores[1] = Constantes.COLOR_CIC_1;
colores[2] = Constantes.COLOR_CIC_2;
colores[3] = Constantes.COLOR_CIC_3;
colores[4] = Constantes.COLOR_CIC_4;
colores[5] = Constantes.COLOR_CIC_5;
super.paint(g);
int x = 0;
int xfin = 0;
int y = Constantes.ALTO_VENTANA / 4;
int yfin = 0;
double x_aux = 0;
int i = 0;
int max = arbol.lastEntry().getKey();
Iterator<Entry<Integer, Integer>> it = arbol.entrySet().iterator();
Iterator<Entry<Integer, Integer>> itaux = arbol.entrySet().iterator();
if (it.hasNext()) {
itaux.next();
}
while (itaux.hasNext()) {
Entry<Integer, Integer> tramoini = it.next();
if (it.hasNext()) {
Entry<Integer, Integer> tramofin = itaux.next();
// pintamos la carretera
g.setColor(Color.BLACK);
// g.drawLine(x, y, (tramofin.getKey() /
// max)*Constantes.ANCHO_VENTANA, y
// - tramoini.getValue());
g.drawLine(
(int) x_aux,
y,
(int) ((tramofin.getKey() / (double) max) * Constantes.ANCHO_PANEL_LIENZO),
y - tramoini.getValue());
// System.out.println(x_aux);
// System.out.println((int)((tramofin.getKey()/(double)max)*Constantes.ANCHO_PANEL_LIENZO));
// pintamos el cielo
Polygon polygonCielo;
polygonCielo = creaPoligono(
new Point((int) x_aux, 0),
new Point((int) x_aux, y - 1),
new Point(
(int) ((tramofin.getKey() / (double) max) * Constantes.ANCHO_PANEL_LIENZO),
(y - tramoini.getValue()) - 1),
new Point(
(int) ((tramofin.getKey() / (double) max) * Constantes.ANCHO_PANEL_LIENZO),
0));
Polygon polygon = new Polygon();
pintaPoligono(polygonCielo, g, Color.CYAN);
// pintamos el suelo
Polygon polygonSuelo;
polygonSuelo = creaPoligono(
new Point((int) x_aux, Constantes.ALTO_VENTANA),
new Point((int) x_aux, y + 1),
new Point(
(int) ((tramofin.getKey() / (double) max) * Constantes.ANCHO_PANEL_LIENZO),
(y - tramoini.getValue()) + 1),
new Point(
(int) ((tramofin.getKey() / (double) max) * Constantes.ANCHO_PANEL_LIENZO),
Constantes.ALTO_VENTANA));
pintaPoligono(polygonSuelo, g, Color.GREEN);
x = tramofin.getKey() / Constantes.FACTORESCALA;
y = y - tramoini.getValue();
x_aux = (tramofin.getKey() / (double) max)
* Constantes.ANCHO_PANEL_LIENZO;
}
}
// pintamos los PK de las curvas
Iterator<Entry<Integer, Integer>> itcurva = curva.getArbolCurvas()
.entrySet().iterator();
while (itcurva.hasNext()) {
Entry<Integer, Integer> tramocurva = itcurva.next();
g.setColor(Color.red);
double xcurva = ((double) tramocurva.getKey() / max);
xcurva = xcurva * Constantes.ANCHO_PANEL_LIENZO - 1;
g.drawLine((int) xcurva, 0, (int) xcurva, Constantes.ALTO_VENTANA);
g.drawString("Curva ",
(int) xcurva - 80, 30);
g.drawString("metro " + tramocurva.getKey(),
(int) xcurva - 80, 40);
g.drawString("vel max " + tramocurva.getValue(),
(int) xcurva - 80, 50);
}
Iterator<Entry<Integer, Integer>> itpend = pendiente.getArbol().entrySet().iterator();
while (itpend.hasNext()) {
Entry<Integer, Integer> tramo = itpend.next();
g.setColor(Color.orange);
double xpend = ((double) tramo.getKey() / max);
xpend = xpend* Constantes.ANCHO_PANEL_LIENZO;
g.drawLine((int) xpend, 0, (int) xpend, Constantes.ALTO_VENTANA);
g.drawString("Pendiente",
(int) xpend - 100, 300);
g.drawString("metro " + tramo.getKey(),
(int) xpend - 100, 310);
g.drawString("porcentaje " + tramo.getValue()+"%",
(int) xpend - 100, 320);
}
// aqui se pondra la informacion del ciclista para que se vaya pintando,
// ahora solo se pinta un punto en pantalla
// for (i = 0; i < cic.size(); i++) {
int id_color_ciclista = 0;
for (Ciclista c : lista_de_ciclistas) {
g.setColor(colores[id_color_ciclista]);
if (calculaYparaPuntoCiclista(c, arbol) == 0)
y = Constantes.ALTO_VENTANA / 4
- Constantes.ANCHO_PUNTO_CICLISTA / 2;
else
y = calculaYparaPuntoCiclista(c, arbol);
g.fillOval(
(int) ((c.getBici().getEspacioRecorrido() / max) * Constantes.ANCHO_PANEL_LIENZO)
- Constantes.ANCHO_PUNTO_CICLISTA / 2, y,
Constantes.ANCHO_PUNTO_CICLISTA,
Constantes.ANCHO_PUNTO_CICLISTA);
id_color_ciclista++;
}
} |
55de1f10-4a77-4ff0-a53f-7841563ce785 | 2 | @Override
public boolean hitField(int x, int y) {
Field tolook = getFields()[y][x];
if(tolook.getBattleState() == null)
{
if (tolook.getFieldState() == eFieldState.Empty) {
tolook.setBattleState(eFieldBattleState.Missed);
return false;
} else {
tolook.setBattleState(eFieldBattleState.Hit);
setHitCount();
return true;
}
}
else
{
throw new UnknownError("Du domme siech hesch scho mou do druf gschosse" + x + " " + y);
}
} |
9ee358b3-9994-400b-b47b-2855d41ae6fa | 5 | @Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
// Controls for player 1
if(keyCode == KeyEvent.VK_W) {
GameMaster.player.moveUp = true;
}
if(keyCode == KeyEvent.VK_S) {
GameMaster.player.moveDown = true;
}
// Controls for player 2
if(keyCode == KeyEvent.VK_UP) {
GameMaster.ai.moveUp = true;
}
if(keyCode == KeyEvent.VK_DOWN) {
GameMaster.ai.moveDown = true;
}
// Close the game
if(keyCode == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
} |
7285c9bf-a536-4e3f-91c9-7d387024e573 | 2 | void setParameter(int position, Object value) {
if (position >= 0 && position < values.length) {
values[position] = value;
}
} |
977f933f-6113-4c5b-b8df-205f3280c2ac | 6 | private String getPage(int page, Map<String, Object> map) {
int factor = 5;
int index = (page - 1) * factor;
int listSize = map.size();
if (index > listSize) {
return "";
}
int upper = index + factor;
if (upper >= listSize) {
upper = listSize;
}
StringBuilder sb = new StringBuilder();
sb.append(ChatColor.RED).append(plugin.getName()).append("\n").append(ChatColor.RESET);
sb.append("Page ").append(page).append("/").append((int) Math.ceil((double) listSize / (double) factor));
sb.append("\n").append(ChatColor.RESET);
String[] list = map.keySet().toArray(new String[listSize]);
Arrays.sort(list);
for (int i = index; i < upper; i++) {
Object test = map.get(list[i]);
if (test != null) {
if (test instanceof SubCommand) {
SubCommand db = (SubCommand) map.get(list[i]);
sb.append(db.getHelp()[0]).append(" - ").append(db.getHelp()[1]);
}
if (i != upper - 1) {
sb.append("\n");
}
}
}
sb.append('\n').append(ChatColor.YELLOW).append("Use /ttp help <command> to get help for a specific command");
return sb.toString();
} |
8123878b-87b8-4bf4-a19d-601de8709d36 | 6 | private static void runTests(){
if(!initializationTests()) return;
if(!insertTests()) return;
if(!selectTests()) return;
if(!updateTests()) return;
if(!deletionTests()) return;
if(!shutdownTests()) return;
} |
0b713a44-9c1d-4e9b-97e8-3bed6c24fd5b | 3 | public Habitat getHabitatByOwner(String owner) {
for (Habitat h : getHabitats().values()) {
if (h != null)
if (h.getOwner().equalsIgnoreCase(owner)) return h;
}
return null;
} |
99cbc8f0-f7e5-4971-aaf0-5d7a271eb866 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
Path other = (Path) obj;
if (endPoint == null) {
if (other.endPoint != null)
return false;
} else if (!endPoint.equals(other.endPoint))
return false;
if (startPoint == null) {
if (other.startPoint != null)
return false;
} else if (!startPoint.equals(other.startPoint))
return false;
if (!super.equals(obj))
return false;
return true;
} |
150a9731-a480-492d-9c09-8a74dd946670 | 1 | public static synchronized ConnectionPool getInstance() {
if (instance == null) {
instance = new ConnectionPool();
}//if
return instance;
}//getInstance |
ede1051a-9b91-4b4f-8aae-ab7cab180e59 | 9 | public static int size(TypeType type) {
switch (type) {
case DOUBLE:
case LONG:
return 2;
case INT:
case SHORT:
case CHAR:
case BYTE:
case BOOLEAN:
return 1;
case REF:
case ARRAY_REF:
return 1;
default:
throw new IllegalArgumentException();
}
} |
4165302a-e3d3-4ccb-bf6c-a7db5f064b0a | 3 | public Dimension getPreferredSize() {
int x = 0, y = 0;
for (Iterator<ZElement> e = enumElements(); e.hasNext();) {
MPDEntite o = (MPDEntite) e.next();
x = o.getX() + o.getWidth() > x ? o.getX() + o.getWidth() : x;
y = o.getY() + o.getHeight() > y ? o.getY() + o.getHeight() : y;
}
return new Dimension(x + 30, y + 30);
} |
06fc1e50-09ea-4a48-a835-72828d733115 | 6 | private void setTotalRecord(Page<?> page, MappedStatement mappedStatement, Connection connection) {
//获取对应的BoundSql,这个BoundSql其实跟我们利用StatementHandler获取到的BoundSql是同一个对象。
//delegate里面的boundSql也是通过mappedStatement.getBoundSql(paramObj)方法获取到的。
BoundSql boundSql = mappedStatement.getBoundSql(page);
//获取到我们自己写在Mapper映射语句中对应的Sql语句
String sql = boundSql.getSql();
//通过查询Sql语句获取到对应的计算总记录数的sql语句
String countSql = "select count(0) from (" + sql+ ") as tmp_count" ; //记录统计
//通过BoundSql获取对应的参数映射
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
//利用Configuration、查询记录数的Sql语句countSql、参数映射关系parameterMappings和参数对象page建立查询记录数对应的BoundSql对象。
BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, parameterMappings, page);
//通过mappedStatement、参数对象page和BoundSql对象countBoundSql建立一个用于设定参数的ParameterHandler对象
ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, page, countBoundSql);
//通过connection建立一个countSql对应的PreparedStatement对象。
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = connection.prepareStatement(countSql);
//通过parameterHandler给PreparedStatement对象设置参数
parameterHandler.setParameters(pstmt);
//之后就是执行获取总记录数的Sql语句和获取结果了。
rs = pstmt.executeQuery();
if (rs.next()) {
int totalRecord = rs.getInt(1);
//给当前的参数page对象设置总记录数
page.setTotalRecord(totalRecord);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
51a4f060-f334-46a0-9e18-7ddce798cc3e | 6 | public SolutionState solve(int timeLimit, int bound) {
int n = graph.getNbVertices();
int minCost = graph.getMinArcCost();
int maxCost = graph.getMaxArcCost();
int[][] cost = graph.getCost();
next = new int[n];
Solver solver = new Solver();
// Create variables
// xNext[i] = vertex visited after i
IntVar[] xNext = new IntVar[n];
for (int i = 0; i < n; i++)
xNext[i] = VariableFactory.enumerated("Next " + i, graph.getSucc(i), solver);
// xCost[i] = cost of arc (i,xNext[i])
IntVar[] xCost = VariableFactory.boundedArray("Cost ", n, minCost, maxCost, solver);
// xTotalCost = total cost of the solution
IntVar xTotalCost = VariableFactory.bounded("Total cost ", n*minCost, bound - 1, solver);
// Add constraints
for (int i = 0; i < n; i++)
solver.post(IntConstraintFactory.element(xCost[i], cost[i], xNext[i], 0, "none"));
solver.post(IntConstraintFactory.circuit(xNext,0));
solver.post(IntConstraintFactory.sum(xCost, xTotalCost));
// limit CPU time
SearchMonitorFactory.limitTime(solver,timeLimit);
// set the branching heuristic (branch on xNext only by selecting smallest domains first)
solver.set(IntStrategyFactory.firstFail_InDomainMin(xNext));
// try to find and prove the optimal solution
solver.findOptimalSolution(ResolutionPolicy.MINIMIZE,xTotalCost);
// record solution and state
if(solver.getMeasures().getSolutionCount()>0){
if (solver.getSearchLoop().hasReachedLimit())
state = SolutionState.SOLUTION_FOUND;
else
state = SolutionState.OPTIMAL_SOLUTION_FOUND;
for(int i=0;i<n;i++) next[i] = xNext[i].getValue();
totalCost = xTotalCost.getValue();
}
else {
if(solver.getSearchLoop().hasReachedLimit())
state = SolutionState.NO_SOLUTION_FOUND;
else
state = SolutionState.INCONSISTENT;
}
return state;
} |
d6292877-647f-4443-b779-0ed5ace7b2e1 | 3 | public Monster(int x, int y, String name,int difficulty){
position = new Position(x, y);
this.target = GameManager.getPlayer().get(0);
//Novice
if(difficulty==1){
power = new AtomicInteger(5);
speed = new AtomicInteger(1);
LIFE_MAX = 50;
life = new AtomicInteger(50);
}
//Normal
else if(difficulty==2){
power = new AtomicInteger(5);
speed = new AtomicInteger(2);
LIFE_MAX = 75;
life = new AtomicInteger(75);
}
//Expert
else if(difficulty==3){
power = new AtomicInteger(15);
speed = new AtomicInteger(3);
LIFE_MAX = 100;
life = new AtomicInteger(100);
}
else{
power = new AtomicInteger(25);
speed = new AtomicInteger(3);
LIFE_MAX = 200;
life = new AtomicInteger(200);
}
moveCounter = new AtomicInteger(0);
pauseCounter = new AtomicInteger(0);
sprite = new AnimatedSprite(name, ANIMATIONSPEED);
} |
bd067fac-4030-41e4-b4c3-1dfeab270a23 | 2 | private boolean goalReached()
{
if(position[0] == bestgoal[0] && position[1] == bestgoal[1])
{
return(true);
}
else
{
return(false);
}
} |
f97faca8-74ba-4978-860e-69c273523ecf | 6 | private static void method495(char arg0[]) {
int off = 0;
for (int chars = 0; chars < arg0.length; chars++) {
if (Censor.method496(arg0[chars])) {
arg0[off] = arg0[chars];
} else {
arg0[off] = ' ';
}
if (off == 0 || arg0[off] != ' ' || arg0[off - 1] != ' ') {
off++;
}
}
for (int chars = off; chars < arg0.length; chars++) {
arg0[chars] = ' ';
}
} |
1872637c-9286-4413-aab2-09bfd5024ffd | 2 | public GuiTest() {
addMenu();
// addToolbar();
addCenter();
addStatusbar();
makeVisible();
new Thread() {
@Override
public void run() {
while (true) {
setColor();
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void setColor() {
// final Color dark = new Color(180, 205, 230);
final Color dark = new Color(206, 221, 237);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
menubar.setBackground(dark);
// toolbar.setBackground(dark);
}
});
};
}.start();
} |
16d42bc5-f6d4-470d-9b00-267e1a7f11f8 | 6 | private static boolean collapseOK(Element e1, Element e2) {
if (e1.getTagName() != e2.getTagName()) return false;
NamedNodeMap nnm1 = e1.getAttributes();
NamedNodeMap nnm2 = e2.getAttributes();
if (nnm1.getLength() != nnm2.getLength()) return false;
for (int i = 0; i < nnm1.getLength(); i++) {
if (nnm1.item(i).getNodeType() != nnm2.item(i).getNodeType()) {
return false;
}
if (nnm1.item(i).getNodeName() != nnm2.item(i).getNodeName()) {
return false;
}
if (nnm1.item(i).getNodeValue() != nnm2.item(i).getNodeValue()) {
return false;
}
}
return true;
} |
a4c6060a-fd22-4e15-bb0e-f6e9815b6eb3 | 3 | public String displayContent() {
String[] temp = this.content.split(" ");
String toReturn = "";
for (int i = 0; i < temp.length; i++) {
if (i % 20 != 0 || i == 0) {
toReturn += temp[i] + " ";
} else {
toReturn += temp[i] + "\n";
}
}
return toReturn;
} |
b32daadb-1208-4c1d-b675-392c3d0fd014 | 2 | public static final ByteBuffer getInfoBytes(byte[] torrent_file_bytes) throws BencodingException
{
Object[] vals = decodeDictionary(torrent_file_bytes,0);
if(vals.length != 3 || vals[2] == null)
throw new BencodingException("Exception: No info bytes found!");
return (ByteBuffer)vals[2];
} |
a4ad71ed-007a-4c87-92bb-bcace7b1a029 | 3 | public boolean play() {
if (playing()) {
return true;
}
for (int i=0; i<buffers.capacity(); i++) {
if (!stream(buffers.get(i))) {
return false;
}
}
AL10.alSourceQueueBuffers(source.get(0), buffers);
AL10.alSourcePlay(source.get(0));
return true;
} |
4dd8bf5e-81fc-46b1-97c0-53be26c7c603 | 5 | public static Matrix getRotationMatrix(int axis, double angle)
throws IndexOutOfBoundsException {
if (axis < X_AXIS || axis > Z_AXIS)
throw new IndexOutOfBoundsException();
double c = Math.cos(angle);
double s = Math.sin(angle);
Matrix rotate = Matrix.getIdentityMatrix();
switch (axis) {
case X_AXIS:
rotate.setDiagonal(1, c);
rotate.setDiagonal(2, c);
rotate.setAntiSymmetricComponent(2, 1, s);
break;
case Y_AXIS:
rotate.setDiagonal(0, c);
rotate.setDiagonal(2, c);
rotate.setAntiSymmetricComponent(0, 2, s);
break;
case Z_AXIS:
rotate.setDiagonal(0, c);
rotate.setDiagonal(1, c);
rotate.setAntiSymmetricComponent(1, 0, s);
break;
}
return rotate;
} |
d06d72ab-4d7f-4ba9-9797-2ad32da46a80 | 5 | private int validaDia( int d ) {
if ( d > 0 && d <= diasPorMes[ mes ] ) return d;
// se Fevereiro: Verifica se ano bissexto
if ( mes == 2 && d == 29 && anoBissexto(ano) )
return d;
System.out.println( "Dia " + d + " invalido. Colocado o dia 1." );
return 1; // Deixa o objecto num estado consistente
} |
145b449b-fcd1-4789-9684-680126b27f02 | 3 | public static <T> T[] intern(T[] arr) {
synchronized(ArrayIdentity.class) {
if(cleanint++ > 100) {
clean();
cleanint = 0;
}
}
Entry<T> e = new Entry<T>(arr);
synchronized(ArrayIdentity.class) {
Entry<T> e2 = getcanon(e);
T[] ret;
if(e2 == null) {
set.put(e, e);
ret = arr;
} else {
ret = e2.arr.get();
if(ret == null) {
set.remove(e2);
set.put(e, e);
ret = arr;
}
}
return(ret);
}
} |
75eab7cc-b54d-416b-a613-830ce7d4a62a | 5 | private void lstKullaniciListesiValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstKullaniciListesiValueChanged
String kulAdi = (String) lstKullaniciListesi.getSelectedValue();
Musteri m = (Musteri) mutlakkafe.MutlakKafe.
mainCont.getMusteriCont().bilgileriGetir(kulAdi);
if( m == null)
return ;
txtAd.setText(m.getAd());
txtSoyad.setText(m.getSoyad());
txtTelefon.setText(m.getTelefon());
txtKullaniciAdi.setText(m.getKulAdi());
txtSifre.setText(m.getSifre());
txtSifreTekrar.setText(m.getSifre());
txtKalanSure.setText(m.getKredi() + "");
txtKullanilanSure.setText(m.getHarcanan() + "");
txtIndirim.setText(m.getIndrim() + "");
txtBorc.setText(m.getBorc() + "");
comboGun.setSelectedIndex(m.getBitisTarihi().getDay());
comboAy.setSelectedIndex(m.getBitisTarihi().getMonth());
comboYil.setSelectedIndex(m.getBitisTarihi().getYear() - 114);
lblKayitTarihi.setText("Kayıt Tarihi :" + m.getKayitTarihi().toLocaleString());
switch(m.getOdemeSecenek()){
case MusteriC.ODEME_ONCEDEN:
radioOnceden.setSelected(true);
break;
case MusteriC.ODEME_SONRADAN:
radioSonradan.setSelected(true);
break;
}
switch (m.getUcretSecenek()) {
case MusteriC.UCRET_STANDART:
radioStandar.setSelected(true);
break;
case MusteriC.UCRET_UCRETSIZ:
radioUcretsiz.setSelected(true);
break;
default:
radioUyeUcreti.setSelected(true);
break;
}
}//GEN-LAST:event_lstKullaniciListesiValueChanged |
f96e176e-a0b6-489a-8291-8193fdece3ed | 0 | public String getSessionId() {
return sessionId;
} |
380a5cfd-6220-449b-b02f-18589a200a49 | 2 | private int high(int startindex)
{
if (startindex == grades.length-1)
{
return grades[startindex];
}
else
{
int highRest = high(startindex+1);
if (grades[startindex] > highRest)
{
return grades[startindex];
}
else
{
return highRest;
}
}
} |
fde455cd-7860-4583-81e4-4a9c94967787 | 1 | @Override
public String toString() {
if(getDenominator() == 1){
return "" + getNumerator();
}
return "" + getNumerator() + '/' + getDenominator();
} |
c5bb8b2c-3e43-41c2-9fe0-9f78ac43b235 | 6 | private int sameHandUpdated(ArrayList<Card> c, int recursion) {
ArrayList<Card> cards_tmp = new ArrayList<Card>();
Card yourCard = c.get(0);
if (recursion==1) {
if (c.get(1).getValue()>yourCard.getValue())
yourCard = c.get(1);
cards_tmp.add(yourCard);
for (int i=2; i<c.size(); i++)
cards_tmp.add(c.get(i));
return calculateValue(cards_tmp);
}
if (recursion==2) {
if (c.get(1).getValue()<yourCard.getValue())
yourCard = c.get(1);
cards_tmp.add(yourCard);
for(int i=2; i<c.size(); i++)
cards_tmp.add(c.get(i));
return calculateValue(cards_tmp);
}
return -1; // Should only pass in 1 or 2 in parameter
} |
c0cdafd5-c891-408b-94c8-e7f11f01af8d | 4 | public boolean createDirs() {
boolean test = false;
if (test || m_test) {
System.out.println("FileManager :: createDirs() BEGIN");
}
new File(getPath()).mkdirs();
if (test || m_test) {
System.out.println("FileManager :: createDirs() END");
}
return true;
} |
40da6e68-b90b-4b46-9935-93b521a2222a | 9 | public static void multipartUploadObejctByMultithreading(KS3Client client,
InputStream inputstream, long offset, long length, String bucketName,
String objectKey,String mimeType) throws Exception {
// 要上传到文件至少要一个Part的大小
if (length < PART_SIZE)
throw new IllegalArgumentException(
"The object you are trying to upload is not large as a PART_SIZE.");
// 起始位置不能在length之后
if (offset < 0 || offset > length)
throw new IllegalArgumentException("Illegal arguments");
//得到实际的length
length = length - offset;
//处理偏移量
try {
inputstream.skip(offset);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Skip data failed.");
}
// 计算上传的块的数量
int partCount = (int) (length / PART_SIZE);
if (length % PART_SIZE != 0)
partCount++;
// 初始化一个指定数量线程的线程池,并构造一个线程安全到list承载上传列表的相关信息
ExecutorService threadPool = Executors.newFixedThreadPool(CONCURRENCIES);
List<UploadPart> partList = Collections.synchronizedList(new ArrayList<UploadPart>());
// 初始化一个上传会话
InitiateMultipartUploadResult imur = client.initiateMultipartUpload(bucketName, objectKey,mimeType);
String uploadId = imur.getUploadId();
// 一次性读到内存,然后多线程同时上传
CopyInputStream copy = new CopyInputStream(inputstream);
System.out.println("[Upload start.]");
//依次启动在线程池内启动线程
for (int i = 0; i < partCount; i++) {
long start = PART_SIZE * i;
long currentPartSize = PART_SIZE < length - start ? PART_SIZE : length - start;
InputStream inputstreamCopy = copy.getCopy();
threadPool.execute(new UploadPartThread(start, bucketName,
objectKey, uploadId, i+1, currentPartSize, inputstreamCopy,client, partList));
}
//等待全部线程执行结束
threadPool.shutdown();
while (!threadPool.isTerminated()) {
threadPool.awaitTermination(5, TimeUnit.SECONDS);
}
//上传失败
if (partList.size() != partCount){
AbortMultipartUploadOptions abortMultipartUploadOptions = new AbortMultipartUploadOptions(bucketName, objectKey, uploadId);
client.abortMultipartUpload(abortMultipartUploadOptions);
throw new Exception("[Upload failed.]");
}
//上传成功
else{
//把partNum排序
Collections.sort(partList, new Comparator<UploadPart>(){
public int compare(UploadPart arg0, UploadPart arg1) {
UploadPart part1= arg0;
UploadPart part2= arg1;
return part1.getPartNumber() - part2.getPartNumber();
}
});
CompleteMultipartUploadOptions completeMultipartUploadOptions = new CompleteMultipartUploadOptions(bucketName, objectKey, uploadId, partList);
client.completeMultipartUpload(completeMultipartUploadOptions);
System.out.println("[Upload Suceess.]");
}
} |
905f5cf9-463c-41d3-a729-34df27db3678 | 6 | ITransientMap doAssoc(Object key, Object val) {
if (key == null) {
if (this.nullValue != val)
this.nullValue = val;
if (!hasNull) {
this.count++;
this.hasNull = true;
}
return this;
}
// Box leafFlag = new Box(null);
leafFlag.val = null;
INode n = (root == null ? BitmapIndexedNode.EMPTY : root)
.assoc(edit, 0, Util.hash(key), key, val, leafFlag);
if (n != this.root)
this.root = n;
if(leafFlag.val != null) this.count++;
return this;
} |
2a7a63b8-4cfd-495c-af35-17895fd3fdf6 | 4 | @Override
public double[] getData()
{
if (ptr != 0) {
return null;
} else {
if (isConstant()) {
if (length > getMaxSizeOf32bitArray()) return null;
double[] out = new double[(int) length];
for (int i = 0; i < length; i++) {
out[i] = data[0];
}
return out;
} else {
return data;
}
}
} |
35e9aa61-fb07-4042-acdb-6e3249c6397c | 4 | @Override
public void sortArray() {
this.arrayAccess = 0;
this.comparisions = 0;
T[] auxArray = array.clone();
for (int d = width - 1; d >= 0; d--) {
count = new int[radix + 1];
for (T item : array) {
count[keyMap.get(item) + 1]++;
}
for (int i = 0; i < radix; i++) {
count[i + 1] += count[i];
}
for (T item : array) {
auxArray[count[keyMap.get(item)]++] = item;
}
array = auxArray;
}
} |
d69f525a-4558-4370-9fdd-789dfa3424d7 | 2 | public static ItemInfo itemByItem(ItemInfo item) {
for (ItemInfo i : items) {
if (item.equals(i)) {
return i;
}
}
return null;
} |
06628cf1-75b5-4eb4-b8b1-7cdb87c9923d | 2 | public static void main(String[] args) {
int len = 10;
Array<Integer> arr = new Array<Integer>(len);
for (int i = 0; i < len; ++i) {
arr.append(i);
}
System.out.println(arr);
for (int i = 0; i < len; ++i) {
System.out.println("Random #" + i + ": " + Array.random(arr));
}
} |
f77bb0b2-df4f-400d-bcb9-2e0822b1528e | 1 | public List<Integer> getValues() {
List<Integer> valuesList = new ArrayList<Integer>();
for(int i = 0; i < size; i++) {
valuesList.addAll(map[i].getValues());
}
return valuesList;
} |
e222093b-94fb-4359-808b-a215cc16071b | 1 | public String toString() {
try {
return this.toJSON().toString(4);
} catch (JSONException e) {
return "Error";
}
} |
7079ce18-47a4-42b0-a1de-cb3ece3f446f | 2 | public State completeWith(State other) {
completeStylesWith(other);
if (other != null) {
description = StringUtils.defaultString(description, other.description);
if(other.isDoubled())
markDoubled();
}
return this;
} |
93b112be-0b8d-4ae8-8380-255baf202b30 | 7 | private void enqueueParents(final SSAConstructionInfo consInfo) {
final Set seen = new HashSet();
final Iterator iter = cfg.nodes().iterator();
while (iter.hasNext()) {
final Block block = (Block) iter.next();
final Iterator e = consInfo.realsAtBlock(block).iterator();
while (e.hasNext()) {
final VarExpr real = (VarExpr) e.next();
Node p = real.parent();
if ((p instanceof StoreExpr) && real.isDef()) {
p = p.parent();
}
if ((p instanceof Expr) && !seen.contains(p)) {
final Expr expr = (Expr) p;
seen.add(p);
if (isFirstOrder(expr)) {
worklist.addReal(expr);
}
}
}
}
} |
7aa153d9-4961-4fd1-b772-46c1b921dcbb | 7 | public static Cons allSuperrelations(NamedDescription relation, boolean removeequivalentsP) {
{ MemoizationTable memoTable000 = null;
Cons memoizedEntry000 = null;
Stella_Object memoizedValue000 = null;
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_ALL_SUPERRELATIONS_MEMO_TABLE_000.surrogateValue));
if (memoTable000 == null) {
Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_ALL_SUPERRELATIONS_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:META-KB-UPDATE))");
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_ALL_SUPERRELATIONS_MEMO_TABLE_000.surrogateValue));
}
memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), relation, ((Context)(Stella.$CONTEXT$.get())), (removeequivalentsP ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER), Stella.MEMOIZED_NULL_VALUE, -1);
memoizedValue000 = memoizedEntry000.value;
}
if (memoizedValue000 != null) {
if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) {
memoizedValue000 = null;
}
}
else {
memoizedValue000 = NamedDescription.helpMemoizeAllSuperrelations(relation, removeequivalentsP);
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000);
}
}
{ Cons value000 = ((Cons)(memoizedValue000));
return (value000);
}
}
} |
d39a19d0-daab-4dc6-b57a-f8fc7cba1730 | 8 | private void toggleDebugger(JMenuItem src, Class<?> listener) {
Bot b = window.getActiveBot();
if (b != null) {
HijackCanvas c = b.getCanvas();
boolean removed = false;
if (c == null) {
b.getLogger().log(new LogRecord(Level.SEVERE, "Error accessing canvas..."));
return;
}
for (int i = 0; i < c.getListeners().size(); i++) {
ProjectionListener pl = c.getListeners().get(i);
if (pl.getClass().equals(listener)) {
Debugger d = (Debugger) pl;
d.uninstall();
c.getListeners().remove(i);
removed = true;
src.setIcon(null);
b.getLogger().log(new LogRecord(Level.FINE, "Uninstalled " + d.getClass().getSimpleName().replaceAll("Debug", "") + " debugger"));
break;
}
}
if (!removed) {
try {
Debugger d = (Debugger) listener.newInstance();
d.install(b);
c.getListeners().add(d);
src.setIcon(tickIcon);
b.getLogger().log(new LogRecord(Level.FINE, "Installed " + d.getClass().getSimpleName().replaceAll("Debug", "") + " debugger"));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
} |
f6e4c5cb-8265-470d-85b7-fa9213338360 | 2 | private static void firstStrategy()
{
Semaphore MReading = new Semaphore(1);
Semaphore MWriting = new Semaphore(1);
int counter = 0;
Random r = new Random();
while(true)
{
if(r.nextDouble() > 0.5)
{
Lecteur l = new Lecteur(MReading,MWriting,counter);
l.run();
counter = l.counter;
}
else
new Redacteur(MWriting).run();
System.out.println("----->Counter : " + counter);
}
} |
dc400bfb-1f80-48ca-a590-56b0306f24e4 | 8 | protected Object evaluateElement(Object current, Object next)
throws UDFArgumentException {
boolean lessThan = false;
if (next==null)
return current;
if (current == null)
return next;
switch (elementOI.getPrimitiveCategory()) {
case INT: lessThan = (((IntObjectInspector)elementOI).get(next) <
((IntObjectInspector)elementOI).get(current));
break;
case FLOAT: lessThan = (((FloatObjectInspector)elementOI).get(next) <
((FloatObjectInspector)elementOI).get(current));
break;
case DOUBLE: lessThan = (((DoubleObjectInspector)elementOI).get(next) <
((DoubleObjectInspector)elementOI).get(current));
break;
case LONG: lessThan = (((LongObjectInspector)elementOI).get(next) <
((LongObjectInspector)elementOI).get(current));
break;
case SHORT: lessThan = (((ShortObjectInspector)elementOI).get(next) <
((ShortObjectInspector)elementOI).get(current));
break;
default: throw new UDFArgumentException("Currently only int, float, double, long and short types are supported for this operation");
}
if (!lessThan){
return next;
}
return current;
} |
077a94f3-67b7-40cc-a260-2df1e04dfed7 | 3 | public int getExperienceToLevel(int skill, int level) {
if (level < 0 || level > 99)
return -1;
int experience = getExperience(skill);
if (experience == -1)
return -1;
return EXPERIENCE_TABLE[level] - experience;
} |
b6f63f59-ec7f-436b-8759-5a1d05cb8622 | 9 | public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(root == null)return result;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.addLast(root);
TreeNode first = root;
int level = 0;
while(!queue.isEmpty()) {
TreeNode node = queue.removeFirst();
if(node == first) {
ArrayList<Integer> oneLevel = new ArrayList<Integer>();
oneLevel.add(node.val);
for(TreeNode n : queue) {
oneLevel.add(n.val);
}
result.add(oneLevel);
if(level%2 != 0)Collections.reverse(oneLevel);
level++;
first = null;
}
if(node.left != null) {
queue.addLast(node.left);
if(first == null) first = node.left;
}
if(node.right != null) {
queue.addLast(node.right);
if(first == null) first = node.right;
}
}
return result;
} |
fedaead4-981d-4e7f-9ac8-7a15654cc5ad | 1 | private void recreateMesh() {
Vertex[] vertexes = new Vertex[text.length() * 4];
int[] indices = new int[6 * text.length()];
float lastX = 0;
for(int i=0; i<text.length(); i++){
Glyph glyph = font.getGlyph((int)text.charAt(i));
vertexes[0 + i*4] = new Vertex(new Vector3f(lastX -(float)glyph.getOffX()/size,-(float)glyph.getOffY()/size,0), new Vector2f((float)glyph.getX()/512,(float)(glyph.getY() + glyph.getYs())/512));
vertexes[1 + i*4] = new Vertex(new Vector3f(lastX -(float)glyph.getOffX()/size,(float)glyph.getYs()/size -(float)glyph.getOffY()/size,0), new Vector2f((float)glyph.getX()/512,(float)glyph.getY()/512));
vertexes[2 + i*4] = new Vertex(new Vector3f((float)glyph.getXs()/size + lastX -(float)glyph.getOffX()/size,(float)glyph.getYs()/size -(float)glyph.getOffY()/size,0), new Vector2f((float)(glyph.getX() + glyph.getXs())/512, (float)glyph.getY()/512));
vertexes[3 + i*4] = new Vertex(new Vector3f((float)glyph.getXs()/size + lastX -(float)glyph.getOffX()/size,-(float)glyph.getOffY()/size,0), new Vector2f((float)(glyph.getX() + glyph.getXs())/512, (float)(glyph.getY() + glyph.getYs())/512));
indices[0 + i*6] = 0 + i*4;
indices[1 + i*6] = 3 + i*4;
indices[2 + i*6] = 2 + i*4;
indices[3 + i*6] = 2 + i*4;
indices[4 + i*6] = 1 + i*4;
indices[5 + i*6] = 0 + i*4;
lastX += (float)glyph.getAdvX()/size;
}
this.mesh = new Mesh(vertexes,indices);
} |
4a291531-e679-48e5-8edc-c72453d48ec6 | 0 | public void setId(String value) {
this.id = value;
} |
df2f350e-5722-4ad9-9598-6c032b593496 | 9 | public boolean checkPossible() {
int[] horizontalMax = new int[myLawn.length];
int[] verticalMax = new int[myLawn[0].length];
for (int i = 0; i < myLawn.length; i++) {
int max = 0;
for (int j = 0; j < myLawn[0].length; j++)
if (max < myLawn[i][j])
max = myLawn[i][j];
horizontalMax[i] = max;
}
for (int i = 0; i < myLawn[0].length; i++) {
int max = 0;
for (int j = 0; j < myLawn.length; j++)
if (max < myLawn[j][i])
max = myLawn[j][i];
verticalMax[i] = max;
}
for (int i = 0; i < myLawn.length; i++)
for (int j = 0; j < myLawn[0].length; j++) {
if (myLawn[i][j] < Math.min(horizontalMax[i], verticalMax[j]))
return false;
}
return true;
} |
4459b018-7804-46f5-a7de-0134e1de2e91 | 3 | */
public void birthNewVictim(int i) {
if (i % 5 == 0) {
ArrayList <Ostrich> arrayList = new ArrayList<Ostrich>();
for (int index = 0; index < animalFactory.getQuantityOfVictims(); index++) {
Ostrich ostrich = (Ostrich) animalFactory.createNewVictim();
ostrich.position = new Position((int) (Math.random() * this.length), (int) (Math.random() * this.height));
ostrich.hurdleFactory = this.hurdleFactory;
ostrich.desert = Desert.this;
arrayList.add(ostrich);
Initialization.numberVictims = animalFactory.getQuantityOfVictims();
Statistic.spawnedVictims++;
}
for (int index = 0; index < arrayList.size(); index++) {
animalFactory.addVictim(arrayList.get(index));
}
}
} |
17dbde7a-2f16-4f0d-9b38-a8ba7f666b62 | 5 | private void updateTabla(){
//** pido los datos a la tabla
Object[][] vcta = this.getDatos();
//** se colocan los datos en la tabla
DefaultTableModel datos = new DefaultTableModel();
tabla.setModel(datos);
datos = new DefaultTableModel(vcta,colum_names_tabla);
tabla.setModel(datos);
//ajustamos tamaño de la celda Fecha Alta
/*TableColumn columna = tabla.getColumn("Fecha Alta");
columna.setPreferredWidth(100);
columna.setMinWidth(100);
columna.setMaxWidth(100);*/
if (!lab_tipo_pto_venta.getText().equals("")){
//posicionarAyuda(lab_tipo_pto_venta.getText());
}
else{
if ((fila_ultimo_registro-1 >= 0)&&(fila_ultimo_registro-1 < tabla.getRowCount())){
tabla.setRowSelectionInterval(fila_ultimo_registro-1,fila_ultimo_registro-1);
scrollCellToView(this.tabla,fila_ultimo_registro-1,fila_ultimo_registro-1);
cargar_ValoresPorFila(fila_ultimo_registro-1);
}
else{
if ((fila_ultimo_registro+1 >= 0)&&(fila_ultimo_registro+1 <= tabla.getRowCount())){
tabla.setRowSelectionInterval(fila_ultimo_registro,fila_ultimo_registro);
scrollCellToView(this.tabla,fila_ultimo_registro,fila_ultimo_registro);
cargar_ValoresPorFila(fila_ultimo_registro);
}
}
}
} |
f51063a4-bd69-4103-8bc0-8ce467ccc8e6 | 9 | public int majorityNumber(List<Integer> nums) {
// write your code
int candicate1 = 0, candicate2 = 0, count1 = 0, count2 = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) == candicate1) {
count1++;
} else if (nums.get(i) == candicate2) {
count2++;
} else if (count1 == 0) {
candicate1 = nums.get(i);
count1 = 1;
} else if (count2 == 0) {
candicate2 = nums.get(i);
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) == candicate1) {
count1++;
} else if (nums.get(i) == candicate2) {
count2++;
}
}
return count1 > count2 ? candicate1 : candicate2;
} |
f6505370-598b-4842-aec0-bc161faebbcc | 2 | @Override
public long defier(String a, String b) {
Player p1 = em.find(Player.class, a);
Player p2 = em.find(Player.class, b);
if (p2 != null && p1 != null) {
Defi d = new Defi(p1, p2);
em.persist(d);
return d.getId();
} else {
return 0;
}
} |
4c12de52-340b-49d5-8e6f-999d4b1d8f33 | 6 | public static void main(String[] args) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("load-database")) {
System.out.println("Loading database...");
SqlFortune f = new SqlFortune();
f.createDb();
f.loadFromFiles();
System.out.println(f.getFortune());
System.out.println(f.getFortune("futurama"));
f.closeDb();
}
} else {
instance = new FortuneBot();
instance.connect();
while (instance.running()) {
try {
// pause briefly
Thread.sleep(500);
if ( !instance.connection.isConnected()) {
instance.connect();
}
}
catch (InterruptedException ex) {
System.err.println("Caught Interrupted Exception");
ex.printStackTrace();
}
}
// another delay, so clean up can occur (eg Wismar msg).
try {
// pause briefly
Thread.sleep(2000);
}
catch (InterruptedException ex) {
System.err.println("Caught Interrupted Exception");
ex.printStackTrace();
}
}
} |
4d890211-1fde-460c-8448-16c61ec2e201 | 3 | public Class<?> getDataType() {
if(superProperty == null) {
if(dataType == null) {
return null;
}
return dataType;
}
return superProperty.getDataType();
} |
c0847c0a-2ed6-45e3-8bc4-c570f0e87001 | 5 | @Override
public boolean perform(final Context context) {
// Example: /<command> off[ <Player>]
OfflinePlayer target = Parser.parsePlayer(context, 1);
if (target == null && context.sender instanceof OfflinePlayer) target = (OfflinePlayer) context.sender;
if (target == null) {
Main.messageManager.send(context.sender, "Unable to determine player", MessageLevel.SEVERE, false);
return false;
}
String targetName = target.getName();
if (target.getPlayer() != null) targetName = target.getPlayer().getName();
if (!Timestamp.isAllowed(context.sender, this.permission, targetName)) {
Main.messageManager.send(context.sender, "You are not allowed to use the " + this.getNamePath() + " action for " + target.getName(), MessageLevel.RIGHTS, false);
return true;
}
final Recipient recipient = Timestamp.getRecipient(target);
recipient.setFormat("%1$s");
recipient.save();
Main.messageManager.send(context.sender, "Timestamp format for " + targetName + " has been set to: " + TimestampFormatGet.message(recipient.load()), MessageLevel.STATUS, false);
return true;
} |
aa669fb9-e0da-4ca2-bfeb-9da60a21132b | 9 | public List<Location> adjacentLocations(Location location) {
assert location != null : "Null location passed to adjacentLocations";
// The list of locations to be returned.
List<Location> locations = new LinkedList<>();
if (location != null) {
int row = location.getRow();
int col = location.getCol();
for (int roffset = -1; roffset <= 1; roffset++) {
int nextRow = row + roffset;
if (nextRow >= 0 && nextRow < depth) {
for (int coffset = -1; coffset <= 1; coffset++) {
int nextCol = col + coffset;
// Exclude invalid locations and the original location.
if (nextCol >= 0 && nextCol < width
&& (roffset != 0 || coffset != 0)) {
locations.add(new Location(nextRow, nextCol));
}
}
}
}
// Shuffle the list. Several other methods rely on the list
// being in a random order.
Collections.shuffle(locations, rand);
}
return locations;
} |
bf9e834d-2249-4e56-9098-bc38eb6017d7 | 4 | public static void editPartDialog(Part p) {
JPanel addPart = new JPanel();
JPanel input = new JPanel(new SpringLayout());
JLabel nameLabel = new JLabel("Name*");
JTextField name = new JTextField(p.name);
JLabel quantLabel = new JLabel("Quantity");
SpinnerNumberModel quantMod = new SpinnerNumberModel(p.quantity,0,10000,1);
JSpinner quant = new JSpinner(quantMod);
JLabel locationLabel = new JLabel("Location");
JComboBox location = new JComboBox(Location.getLocationNames());
location.setSelectedIndex(p.location.getLocationNum());
JLabel descriptionLabel = new JLabel("Description");
JTextField description = new JTextField(p.description);
JLabel notesLabel = new JLabel("Notes");
JTextField notes = new JTextField(p.notes);
input.add(nameLabel);
input.add(name);
input.add(quantLabel);
input.add(quant);
input.add(locationLabel);
input.add(location);
input.add(descriptionLabel);
input.add(description);
input.add(notesLabel);
input.add(notes);
name.setFocusable(true);
name.requestFocusInWindow();
location.setSelectedIndex(last);
SpringUtilities.makeCompactGrid(input, 5, 2, 6, 6, 10, 10);
boolean add = true;
while(add) {
int val = JOptionPane.showOptionDialog(null, input,"Edit Part",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE, null, new Object[] {"OK", "Cancel"}, name);
System.out.println(val);
if (val==2||val==-1)
break;
if (name.getText().replace("~", "").equals("")) {
JOptionPane.showMessageDialog(null, "Items must have a name.");
continue;
}
add = false;
p.name = name.getText().replace("~", "");
p.quantity = (Integer) quant.getValue();
p.location = Location.values()[location.getSelectedIndex()];
last = location.getSelectedIndex();
p.description = description.getText().replace("~", "");
p.notes = notes.getText().replace("~", "");
Main.mainInstance.updateTable();
Main.mainInstance.setTableScrollTo(Main.partList.indexOf(p));
}
} |
8565fdba-b54c-486c-b436-1d26927c4697 | 8 | public static void main(String[] args) {
ConsistentGlobalProblemSetInitialisation starter = new ConsistentGlobalProblemSetInitialisation();
starter.initLanguage(new char[] { '0', '1' }, 10, "(1(01*0)*1|0)*");
int solutionFoundCounter = 0;
int noSolutionFound = 0;
List<Long> cycleCount = new LinkedList<Long>();
long tmpCycle;
long timeStamp;
int[] problemCount = new int[5];
int[] candidatesCount = new int[5];
int[] noCycles = new int[2];
problemCount[0] = 10;
problemCount[1] = 20;
problemCount[2] = 30;
problemCount[3] = 40;
problemCount[4] = 50;
candidatesCount[0] = 10;
candidatesCount[1] = 20;
candidatesCount[2] = 30;
candidatesCount[3] = 40;
candidatesCount[4] = 50;
noCycles[0] = 250;
noCycles[1] = 500;
int pc = 0;
int cc = 0;
int nc = 0;
for (int x = 0; x < 1; x++) {
System.out.println("x:"+x);
for (int n = 0; n < 25; n++) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
Logger l = new Logger("C_G_" + df.format(new Date()) + ".log", true);
pc = problemCount[n % 5];
cc = candidatesCount[(int) Math.floor(n / 5)];
nc = noCycles[1];
l.log("Problem Count: " + pc);
l.log("CandidatesCount: " + cc);
l.log("Max Cycles: " + nc);
solutionFoundCounter = 0;
noSolutionFound = 0;
cycleCount = new LinkedList<Long>();
for (int i = 0; i < 100; i++) {
timeStamp = System.currentTimeMillis();
starter.initProblems(pc);
starter.initCandidates(cc);
tmpCycle = starter.startEvolution(nc);
l.log(i + ": finished ("
+ (System.currentTimeMillis() - timeStamp) + "ms, "
+ tmpCycle + "cycles)");
if (starter.getWinner() != null) {
solutionFoundCounter++;
cycleCount.add(tmpCycle);
l.log(i + ": Solution found.");
} else {
noSolutionFound++;
l.log(i + ": No solution found.");
}
}
long max = 0;
long min = 10000;
long sum = 0;
for (long no : cycleCount) {
sum += no;
max = (no > max ? no : max);
min = (no < min ? no : min);
}
l.log("Solution Found: " + solutionFoundCounter);
l.log("Avg cycles: "
+ (cycleCount.size() > 0 ? sum / cycleCount.size()
: '0'));
l.log("Max cycles: " + max);
l.log("Min cycles: " + min);
l.log("No solution found: " + noSolutionFound);
l.finish();
}
}
} |
ec8aed8a-b153-4861-bfee-6d7160265ce0 | 6 | public <T extends ActiveRecord> T createObject(ResultSet rs, Class<T> clazz,
PropertyDescriptor[] props, int[] columnToProperty)
throws SQLException {
T object = newInstance(clazz);
for (int i = 1; i < columnToProperty.length; i++) {
if (columnToProperty[i] == -1) {
continue;
}
PropertyDescriptor prop = props[columnToProperty[i]];
Class<?> propertyType = prop.getPropertyType();
Object value = processColumn(rs, i, propertyType);
if (propertyType != null && propertyType.isPrimitive()
&& value == null) {
value = primitives.get(propertyType);
}
invokeSetter(object, prop, value);
}
return object;
} |
40143eec-60d3-4de0-ad41-3ceccee57ad2 | 0 | public void setPassword(String password) {
this.password = password;
} |
bbafbcaa-df59-47ec-97bf-64431da78b36 | 8 | public static int deleteFileByScanPrefixFilter(String tablename, String rowPrifix) {
HTableInterface table = null;
int count = 0;
try {
table = getTable(tablename);
Scan s = new Scan();
s.setFilter(new PrefixFilter(rowPrifix.getBytes()));
ResultScanner rss = table.getScanner(s);
for (Result rs : rss) {
Cell[] cells = rs.rawCells();
for (Cell cell : cells) {
if (toString(CellUtil.cloneQualifier(cell)).equals("repeatFileRowKey")) {
String value = toString(CellUtil.cloneValue(cell));
if (value.contains(",")) {
String rowKeys[] = value.split(",");
// 根据文件标题删除重复的文件,留最后一个
if (rowKeys != null && rowKeys.length > 0) {
for (int i = 0; i < rowKeys.length - 1; i++) {
table.delete(new Delete(toBytes(rowKeys[i])));
count = count + 1;
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
closeTable(table);
}
return count;
} |
372fbf51-3495-4d93-8024-25e7f2c9fffa | 6 | public void render() {
counter++;
if (counter % 100 == 0)
xtime++;
if (counter % 100 == 0)
ytime++;
for (int y = 0; y < height; y++) {
if (ytime >= height)
break;
for (int x = 0; x < width; x++) {
if (xtime >= width)
break;
pixels[xtime + ytime * width] = 0xff00ff;
}
}
} |
bcd121f2-d2ad-4f7d-aa39-69a833577c90 | 0 | public void sign(String file, String encrypted_file) throws Exception {
FileOutputStream PGP_file = new FileOutputStream(encrypted_file, true);
SP sp = new SP(file, pub_exp, priv_exp, mod);
sp.dump(PGP_file);
//PGP_file.write((byte)0xDE);
//PGP_file.write((byte)0xAD);
PGP_file.close();
} |
5c82945a-8154-46b3-8a6a-95fd40548ed6 | 8 | public static String getEntityName(Class<?> clazz) {
Annotation entityAnnotation = null;
for (Annotation annotation : clazz.getAnnotations()) {
Class<?> annotationClass = annotation.annotationType();
if (annotationClass.getName().equals("javax.persistence.Entity")) {
entityAnnotation = annotation;
}
}
if (entityAnnotation == null) {
return null;
}
try {
Method method = entityAnnotation.getClass().getMethod("name");
String name = (String) method.invoke(entityAnnotation);
if (name != null && name.length() > 0) {
return name;
} else {
return null;
}
} catch (Exception e) {
throw new IllegalStateException("Could not get entity name from class " + clazz, e);
}
} |
8a389746-3338-46ee-95bc-640d76f40076 | 9 | private final int getNextProbableNode(int y) {
if (toVisit > 0) {
int danglingUnvisited = -1;
final double[] weights = new double[visited.length];
double columnSum = 0.0d;
for (int i = 0; i < visited.length; i++) {
columnSum += Math.pow(instance.readPheromone(y, i), AntColony.ALPHA)
* Math.pow(instance.invertedMatrix[y][i], AntColony.BETA);
}
double sum = 0.0d;
for (int x = 0; x < visited.length; x++) {
if (!visited[x]) {
weights[x] = calculateProbability(x, y, columnSum);
sum += weights[x];
danglingUnvisited = x;
}
}
if (sum == 0.0d)
return danglingUnvisited;
// weighted indexing stuff
double pSum = 0.0d;
for (int i = 0; i < visited.length; i++) {
pSum += weights[i] / sum;
weights[i] = pSum;
}
final double r = random.nextDouble();
for (int i = 0; i < visited.length; i++) {
if (!visited[i]) {
if (r <= weights[i]) {
return i;
}
}
}
}
return -1;
} |
8083041e-a7d4-4c36-b3d5-59f050c9ae82 | 3 | public JsonSettings() {
String jsonData = "";
try {
//TODO Find a better way to store the settings file
FileInputStream settingsStream = new FileInputStream("/tmp/settings.json");
try (java.util.Scanner s = new java.util.Scanner(settingsStream)) {
jsonData = s.useDelimiter("\\A").hasNext() ? s.next() : "";
}
} catch (Exception e) {
e.printStackTrace();
}
Gson gson = new Gson();
Settings settings = gson.fromJson(jsonData, Settings.class);
String tmpIP = settings.getHubConnectDetails().getAddress();
if (tmpIP.startsWith("dchub://")) {
IP = tmpIP.replace("dchub://", "");
} else{
IP = tmpIP;
}
port = settings.getHubConnectDetails().getPort().intValue();
username = settings.getUserDetails().getUsername();
password = settings.getUserDetails().getPassword();
description = settings.getUserDetails().getDescription();
email = settings.getUserDetails().getEmail();
supportedFeatures = settings.getSupportedFeatures();
} |
1fb68b91-378c-449d-b205-d48d9b696c3a | 0 | public void setFunHabilitado(String funHabilitado) {
this.funHabilitado = funHabilitado;
} |
a9d6280a-42ee-41d4-81bc-470d18a9a361 | 3 | void assignBMEWeights( double[][] A )
{
edge e;
e = depthFirstTraverse(null);
while (null != e)
{
if ( e.head.leaf() || e.tail.leaf() )
e.BalWFext(A);
else
e.BalWFint(A);
e = depthFirstTraverse(e);
}
} |
1cfcd5bd-0724-4dea-94ee-6bb9f0d78f70 | 1 | @Override
public void clear() {
for (int i=0; i<filter.length; i++) { filter[i] = 0; }
} |
2b46d0e5-21c8-4729-b762-681c6188ff62 | 9 | public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
if(container.getInput().isKeyPressed(Keyboard.KEY_ESCAPE)){
game.enterState(MenuState.ID);
}
if(!b.isGameOver()){
TetrisRobot.findGhost();
totalDelta += delta;
if(FacebookBoard.isFound()){
if(moved){
b.setPiece(FacebookBoard.nextPiece);
if(b.getPiece() != null)
moved = false;
return;
}
if(!moved){
b.setBoard(TetrisRobot.parseBoard());
Move m = MoveFinder.getBestMove(b, b.getPiece().clonePiece(), agent);
if(m != null){
TetrisRobot.rotate(-m.rot);
if(3 < m.x){
TetrisRobot.right(m.x-3);
}else if(3 > m.x){
TetrisRobot.left(3-m.x);
}
TetrisRobot.drop();
b.getPiece().setRoation(m.rot);
b.getPiece().setLocation(m.x, m.y);
b.drop(true);
totalDelta = 0;
moved = true;
b.setPiece(null);
}
}
}
}
} |
f0d3aa26-8342-45de-b2ea-28bd37d9ec7e | 1 | public GT getGameTable() {
if(gameTable.isSetUp) {
return gameTable;
} else {
gameTable.setupTable();
return gameTable;
}
} |
41b2fcc1-6652-49a2-90c0-440dd60b9145 | 1 | public DataModule getDataModule(String moduleName) {
if(!fragments.contains(moduleName)){
addModule(moduleName);
}
return NSpaceManager.getDataModule(moduleName);
} |
d723cd0e-89d1-4139-b919-ddc3c6095fee | 4 | public boolean isUpperTriagonal(){
boolean test = true;
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
if(j<i && this.matrix[i][j]!=0.0D)test = false;
}
}
return test;
} |
8cc02bd9-a1c4-41b9-8b23-db157cce5463 | 9 | private void routeReplyReceived(RREP rrep, int senderNodeAddress) {
//rrepRoutePrecursorAddress is an local int used to hold the next-hop address from the forward route
int rrepRoutePrecursorAddress = -1;
//Create route to previous node with unknown seqNum (neighbour)
if(routeTableManager.createForwardRouteEntry( senderNodeAddress,
senderNodeAddress,
Constants.UNKNOWN_SEQUENCE_NUMBER, 1, true)){
Debug.print("Receiver: RREP where received and route to: "+senderNodeAddress+" where created with destSeq: "+Constants.UNKNOWN_SEQUENCE_NUMBER);
}
rrep.incrementHopCount();
if (rrep.getSourceAddress() != nodeAddress) {
//forward the RREP, since this node is not the one which requested a route
sender.queuePDUmessage(rrep);
// handle the first part of the route (reverse route) - from this node to the one which originated a RREQ
try {
//add the sender node to precursors list of the reverse route
ForwardRouteEntry reverseRoute = routeTableManager.getForwardRouteEntry(rrep.getSourceAddress());
reverseRoute.addPrecursorAddress(senderNodeAddress);
rrepRoutePrecursorAddress = reverseRoute.getNextHop();
} catch (AodvException e) {
//no reverse route is currently known so the RREP is not sure to reach the originator of the RREQ
}
}
// handle the second part of the route - from this node to the destination address in the RREP
try {
ForwardRouteEntry oldRoute = routeTableManager.getForwardRouteEntry(rrep.getDestinationAddress());
if(rrepRoutePrecursorAddress != -1){
oldRoute.addPrecursorAddress(rrepRoutePrecursorAddress);
}
//see if the RREP contains updates (better seqNum or hopCountNum) to the old route
routeTableManager.updateForwardRouteEntry(oldRoute,
new ForwardRouteEntry( rrep.getDestinationAddress(),
senderNodeAddress,
rrep.getHopCount(),
rrep.getDestinationSequenceNumber(),
oldRoute.getPrecursors()));
} catch (NoSuchRouteException e) {
ArrayList<Integer> precursorNode = new ArrayList<Integer>();
if(rrepRoutePrecursorAddress != -1){
precursorNode.add(rrepRoutePrecursorAddress);
}
routeTableManager.createForwardRouteEntry( rrep.getDestinationAddress(),
senderNodeAddress,
rrep.getDestinationSequenceNumber(),
rrep.getHopCount(),
precursorNode, true);
} catch (RouteNotValidException e) {
//FIXME den er gal paa den
Debug.print("Receiver: FATAL ERROR");
try {
//update the previously known route with the better route contained in the RREP
routeTableManager.setValid(rrep.getDestinationAddress(), rrep.getDestinationSequenceNumber());
if(rrepRoutePrecursorAddress != -1){
routeTableManager.getForwardRouteEntry(rrep.getDestinationAddress()).addPrecursorAddress(rrepRoutePrecursorAddress);
}
}catch (AodvException e1) {
}
}
} |
e7184192-fd0b-4433-a0c4-e6415a2d5bbc | 2 | public ServerConnection(String server, int id, int tab)
{
serverid = id;
servertab = tab;
serverip = server;
setName(Main.user);
try
{
connect(server);
}
catch (IOException e)
{
Main.gui.tabs.get(tab).addMessage((e.getMessage()));
}
catch (IrcException e)
{
Main.gui.tabs.get(tab).addMessage((e.getMessage()));
}
} |
ecc062db-f55a-40d5-b0d0-37afe67fdb7e | 9 | public static void main(String[] a) throws IOException {
Scanner s = new Scanner(new File(a[0]));
while (s.hasNextLine()) {
String[] arr1 = s.nextLine().split("\\|");
String sub = arr1[1].trim();
String[] arr2 = arr1[0].split(" ");
// init
Map<char[], String> map = new LinkedHashMap<char[], String>();
for (String str : arr2) {
char[] arr = str.trim().toCharArray();
map.put(arr, str.trim());
}
for (char c : sub.toCharArray()) {
List<char[]> toRemove = new ArrayList<char[]>();
for (char[] arr : map.keySet()) {
Arrays.sort(arr);
int index = Arrays.binarySearch(arr, c);
if (index > -1) {
arr[index] = ' ';
} else {
toRemove.add(arr);
}
}
// remove
for (char[] arr : toRemove) {
map.remove(arr);
}
}
// print
int i = 0;
if (map.isEmpty()) {
System.out.println("False");
} else {
for (char[] arr : map.keySet()) {
System.out.print(map.get(arr));
if (i < map.size() - 1) {
System.out.print(" ");
}
i++;
}
System.out.println();
}
}
} |
f1c0316c-5135-458e-901a-b4625baba0b7 | 4 | public void release(int x, int y) {
if (amplitude.isActive()) {
amplitude.release();
} else if (period.isActive()) {
period.release();
} else if (amplitude2.isActive()) {
amplitude2.release();
} else if (period2.isActive()) {
period2.release();
}
} |
f688f69a-a9c9-4559-8305-fba5a87f403a | 8 | private void method98(Mobile mobile) {
if (mobile.anInt1548 == Client.loopCycle || mobile.animationId == -1 || mobile.animationDelay != 0 || mobile.anInt1528 + 1 > Sequence.sequenceCache[mobile.animationId].getFrameLength(mobile.anInt1527)) {
int i = mobile.anInt1548 - mobile.anInt1547;
int j = Client.loopCycle - mobile.anInt1547;
int k = mobile.anInt1543 * 128 + mobile.anInt1540 * 64;
int l = mobile.anInt1545 * 128 + mobile.anInt1540 * 64;
int i1 = mobile.anInt1544 * 128 + mobile.anInt1540 * 64;
int j1 = mobile.anInt1546 * 128 + mobile.anInt1540 * 64;
mobile.x = (k * (i - j) + i1 * j) / i;
mobile.y = (l * (i - j) + j1 * j) / i;
}
mobile.anInt1503 = 0;
if (mobile.anInt1549 == 0) {
mobile.turnDirection = 1024;
}
if (mobile.anInt1549 == 1) {
mobile.turnDirection = 1536;
}
if (mobile.anInt1549 == 2) {
mobile.turnDirection = 0;
}
if (mobile.anInt1549 == 3) {
mobile.turnDirection = 512;
}
mobile.anInt1552 = mobile.turnDirection;
} |
fb6626d7-9ded-43fc-91e2-b99e1b55e3ef | 7 | public void atualizar(Material material) {
jComboBoxEdicao.removeAllItems();
jComboBoxAnoPublicacao.removeAllItems();
jComboBoxAutor.removeAllItems();
jComboBoxEditora.removeAllItems();
jComboBoxCategoria.removeAllItems();
jComboBoxPublico.removeAllItems();
jComboBoxFormato.removeAllItems();
jTextFieldTitulo.setText(material.getDadoMaterial().getTitulo());
jTextFieldDescricao.setText(material.getDadoMaterial().getDescricao());
for (Edicao edicao : listaView.getMaterialComboBox().getEdicoes()) {
jComboBoxEdicao.addItem(edicao);
}
jComboBoxEdicao.setSelectedItem(material.getDadoMaterial().getEdicao());
for (AnoPublicacao anoPublicacao : listaView.getMaterialComboBox().getAnosPublicacoes()) {
jComboBoxAnoPublicacao.addItem(anoPublicacao);
}
jComboBoxAnoPublicacao.setSelectedItem(material.getDadoMaterial().getAnoPublicacao());
for (Autor autor : listaView.getMaterialComboBox().getAutores()) {
jComboBoxAutor.addItem(autor);
}
jComboBoxAutor.setSelectedItem(material.getDadoMaterial().getAutor());
for (Editora editora : listaView.getMaterialComboBox().getEditoras()) {
jComboBoxEditora.addItem(editora);
}
jComboBoxEditora.setSelectedItem(material.getDadoMaterial().getEditora());
for (Categoria categoria : listaView.getMaterialComboBox().getCategorias()) {
jComboBoxCategoria.addItem(categoria);
}
jComboBoxCategoria.setSelectedItem(material.getDadoMaterial().getCategoria());
for (Publico publico : listaView.getMaterialComboBox().getPublicos()) {
jComboBoxPublico.addItem(publico);
}
jComboBoxPublico.setSelectedItem(material.getDadoMaterial().getPublico());
for (Formato formato : listaView.getMaterialComboBox().getFormatos()) {
jComboBoxFormato.addItem(formato);
}
jComboBoxFormato.setSelectedItem(material.getFormato());
jTextFieldInformacao.setText(material.getInformacao());
this.material = material;
} |
90b6f288-84a2-40ad-b3c1-9bc7ef23f3b9 | 0 | public Destination destination(String s) {
return new PDestination(s);
} |
644df8c0-2077-47a5-be86-26ea7448a9df | 1 | public void addAllShips()
{
for(int i = 0; i < BattleShipGame.shipSizes.length; i++)
addShip(BattleShipGame.shipSizes[i]);
updateNums();
} |
f87030b2-ce9e-4720-b010-9e194e55fbc5 | 6 | public void stateChanged(ChangeEvent e){
SpinnerModel hModel = HSelector.getModel();
SpinnerModel wModel = WSelector.getModel();
Integer hValue = this.getHSelectorValue();
Integer wValue = this.getWSelectorValue();
if (hModel instanceof SpinnerNumberModel || wModel instanceof SpinnerNumberModel){
if (hValue <= 0 || hValue > 9999 || wValue <= 0 || wValue > 9999){
JOptionPane.showMessageDialog(null, "Value must be between 0 and 9999", "Warning", JOptionPane.WARNING_MESSAGE);
}
}
} |
52e280de-8c0f-41a3-8874-f742c218cce7 | 8 | public int getGridX(int x, int y)
{
Insets myInsets = getInsets();
int x1 = myInsets.left;
int y1 = myInsets.top;
x = x - x1 - GRID_X;
y = y - y1 - GRID_Y;
if (x < 0)
{ //To the left of the grid
return -1;
}
else if (y < 0)
{ //Above the grid
return -1;
}
else if ((x % (INNER_CELL_SIZE + 1) == 0) || (y % (INNER_CELL_SIZE + 1) == 0))
{ //Coordinate is at an edge; not inside a cell
return -1;
}
x = x / (INNER_CELL_SIZE + 1);
y = y / (INNER_CELL_SIZE + 1);
if (x < 0 || x > getTotalColumns() - 1 || y < 0 || y > TOTAL_ROWS - 1)
{ //Outside the rest of the grid
return -1;
}
return x;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.