method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
16119b3c-cd98-46bf-a9f5-5fbedba69151 | 3 | public void addEffectToGrid(Effect effect) {
if (effect == null)
throw new IllegalArgumentException("Effect can't be null!");
if (effects.contains(effect))
throw new IllegalArgumentException("The argument is already on the grid!");
if (!validPosition(effect.getPosition()))
throw new IllegalArgumentException("The argument hasn't got a valid position "
+ effect.getPosition() + "!");
/*if (effects.containsKey(effect.getPosition()))
effects.get(effect.getPosition()).setLifeTimeToMax();
else
effects.put(effect.getPosition(), effect);*/
effects.add(effect);
// effects.put(effect.getPosition(), effect);
} |
6e9a50ea-ed4f-4dd3-ace3-f7d952ea5054 | 2 | private int modifyFile(BufferedWriter out, Object fileToModify, int fileSize, int... bytesStart) throws IOException {
int dataModified = 0;
ArrayList<ByteRange> ranges = new ArrayList<ByteRange>();
for (int byteStart : bytesStart) {
// int byteStart = this.getRealisticByteModification(fileSize);
int byteEnd = byteStart + this.modificationSize; // Default 40 KB
if (byteEnd > fileSize) {
byteEnd = fileSize;
}
dataModified = byteEnd - byteStart;
// This is not tested...
/*
* if (dataModified > dataToModify) { byteEnd -= (dataModified -
* dataToModify); }
*/
ranges.add(new ByteRange(byteStart, byteEnd));
}
int time = this.getWaitTime();
totalTime += time;
Update update = new Update(totalTime, (String) fileToModify, ranges);
out.write(update.toString());
return dataModified;
} |
9bfe3d57-0579-4b77-92fc-92deef1e4239 | 1 | @Override
public int getHeight() {
int height = 0;
if (this.fontmetrics != null) {
height = this.fontmetrics.getHeight();
}
return height;
} |
72de6b7d-98c3-4fbe-b8d2-9c857105c3a8 | 3 | public static boolean isOwner(final CommandSender sender, final Region region) {
if (sender.hasPermission("simpleregions.override.commands")) return true;
if ((sender instanceof Player) && region.owners.inherits(sender)) return true;
return false;
} |
74c98d66-3346-4667-bbb9-c7801f64016c | 4 | @Override
protected void updateComponent(long currentTime) {
Card thisTopPlayCard = Game.linkedGet().getPlayPile().peek();
ArrayList<Card> thisCurrentHand = (Game.linkedGet().getCurrentPlayer() == null) ? null : (ArrayList<Card>) Game.linkedGet().getCurrentPlayer().getCards().clone();
if ((thisTopPlayCard != lastTopPlayCard) || !ProjUtils.listsEquivalent(thisCurrentHand, lastCurrentHand)) {
if (Game.linkedGet().getCurrentPlayer().hasPlayableCard()) {
this.animateColor(new RGBColorAnimation(500, Animation.PACE_LINEAR, false, this.getColor(), Game.linkedGet().getCurrentPlayer().getColor(), true));
}
else {
this.animateColor(new RGBColorAnimation(500, Animation.PACE_LINEAR, false, this.getColor(), ProjUtils.transparentColor(Game.linkedGet().getCurrentPlayer().getColor()), true));
}
}
lastTopPlayCard = thisTopPlayCard;
lastCurrentHand = thisCurrentHand;
} |
23e76b5c-a2e7-46b5-846a-6b0f99397e7c | 2 | public Color getCityColor(Fraktion f) {
if (f == Fraktion.Blau) {
return blau;
} else if (f == Fraktion.Rot) {
return rot;
}
return neutralColor;
} |
53095e21-a86b-4648-968f-d30e361b0138 | 6 | public void cargarEstudianteActualizar(int cedula) {
String sql = "select * from actualizar(" + cedula + ")";
try {
conexion.consultar(sql);
while (conexion.getRes().next()) {
this.setNombre(conexion.getRes().getString(1));
this.setApellido(conexion.getRes().getString(2));
this.setCedula(Integer.parseInt(conexion.getRes().getString(3)));
try {
this.setTelefono1(conexion.getRes().getString(4));
this.setTelefono2(conexion.getRes().getString(5));
} catch (NumberFormatException e) {
}
String direccion = conexion.getRes().getString(6);
this.setDireccion((direccion == null) ? "----" : direccion);
this.setSeccion(Integer.parseInt(conexion.getRes().getString(7)));
this.setEmail(conexion.getRes().getString(8));
this.setPassword(conexion.getRes().getString(9));
this.setEsMonitoreo((conexion.getRes().getString(10).equalsIgnoreCase("t")) ? true : false);
this.setEsInvestigacion((conexion.getRes().getString(11).equalsIgnoreCase("t")) ? true : false);
this.setId(Integer.parseInt(conexion.getRes().getString(12)));
}
} catch (NumberFormatException | SQLException e) {
System.out.println(e.toString());
}
} |
2ed0a35c-3b08-4d36-91ca-3e858b23758c | 1 | public String toString() {
StringBuilder sb = new StringBuilder();
for (Vehicle v: this.getCars()) {
sb.append(v.toString());
}
return "Road(" + this.hashCode() + "): " + sb.toString();
} |
ae2adbc5-a466-4946-b14e-1f5a6d1aa468 | 0 | @XmlElementDecl(namespace = "http://www.rsasecurity.com/rsalabs/pkcs/schemas/pkcs-5v2-0#", name = "PBKDF2-params")
public JAXBElement<PBKDF2ParameterType> createPBKDF2Params(PBKDF2ParameterType value) {
return new JAXBElement<PBKDF2ParameterType>(_PBKDF2Params_QNAME, PBKDF2ParameterType.class, null, value);
} |
a2115621-73f7-4e0b-81e4-a4c5b1dfefb1 | 5 | public String[] setTribeNames(String tribeOne, String tribeTwo){
// temp tribe vars.
String oldT1 = tribeNames[0];
String oldT2 = tribeNames[1];
// set the new tribes (Contestant requires this)
tribeNames[0] = Utils.strCapitalize(tribeOne.toLowerCase().trim());
tribeNames[1] = Utils.strCapitalize(tribeTwo.toLowerCase().trim());
// update all tribes first..
for (Contestant c : allContestants) {
if (c.getTribe().equalsIgnoreCase(oldT1)) {
try {
c.setTribe(tribeOne);
} catch (InvalidFieldException e) {
}
} else if (c.getTribe().equalsIgnoreCase(oldT2)) {
try {
c.setTribe(tribeTwo);
} catch (InvalidFieldException e) {
}
}
}
notifyAdd(UpdateTag.SET_TRIBE_NAMES);
return tribeNames;
} |
a819ce44-e640-4628-8b97-0fd072bcf3e8 | 4 | public int getTurnCount() {
boolean test = false;
if (test || m_test) {
System.out.println("Game :: getTurnCount() BEGIN");
}
if (test || m_test) {
System.out.println("Game :: getTurnCount() END");
}
return m_turnCount;
} |
c00f362a-3c24-4510-b86e-f7a0760ab648 | 6 | private void acceptNewClient()
{
System.out.println("Waiting for a new client");
(new Thread()
{
@Override
public void run()
{
try
{
Client c = new Client(server.accept());
clients.add(c);
System.out.println("Client " + c + " accepted");
System.out.println(clients.size() + " client(s) in server");
acceptNewClient();
String line = null;
while ((line = c.read()) != null
&& ! CommandAnalizer.getCommand(line).equals("SALIR")
&& c.isOpen())
{
doCommand(line, c);
}
if (line != null)
{
c.write("318 OK Adios.");
}
c.close();
clients.remove(c);
System.out.println("Client " + c + " closed");
}
catch (SocketException e)
{}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
} |
6c3b1c6d-1d01-4b3c-9ea8-a9f42f656bed | 2 | public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> words = new ArrayList<String>();
for (int i = 0; i < 20; i++)
{
words.add(reader.readLine());
}
Map<String, Integer> map = countWords(words);
for (Map.Entry<String, Integer> pair : map.entrySet())
{
System.out.println(pair.getKey() + " " + pair.getValue());
}
} |
74bc5f87-1194-4593-9fd2-caa773545a22 | 2 | @Override
protected Transferable createTransferable(JComponent c) {
Transferable t = null;
if (c instanceof JList) {
@SuppressWarnings("unchecked")
JList<RosterComponent> list = (JList<RosterComponent>) c;
Object value = new RosterTransferComponent(list.getSelectedValue());
if (value instanceof RosterTransferComponent) {
t = (Transferable) value;
}
}
return t;
} |
5d7f6fa1-fdd3-4284-b043-96141af8b76d | 9 | @Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
if (power != player.power) return false;
if (size != player.size) return false;
if (name != null ? !name.equals(player.name) : player.name != null) return false;
if (position != null ? !position.equals(player.position) : player.position != null) return false;
return true;
} |
6f5aa130-29f3-4c40-a2c4-483d0172cc8d | 4 | public void Compute(HashMap<Integer, Integer> events){
m_coordinates.setX(m_coordinates.getX() + Math.round(m_velocity.X()));
m_coordinates.setY(m_coordinates.getY() + Math.round(m_velocity.Y()));
if((m_coordinates.getX() < 0 ) || (m_coordinates.getX() > Physics.MAX_X) || (m_coordinates.getY() < 0 ) || (m_coordinates.getY() > Physics.MAX_Y))
m_is_alive = false;
} |
49cf9b5e-6ba9-4023-bba2-f6842b69d01a | 2 | public static String getWord() {
skipWhitespace();
StringBuffer str = new StringBuffer(50);
char ch = lookChar();
while (ch == EOF || !Character.isWhitespace(ch)) {
str.append(readChar());
ch = lookChar();
}
return str.toString();
} |
d5c769ee-abb7-49e8-ad87-acc0adc856cf | 4 | public String formatPlayTimeLeft(Player p, int min, int sec){
if(p.hasPermission(DeityNether.OVERRIDE_PERMISSION)){
return cu.format(lang.getString("nether.time.play.override").replaceAll("%header", getHeader()));
}else if(p.hasPermission(DeityNether.GENERAL_PERMISSION)){
String m = "";
String s = "";
if(min != 0)
m = min + "m";
if(sec != 0)
s = sec + "s";
return cu.format(lang.getString("nether.time.play.time_left").replaceAll("%header", getHeader())
.replaceAll("%numMin", m)
.replaceAll("%numSec", s));
}else{
return cu.format(lang.getString("nether.time.play.perm_error").replaceAll("%header", getHeader()));
}
} |
d236c3de-2fa5-41b3-86d0-eb20b2aa019a | 2 | @Override
public int compareTo(LabelGeneOverlap o) {
double difference = o.overlapArea-overlapArea;
if(difference==0){
return 0;
}
if(difference<0){
return -1;
}
return 1;
} |
3e687a02-ab44-4fe3-8c8b-4b006cb0e32e | 7 | private static List<String> makePluginNameList(final Map<?, ?> map,
final String key) throws InvalidDescriptionException {
final Object value = map.get(key);
if (value == null) {
return new GapList<>();
}
final GapList<String> pluginNameList = new GapList<>();
try {
for (final Object entry : (Iterable<?>) value) {
pluginNameList.add(entry.toString().replace(' ', '_'));
}
}
catch (ClassCastException ex) {
throw new InvalidDescriptionException(
key + " is of the wrong type", ex);
}
catch (NullPointerException ex) {
throw new InvalidDescriptionException("invalid " + key + " format",
ex);
}
return pluginNameList;
} |
e4488431-5005-42d1-9ae1-a41a6e3cbfee | 4 | public boolean equals(Vector4f v) {
if (this.x == v.getX() && this.y == v.getY() && this.z == v.getZ() && this.w == v.getW())
return true;
return false;
} |
e97db7a5-fc4c-427f-91ec-cf0eb30277dd | 4 | public void triggerEvent(final DTimer event) {
List<DTimerListener> eventListeners = this.listeners.get(event
.getEventName());
if (eventListeners == null || eventListeners.size() == 0) {
// debug no list
}
for (final DTimerListener listener : eventListeners) {
// Bukkit injection
if (event.isAsyncTask()) {
Bukkit.getScheduler().scheduleAsyncDelayedTask(
this.plugins.get(event.getPluginName()),
new Runnable() {
@Override
public void run() {
listener.onDTimerEvent(event);
}
});
} else {
Bukkit.getScheduler().scheduleSyncDelayedTask(
this.plugins.get(event.getPluginName()),
new Runnable() {
@Override
public void run() {
listener.onDTimerEvent(event);
}
});
}
}
} |
a76bb9d1-d92b-4498-8e02-39d5e5c76629 | 0 | public void setFooArray(T[] fooArray)
{
this.fooArray = fooArray;
} |
35266647-25d8-4fb6-9ed9-a2aa3bea5e01 | 7 | public JComponent getGui() {
if (gui==null) {
Map<Key, Object> hintsMap = new HashMap<RenderingHints.Key,Object>();
hintsMap.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
hintsMap.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
renderingHints = new RenderingHints(hintsMap);
setImage (new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB));
gui = new JPanel(new BorderLayout(4,4));
gui.setBorder(new EmptyBorder(5,3,5,3));
JPanel imageView = new JPanel(new GridBagLayout());
imageView.setPreferredSize(new Dimension(800, 600));
imageLabel = new JLabel(new ImageIcon(canvasImage));
JScrollPane imageScroll = new JScrollPane(imageView);
imageView.add(imageLabel);
imageLabel.addMouseMotionListener(new ImageMouseMotionListener());
imageLabel.addMouseListener(new ImageMouseListener());
gui.add(imageScroll,BorderLayout.CENTER);
JToolBar tb = new JToolBar();
tb.setFloatable(false);
JButton colorButton = new JButton("Color");
colorButton.setMnemonic('o');
colorButton.setToolTipText("Choose a Color");
ActionListener colorListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color c = JColorChooser.showDialog(
gui, "Choose a color", color);
if (c!=null) {
setColor(c);
}
}
};
colorButton.addActionListener(colorListener);
colorButton.setIcon(new ImageIcon(colorSample));
tb.add(colorButton);
setColor(color);
final SpinnerNumberModel strokeModel =
new SpinnerNumberModel(3,1,16,1);
JSpinner strokeSize = new JSpinner(strokeModel);
ChangeListener strokeListener = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
Object o = strokeModel.getValue();
Integer i = (Integer)o;
stroke = new BasicStroke(
i.intValue(),
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND,
1.7f);
}
};
strokeSize.addChangeListener(strokeListener);
strokeSize.setMaximumSize(strokeSize.getPreferredSize());
JLabel strokeLabel = new JLabel("Stroke");
strokeLabel.setLabelFor(strokeSize);
strokeLabel.setDisplayedMnemonic('t');
tb.add(strokeLabel);
tb.add(strokeSize);
tb.addSeparator();
ActionListener clearListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.OK_OPTION;
if (dirty) {
result = JOptionPane.showConfirmDialog(
gui, "Erase the current painting?");
}
if (result==JOptionPane.OK_OPTION) {
clear(canvasImage);
}
}
};
JButton clearButton = new JButton("Clear");
tb.add(clearButton);
clearButton.addActionListener(clearListener);
gui.add(tb, BorderLayout.PAGE_START);
JToolBar tools = new JToolBar(JToolBar.VERTICAL);
tools.setFloatable(false);
JButton crop = new JButton("Crop");
final JRadioButton select = new JRadioButton("Select", true);
final JRadioButton draw = new JRadioButton("Draw");
final JRadioButton text = new JRadioButton("Text");
tools.add(crop);
tools.add(select);
tools.add(draw);
tools.add(text);
ButtonGroup bg = new ButtonGroup();
bg.add(select);
bg.add(text);
bg.add(draw);
ActionListener toolGroupListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource()==select) {
activeTool = SELECTION_TOOL;
} else if (ae.getSource()==draw) {
activeTool = DRAW_TOOL;
} else if (ae.getSource()==text) {
activeTool = TEXT_TOOL;
}
}
};
select.addActionListener(toolGroupListener);
draw.addActionListener(toolGroupListener);
text.addActionListener(toolGroupListener);
gui.add(tools, BorderLayout.LINE_END);
gui.add(output,BorderLayout.PAGE_END);
clear(colorSample);
clear(canvasImage);
}
return gui;
} |
54475c16-724b-4af9-8928-feb9de0d03e1 | 7 | boolean isLegalCharacter(char c)
{
// CheckStyle:MagicNumber OFF
if (c == 0x9 || c == 0xA || c == 0xD)
{
return true;
}
else if (c < 0x20)
{
return false;
}
else if (c <= 0xD7FF)
{
return true;
}
else if (c < 0xE000)
{
return false;
}
else if (c <= 0xFFFD)
{
return true;
}
// CheckStyle:MagicNumber ON
return false;
} |
da9d303b-29e1-4746-ac78-02352b65119e | 4 | public void generate(String year, String title, ArrayList<String> authors,
ArrayList<String> categories, String shortDescription,
String dpublic, String age, ArrayList<String> notes, String gamePlay,
String gameRules) {
Element xmlRoot = new Element("infos");
Element xmlYear = new Element("year");
Element xmlCategories = new Element("gamecategories");
Element xmlShortDescription = new Element("shortdescription");
Element xmlPublic = new Element("public");
Element xmlGameState = new Element("gamestate");
Element xmlAge = new Element("age");
Element xmlTitle = new Element("title");
Element xmlAuthors = new Element("authors");
Element xmlNotes = new Element("notes");
Element xmlGameplay = new Element("gameplay");
Element xmlGamerules = new Element("gamerules");
xmlYear.addContent(new CDATA(year));
for (String category : categories) {
Element xmlCategory = new Element("gamecategory");
xmlCategory.addContent(new CDATA(category));
xmlCategories.addContent(xmlCategory);
}
xmlShortDescription.addContent(new CDATA(shortDescription));
xmlPublic.addContent(new CDATA(dpublic));
xmlGameState.addContent(new CDATA(GameState.OK.toString()));
xmlAge.addContent(new CDATA(age));
xmlTitle.addContent(new CDATA(title));
for (String author : authors) {
Element xmlAuthor = new Element("author");
xmlAuthor.addContent(new CDATA(author));
xmlAuthors.addContent(xmlAuthor);
}
for (String note : notes) {
Element xmlNote = new Element("note");
xmlNote.addContent(new CDATA(note));
xmlNotes.addContent(xmlNote);
}
xmlGameplay.addContent(new CDATA(gamePlay));
xmlGamerules.addContent(new CDATA(gameRules));
xmlRoot.addContent(xmlYear);
xmlRoot.addContent(xmlCategories);
xmlRoot.addContent(xmlShortDescription);
xmlRoot.addContent(xmlPublic);
xmlRoot.addContent(xmlGameState);
xmlRoot.addContent(xmlAge);
xmlRoot.addContent(xmlTitle);
xmlRoot.addContent(xmlAuthors);
xmlRoot.addContent(xmlNotes);
xmlRoot.addContent(xmlGameplay);
xmlRoot.addContent(xmlGamerules);
Document xmlDocument = new Document(xmlRoot);
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
File outputFile = new File("infos.xml");
outputter.output(xmlDocument, new FileOutputStream(outputFile));
} catch (IOException e) {
e.printStackTrace();
}
} |
c77cc17d-a012-4387-8adb-36a1d5ece5e1 | 8 | public boolean similar(Object other) {
if (!(other instanceof JSONArray)) {
return false;
}
int len = this.length();
if (len != ((JSONArray)other).length()) {
return false;
}
for (int i = 0; i < len; i += 1) {
Object valueThis = this.get(i);
Object valueOther = ((JSONArray)other).get(i);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
} |
a0117eb3-474d-44d1-b556-d8d751733978 | 9 | private float[][][] cuboidResponse(List<IplImage> gaussianList, double omega)
{
if(gaussianList == null || gaussianList.size() == 0)
{
return null;
}
IplImage firstIamge = gaussianList.get(0);
int width = firstIamge.width();
int height = firstIamge.height();
int length = gaussianList.size();
float[][][] response = new float[length][height][width];
double[] gaborKernelEven = generateGaborKernel(true, omega);
double[] gaborKernelOdd = generateGaborKernel(false, omega);
int kernelLength = gaborKernelEven.length;
for(int i = 0; i < length; i++)
{
int imgConvStartIndex = i - kernelLength / 2;
int kernelConvStartIndex = imgConvStartIndex < 0 ? -imgConvStartIndex : 0;
imgConvStartIndex = imgConvStartIndex < 0 ? 0 : imgConvStartIndex;
int imgConvEndIndex = i + kernelLength / 2 + 1;
imgConvEndIndex = imgConvEndIndex >= length ? length : imgConvEndIndex;
for(int j = 0; j < height; j++)
{
for(int k = 0; k < width; k++)
{
double convResultEven = 0;
double convResultOdd = 0;
int kernelI = kernelConvStartIndex;
for(int imgI = imgConvStartIndex; imgI < imgConvEndIndex; imgI++)
{
byte pixel = gaussianList.get(imgI).arrayData().get(j * width + k);
convResultEven += (pixel & 0xFF) * gaborKernelEven[kernelI];
convResultOdd += (pixel & 0xFF) * gaborKernelOdd[kernelI++];
}
response[i][j][k] = (float) (Math.pow(convResultEven, 2) + Math.pow(convResultOdd, 2));
}
}
}
return response;
} |
c4ef899c-89e5-42ca-b8ce-f46086e562af | 1 | public V getFinalValue() {
if (isSetValue()) { return value; }
return defaultValue;
} |
a220677b-d12f-4e64-93ec-c0d72a17bbd8 | 7 | public static ListNode removeDuplicatesSolutionTwo(ListNode head) {
if (head == null || head.next == null) {
return head;
}
/* PHASE #1: Count number of appearances for each element */
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
ListNode ptr = head;
while (ptr != null) {
if (counts.containsKey(ptr.data)) {
Integer c = counts.get(ptr.data);
counts.put(ptr.data, c + 1);
}else {
counts.put(ptr.data, 1);
}
ptr = ptr.next;
}
/* PHASE #2: Remove duplicate elements */
ListNode ptr2 = null;
ListNode ptr1 = head.next;
while (ptr1 != null) {
Integer c = counts.get(ptr1.data);
if (c > 1) {
System.out.println("Duplicate: " + ptr1.data);
counts.put(ptr1.data, c - 1);
if (ptr2 == null) {
head = head.next;
ptr2 = head;
}else {
ptr2.next = ptr1.next;
}
ptr1 = ptr2.next;
}else {
ptr2 = ptr1;
ptr1 = ptr1.next;
}
}
return head;
} |
57872b4b-cb89-4ba3-9dbb-61d1ba4c0dbd | 1 | @Override
protected void onKick(String channel, String kickerNick, String kickerLogin, String kickerHostname, String recipientNick, String reason) {
if ( recipientNick.equals( getNick() ) ) {
joinChannel(channel);
sendMessage(channel, kickerNick + ": polib si elipsy");
}
} |
1600b996-6b97-4fe1-be14-bd8123d72a5a | 2 | public static int getIntValue(String value) {
if(value != null) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException exception) {}
}
throw new IllegalArgumentException("Invalid value");
} |
88eb46f4-844a-4bf2-9ef8-5c19f2cd479d | 0 | public Rectangle getFirstCorner() {
return firstCorner;
} |
8c378a53-d099-431b-83af-48d78712ca6d | 3 | public static Timestamp getDatahMaxPesquisa() throws SQLException, ClassNotFoundException {
ResultSet rs;
Timestamp z = null;
Connection conPol = conMgr.getConnection("PD");
if (conPol == null) {
throw new SQLException("Numero Maximo de Conexoes Atingida!");
}
try {
call = conPol.prepareCall(" SELECT MAX(datah) FROM tb_registro WHERE inspecao = 'i'; "); //--
rs = call.executeQuery();
while (rs.next()) {
z = rs.getTimestamp(1);
}
call.close();
} finally {
if (conPol != null) {
conMgr.freeConnection("PD", conPol);
}
}
return z;
} |
e6cde612-5ce8-4060-aa36-df90a3efcb41 | 7 | @SuppressWarnings("deprecation")
public static void main(String[] args)
{
//declare variables
//tracks number of incorrect answers
int failures=0;
//number of allowed failures
int numOfFailures=7;
//temp word, will come from a file or database in the end
String word="Love";
StringBuilder visibleWord = new StringBuilder("----");
//game loop controller
boolean runGame = true;
Main_GUI.main(null);
word = word.toUpperCase();
//StreamTokenizer
StreamTokenizer Input=new StreamTokenizer(System.in);
//Run the input/output portion
while(runGame){
try{
System.out.println("Failures: " + failures + "\n");
System.out.println("Clue: " + visibleWord.toString() + "\n");
System.out.print("Enter your guess?" + "\n");
Input.nextToken();
//local variables
String guess = Input.sval;
guess = guess.toUpperCase();
guess = guess.substring(0,1);
System.out.print("Your guess is:" + guess + "\n");
//keeps track of most recent answers state
boolean guessChecker = word.contains(guess);
int index = word.indexOf(guess);
if(index>=0)
for (int i = word.indexOf(guess);
i >= 0;
i = word.indexOf(guess, i + 1))
{
visibleWord.setCharAt(i, guess.charAt(0));
}
System.out.print("Is it in the word: " + guessChecker + "\n");
// System.out.print(word.matches(visibleWord.toString()));
if(guessChecker==false)
failures++;
int temp = Main_GUI.getImgPointer();
Main_GUI.setImgPointer(temp++);
//win state
if(word.matches(visibleWord.toString()))
{
System.out.print("You win\n");
runGame=false;
}
//lose state
if(failures == numOfFailures)
{
System.out.print("You lose\n");
runGame=false;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}//end main |
bcc52cb5-3171-415c-b7a7-f302d4d9f387 | 9 | private void showTip() {
String text = null;
tooltipowner = null;
String classname = getClass(mouseinside);
if ((classname == "tabbedpane") || (classname == "menubar") || (classname == ":popup")) {
if (insidepart != null) {
text = getString(insidepart, "tooltip", null);
}
}
else if (classname == ":combolist") {
if (insidepart instanceof Object[]) {
text = getString(insidepart, "tooltip", null);
}
}
// TODO list table tree
if (text == null) { text = getString(mouseinside, "tooltip", null); }
else { tooltipowner = insidepart; }
if (text != null) {
FontMetrics fm = getFontMetrics(font);
int width = fm.stringWidth(text) + 4;
int height = fm.getAscent() + fm.getDescent() + 4;
if (tooltipowner == null) { tooltipowner = mouseinside; }
Rectangle bounds = getRectangle(content, "bounds");
int tx = Math.max(0, Math.min(mousex + 10, bounds.width - width));
int ty = Math.max(0, Math.min(mousey + 10, bounds.height - height));
setRectangle(tooltipowner, ":tooltipbounds", tx, ty, width, height);
repaint(tx, ty, width, height);
}
} |
e2d13980-18d6-4e02-bf45-7cf3f54837ea | 3 | @Override
public synchronized void send(String s) throws RemoteException {
ClientService chatClient = null;
for(String username : chatClients){
try {
chatClient = (ClientService) Naming.lookup(username);
chatClient.send(s);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (NotBoundException e) {
System.out.println(username + " hat den Chat bereits verlassen!");
chatClients.remove(s);
}
}
} |
9c4f3815-9c10-442e-b59e-71aa73766e04 | 6 | @Override
public void onKeyDown(char key, int keyCode, boolean coded)
{
if (coded)
{
// Turns with left / right arrowkey
if (keyCode == KeyEvent.VK_LEFT)
{
//System.out.println(calculateTurning());
turn(calculateTurning());
}
else if (keyCode == KeyEvent.VK_RIGHT)
turn(-calculateTurning());
// Goes forward with up arrowkey
else if (keyCode == KeyEvent.VK_UP)
{
addCheckedBoost(getAngle(), getFriction() + this.acceleration,
this.maxdrivespeed);
}
// Goes backwards with bottomkey
else if (keyCode == KeyEvent.VK_DOWN)
addCheckedBoost(HelpMath.checkDirection(getAngle() + 180),
getFriction() + this.brakepower, this.maxreversespeed);
}
else
{
// If C was pressed, turbos
if (key == 'c')
{
addCheckedBoost(getAngle(), this.turbopower, this.turbospeed);
}
}
} |
b5061f14-8aec-48fa-87e5-b2b9ec5d869c | 7 | public static double evaluateAveragePrecision( HashMap<String, HashMap<Integer,Double>> relevance_judgments,
String path){
double value = 0.0;
double AP = 0.0;
int RR = 0;
int i=0;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String readLineString = reader.readLine();
while(readLineString!=null){
i++;
Scanner s = new Scanner(readLineString).useDelimiter("\t");
String query = s.next();
int did = s.nextInt();
if(!relevance_judgments.containsKey(query)){
throw new IOException("query not found");
}
readLineString = reader.readLine();
HashMap<Integer,Double> qr = relevance_judgments.get(query);
if(qr.containsKey(did) && qr.get(did) == 1.0){
RR++;
AP = AP + (double)RR/i;
}
}
if(RR != 0){
value = AP/RR;
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
} |
88e8f40f-53bf-4f68-a2e9-db880b0c8b14 | 5 | public void setAttackValue(int x, int y, int value, String player)
{
WorldChunk chunk = getChunkAt(x,y, false);
if(chunk == null)
return;
if(this.worldType == WorldType.CLIENT && !handlingChanges)
{
// if(NettyClientHandler.current != null)
// try
// {
// NettyCommons.sendPacket(new PacketBlockInfos(new BlockInfo(x,y,BlockInfo.ATTACK_VALUE, value+"\001"+player)), NettyClientHandler.current.serverChannel);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
}
if(x != 0)
{
x = x-chunk.chunkID*16;
if(chunk.chunkID < 0)
{
x = 15-x;
}
}
chunk.setAttackValueToBlock(x, y, value, player);
} |
92655fe7-cee5-4102-ac63-2a4e21b94548 | 6 | private static Map<String, String> loadSeedProducts(String seedFileName) throws Exception {
int totalRows = 0, badUPCCount = 0, badProductIdCount = 0;
Map<String, String> products = new LinkedHashMap<String, String>();
XSSFWorkbook wb = readFile(seedFileName);
for (int k = 0; k < 1; k++) {
XSSFSheet sheet = wb.getSheetAt(k);
int rows = sheet.getPhysicalNumberOfRows();
totalRows = rows - 1;
for (int r = 1; r < rows; r++) {
try {
XSSFRow row = sheet.getRow(r);
if (row == null) {
System.out.println("Ignoring Empty Row: " + r);
continue;
}
XSSFCell cell0 = row.getCell(0);// SKU
XSSFCell cell1 = row.getCell(1);// Viking URL
if (cell0 != null) {
String sku = getCellData(cell0);
if (cell1 != null) {
String url = cell1.getStringCellValue();
products.put(sku, url);
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("row = " + r + " has invalid data.");
badUPCCount++;
throw ex;
}
}
}
System.out.println("Valid Seed Products = " + products.size());
System.out.println("Bad UPCs = " + badUPCCount);
System.out.println("No RSProduct Ids = " + badProductIdCount);
System.out.println(" -----");
System.out.println("Total Seed Products = " + totalRows);
return products;
} |
c0c8e48f-bdf1-460a-8d58-f562fb2361e5 | 6 | @Override
/**
* Returns true if managed to find a free square adjacent to target, and teleport there.
* False if none found.
*/
public boolean execute(Entity actor, Entity target, Parameters context) {
if(!(actor instanceof game.objects.Unit)){
throw new IllegalStateException("TeleportToTarget effect is only for units");
}
boolean isHero = actor instanceof Hero;
for(Point adjLocation : Physics.getAdjacentLocations(target.getLocation())){
if(isHero || ! ((Enemy)actor).isInTDMode()){
if(Map.blockedForHero(adjLocation.x, adjLocation.y)){
continue;
}
}else{
if(Map.blockedForTowers(adjLocation.x, adjLocation.y)){
continue;
}
}
GamePlayState.addSpecialEffect(new AnimationBasedVisualEffect(actor, animation));
((Unit)actor).teleportToLocation(adjLocation.x, adjLocation.y);
GamePlayState.addSpecialEffect(new AnimationBasedVisualEffect(actor, animation));
return true;
}
return false;
} |
0c89cb1e-eaf9-411a-a713-53be0e941d55 | 1 | public JMenu getMnChat() {
if (mnChat == null) {
mnChat = new JMenu("Chat");
mnChat.add(getMntmConectar());
mnChat.add(getMntmDesconectar());
mnChat.add(getMntmSalir());
}
return mnChat;
} |
5b734521-3736-48a6-8433-e24d78f9bb6c | 2 | @Override
protected void onComplete() {
if (!cancelled) {
if (soundAtEnd != null)
soundAtEnd.play();
//end.setResource(transform);
panel.remove(moving);
}
} |
bb6e61ef-e7e7-433d-b72e-f38d81230631 | 5 | @Override
public void run() {
int i = 0;
try {
listenerSocket = new ServerSocket(port);
Socket socket;
EIError.debugMsg("Listening");
gameController.showMessage("Success", "Waiting for incoming connection...");
gameController.multiplayerMode = gameController.multiplayerMode.SERVER;
EIError.debugMsg("Waiting for Connection...");
while ((i++ < maxConnections) || (maxConnections == 0)) {
socket = listenerSocket.accept();
if (!shuttingDown) {
TCPServer connection = new TCPServer(registry, gameController, socket, port + (i - 1));
tcpServers.add(connection);
connection.start();
EIError.debugMsg("Connected");
gameController.setNetworkMode(true);
gameController.showMessage("Success", "Network Connection Established");
}
}
} catch (IOException ioe) {
if (!shuttingDown) {
gameController.showMessage("Error", "Couldn't listen on port " + port);
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
} |
808b0422-491d-4f02-8702-2acc64cc6751 | 2 | public boolean contains(Object li) {
li = ((LocalInfo) li).getLocalInfo();
for (int i = 0; i < count; i++)
if (locals[i].getLocalInfo() == li)
return true;
return false;
} |
763a6758-1cf1-4dd3-8723-114f23c9e698 | 1 | public int destroy(int idCrlv) throws ClassNotFoundException, ClassNotFoundException, SQLException{
int result;
con = abrirBanco(con);
PreparedStatement stm;
String sql = "delete from ipva where crlv_id_crlv = ?";
stm = con.prepareStatement(sql);
stm.setInt(1, idCrlv);
result = stm.executeUpdate();
if(result == 1){
sql = "delete from crlv where id_crlv = ?";
stm = con.prepareStatement(sql);
stm.setInt(1, idCrlv);
result = stm.executeUpdate();
}
return result;
} |
8a8197ba-8743-4c5e-90b2-eb15332e7858 | 9 | public byte getPositionCode(int x, int y) {
if (rectNW.contains(x, y))
return NW;
if (rectN.contains(x, y))
return NORTH;
if (rectNE.contains(x, y))
return NE;
if (rectE.contains(x, y))
return EAST;
if (rectSE.contains(x, y))
return SE;
if (rectS.contains(x, y))
return SOUTH;
if (rectSW.contains(x, y))
return SW;
if (rectW.contains(x, y))
return WEST;
if (contains(x, y))
return INSIDE;
return -1;
} |
629babcd-8714-4438-a7b7-0ebb1b3c2eac | 4 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof MyNode))
return false;
MyNode other = (MyNode) obj;
if (id != other.id)
return false;
return true;
} |
a76a1f9e-6220-492a-b2c2-5a5af0a221fd | 9 | private void setKey(byte[] key)
{
int[] k32e = new int[MAX_KEY_BITS/64]; // 4
int[] k32o = new int[MAX_KEY_BITS/64]; // 4
int[] sBoxKeys = new int[MAX_KEY_BITS/64]; // 4
gSubKeys = new int[TOTAL_SUBKEYS];
if (k64Cnt < 1)
{
throw new IllegalArgumentException("Key size less than 64 bits");
}
if (k64Cnt > 4)
{
throw new IllegalArgumentException("Key size larger than 256 bits");
}
/*
* k64Cnt is the number of 8 byte blocks (64 chunks)
* that are in the input key. The input key is a
* maximum of 32 bytes (256 bits), so the range
* for k64Cnt is 1..4
*/
for (int i=0; i<k64Cnt ; i++)
{
int p = i* 8;
k32e[i] = BytesTo32Bits(key, p);
k32o[i] = BytesTo32Bits(key, p+4);
sBoxKeys[k64Cnt-1-i] = RS_MDS_Encode(k32e[i], k32o[i]);
}
int q,A,B;
for (int i=0; i < TOTAL_SUBKEYS / 2 ; i++)
{
q = i*SK_STEP;
A = F32(q, k32e);
B = F32(q+SK_BUMP, k32o);
B = B << 8 | B >>> 24;
A += B;
gSubKeys[i*2] = A;
A += B;
gSubKeys[i*2 + 1] = A << SK_ROTL | A >>> (32-SK_ROTL);
}
/*
* fully expand the table for speed
*/
int k0 = sBoxKeys[0];
int k1 = sBoxKeys[1];
int k2 = sBoxKeys[2];
int k3 = sBoxKeys[3];
int b0, b1, b2, b3;
gSBox = new int[4*MAX_KEY_BITS];
for (int i=0; i<MAX_KEY_BITS; i++)
{
b0 = b1 = b2 = b3 = i;
switch (k64Cnt & 3)
{
case 1:
gSBox[i*2] = gMDS0[(P[P_01][b0] & 0xff) ^ b0(k0)];
gSBox[i*2+1] = gMDS1[(P[P_11][b1] & 0xff) ^ b1(k0)];
gSBox[i*2+0x200] = gMDS2[(P[P_21][b2] & 0xff) ^ b2(k0)];
gSBox[i*2+0x201] = gMDS3[(P[P_31][b3] & 0xff) ^ b3(k0)];
break;
case 0: /* 256 bits of key */
b0 = (P[P_04][b0] & 0xff) ^ b0(k3);
b1 = (P[P_14][b1] & 0xff) ^ b1(k3);
b2 = (P[P_24][b2] & 0xff) ^ b2(k3);
b3 = (P[P_34][b3] & 0xff) ^ b3(k3);
case 3:
b0 = (P[P_03][b0] & 0xff) ^ b0(k2);
b1 = (P[P_13][b1] & 0xff) ^ b1(k2);
b2 = (P[P_23][b2] & 0xff) ^ b2(k2);
b3 = (P[P_33][b3] & 0xff) ^ b3(k2);
case 2:
gSBox[i*2] = gMDS0[(P[P_01]
[(P[P_02][b0] & 0xff) ^ b0(k1)] & 0xff) ^ b0(k0)];
gSBox[i*2+1] = gMDS1[(P[P_11]
[(P[P_12][b1] & 0xff) ^ b1(k1)] & 0xff) ^ b1(k0)];
gSBox[i*2+0x200] = gMDS2[(P[P_21]
[(P[P_22][b2] & 0xff) ^ b2(k1)] & 0xff) ^ b2(k0)];
gSBox[i*2+0x201] = gMDS3[(P[P_31]
[(P[P_32][b3] & 0xff) ^ b3(k1)] & 0xff) ^ b3(k0)];
break;
}
}
/*
* the function exits having setup the gSBox with the
* input key material.
*/
} |
7b5e5baa-8073-4f92-9735-ed2d8e093151 | 1 | @Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
} |
b67950c1-678e-47b9-ae84-cedadfa15ca7 | 4 | private void procServerMap(Packet p) {
PacketReader pr = p.getByteBufferReader();
switch (MapPacketType.valueOf(pr.readUint8())) {
case MAP_PACKET_START:
long frameCounter = pr.readUint32();
this.expectedSaveLength = (int) pr.readUint32();
break;
case MAP_PACKET_NORMAL:
this.saveGameData = ArrayUtils.addAll(this.saveGameData, pr.getRemainingBytes());
break;
case MAP_PACKET_END:
try {
this.game = new LoadGame(this.saveGameData).getGame();
sendClientMapOK();
} catch (Exception e) {
sendClientError(NetworkErrorPacketType.NETWORK_ERROR_SAVEGAME_FAILED);
sendClientQuit();
}
break;
}
} |
6dfe724b-21e5-4818-a589-373669eac73a | 4 | @Override
public void run() {
try {
socket = new Socket("localhost", 7000);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println(new Date() + " --> Connected to server at "
+ socket.getLocalAddress() + ":" + socket.getLocalPort());
try {
toNetOutputStream = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
fromNetInputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
} |
5d8b279c-0bd1-4f9b-81e7-2f2dd05469ce | 6 | private Object[] getDecodedStreamBytesAndSize(int presize) {
InputStream input = getInputStreamForDecodedStreamBytes();
if (input == null)
return null;
try {
int outLength;
if (presize > 0)
outLength = presize;
else
outLength = Math.max(1024, (int) streamInput.getLength());
ConservativeSizingByteArrayOutputStream out = new
ConservativeSizingByteArrayOutputStream(outLength, library.memoryManager);
byte[] buffer = new byte[(outLength > 1024) ? 4096 : 1024];
while (true) {
int read = input.read(buffer);
if (read <= 0)
break;
out.write(buffer, 0, read);
}
out.flush();
out.close();
input.close();
int size = out.size();
boolean trimmed = out.trim();
byte[] data = out.relinquishByteArray();
Object[] ret = new Object[]{data, size};
return ret;
}
catch (IOException e) {
logger.log(Level.FINE, "Problem decoding stream bytes: ", e);
}
return null;
} |
56313360-5e9d-44ef-8901-0ec2b9c17483 | 5 | public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType();
Class<? super T> rawType = typeToken.getRawType();
if (!Map.class.isAssignableFrom(rawType)) {
return null;
}
Class<?> rawTypeOfSrc = $Gson$Types.getRawType(type);
Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc);
TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]);
TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);
@SuppressWarnings({"unchecked", "rawtypes"})
// we don't define a type parameter for the key or value types
TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter,
keyAndValueTypes[1], valueAdapter, constructor);
return result;
} |
9acdd981-1ea0-4b6c-9813-1b737d685eeb | 4 | public static int firstIndexOfNonWhiteSpace( String string )
{
if ( isEmpty( string ) ) {
return 0;
}
int left = 0;
for ( char eachChar : string.toCharArray() ) {
if ( eachChar != ' ' && eachChar != '\t' ) {
break;
}
left++;
}
return left;
} |
036247ad-07c6-4d41-9f6d-7923328d2d12 | 4 | public static void main(String[] args) {
// TODO Auto-generated method stub
//func = ScoreFunctionFactory.getScoreFunction("KLSum+");
Document.initialize(Document.ParseMode.POS);
String fname = "Sentiment";
String docset = ".Crawler";
if (ROOTDIR.equals("/home/graveendran/Downloads/DUC")) {
docset = ".DUC";
}
p = new Printer(Printer.Type.BOTH, fname + docset);
p.startRow();
p.addColumn("Topic", Printer.Type.BOTH);
p.addColumn("Num Comments", Printer.Type.BOTH);
p.addColumn("Num Sentences", Printer.Type.BOTH);
p.addColumn("Positive Summary Word Count", Printer.Type.BOTH);
p.addColumn("Negative Summary Word Count", Printer.Type.BOTH);
p.addColumn("Total Word Count", Printer.Type.BOTH);
p.addColumn("Execution Time", Printer.Type.TIMING);
p.addColumn("Positive Summary", Printer.Type.TEXT);
p.addColumn("Negative Summary", Printer.Type.TEXT);
p.addColumn("Summary", Printer.Type.BOTH);
p.endRow();
func = new SentimentScoreFunction();
//func.setBackgroundCorpus();
props.put("annotators", "tokenize, ssplit, pos");
pipeline = new StanfordCoreNLP(props);
Annotation document = new Annotation("not a good car. it won't start. it never eats pie.,!;");
pipeline.annotate(document);
for(CoreMap sentence: document.get(SentencesAnnotation.class)) {
for (CoreLabel token: sentence.get(TokensAnnotation.class))
{
String term = token.get(TextAnnotation.class);
String pos = token.get(PartOfSpeechAnnotation.class);
System.out.print(term + "/" + pos + " ");
}
System.out.println("");
}
Path startingDir = FileSystems.getDefault().getPath(ROOTDIR);
try {
long start = System.currentTimeMillis();
Files.walkFileTree(startingDir, new SentimentSumVisitor());
long end = System.currentTimeMillis();
System.out.println(end - start);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
54c73a7b-1e55-4bad-bda2-b36c755058c1 | 5 | public void AddGlobalObj(int objectX, int objectY, int NewObjectID, int Face, int ObjectType) {
for (Player p : server.playerHandler.players)
{
if(p != null)
{
client person = (client)p;
if((person.playerName != null || person.playerName != "null"))
{
if(person.distanceToPoint(objectX, objectY) <= 60)
{
person.ReplaceObject2(objectX, objectY, NewObjectID, Face, ObjectType);
}
}
}
}
} |
f28c30bc-d9c2-4a45-bdba-dd978f66c44f | 5 | public Item addItemInList(ItemDTO dto) {
Item itemList = null;
if (dto.getDtoMap().get(Constants.TYPE)
.equalsIgnoreCase(Constants.RAW_ITEM)) {
itemList = new RawItem();
} else if (dto.getDtoMap().get(Constants.TYPE)
.equalsIgnoreCase(Constants.MANUFACTURED_ITEM)) {
itemList = new ManufacturedItem();
} else if (dto.getDtoMap().get(Constants.TYPE)
.equalsIgnoreCase(Constants.IMPORTED_ITEM)) {
itemList = new ImportedItem();
}
itemList.setName(dto.getDtoMap().get(Constants.NAME));
itemList.setType(dto.getDtoMap().get(Constants.TYPE));
if (dto.getDtoMap().containsKey(Constants.PRICE)) {
itemList.setPrice(Float.parseFloat(dto.getDtoMap().get(
Constants.PRICE)));
}
if (dto.getDtoMap().containsKey(Constants.QUANTITY)) {
itemList.setQuantity(Integer.parseInt(dto.getDtoMap().get(
Constants.QUANTITY)));
}
System.out.println("Item Added Successfully");
return itemList;
} |
9e6778dd-66c5-4031-8c8b-b7919975b902 | 4 | @SuppressWarnings("unchecked")
public String getEventAveragesTable() {
PreparedStatement st = null;
ResultSet rs = null;
JSONArray json = new JSONArray();
try {
conn = dbconn.getConnection();
st = conn.prepareStatement("SELECT m.event_id, e.name, avg(m.auton_top)*6 + avg(m.auton_middle)*4 + avg(m.auton_bottom)*2 as auton, avg(m.teleop_top)*3 + avg(m.teleop_middle)*2 + avg(m.teleop_bottom) + avg(m.teleop_pyramid)*5 as teleop, avg(m.pyramid_level)*10 as climb, avg(m.auton_top)*6 + avg(m.auton_middle)*4 + avg(m.auton_bottom)*2 + avg(m.teleop_top)*3 + avg(m.teleop_middle)*2 + avg(m.teleop_bottom) + avg(m.teleop_pyramid)*5 + avg(m.pyramid_level)*10 as total FROM match_record_2013 m, events e WHERE m.team_id = ? and m.event_id = e.id GROUP BY event_id");
st.setInt(1, getSelectedTeam());
rs = st.executeQuery();
while (rs.next()) {
JSONObject o = new JSONObject();
o.put("id", rs.getInt("event_id"));
o.put("name", rs.getString("name"));
o.put("autonomous", rs.getInt("auton"));
o.put("teleop", rs.getInt("teleop"));
o.put("climb", rs.getInt("climb"));
o.put("total_points", rs.getInt("total"));
json.add(o);
}
st = conn.prepareStatement("SELECT avg(auton_top)*6 + avg(auton_middle)*4 + avg(auton_bottom)*2 as auton, avg(teleop_top)*3 + avg(teleop_middle)*2 + avg(teleop_bottom) + avg(teleop_pyramid)*5 as teleop, avg(pyramid_level)*10 as climb, avg(auton_top)*6 + avg(auton_middle)*4 + avg(auton_bottom)*2 + avg(teleop_top)*3 + avg(teleop_middle)*2 + avg(teleop_bottom) + avg(teleop_pyramid)*5 + avg(pyramid_level)*10 as total FROM match_record_2013 where team_id = ?");
st.setInt(1, getSelectedTeam());
rs = st.executeQuery();
if (rs.next()) {
JSONObject o = new JSONObject();
o.put("id", "total");
o.put("name", "total");
o.put("autonomous", rs.getInt("auton"));
o.put("teleop", rs.getInt("teleop"));
o.put("climb", rs.getInt("climb"));
o.put("total_points", rs.getInt("total"));
json.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
conn.close();
st.close();
rs.close();
}catch (SQLException e) {
System.out.println("Error closing query");
}
}
return json.toString();
} |
93cf381f-4f7d-4b6c-98aa-b82091a22359 | 4 | public FlacAudioFrame getNextAudioPacket() throws IOException {
int skipped = 0;
int b1 = 0;
int b2 = input.read();
while (b1 != -1 && b2 != -1) {
b1 = b2;
b2 = input.read();
if (FlacAudioFrame.isFrameHeaderStart(b1, b2)) {
if (skipped > 0)
System.err.println("Warning - had to skip " + skipped +
" bytes of junk data before finding the next packet header");
return new FlacAudioFrame(b1, b2, input, info);
}
skipped++;
}
return null;
} |
13672f53-8b96-45fd-986b-fa5605a7dad1 | 2 | public void pesquisaTurma(String disc, int num) {
try {
Disciplina dis = sistemaFrontEnd.pesquisaDisciplina(disc);
try {
JOptionPane.showMessageDialog(null,
sistemaFrontEnd.pesquisaTurma(disc, num));
} catch (TurmaInexistenteException e) {
front.exibirMsg("Turma Inexistente!!");
}
} catch (DisciplinaInexistenteException e1) {
front.exibirMsg("Disciplina Inexistente!!");
}
} |
77dc845d-729a-465b-aa29-d49634a8fb7e | 2 | public TitleScreen(int frameWidth, int frameHeight)
{
try
{
image = ImageIO.read(new File("logo.png"));
}
catch (IOException ex)
{
System.out.println("Can't read image.");
}
this.frameWidth = frameWidth;
this.frameHeight = frameHeight;
asteroidList = new ArrayList<Asteroid>();
Random r = new Random();
//Creates 10 random asteroids
for (int i = 1; i <= 10; i++)
{
int x = r.nextInt(frameWidth - GameEngine.ASTEROID_WIDTH);
int y = r.nextInt(frameHeight - GameEngine.ASTEROID_HEIGHT);
double angle = r.nextDouble() * 359;
int size = r.nextInt(3) + 1;
asteroidList.add(new Asteroid(x, y, angle, size, frameWidth,frameHeight ));
}
} |
c37ce990-5f9e-462c-a567-8ff80ad94063 | 9 | private void evaluateInput(String message) throws Exception {
// Parse the input message
Matcher matcher = pattern.matcher(message);
if (matcher.matches() == false) {
throw new IllegalArgumentException(
"Syntax error: " + message);
}
// Parse the received command
String command = matcher.group(1);
String params = matcher.group(2);
if ("id".equals(command)) {
parseID(params);
} else if ("uciok".equals(command)) {
parseUCIOk(params);
} else if ("readyok".equals(command)) {
parseReadyOk(params);
} else if ("bestmove".equals(command)) {
parseBestMove(params);
} else if ("copyprotection".equals(command)) {
parseCopyProtection(params);
} else if ("registration".equals(command)) {
parseRegistration(params);
} else if ("info".equals(command)) {
parseInfo(params);
} else if ("option".equals(command)) {
parseOption(params);
} else {
throw new IllegalArgumentException(
"Unknown engine command: " + command);
}
} |
2861e7a8-1298-45cf-a6c2-8b44d2cac70f | 8 | private Map<Good, HashMap<Enums.MarketValues, Integer>> filterGoods(Map<Good, HashMap<Enums.MarketValues, Integer>> candidateValues, RandomPort port){ //}, RandomPort port){
Set<Good> keys = new HashSet<Good>();
for (Good good : candidateValues.keySet()){
if (filterIfPreAgriculture(port, good) ||
filterIfAgriculture(port, good) ||
filterIfMedieval(port, good) ||
filterIfRenaissance(port, good) ||
filterIfEarly(port, good) ||
filterIfIndustrial(port, good)){
keys.add(good);
}
}
for (Good key : keys) {
candidateValues.remove(key);
}
return candidateValues;
} |
e7ce33ee-58d5-4f03-8562-624909719110 | 7 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
63c2dc1b-7316-4436-a6f5-7c6fe164cad1 | 8 | public static boolean computeCell(boolean[][] world, int col, int row)
{
// liveCell is true if the cell at position (col,row) in world is live
boolean liveCell = getCell(world, col, row);
// neighbours is the number of live neighbours to cell (col,row)
int neighbours = countNeighbours(world, col, row);
// we will return this value at the end of the method to indicate whether
// cell (col,row) should be live in the next generation
boolean nextCell = false;
// A live cell with less than two neighbours dies (underpopulation)
if (neighbours < 2) nextCell = false;
// A live cell with two or three neighbours lives (a balanced population)
if (liveCell && (neighbours == 2 || neighbours == 3)) nextCell = true;
// A live cell with more than three neighbours dies (overcrowding)
if (liveCell && neighbours > 3) nextCell = false;
// A dead cell with exactly three live neighbours comes alive
if (!liveCell && neighbours == 3) nextCell = true;
return nextCell;
} |
d2d878e2-c9f1-40e6-8052-43e58c40198f | 4 | @Test
public void test_addition() {
int m = 2;
int n = 3;
Matrix m1 = new MatrixArrayList(m, n);
Matrix m2 = new MatrixArrayList(m, n);
Matrix m3 = new MatrixArrayList(m, n);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
m1.insert(i, j, (double) (2 * i + j));
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
m2.insert(i, j, (double) (i * i * j * j));
}
// m1:
// [
// [3.0, 4.0, 5.0],
// [5.0, 6.0, 7.0]
// ]
// m2:
// [
// [1.0, 4.0, 9.0],
// [4.0, 16.0, 36.0]
// ]
// Erwartetes Ergebnis:
// [
// [4.0, 8.0, 14.0],
// [9.0, 22.0, 43.0]
// ]
m3.insert(1, 1, 4.0);
m3.insert(1, 2, 8.0);
m3.insert(1, 3, 14.0);
m3.insert(2, 1, 9.0);
m3.insert(2, 2, 22.0);
m3.insert(2, 3, 43.0);
assertEquals(m1.add(m2), m3);
} |
6b981390-1f8d-4b98-bcce-4e884a0ad01b | 8 | public static File getFile(int column)
{
switch (column) {
case 1: return File.a;
case 2: return File.b;
case 3: return File.c;
case 4: return File.d;
case 5: return File.e;
case 6: return File.f;
case 7: return File.g;
case 8: return File.h;
default:
throw new IllegalArgumentException(
"Given column: " + column + " is not between 1 and 8.");
}
} |
c5ae06a6-ca4f-4f5d-bc9c-e27b56c80b81 | 4 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof BaggageCarriage))
return false;
BaggageCarriage other = (BaggageCarriage) obj;
if (shelfCount != other.shelfCount)
return false;
return true;
} |
5717030f-3e4e-45a7-912c-beef19394661 | 2 | private void lockedAndPreventingPlayerUse(JButton button, boolean trueOrFalse) {
if(!areWeUnlocked) {
setUpButtonImage(button, lockImage, 100, 50);
areWeUnlocked = true;
}
else if(areWeUnlocked) {
setUpButtonImage(button, unlockImage, 100, 50);
areWeUnlocked = false;
}
mediaPlayer.stop();
LockedPlaylistValueAccess.lockedPlaylist = trueOrFalse;
fileChooser.lockTheOpenButton(trueOrFalse);
button.repaint();
} |
4b73464a-1426-477d-9d60-a912371f34f7 | 5 | private static BigInteger mp(BigInteger base,BigInteger exponent,BigInteger modulus) {
BigInteger result=BigInteger.ONE; // initialize variable
// failsafe
if( base.compareTo(BigInteger.ONE) < 0 || exponent.compareTo(BigInteger.ZERO) < 0 || modulus.compareTo(BigInteger.ONE) < 1) {
return BigInteger.ZERO;
}
while(exponent.compareTo(BigInteger.ZERO) > 0) {
// if ((exponent % 2) == 1)
if(exponent.mod( BigInteger.ONE.add(BigInteger.ONE )).equals(BigInteger.ONE)) {
// result = (result*base)%modulus;
result = (result.multiply(base)).mod(modulus);
}
// base = (base*base) %mod
base = (base.multiply(base)).mod(modulus);
// exponent = floor(exponent/2)
exponent = exponent.divide(BigInteger.ONE.add(BigInteger.ONE ));
}
return result;
} |
c791a864-5166-483b-ad81-cb538f832c3b | 9 | public void initProvider(String initialContextFactory, String jndiProviderUrl, Map<String, String> settings) throws Exception {
Properties env = new Properties( );
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, jndiProviderUrl);
initialContext = new InitialContext(env);
if (settings != null) {
String lookupName = settings.get(Options.SETTINGS_KW_CONNECTION_FACTORY_LOOKUP_NAME);
boolean connect = Boolean.parseBoolean(settings.get(Options.SETTINGS_KW_CONNECT));
String username = settings.get(Options.SETTINGS_KW_USERNAME);
String password = settings.get(Options.SETTINGS_KW_PASSWORD);
String clientId = settings.get(Options.SETTINGS_KW_CLIENT_ID);
boolean start = Boolean.parseBoolean(settings.get(Options.SETTINGS_KW_START_CONNECTION));
boolean transacted = Boolean.parseBoolean(settings.get(Options.SETTINGS_KW_TRANSACTED));
String type = settings.get(Options.SETTINGS_KW_TYPE);
if (lookupName != null) {
connectionFactory = (ConnectionFactory)initialContext.lookup(lookupName);
} else {
connectionFactory = (ConnectionFactory)initialContext.lookup(Options.DEFAULT_CONNECTION_FACTORY_LOOKUP_NAME);
}
if (connect) {
if (providerConnection != null) {
closeConnection();
}
if (username != null && password != null) {
connect(username, password);
} else {
connect();
}
if (clientId != null) {
setClientId(clientId);
}
if (start) {
if (type != null) {
initSession(transacted, type);
} else {
initSession();
}
start();
}
}
} else {
connectionFactory = (ConnectionFactory)initialContext.lookup(Options.DEFAULT_CONNECTION_FACTORY_LOOKUP_NAME);
}
} |
a4538ff6-9d56-4669-9551-abdd942d61dc | 6 | public boolean onCommand(CommandSender cs, Command cmnd, String string, String[] args) {
if (args.length == 0) {
if (cs instanceof Player) {
args = new String[]{cs.getName()};
} else {
cs.sendMessage(ChatColor.RED + "Invalid usage: " + getHelp());
return true;
}
}
Player target = Bukkit.getPlayer(args[0]);
if (target == null) {
cs.sendMessage(ChatColor.RED + "That player is not online");
return true;
}
if (!target.getName().equalsIgnoreCase(cs.getName())) {
if (!cs.hasPermission(permission + ".other")) {
cs.sendMessage(ChatColor.RED + "You do not have permission to teleport others");
return true;
}
}
target.teleport(target.getWorld().getSpawnLocation());
target.sendMessage(ChatColor.YELLOW + "You were teleported to spawn");
if (!target.getName().equalsIgnoreCase(cs.getName())) {
cs.sendMessage(ChatColor.YELLOW + target.getName() + " was teleported to the spawn");
}
return true;
} |
170d3b9a-cf66-4f0d-9d82-4d24134f5cc4 | 3 | private void drawConnectors(Graphics2D g) {
for (Connector c : connectors) {
Color cSave = g.getColor();
Stroke sSave = g.getStroke();
if (c.isSelected()) {
g.setColor(Color.red);
g.setStroke(new BasicStroke(2f));
}
if (c instanceof InputConnector) {
drawInput(g, (InputConnector) c);
} else {
drawOutput(g, (OutputConnector) c);
}
g.setColor(cSave);
g.setStroke(sSave);
c.drawName(g, connectorSize);
}
} |
39387cde-54cd-4b98-af56-2a8b3db19def | 8 | public void swapView(String name)
{
myLayout.show(getContentPane(), name);
if(name.equals("The Game"))
{
if(mainGame.volumeOn)
{
//sequencer.stop();
try
{
sequencer.setSequence(SORAIRO_DAYS);
}
catch (InvalidMidiDataException e) {}
sequencer.setLoopCount(Integer.MAX_VALUE);
sequencer.start();
}
mainGame.requestFocusInWindow();
previousScreen = "Game";
}
else if(name.equals("Start Menu"))
{
if(previousScreen.equals("Game"))
{
sequencer.stop();
mainGame.requestFocusInWindow();
// try
// {
// sequencer.setSequence(ROCK_SHOW);
// }
// catch (InvalidMidiDataException e) {}
//sequencer.setLoopCount(Integer.MAX_VALUE);
//sequencer.start();
}
startMenu.requestFocusInWindow();
previousScreen = "Start";
}
else if(name.equals("Highscores"))
{
try
{
highscores.refreshHighScores();
}
catch(Exception e){}
highscores.requestFocusInWindow();
previousScreen = "Highscores";
}
else if(name.equals("DeathScreen"))
{
deathScreen.requestFocusInWindow();
previousScreen = "Deathscreen";
}
} |
7578e853-681d-44dd-a069-98a37f654b40 | 1 | public static void main(String[] args) throws InterruptedException {
Callable<Integer> callable = new CallableImpl(2);
ExecutorService executor = new ScheduledThreadPoolExecutor(1);
Future<Integer> future = executor.submit(callable);
try {
System.out.println("Future value: " + future.get());
} catch (Exception ignored) {}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS);
} |
c9d6f82d-a2eb-4f6e-a427-f8a671bb6e23 | 5 | public int[] getRowColBounds()
{
/* KSC: try to decrease processing time by using refPtgs treemap
int[] retValues = {0,0,0,0};
for (int i=0;i<sqrefs.size();i++) {
SqRef sref = (SqRef)sqrefs.get(i);
int[] locs = sref.getIntLocation();
for (int x=0;x<2;x++) {
if((locs[x]<retValues[x])||i==0)retValues[x]=locs[x];
}
for (int x=2;x<4;x++) {
if((locs[x]>retValues[x])||i==0)retValues[x]=locs[x];
}
}*/
/* Object[] refs= allrefs.values().toArray();
for (int i= refs.length-1; i >= 0; i--) {*/
int[] retValues = { Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 0 };
Iterator ptgs = allrefs.values().iterator();
int i = 0;
while( ptgs.hasNext() )
{
PtgRef pr = (PtgRef) ptgs.next();
// PtgRef pr= (PtgRef)refs[i];
int[] locs = pr.getIntLocation();
for( int x = 0; x < 2; x++ )
{
if( (locs[x] < retValues[x]) )
{
retValues[x] = locs[x];
}
}
for( int x = 2; x < 4; x++ )
{
if( (locs[x] > retValues[x]) )
{
retValues[x] = locs[x];
}
}
i++;
}
return retValues;
} |
c91454b6-5bd3-40bf-8482-598c32dacca8 | 8 | public boolean submitClaim(Claim c, String actionType) {
boolean flag = false;
Element claimE = (Element) document
.selectSingleNode("//" + actionType + "[@id='" + c.getId() + "']");
if (claimE != null) {
claimE.element("dialogState").setText(c.getDialogState());
// Write to xml
try {
XmlUtils.write2Xml(fileName, document);
flag = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Copy to public dialog
ClaimDao claimDao = new ClaimDao(publicFileName);
if (actionType.equals("claim")) {
if (claimDao.addClaim(c, c.getTeamType())) {
flag = true;
} else {
flag = false;
}
} else if (actionType.equals("subclaim")) {
if (claimDao.addSubClaim(c, c.getTeamType())) {
flag = true;
} else {
flag = false;
}
} else if (actionType.equals("counterclaim")) {
if (claimDao.addCounterClaim(c, c.getTeamType())) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
} |
a091eb90-93c7-4431-8458-36059d11c352 | 7 | public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
boolean retry;
Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if(executionCount > maxRetries) {
// Do not retry if over max retry count
retry = false;
} else if (exceptionBlacklist.contains(exception.getClass())) {
// immediately cancel retry if the error is blacklisted
retry = false;
} else if (exceptionWhitelist.contains(exception.getClass())) {
// immediately retry if error is whitelisted
retry = true;
} else if (!sent) {
// for most other errors, retry only if request hasn't been fully sent yet
retry = true;
} else {
// resend all idempotent requests
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
String requestType = currentReq.getMethod();
if(!requestType.equals("POST")) {
retry = true;
} else {
// otherwise do not retry
retry = false;
}
}
if(retry) {
SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
} else {
exception.printStackTrace();
}
return retry;
} |
7e0fe9a0-743f-4e66-84f6-ca9e588484d6 | 9 | public int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
int limit = Math.min(needle.length(), haystack.length() - needle.length());
int[] pm = partialMatch(needle, limit);
for (int i = 0; i <= haystack.length() - needle.length(); ) {
if (haystack.charAt(i) != needle.charAt(0)) {
i++;
} else {
boolean find = true;
for (int j = 1; j != needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
find = false;
i += (j - pm[j - 1]);
break;
}
}
if (find) {
return i;
}
}
}
return -1;
} |
90aaa547-bd62-465d-b294-25dd9c984976 | 6 | static private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
} |
0ded67f7-239f-4874-b6cd-5f16f61957f7 | 8 | @Override
public synchronized void close() throws IOException {
if(!this.closed) {
LOG.info("closing a file");
if(this.keepaliveThread != null && this.keepaliveThread.isAlive()) {
this.keepaliveThread.interrupt();
}
this.keepaliveThread = null;
Future<ClientResponse> closeFuture = this.filesystem.getUGRestClient().close(this.status.getPath().getPath(), this.fileDescriptor);
if(closeFuture != null) {
try {
this.filesystem.getUGRestClient().processClose(closeFuture);
} catch (Exception ex) {
LOG.error("exception occurred", ex);
throw new IOException(ex);
}
} else {
throw new IOException("Can not create a REST client");
}
this.closed = true;
if(!this.readonly) {
if(this.modified) {
this.status.setDirty();
}
}
if(this.localCachedBlocks != null) {
this.localCachedBlocks.clear();
}
}
} |
bf1ff143-a055-40da-a648-af8b8853d625 | 5 | public JSONObject increment(String key) throws JSONException {
Object value = opt(key);
if (value == null) {
put(key, 1);
} else if (value instanceof Integer) {
put(key, ((Integer) value).intValue() + 1);
} else if (value instanceof Long) {
put(key, ((Long) value).longValue() + 1);
} else if (value instanceof Double) {
put(key, ((Double) value).doubleValue() + 1);
} else if (value instanceof Float) {
put(key, ((Float) value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} |
05507d22-d418-4c57-a665-6a2a0e44f562 | 0 | public String toString() {
return this.getName();
} |
3dded4b2-320d-4f89-9182-2f0f77f6d09d | 1 | public void close() throws IOException {
while (numBitsInCurrentByte != 0)
write((byte)0);
output.close();
} |
e81f0047-ba25-4182-a662-d56cb5fbab41 | 8 | public static ArrayList<Node> getNodes(SQLiteConnection db) {
ArrayList<Node> nodes = new ArrayList<>();
try{
SQLiteStatement st = db.prepare("SELECT * FROM node");
while (st.step()){
Node nod = new Node(db, st.columnInt(1),
new Point(st.columnInt(2), st.columnInt(3)));
ArrayList<Appliance> types = new ArrayList<>();
SQLiteStatement st2 = db.prepare("SELECT * FROM node_objects WHERE nodeid = " + st.columnInt(1) + ";");
while(st2.step()){
String poses = st2.columnString(3);
if(poses != null){
String[] poseVals = poses.split(" ");
Set<String> poseSet = new HashSet<>(Arrays.asList(poseVals));
types.add(new Appliance(st2.columnString(2), nod, poseSet));
}else types.add(new Appliance(st2.columnString(2), nod));
}
nod.types = types;
nodes.add(nod);
}
ArrayList<Edge> edges = Edge.getEdges(nodes, db);
for(Node node: nodes){
for(Edge edge: edges){
if(node.id == edge.a.id) node.addNeighbour(edge.b);
else if(node.id == edge.b.id) node.addNeighbour(edge.a);
}
}
}catch(Exception e){
e.printStackTrace();
}return nodes;
} |
1bea7f65-0ed1-4d82-ba80-aa18c90d6861 | 0 | protected Spielgrenze(Rectangle masse, IntHolder unit) {
super(masse, unit);
} |
58eed814-18fd-4b39-b9b2-73ac4fcffb34 | 8 | private void shutdown() {
try {
isRunning = false;
FileWriter fileWriter = new FileWriter(FileCreator.getStreamListFile());
ArrayList<String> streamList = TwitchStream.getStreamList(); //ids for stream
ArrayList<String> streamName = TwitchStream.getStreamName(); //name for streamer
fileWriter.write("Twitch Streams\r\n");
fileWriter.write("\r\n");
for (int i = 0; i < streamList.size(); i++) {
System.out.println(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_"));
fileWriter.write(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_") +"\r\n");
}
fileWriter.write("\r\n");
fileWriter.write("Azubu Streams\r\n");
fileWriter.write("\r\n");
streamList = AzubuStream.getStreamList(); //ids for stream
streamName = AzubuStream.getStreamName(); //name for streamer
for (int i = 0; i < streamList.size(); i++) {
System.out.println(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_"));
fileWriter.write(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_") +"\r\n");
}
fileWriter.close();
} catch (Exception e) {
if (tryAmount < 500) {
tryAmount++;
shutdown();
}
if (tryAmount == 500) {
try{
isRunning = false;
FileWriter fileWriter = new FileWriter(FileCreator.getDesktopDirectory());
ArrayList<String> streamList = TwitchStream.getStreamList(); //ids for stream
ArrayList<String> streamName = TwitchStream.getStreamName(); //name for streamer
fileWriter.write("Twitch Streams\r\n");
fileWriter.write("\r\n");
for (int i = 0; i < streamList.size(); i++) {
System.out.println(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_"));
fileWriter.write(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_") +"\r\n");
}
fileWriter.write("\r\n");
fileWriter.write("Azubu Streams\r\n");
fileWriter.write("\r\n");
streamList = AzubuStream.getStreamList(); //ids for stream
streamName = AzubuStream.getStreamName(); //name for streamer
for (int i = 0; i < streamList.size(); i++) {
System.out.println(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_"));
fileWriter.write(streamList.get(i) + " " +streamName.get(i).replaceAll(" ", "_") +"\r\n");
}
fileWriter.close();
} catch (Exception ignored) { }
}
System.out.println("Errored out while writing!");
}
} |
739b8b0a-f60e-4b88-8aae-e7779828115b | 9 | public final void shutdown() {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
try {
if (soundPlayer != null) {
soundPlayer.running = false;
}
if (resourceThread != null) {
resourceThread.running = true;
}
} catch (Exception ex) {
LogUtil.logError("Error shutting down threads.", ex);
}
if (!isLevelLoaded) {
try {
if (level != null && isSinglePlayer) {
if (level.creativeMode) {
new LevelSerializer(level).saveMap("levelc");
} else {
new LevelSerializer(level).saveMap("levels");
}
}
} catch (Exception ex) {
LogUtil.logError("Error saving single-player level.", ex);
}
}
Mouse.destroy();
Keyboard.destroy();
} |
32a6ecba-02f3-4371-9bb1-f2c643ac090b | 5 | public void play() {
if (sequence == null) {
throw new IllegalStateException("MidiAsset.play: " +
"Midi sequence not loaded");
}
if (sequencer == null) {
initialiseSequencer();
}
try {
sequencer.setSequence(sequence);
if (continuallyPlay) {
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
}
sequencer.start();
channels = synthesizer.getChannels();
if (volume != -1) {
setVolume(volume);
}
} catch (InvalidMidiDataException exception) {
throw new IllegalStateException("MidiAsset.play: " +
"Cannot play Midi sequence.");
}
} |
374e1a17-0025-4d41-b0fb-3f64e95a1280 | 9 | public JsonObject deleteActivity( JsonObject json ) {
// Get and validate parameters
JsonValue activityJsonValue = json.get("activity");
if ( activityJsonValue == null ) return new JsonObject().add("error", "Parameter activity is null");
if ( !activityJsonValue.isObject() ) return new JsonObject().add("error", "Parameter activity isn't a json object");
JsonObject activityJson = activityJsonValue.asObject();
JsonValue nameValue = activityJson.get("name");
if ( nameValue == null ) return new JsonObject().add("error", "Parameter name is null");
if ( !nameValue.isString() ) return new JsonObject().add("error", "Parameter name isn't a string");
String name = nameValue.asString();
// Delete the activity from the database
ActivityDAO adao = new ActivityDAO();
Activity activity = adao.select(name);
// Some error might have happened
if ( activity == null ) {
if ( adao.getError() == null || adao.getError().equals("") )
return new JsonObject().add("error", "The requested activity doesn't exist");
else
return new JsonObject().add("error", adao.getError());
}
// We only accept uninstallation requests if the activity status is approved or error
// For example, if the activity status is installing, we shouldn't accept them
if ( ! ( "approved".equals(activity.getStatus()) || "error".equals(activity.getStatus()) ) )
return new JsonObject().add("error", "The requested activity isn't available for uninstalling yet");
// Update the activity status to uninstalling so we don't accept more execution requests
adao.updateStatus( activity.getId() , "uninstalling");
// Delete pending executions of this activity from queue
ExecutionWaitingQueue queue = new ExecutionWaitingQueue();
queue.deleteAll( activity.getId() );
// Launch a thread that for every worker, sends a request to perform the installation
new Thread ( new ActivityInstallationNotifier(activity, Action.UNINSTALL_ACTIVITY ) ).start();
// No error happened
return new JsonObject().add("activity", activity.toJsonObject()).add("status", "uninstalling");
} |
a39e347d-f9c8-4a91-810a-c7b89e96285a | 5 | public void loadPropertiesForClass(String className){
try{
Properties props = new Properties();
String softwareProperties = System.getProperty(SOFTWARE_PROPERTIES);
props.load(new FileInputStream(softwareProperties != null ? softwareProperties : HARD_CODED_SOFTWARE_PROPERTIES));
Set<String> propertyNames = props.stringPropertyNames();
for(String name : propertyNames){
// Load only properties that match this given class name
if(name.indexOf('.') > -1 && name.substring(0, name.indexOf('.')).equalsIgnoreCase(className)){
properties.put(name,props.getProperty(name));
}
}
}catch(Exception e){
e.printStackTrace();
}
} |
d386ecc4-7198-4aef-bdb8-776f4e9bfc52 | 1 | public boolean isRemover() {
return (remover) ? true : false;
} |
dea93c7a-c4c4-479d-8ca0-0945608995bf | 1 | public void addToInput(String input) {
if(!this.input.contains(input))
this.input.add(input);
} |
cc650c00-7302-4569-8fb7-dd3d83823522 | 5 | public void run() {
while (running) {
try {
sleep(10000);
//LazyHomer.setLastSeen();
for(Iterator<MargeObserver> iter = observers.keySet().iterator(); iter.hasNext(); ) {
MargeObserver obs = (MargeObserver)iter.next();
String url = observers.get(obs);
obs.remoteSignal("localhost","GET", url); // maintainance call?
}
counter++;
} catch(InterruptedException i) {
if (!running) break;
} catch(Exception e) {
LOG.info("ERROR MargeTimerThread");
e.printStackTrace();
}
}
} |
f685cbed-3ac8-4765-92eb-bba05fccfd07 | 6 | public void addEntry(Catalog cat, Node node) {
NodeList childNodes = node.getChildNodes();
Elev key = null;
HashMap<Materie, SituatieMaterieBaza> value = new HashMap<Materie, SituatieMaterieBaza>();
for (int i = 0; i < childNodes.getLength(); i++) {
Node cNode = childNodes.item(i);
if (cNode instanceof Element) {
String content = cNode.getLastChild().getTextContent().trim();
switch (cNode.getNodeName()) {
case "CNP":
for (Elev e : elevi) {
if (e.getCNP().equals(content)) {
key = e;
break;
}
}
break;
case "Materie":
addSituatie(value, cNode);
cat.addEntry(key, value);
break;
default:
break;
}
}
}
} |
64a0408c-f38e-4947-9679-cc14d84aa1c8 | 6 | @Get("json")
public Representation _get() {
String keyword = getAttribute("keyword");
String query = format(FIND_RSRC, keyword);
Map<?, ?> anno = $annotations.findOne(query).as(Map.class);
if (anno == null) {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
return null;
}
String name = (String) anno.get("name");
String kword = (String) anno.get("keyword");
String type = (String) anno.get("type");
String usage = (String) anno.get("usage");
String desc = (String) anno.get("description");
Objects.Annotation obja = new Objects.Annotation(name, kword, type);
obja.setUsage(usage);
obja.setDescription(desc);
Object _id = anno.get("_id");
Find find = $annovalues.find(FIND_VALUES, _id);
List<String> values = new LinkedList<>();
for (Map<?, ?> map : find.as(Map.class)) {
values.add((String) map.get("val"));
}
obja.put("values", values);
// links
String path = declaredPath(Objects.Annotations.class);
obja.addLink("self", urlify(path, keyword, "values"));
obja.addLink("related", urlify(path, keyword));
return obja.json();
} |
61c070ae-e497-41dc-bcd6-ebdc92f1bb6f | 2 | public List<Row> getTopLevelRows() {
ArrayList<Row> list = new ArrayList<>();
for (Row row : mRows) {
if (row.getParent() == null) {
list.add(row);
}
}
return list;
} |
cafc98f8-3400-4d99-997a-23d3647fd2d8 | 3 | public void addSymbolsFromChilds(GoTerm goTerm) {
// Add symbols
for( String symbolId : symbolIdSet )
goTerm.addSymbolId(symbolId);
// Add interesting symbols
for( String symbolId : interestingSymbolIdSet )
goTerm.addInterestingSymbolId(symbolId);
// Recurse
for( GoTerm child : childs )
child.addSymbolsFromChilds(goTerm);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.