method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
567a2b44-f8e5-483b-bcb0-60c39e970616 | 7 | public static void matMultiply(Matrix A, Matrix B, Matrix C) {
int rowsOut = B.height;
int innerProdDim = B.width;
int colsOut = C.width;
if ((A.height != rowsOut) || (A.width != C.width) || (B.width != C.height)) {
throw new RuntimeException("Error: The matrices have inconsistant dimensions!");
}
float sum;
// matrices are in column-major, so use a temporary array containign
// the current row of B.
float[] rowB = new float[innerProdDim];
// Now, for each row of B, compute inner products with all columns of C.
for (int i=0; i < rowsOut; i++) {
// i = current row of the output matrix.
// Copy the i'th row of B into the temp array.
for (int n=0; n < innerProdDim; n++) {
rowB[n] = B.get(i, n);
}
// Now perform the inner products for each column of C.
for (int j=0; j < colsOut; j++) {
sum = 0;
for (int m = 0; m < innerProdDim; m++) {
sum += rowB[m]*C.get(m, j);
}
A.set(i,j, sum);
}
}
} |
0caee412-c677-4f00-9f77-2f72508ea38c | 3 | private String replaceInString(final String regex,
final String srcString,
final String replacement) {
// Exit
if (srcString == null || "".equals(srcString)) { return null; }
// Replace all found files with the value of
// <code>ApplicationProperties.LOG_FILE_PATH.getDefaultValue()</code>
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(srcString);
String fileContent = srcString;
while (matcher.find()) {
fileContent = fileContent.replace(matcher.group(1), replacement);
}
return fileContent;
} |
ebd51882-7191-48c2-bf6a-b13bcc9d40fe | 3 | public synchronized byte[] getMessage() {
if(pendingMessage != null) {
// Padding has already been applied earlier, so we can just return the pending message.
return pendingMessage;
} else if(!messageBuffer.isEmpty()) {
// Fetch the last message from the buffer and apply padding
pendingMessage = Padding10.apply10padding(messageBuffer.poll(), payloadSize);
return pendingMessage;
} else if(writePointer > 0) {
// Only in this case we have to apply padding
synchronized(this) {
byte[] message = Padding10.apply10padding(currentMessage, writePointer, payloadSize);
currentMessage = new byte[messageSize];
writePointer = 0;
pendingMessage = message;
return message;
}
}
// This catches everything that was not caught by previous conditions
// We do not apply padding since the message is meant to be _empty_.
// We do not send a pending message, either.
return new byte[payloadSize];
} |
f4adb434-4925-4fb3-becb-12d0b40767ce | 8 | public ShowCompanyPanel() {
super(null);
this.setBackground(Color.black);
model = new CompanyTableModel();
sorter = new TableRowSorter<CompanyTableModel>(model);
companyTable = new JTable(model);
companyTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
companyTable.setFillsViewportHeight(true);
companyTable.setRowSorter(sorter);
companyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
companyTable.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
int tableRow = companyTable.rowAtPoint(e.getPoint());
Company[] companyData = ReadFromFile.findAllCompanyData();
try
{
String indexValue =(String)companyTable.getValueAt(tableRow, 0);
for(int i = 0; i < companyData.length; i++) {
if(indexValue.equals(companyData[i].getID())) {
JOptionPane.showMessageDialog(null,
companyDataInfo(Integer.parseInt(indexValue)-1, companyData), "Company Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch(IndexOutOfBoundsException f){}
}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
});
try {
logo = ImageIO.read(new File("MMT_Logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
try{
background = ImageIO.read(new File("DAPP_Background2.jpg"));
}catch(IOException e) {
e.printStackTrace();
}
chooseFilter = new JComboBox(filterLabels);
filterText = new JTextField();
//Whenever filterText changes, invoke newFilter.
filterText.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
newFilter();
}
public void insertUpdate(DocumentEvent e) {
newFilter();
}
public void removeUpdate(DocumentEvent e) {
newFilter();
}
});
/*
* The registration part of the panel initialized here.
* includes the text fields, buttons, and JLabels
*/
companytxt = "company.txt";
companyTableData = new String[9];
logo = null;
try {
logo = ImageIO.read(new File("MMT_Logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
try{
background = ImageIO.read(new File("DAPP_Background2.jpg"));
}catch(IOException e) {
e.printStackTrace();
}
// Labels declared and initialized
companynameLabel = new JLabel("Company Name : ");
companynameLabel.setForeground(allColor);
companynameLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
contactLabel = new JLabel("Contact Person : ");
contactLabel.setForeground(allColor);
contactLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
emailLabel = new JLabel("Email : ");
emailLabel.setForeground(allColor);
emailLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
phoneLabel = new JLabel("Phone Number : ");
phoneLabel.setForeground(allColor);
phoneLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
addressLabel = new JLabel("Address : ");
addressLabel.setForeground(allColor);
addressLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
cityLabel = new JLabel("City : ");
cityLabel.setForeground(allColor);
cityLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
stateLabel = new JLabel("State : ");
stateLabel.setForeground(allColor);
stateLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
zipLabel = new JLabel("Zip Code : ");
zipLabel.setForeground(allColor);
zipLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
// JTextFields declared with their lengths declared as well
companynameField = new JTextField();
contactField = new JTextField();
emailField = new JTextField();
phoneField = new JTextField();
addressField = new JTextField();
cityField = new JTextField();
stateField = new JTextField();
zipField = new JTextField();
// Button which cancels the registration, going back to the Main Frame
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
clearTextFields();
}
});
// Button that enters all the data to an Employee file and also prints to txt file
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(checkTextFields()) {
getText();
clearTextFields();
enterToFile();
model.changeData();
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, "Your information on this company has been submitted");
}
}
});
/*
* Adds all the Components into the Panel
* Has same method as ShowEmployeePanel for labeling and
* ordering as well as spacing.
*/
this.setBorder(BorderFactory.createEmptyBorder(50, 200, 50, 190));
currentY = registerY;
this.add(companynameLabel);
companynameLabel.setBounds(registerX, currentY, 150, 20);
this.add(companynameField);
companynameField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(contactLabel);
contactLabel.setBounds(registerX, currentY, 150, 20);
this.add(contactField);
contactField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(emailLabel);
emailLabel.setBounds(registerX, currentY, 150, 20);
this.add(emailField);
emailField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(phoneLabel);
phoneLabel.setBounds(registerX, currentY, 150, 20);
this.add(phoneField);
phoneField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(addressLabel);
addressLabel.setBounds(registerX, currentY, 150, 20);
this.add(addressField);
addressField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(cityLabel);
cityLabel.setBounds(registerX, currentY, 150, 20);
this.add(cityField);
cityField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(stateLabel);
stateLabel.setBounds(registerX, currentY, 150, 20);
this.add(stateField);
stateField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(zipLabel);
zipLabel.setBounds(registerX, currentY, 150, 20);
this.add(zipField);
zipField.setBounds(registerX + 170, currentY, fieldSize, 20);
currentY+= addition;
this.add(cancel);
cancel.setBounds(registerX, currentY, 70, 20);
this.add(submit);
submit.setBounds(registerX + 90, currentY, 70, 20);
this.add(chooseFilter);
chooseFilter.setBounds(tableX, 590, 150, 20);
this.add(filterText);
filterText.setBounds(tableX + 170, 590, 300, 20);
tablePane = new JScrollPane(companyTable);
this.add(tablePane);
tablePane.setBounds(tableX, tableY, 500, 500);
} |
ed50bb58-01e6-41e8-8466-60ff4e0476d8 | 6 | @Override
public void playCard(int playerId, int cardId) throws ActionNotAllowedException {
Card cardPlayed = cardDAO.getCard(cardId);
if (!gameStatus.beginningCardDrawn && playerOnTheMove(playerId)) {
throw new ActionNotAllowedException(EXCEPTION_PLAY_CARD_BEGINNING_CARD_NOT_DRAWN);
}
if (playerPointsTooHigh(playerId, cardPlayed)) {
throw new ActionNotAllowedException(EXCEPTION_PLAY_TOO_MUCH_RESOURCES);
}
if (cardIsEvent(cardPlayed)) {
playEventCard(cardPlayed, playerId);
} else {
if (cardIsResource(cardPlayed)) {
playResourceCard(cardPlayed, playerId);
} else {
if (cardIsMultiplier(cardPlayed)) {
putCardInPlayersResources(cardPlayed, playerId);
} else {
throw new ActionNotAllowedException();
}
}
}
removeCardFromPlayersHand(cardPlayed, playerId);
} |
ce34272e-df71-499f-a7ae-17ceff6710a3 | 2 | public void draw( Graphics2D g, Scale s){
int numPoints = 10;
for( int i=0; i<numPoints; i++){
for( int j=0; j<numPoints; j++){
drawSlope( g, s.new Converter( numPoints,
new Point(i,j) ) );
}
}
} |
9faa5588-f798-4215-bb2b-79cc37699b15 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof RGB)) return false;
return ((RGB) obj).r == r && ((RGB) obj).g == g && ((RGB) obj).b == b && ((RGB) obj).a == a;
} |
e58dd768-d1c7-471e-bae9-60d3454967ea | 0 | public static int contains(String text, String match) {
return StringTools.contains(text, match);
} |
7b09d638-4e24-4814-9634-8c14543e6717 | 2 | public void playSounds(){
if(LockedPlaylistValueAccess.lockedPlaylist) {
ArrayList<Sound> soundList = currentSlide.getSoundList();
if(!soundList.isEmpty())
{
Sound sound = soundList.get(0);
audioPlayer.prepareMedia(sound.getFile(), sound.getStart());
audioPlayer.playMedia();
}
}
} |
380bb7c3-23b9-47f1-a2c2-4b690df0865a | 3 | private void btnSwitchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSwitchActionPerformed
UsuariosCRUD udao = new UsuariosCRUD(MyConnection.getConnection());
if(btnSwitch.getText().equals("Actualizar")){
Usuarios u = new Usuarios(
edtCodigo.getText().toString(),
edtNombre.getText().toString(),
edtDNI.getText().toString()
);
if(udao.update(u)){
JOptionPane.showMessageDialog(
this,
"Registro Guardado Con exito!!!",
"Notificación",
JOptionPane.INFORMATION_MESSAGE
);
}
}else{
Usuarios u = new Usuarios(
edtCodigo.getText().toString(),
edtNombre.getText().toString(),
edtDNI.getText().toString()
);
if(udao.add(u)){
JOptionPane.showMessageDialog(
this,
"Registro Guardado Con exito!!!",
"Notificación",
JOptionPane.INFORMATION_MESSAGE
);
clearForm();
}
}
}//GEN-LAST:event_btnSwitchActionPerformed |
539dc075-0fc4-402a-8183-c8c5db9915a5 | 1 | public static void insert(Girl newNode){
if(head == null){
head = newNode;
tail = newNode;
}
else{
tail.next = newNode;
tail = tail.next;
}
} |
ee15984b-43b0-4891-806c-e31a53c8c664 | 1 | public FlacHeader(int sampleRateHz, byte numChannels, byte bitsPerSample,
long numSamples,byte[] md5,int numMetadataBlocks, long frameDataStart) {
super();
this.sampleRateHz = sampleRateHz;
this.numChannels = numChannels;
this.bitsPerSample = bitsPerSample;
this.numSamples = numSamples;
this.numMetadataBlocks = numMetadataBlocks;
this.frameDataStart = frameDataStart;
if(md5.length != 16 ) {
throw new RuntimeException("internal error, flac stream must have 128-bit md5");
}
this.md5=md5;
} |
6700afd4-d2d3-436f-bbbe-b6529ceb5df0 | 2 | private void insert(int put) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if ((put & 1) == 1)
sb.append('Q');
else
sb.append('.');
put >>>= 1;
}
oneSolution[row] = sb.toString();
row++;
} |
8e4349cb-ed78-4ec5-a128-4bf9e8be7adb | 8 | public static boolean isValidDate(String dateString){ //for checking if date is a valid date, surprise surprise
if (dateString == null || dateString.length() != "yyyyMMdd".length()){
return false;
}//end of if statement
int date;
try{
date = Integer.parseInt(dateString);
}//end of try statement
catch (NumberFormatException e){
return false;
}//end of catch statement
int year = date / 10000;
int month = (date % 10000) / 100;
int day = date % 100;
// leap years calculation not valid before 1581
boolean yearOk = (year >= 1581) && (year <= 2500);
boolean monthOk = (month >= 1) && (month <= 12);
boolean dayOk = (day >= 1) && (day <= daysInMonth(year, month));
return (yearOk && monthOk && dayOk);
}//end of isValidDate method |
93a35127-66df-4495-bdde-bf6c122c9c22 | 2 | public Sentence getSentence(String id) {
for (Sentence sentence : sentences) {
if (sentence.getId().equals(id))
return sentence;
}
return null;
} |
4cc89e03-a33d-45e7-af22-6da95da157eb | 6 | public boolean canSupport(Territory territory, int SeatNum) { //!territory.getOrder().getUse() semble pas fonctionner
return (territory2.getNeighbors().contains(territory)&& territory.getOrder()!=null && territory.getFamily().getPlayer()==SeatNum && territory.getOrder().getType()==OrderType.SUP && (!territory.getOrder().getUse())&& (territory instanceof Water || territory2 instanceof Land));
} |
87cce1be-5784-45c2-934d-4b411f1dddab | 7 | public void setFontSmoothingValue(Object sv)
{
if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
{
font_smoothing_value = 1;
}
else if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
{
font_smoothing_value = 2;
}
else if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_GASP)
{
font_smoothing_value = 3;
}
else if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR)
{
font_smoothing_value = 4;
}
else if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
{
font_smoothing_value = 5;
}
else if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR)
{
font_smoothing_value = 6;
}
else if(sv == RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB)
{
font_smoothing_value = 7;
}
else
{
font_smoothing_value = 0;
}
} |
d82568f5-83ce-4a26-878d-6ebb5972a0ae | 1 | public void testConstructor_ObjectStringEx2() throws Throwable {
try {
new LocalDate("1970-04-06T10:20:30.040");
fail();
} catch (IllegalArgumentException ex) {}
} |
8df4e19d-aa84-414c-8f9b-c56b9c21f0ad | 5 | @Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (qName.equals("onStandingDrop")) {
response.setOnStandingDrop(getCombatSetting(attrs));
} else if (qName.equals("onStatusDrop")) {
response.setOnStatusDrop(getCombatSetting(attrs));
} else if (qName.equals("onAggression")) {
response.setOnAggression(getCombatSetting(attrs));
} else if (qName.equals("onCorporationWar")) {
response.setOnCorporationWar(getCombatSetting(attrs));
} else if (qName.equals("row")) {
response.addFuelLevel(getInt(attrs, "typeID"), getInt(attrs, "quantity"));
} else
super.startElement(uri, localName, qName, attrs);
} |
91090383-d298-4b9f-90fe-40eabc0f64e4 | 5 | public float GetLineThickness(){
switch (LineWidthComboBox.getSelectedIndex()) {
case 0:
return 1.00f;
case 1:
return 2.00f;
case 2:
return 3.00f;
case 3:
return 4.00f;
case 4:
return 5.00f;
default:
return 0f;
}
} |
4b4aa5c0-45b7-464a-bf2c-ffed63409575 | 8 | private boolean r_tidy_up() {
int among_var;
// (, line 183
// [, line 184
ket = cursor;
// substring, line 184
among_var = find_among_b(a_7, 4);
if (among_var == 0)
{
return false;
}
// ], line 184
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 188
// delete, line 188
slice_del();
// [, line 189
ket = cursor;
// literal, line 189
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// ], line 189
bra = cursor;
// literal, line 189
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// delete, line 189
slice_del();
break;
case 2:
// (, line 192
// literal, line 192
if (!(eq_s_b(1, "\u043D")))
{
return false;
}
// delete, line 192
slice_del();
break;
case 3:
// (, line 194
// delete, line 194
slice_del();
break;
}
return true;
} |
db25d186-92f5-4bde-bb12-6fd8f47905ab | 5 | @Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Invoke the painter for the background
if (painter != null)
{
Dimension d = getSize();
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(painter);
g2.fill( new Rectangle(0, 0, d.width, d.height) );
}
// Draw the image
if (image == null ) return;
switch (style)
{
case SCALED :
drawScaled(g);
break;
case TILED :
drawTiled(g);
break;
case ACTUAL :
drawActual(g);
break;
default:
drawScaled(g);
}
} |
626ee9e3-c40b-4507-b504-2f6b3997311b | 0 | private void Initialize() {
//initialize cars
playerCar = new Car();
enemyCar = new EnemyCar();
//create the course
CreateCourse();
//create the background
movingBg = new MovingBackground();
} |
38af909d-b0a1-4472-9bb2-a2707b6ba788 | 0 | void f() {
print("Pie.f();");
} |
a288e45d-6c14-4edd-8c2a-f21af3855977 | 8 | private Component cycle(Component currentComponent, int delta) {
int index = -1;
loop : for (int i = 0; i < m_Components.length; i++) {
Component component = m_Components[i];
for (Component c = currentComponent; c != null; c = c.getParent()) {
if (component == c) {
index = i;
break loop;
}
}
}
// try to find enabled component in "delta" direction
int initialIndex = index;
while (true) {
int newIndex = indexCycle(index, delta);
if (newIndex == initialIndex) {
break;
}
index = newIndex;
//
Component component = m_Components[newIndex];
if (component.isEnabled() && component.isVisible() && component.isFocusable()) {
return component;
}
}
// not found
return currentComponent;
} |
669ae8b2-e9e9-4798-9009-503f7372ffd1 | 2 | public final LogoParser.statement_return statement() throws RecognitionException {
LogoParser.statement_return retval = new LogoParser.statement_return();
retval.start = input.LT(1);
Object root_0 = null;
LogoParser.singleLine_return singleLine8 =null;
try {
// /home/carlos/Proyectos/logojava/Logo.g:43:2: ( singleLine )
// /home/carlos/Proyectos/logojava/Logo.g:43:4: singleLine
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_singleLine_in_statement118);
singleLine8=singleLine();
state._fsp--;
adaptor.addChild(root_0, singleLine8.getTree());
(singleLine8!=null?singleLine8.value:null).execute(context);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} |
248e3c26-8c2a-4b4a-9f70-74462b620e07 | 3 | @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Produto)) {
return false;
}
Produto produto = (Produto) obj;
if (this.id == produto.getId()) {
return true;
}
return false;
} |
8044e28f-3d68-44ac-a43e-c190d8acfeb9 | 8 | @EventHandler(priority = EventPriority.LOW)
public void onPlayerMove (PlayerMoveEvent event) {
//plugin.log.info("active " + plugin.active);
if(plugin.active == false)
return;
Player p = event.getPlayer();
//plugin.log.info("cacheVar " + plugin.cacheage);
//plugin.log.info("playerCacheAge " + PlayerCache.getLocationCacheAge(p));
// Let's ask the admin how often he want us to check he moving.
if(!(PlayerCache.getLocationCacheAge(p) > plugin.cacheage * 1000))
return;
// If not, do he have permission to stay outside?
if(p.hasPermission("holdguest.nohold")) {
PlayerCache.setLocation(p, p.getLocation());
//plugin.log.info("Allowed to stay outside of box");
return;
}
//plugin.log.info("vector: " + plugin.vector);
//plugin.log.info("curVec: " + p.getLocation().toVector());
//plugin.log.info("holdradius: " + plugin.holdradius);
//plugin.log.info("world: " + plugin.world.toString());
//plugin.log.info("vec: " + plugin.vector.distance(p.getLocation().toVector()));
// let's check if the player is inside the field? If he is, no reason to check more.
if(plugin.vector.distance(p.getLocation().toVector()) < plugin.holdradius) {
if(PlayerCache.getLocationCacheAge(p) > plugin.cacheage * 1000) {
PlayerCache.setLocation(p, p.getLocation());
//plugin.log.info("Player was inside box");
}
return;
}
// Not working right now.
// p.sendMessage( misc.customMessage("keepinside"));
p.sendMessage(plugin.keepinside);
// Okay, the player is outside the field and have no permission? We should help him inside.
//Let's first check if he recently went outside and we have the old location in cache.
if(PlayerCache.getLocation(p).toVector().distance(plugin.vector) < plugin.holdradius - 0.1) {
// We should check if the block he will be standing on is solid.
if( p.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || p.getLocation().getBlock().getRelative(BlockFace.DOWN).isEmpty()) {
p.setVelocity( new Vector (0,0,0));
p.teleport( plugin.vector.toLocation( plugin.world ) );
PlayerCache.setLocationCacheAge(p, System.currentTimeMillis());
//plugin.log.info("The cached location wasn't solid.");
return;
}
p.setVelocity( new Vector (0,0,0));
p.teleport( PlayerCache.getLocation(p));
//plugin.log.info("The cached location was inside the box.");
PlayerCache.setLocationCacheAge(p, System.currentTimeMillis());
return;
}
// We will just have to send him to the middle of the spawn
p.setVelocity( new Vector (0,0,0));
p.teleport( plugin.vector.toLocation(plugin.world) );
//plugin.log.info("Moved player to middle of zone");
return;
} |
fdfad5e6-8415-465d-9d98-b16bd5f710ac | 3 | @Override
public void dragGestureRecognized(DragGestureEvent dge) {
if (mSortColumn != null && mOwner.allowColumnDrag()) {
mOwner.setSourceDragColumn(mSortColumn);
if (DragSource.isDragImageSupported()) {
Point pt = dge.getDragOrigin();
dge.startDrag(null, mOwner.getColumnDragImage(mSortColumn), new Point(-(pt.x - mOwner.getColumnStart(mSortColumn)), -pt.y), mSortColumn, this);
} else {
dge.startDrag(null, mSortColumn, this);
}
mSortColumn = null;
}
} |
77fd732e-700d-40fb-94a3-f0b7221d4a87 | 9 | public SegmentGroup joinSplines() {
long startTime = System.currentTimeMillis();
System.out.println("Sorting and joining Splines...");
SegmentGroup s = new SegmentGroup();
recalculateAllSplines(splines, sGroups, HIGH_RES);
printl(currentID + " curr Id");
for (int i = 0; i < currentID; i++) {
//loops once per each spline.
boolean isGroup = false;
Spline spline = null;
SplineGroup sGroup = null;
for (int j = 0; j < currentID; j++) {
try {
if (splines.get(j).splineID() == i) {
isGroup = false;
spline = splines.get(j);
printl(j + " j");
}
} catch (IndexOutOfBoundsException e) {
}
//if the desired spline is a spline.
try {
if (sGroups.get(j).splineID() == i) {
isGroup = true;
sGroup = sGroups.get(j);
}
} catch (IndexOutOfBoundsException e) {
}
}
if (isGroup) {
ArrayList<Segment> p = sGroup.getSegments().s;
for (int k = 0; k < sGroup.getSegments().s.size(); k++) {
Segment seg = new Segment();
seg.x = p.get(k).x;
seg.y = p.get(k).y;
s.add(seg);
}
} else {
ArrayList<Segment> p = spline.getSegments().s;
System.out.println(spline.getSegments().s.size());
// for (int l = 0; l < spline.getSegments().s.size(); l++) {
//// Segment seg = new Segment();
//// seg.x = p.get(l).x;
//// seg.y = p.get(l).y;
//// s.add(seg);
//// //System.out.println("t");
//// //System.out.println(spline.getSegments().s.size() + " size");
// }
for(int turd = p.size()-1; turd > -1; turd--){
Segment seg = new Segment();
seg.x = p.get(turd).x;
seg.y = p.get(turd).y;
s.add(seg);
}
}
}
System.out.println("Done! In " + (System.currentTimeMillis()-startTime) + " ms.");
return s;
} |
a8c35012-6c89-4452-a3d1-6ac84b4d252c | 4 | @Override
public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
if (aSmile && bSmile) {
return true;
}
if (!aSmile && !bSmile) {
return true;
}
return false;
// The above can be shortened to:
// return ((aSmile && bSmile) || (!aSmile && !bSmile));
// Or this very short version (think about how this is the same as the above)
// return (aSmile == bSmile);
} |
2847e718-42bb-45b0-aaf5-4db97225b2c9 | 5 | public void cancel(){
synchronized (this) {
log("Cancelled");
isCancelled = true;
if (youtubeProc!=null)
youtubeProc.destroy();
if (convertThread!=null)
convertThread.interrupt();
if (downloadThread!=null)
downloadThread.interrupt();
if (ffmpegProc!=null)
ffmpegProc.destroy();
songPanel.cancelButton.setEnabled(false);
songPanel.editButton.setEnabled(false);
if (downloadedListener!=null)
downloadedListener.songDownloaded();
}
} |
2691839f-82a6-49d1-93e0-d4442f60d37f | 5 | private void sysCallOpen()
{
//Get the device ID
int deviceID = m_CPU.popStack();
//SOS.debugPrintln("sysCallOpen");
//Add the current process to the device to indicate that it's using the device
//If the device exists
DeviceInfo di;
if((di = findDevice(deviceID)) != null)
{
//Also if you've already opened the device
if(!di.procs.contains(m_currProcess))
{
//Also check that the device is sharable if another process is using it
if((di.procs.size() > 0 && di.device.isSharable()) || di.unused())
{
di.procs.add(m_currProcess);
m_CPU.pushStack(SYSCALL_SUCCESS);
}
else
{
di.procs.add(m_currProcess);
m_currProcess.block(m_CPU, di.device, SYSCALL_OPEN, 0);
m_CPU.pushStack(SYSCALL_SUCCESS);
scheduleNewProcess();
}
}
else
m_CPU.pushStack(ERROR_DEVICE_OPEN);
}
else
m_CPU.pushStack(ERROR_DEVICE_NOT_FOUND);
} |
63ab4af1-6f50-4beb-9477-68e3e49e7adb | 6 | private void transverseStation(RailwayStation currStation,
RailwayStation prevStation,
final RailwayStation toStation,
int distanceTraveled,
String transversedStation,
TreeMap<Integer, String> bestSolution) throws NoSuchRouteException {
int maxEffort = bestSolution.firstKey(); // define search space
int effortSnapshot = distanceTraveled;
String transversedStatioSnapshot = transversedStation;
// Only search further if the effort used is less than or equals to the specified max steps
for (char nextStationName : currStation.getAllTransversibleLocation()) {
RailwayStation nextStation = this.trainMap.getStation(nextStationName);
// Not yet reach destination and the effort spent so far is still within max limit, travel deeper
distanceTraveled += /* increment dist=*/currStation.getDistanceToDestination(nextStation);
if (distanceTraveled <= maxEffort) {
// Still within search space.
transversedStation += nextStationName;
// Detect cyclic relation
if (prevStation != null && prevStation.equals(nextStation)) {
// break loop to avoid stackoverflow
continue;
}
if (nextStation.equals(toStation)) {
// Reach a destination
// Review the solution
int bestSolutionEffort = bestSolution.firstKey();
if (distanceTraveled < bestSolutionEffort) {
// Found a better solution, replace with previous discovered solution.
bestSolution.remove(bestSolutionEffort);
bestSolution.put(distanceTraveled, transversedStation);
maxEffort = distanceTraveled; // redefine search space.
}
}
// Visit the next node
transverseStation(nextStation,
currStation,
toStation,
distanceTraveled,
transversedStation,
bestSolution);
}
else {
// Gone beyond searchspace. Exit
return;
}
transversedStation = transversedStatioSnapshot;
distanceTraveled = effortSnapshot; // restore previous effort value
} // end for each transversible station
} |
eff5b0d8-fc00-446d-8f48-35c55e9aa57c | 5 | private static void loadFEP() {
try {
FileInputStream fstream;
fstream = new FileInputStream("fep.conf");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
HashMap<String, Float> fep = new HashMap<String, Float>();
String[] tmp = strLine.split("=");
String name;
name = tmp[0].toLowerCase();
if (name.charAt(0) == '@') {
name = name.substring(1);
fep.put("isItem", (float) 1.0);
}
tmp = tmp[1].split(" ");
for (String itm : tmp) {
String tmp2[] = itm.split(":");
fep.put(tmp2[0], Float.valueOf(tmp2[1]).floatValue());
}
FEPMap.put(name, fep);
}
br.close();
in.close();
fstream.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} |
c42aaa0a-24b8-432e-9f2c-1ce651af6a38 | 6 | protected void mouseClicked(int par1, int par2, int par3)
{
super.mouseClicked(par1, par2, par3);
int var4 = (this.width - this.xSize) / 2;
int var5 = (this.height - this.ySize) / 2;
for (int var6 = 0; var6 < 3; ++var6)
{
int var7 = par1 - (var4 + 60);
int var8 = par2 - (var5 + 14 + 19 * var6);
if (var7 >= 0 && var8 >= 0 && var7 < 108 && var8 < 19 && this.containerEnchantment.enchantItem(this.mc.thePlayer, var6))
{
this.mc.playerController.func_40593_a(this.containerEnchantment.windowId, var6);
}
}
} |
a6511420-fd0e-4c39-a9e8-05d1383bd317 | 2 | public void addTryCatch(final TryCatch tryCatch) {
if (this.isDeleted) {
final String s = "Cannot change a field once it has been marked "
+ "for deletion";
throw new IllegalStateException(s);
}
if (ClassEditor.DEBUG) {
System.out.println("add " + tryCatch);
}
tryCatches.add(tryCatch);
this.setDirty(true);
} |
ca7c7730-790c-41bb-a9af-fae44a9f312c | 5 | public String getRepTitle() throws SQLException
{
if (!getFormat().getBaseFormat().equals("CD"))
return getTitle();
// Check the database for other titles
List<Record> recs = GetRecords.create().getRecords(this.getTitle());
int count = 0;
for (Record rec : recs)
if (rec.getFormat().getBaseFormat().equals("CD")
&& rec.getAuthor().equals(this.getAuthor()))
count++;
if (count == 1)
return getTitle();
else
return getTitle() + " " + getCatNoString();
} |
5daab485-ebaf-4b83-b96c-95d5dd19e1cf | 6 | public static String qualifyCellAddress( String s )
{
String prefix = "";
if( !s.contains( "$" ) )
{ // it's not qualified yet
int i = s.indexOf( "!" );
if( i > -1 )
{
prefix = s.substring( 0, i + 1 );
s = s.substring( i + 1 );
}
s = "$" + s;
i = 1;
while( (i < s.length()) && !Character.isDigit( s.charAt( i++ ) ) )
{
;
}
i--;
if( (i > 0) && (i < s.length()) )
{
s = s.substring( 0, i ) + "$" + s.substring( i );
}
}
return prefix + s;
} // determine behavior |
9a1cd7ae-7b66-4085-b0d5-3ba44ed141b4 | 3 | public List<String> retrieve(String extension) throws Exception {
List<String> filelist = new ArrayList<String>();
try {
ResultSet rs = stmt.executeQuery("SELECT filepath from "
+ tablename + " WHERE filepath LIKE '%." + extension + "'");
try {
while (rs.next()) {
String sResult = rs.getString("filepath");
System.out.println(sResult);
filelist.add(sResult);
}
} finally {
try {
rs.close();
} catch (Exception ignore) {
}
}
} finally {
try {
stmt.close();
} catch (Exception ignore) {
}
}
return filelist;
} |
140e045d-dc1f-4e55-805b-17865a1c930a | 6 | public ViewMap(Tile[][] fullMap,Point centerPosition) {
map = new Tile[DrawUtil.TILES_WIDTH][DrawUtil.TILES_HEIGHT];
Point topLeft = new Point(centerPosition.x-DrawUtil.TILES_WIDTH/2,centerPosition.y-DrawUtil.TILES_HEIGHT/2);
for(int i = 0;i<DrawUtil.TILES_WIDTH;i++){
for(int j = 0;j<DrawUtil.TILES_HEIGHT;j++){
if((topLeft.x+i)<0||(topLeft.y+j)<0||(topLeft.x+i)>fullMap.length||(topLeft.y+j)>fullMap[i].length){
map[i][j]=new Tile();
map[i][j].setBase(TileEnum.NULL.createInstance());
}else{
map[i][j]=fullMap[topLeft.x+i][topLeft.y+j];
}
}
}
} |
5113bcaa-1d43-4c23-bd35-5d4f9b519471 | 9 | public void act() {
switch(state) {
case WAITING: // if he is waiting
// he will stop waiting if you command him to walk
if(Keyboard.keyCheck(KeyEvent.VK_RIGHT)) {
state = State.WALKING;
dx = +mov_speed;
col = 1;
dir = RIGHT;
break;
} else if(Keyboard.keyCheck(KeyEvent.VK_LEFT)) {
state = State.WALKING;
dx = -mov_speed;
col = 1;
dir = LEFT;
break;
}
state = waitStopped();
break;
case WALKING: // if he is walking
// he will stop walking and attack if you command him
if(Keyboard.keyCheck(KeyEvent.VK_D)) {
state = State.ATTACKING;
break;
}
// PS:
// for some reason sometimes he thinks that the button is not pressed, even if it stills.
// have to check this
// he will stop walking and wait if you stop commanding him to walk
if(!Keyboard.keyCheck(KeyEvent.VK_RIGHT) && !Keyboard.keyCheck(KeyEvent.VK_LEFT)) {
state = State.WAITING;
dx = 0;
col = 0;
break;
}
// in case something happens, the state will change
state = walk();
break;
case ATTACKING:
// he just stops when attacked back or finished the attack
state = attack();
break;
case JUMPING:
// he just stops when he touches the ground
state = jump();
break;
default:
break;
}
} |
db16ab2c-b1bc-43e3-8708-5f48da62747d | 1 | protected void btnAdicionarEnderecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarEnderecoActionPerformed
Endereco temp = new Endereco();
temp.setBairro(txtBairro.getText());
temp.setCep(txtCep.getText());
temp.setCidade(txtCidade.getText());
temp.setEstado(txtEstado.getText());
try{
temp.setNumero(Integer.parseInt(txtNumeroEndereco.getText()));// ADICIONAR EXCESSAO
}catch(NumberFormatException ex){
JOptionPane.showMessageDialog(rootPane, "O campo número só pode receber valores numericos");
}
temp.setRua(txtRua.getText());
listaEnderecos.add(temp);
carregaTabelaEnderecos(this.listaEnderecos);
}//GEN-LAST:event_btnAdicionarEnderecoActionPerformed |
c3be02f5-dbbf-4392-966f-3338cc4809f5 | 1 | @Override
protected Statement methodInvoker(FrameworkMethod method, Object test)
{
try {
return new JCheckStatement((Configuration) configuration.clone(),
classGenerators,
method, test);
}
catch (CloneNotSupportedException ex) {
throw new RuntimeException("Unable to copy configuration.", ex);
}
} |
ad3c3a4e-fd77-4f88-acb7-7c363f89bedd | 4 | public void executeOnAllAccounts(Method action, BigInteger bonus) {
if (bonus.compareTo(BigInteger.ZERO) <= 0)
throw new IllegalArgumentException();
for (BankAccount account: getAllAccounts())
try {
action.invoke(account, bonus);
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} |
fbe53dff-e79e-4a19-a5c2-c393740e3874 | 8 | public boolean makeTurn(){
ArrayList<Player> winners = new ArrayList<Player>();
for (Player p : this.players) {
if (p.getTurn() == 1) this.displaySet();
int current_dice = this.dice.randomNumber();
System.out.println(p.getPseudo() + " is throwing a dice : " + current_dice);
p.goForward(current_dice);
this.displaySet();
if (p.getPosition() == this.set.getCases().size() - 1){
winners.add(p);
}
else if (p.getPosition() > this.set.getCases().size() - 1){
p.goTo(0);
}
else {
while (this.set.getCases().get(p.getPosition()).doSomething(p)) {
this.displaySet();
}
}
}
if (!winners.isEmpty()) {
if (winners.size() == 1) {
System.out.println("The winner is " + winners.get(0).getPseudo() + " ! Congratulations !");
}
else {
String congrat = "The winners are ";
for (int i = 0; i < winners.size() - 2; i++) {
congrat += winners.get(i).getPseudo();
congrat += ", ";
}
congrat += winners.get(winners.size() - 2).getPseudo() + " and " + winners.get(winners.size() - 1).getPseudo() + " ! Congratulations !";
System.out.println(congrat);
}
return true;
}
else {
return false;
}
} |
3d5bb60a-302d-4975-b155-36d5054b98b3 | 7 | public static char[] replaceSpacesInStr(char[] str, int true_length){
System.out.print("\"");
System.out.print(str);
SOP("\"");
SOP(true_length);
//first get pos of last char
//then we'll go through and figure out num spaces from start to last char
//if true_length != (last_char_pos+1) + (2*num_spaces) then return meaning not enough space
//if there is enough space, then we work from the end of the string and copy over one by one
//when we encounter space, we write %20
int last_char_pos = true_length -1;
for(int i = true_length - 1; i>=0; i--){
if(str[i] != ' '){
last_char_pos = i;
break;
}
}
int num_spaces = 0;
for(int i=0; i<=last_char_pos; i++)
if(str[i] == ' ') num_spaces++;
if(true_length != (last_char_pos +1) + (2*num_spaces)) return null;
int curr = true_length - 1;
while(last_char_pos >=0){
if(str[last_char_pos] == ' '){
str[curr] = '0';
str[curr-1] = '2';
str[curr-2] = '%';
curr-=3;
last_char_pos--;
}
else{
str[curr] = str[last_char_pos];
curr--;
last_char_pos--;
}
}
return str;
} |
a59132b7-6ac6-4059-9bde-08511301cc4f | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
Contact otherContact = (Contact) obj;
return new EqualsBuilder().append(firstName, otherContact.firstName).append(lastName, otherContact.lastName).append(phoneNumbers, otherContact.phoneNumbers).isEquals();
} |
d64d624b-7d76-4a1a-a8bc-b87654a12d99 | 7 | public void tick(Point point){
if(point != getLocation()){
double nx = (int)(point.getX() - x) * .04;
double ny = (int)(point.getY() - y) * .04;
if(y + ny >= 0 && y + ny <= maxY - height){
y += ny;
}
if(x + nx >= 0 && x + nx <= maxX -width){
x += nx;
}
this.setLocation(x, y);
}
if(shields){
if(shieldTimer <= 0){
shields = false;
}else{
shieldTimer--;
}
}
} |
15e62014-defb-43a7-8f32-da58b4693054 | 2 | protected boolean isDeprecated(String fieldKey) {
boolean isDeprecated = false;
for (Pattern deprecatedKey : deprecatedKeys) {
if (deprecatedKey.matcher(fieldKey).find()) {
isDeprecated = true;
break;
}
}
return isDeprecated;
} |
470cca5d-5eb9-4da8-b0dc-ee55516d2d72 | 3 | public static final String[] getLinesAndClose(Reader reader) throws IOException {
if(reader != null) {
try {
final BufferedReader input = new BufferedReader(reader);
ArrayList<String> lines = new ArrayList<String>();
while(true) {
String line = input.readLine();
if(line == null) {
break;
}
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
} finally {
reader.close();
}
}
return null;
} |
198dcfba-f6bd-4704-b92f-201ec122cb0f | 5 | private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed
String s = (String) listaSecretari.getSelectedValue();
liceu.Administrator admin = new liceu.Administrator();
admin.delUser(s);
BufferedReader fisier;
try {
fisier = new BufferedReader(new FileReader("credentials"));
ArrayList<String> vector = new ArrayList<>();
for(String line; (line = fisier.readLine())!= null;){
vector.add(line);
}
listModelSecretari.clear();
for(int i=0;i<vector.size();i=i+5){
if(vector.get(i+4).equals("Secretar"))
listModelSecretari.addElement(vector.get(i));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton24ActionPerformed |
2c151e17-c25a-4a23-ad0d-8155cc86dd9b | 7 | public JsonElement toJSON() {
JsonObject obj = new JsonObject();
String[] properties = new String[]{"prefix", "name", "title", "pagebreak", "notitle", "noheader", "wiki", "entrypicture"};
for(String prop: properties) {
try {
Field field = this.getClass().getDeclaredField(prop);
Object v1 = field.get(this);
Object v2 = field.get(defaultPage);
if(!field.get(this).equals(field.get(defaultPage))) {
if(field.getType().equals(String.class)) {
obj.addProperty(prop, (String)field.get(this));
} else if(field.getType().equals(Boolean.TYPE)) {
obj.addProperty(prop, (Boolean)field.get(this));
} else if(field.getType().equals(Integer.TYPE)) {
obj.addProperty(prop, (Integer) field.get(this));
} else {
System.out.println("Weve got a problem");
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return obj;
} |
1f2ef3ec-58f3-476e-844f-75d6e05f66cf | 1 | public void initTableModel(JTable table, List<Client> list) {
//Формируем массив клиентов для модели таблицы
Object[][] clientArr = new Object[list.size()][table.getColumnCount()];
int i = 0;
for (Client client : list) {
//Создаем массив для клиента
Object[] row = new Object[table.getColumnCount()];
//Заполняем массив данными
row[0] = client.getId();
row[1] = client.getFio();
row[2] = client.getAddress();
row[3] = client.getPassport();
row[4] = client.getIdCod();
row[5] = client.getTel();
row[6] = client.getLevel();
row[7] = client.getWorkInfo();
clientArr[i++] = row;
}
table.setModel(new DefaultTableModel(
clientArr,
ClientDAO.getFieldsName()) {
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(180);
table.getColumnModel().getColumn(2).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(120);
table.getColumnModel().getColumn(4).setPreferredWidth(160);
table.getColumnModel().getColumn(5).setPreferredWidth(140);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(180);
} |
9a003cde-b5bf-46e6-a3d3-07d0610eceaf | 7 | public void getKeyPath(GraphList glf)
{
Stack<GraphPoint> s = TopologicalSort(glf);
Integer i;
for(i=0;i<ltv.length ;i++)
{
ltv[i] = etv[etv.length-1];
}
while(!s.isEmpty())
{
GraphPoint gp = s.pop();
EdgePoint e = gp.firstEdge;
while (e!=null)
{
int k = e.index;
if(ltv[gp.index] > ltv[k] - e.weight )
{
ltv[gp.index] = ltv[k] - e.weight;
}
e = e.next;
}
}
//构造边的时间s
int ete,lte;
for (i=0;i<glf.count;i++)
{
GraphPoint gp = glf.getPoint(i);
EdgePoint e = gp.firstEdge;
while(e!=null)
{
int k = e.index;
ete = etv[i];
lte = ltv[k] - e.weight;
if(ete == lte)
{
System.out.println("Node "+i+" to Node " + k+" with Edge "+e.weight);
}
e= e.next;
}
}
} |
c0ffc9b7-a3b4-4c35-b128-8a72196d11cb | 6 | @EventHandler
public void CaveSpiderPoison(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getCaveSpiderConfig().getDouble("CaveSpider.Poison.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getCaveSpiderConfig().getBoolean("CaveSpider.Poison.Enabled", true) && damager instanceof CaveSpider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getCaveSpiderConfig().getInt("CaveSpider.Poison.Time"), plugin.getCaveSpiderConfig().getInt("CaveSpider.Poison.Power")));
}
} |
f88d2d06-336a-4fd9-bcc7-545ba54ca45a | 6 | public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(EliminarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EliminarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EliminarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EliminarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
EliminarProveedor dialog = new EliminarProveedor(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
8c6caf6b-f425-48d6-b7a8-50f87163538e | 1 | private void onOpen(){
FileNameExtensionFilter filter = new FileNameExtensionFilter(".wav files", "wav", "mp3");
fileChooser.setFileFilter(filter);
if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
File file = fileChooser.getSelectedFile();
controller.open(file);
}
} |
ab2369ce-c6e6-4ebf-b441-67d50b17b738 | 3 | public Paintimator() throws IOException, UnsupportedAudioFileException, LineUnavailableException{
super();
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setTitle(FRAME_TITLE);
//create a contentPane that can hold an image
contentPane = new BackgroundPanel("images/background2.png");
contentPane.setLayout(new BorderLayout());
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int myWidth = gd.getDisplayMode().getWidth();
int myHeight = gd.getDisplayMode().getHeight();
//System.out.println(width + " X " + height);
if(myHeight < height || myWidth < width){
height = 768;
width = 1366;
}
this.setPreferredSize(new Dimension(width, height));
//canvas panel
layeredPanel = new LayeredPanel();
layeredPanel.setDrawColor(Color.BLACK);
layeredPanel.setPreferredSize(new Dimension(width-450,height-300));
myListener = new Listener(layeredPanel, this);
layeredPanel.addMouseListener(myListener);
layeredPanel.addMouseMotionListener(myListener);
//center panel
centerPanel = new JPanel(new GridBagLayout());
centerPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPanel.setOpaque(false);
this.createButtons();
//animation panel
animationPane = new AnimationPane(layeredPanelList, this);
//animationPane.setPreferredSize(new Dimension(width-450, 150));
animationPane.setOpaque(false);
su = new StorageUtil(this);
layeredPanelList = new LayeredPanelList();
fc = new JFileChooser();
fc.addChoosableFileFilter(new ImageFilter());
fc.setAcceptAllFileFilterUsed(false);
layeredPanelList.add(layeredPanel);
animationPane.updateAnimation(layeredPanelList, 1);
//side panel
sidePanel = new JPanel(new GridBagLayout());
optionsPanel = new OptionsPanel(this);
toolPanel = new ToolPanel(this, optionsPanel);
cwPanel = new ColorWheelPanel(this);
toolPanel.setOpaque(false);
optionsPanel.setOpaque(false);
cwPanel.setOpaque(false);
sidePanel.setOpaque(false);
sidePanel.setPreferredSize(new Dimension(220, height));
//menu bar
menu = new MyMenu(this);
this.setJMenuBar(menu);
//add everything to correct locations
gbc = new GridBagConstraints();
gbc.weightx = 0.50;
gbc.weighty = 0.50;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
centerPanel.add(layeredPanelList.getSelected(), gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LAST_LINE_START;
centerPanel.add(backPage, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LAST_LINE_END;
centerPanel.add(fwdPage, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
//gbc.insets = new Insets(10,0,0,0);
gbc.anchor = GridBagConstraints.CENTER;
centerPanel.add(animationPane, gbc);
gbc.weightx = 0.50;
gbc.weighty = 0.50;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0,0,0,0);
gbc.fill = GridBagConstraints.BOTH;
sidePanel.add(toolPanel, gbc);
gbc.weightx = 0.50;
gbc.weighty = 0.50;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
sidePanel.add(optionsPanel, gbc);
gbc.weightx = 0;
gbc.weighty = 0;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
JPanel cwBuffer = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 5));
cwBuffer.setOpaque(false);
cwBuffer.add(cwPanel);
sidePanel.add(cwBuffer, gbc);
if(debug){
sidePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
centerPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
animationPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
toolPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
optionsPanel.setBorder(BorderFactory.createLineBorder(Color.MAGENTA));
cwPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
}
//add panels to the content pane
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(sidePanel, BorderLayout.WEST);
//set it and show it
this.setContentPane(contentPane);
this.pack();
this.setVisible(true);
this.setResizable(false);
refreshDrawPanel(layeredPanelList.getSelected());
layeredPanelList.getSelected().clearRootPane();
} |
32708702-07c3-40a4-8ae8-c4b7bbdb4509 | 1 | private void compute_pcm_samples5(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
final float[] dp = d16[i];
float pcm_sample;
pcm_sample = (float)(((vp[5 + dvp] * dp[0]) +
(vp[4 + dvp] * dp[1]) +
(vp[3 + dvp] * dp[2]) +
(vp[2 + dvp] * dp[3]) +
(vp[1 + dvp] * dp[4]) +
(vp[0 + dvp] * dp[5]) +
(vp[15 + dvp] * dp[6]) +
(vp[14 + dvp] * dp[7]) +
(vp[13 + dvp] * dp[8]) +
(vp[12 + dvp] * dp[9]) +
(vp[11 + dvp] * dp[10]) +
(vp[10 + dvp] * dp[11]) +
(vp[9 + dvp] * dp[12]) +
(vp[8 + dvp] * dp[13]) +
(vp[7 + dvp] * dp[14]) +
(vp[6 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} |
dd02b5ae-d1f7-4442-882d-2fc095a28c23 | 1 | public boolean isUpdating() {
return db != null && db.isForceEnabled();
} |
02f370db-be4c-49aa-8a74-220062f3c9d7 | 8 | public boolean onPlayerRightClick(EntityPlayer par1EntityPlayer, World par2World, ItemStack par3ItemStack, int par4, int par5, int par6, int par7)
{
if (par3ItemStack != null &&
par3ItemStack.getItem() != null &&
par3ItemStack.getItem().onItemUseFirst(par3ItemStack, par1EntityPlayer, par2World, par4, par5, par6, par7))
{
return true;
}
int var8 = par2World.getBlockId(par4, par5, par6);
if (var8 > 0 && Block.blocksList[var8].blockActivated(par2World, par4, par5, par6, par1EntityPlayer))
{
return true;
}
if (par3ItemStack == null)
{
return false;
}
if (!par3ItemStack.useItem(par1EntityPlayer, par2World, par4, par5, par6, par7))
{
return false;
}
if (par3ItemStack.stackSize <= 0)
{
ForgeHooks.onDestroyCurrentItem(par1EntityPlayer, par3ItemStack);
}
return true;
} |
81370037-558b-4dd8-b55c-9704a90b5145 | 8 | public void saveGame()
{
File file = new File("Saved_Games.txt");
FileWriter writer;
boolean flag = false;
ArrayList<String> data = new ArrayList<String>();
ListIterator<String> iterator;
String currentPuzzle = getCurrentPuzzle();
try
{
Scanner s = new Scanner(file);
while(s.hasNextLine())
{
data.add(s.nextLine());
}
s.close();
iterator = data.listIterator();
while(iterator.hasNext())
{
if(iterator.next().equals(user.getUsername()))
{
iterator.next();
iterator.set(difficulty);
iterator.next();
iterator.set("16x16");
iterator.next();
iterator.set(String.valueOf(currentTime));
iterator.next();
iterator.set(String.valueOf(numberOfHints));
if(iterator.hasNext())
{
iterator.next();
iterator.set(currentPuzzle);
flag = true;
break;
}
else
{
data.add(currentPuzzle);
break;
}
}
}
if(flag == false)
{
data.add(user.getUsername());
data.add(difficulty);
data.add("16x16");
data.add(String.valueOf(currentTime));
data.add(String.valueOf(numberOfHints));
data.add(currentPuzzle);
}
writer = new FileWriter("Saved_Games.txt");
iterator = data.listIterator();
while(iterator.hasNext())
{
writer.write(iterator.next());
writer.write("\n");
}
writer.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "Could not find Saved_Games. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "Could not update Saved_Games. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE);
}
setUserSavedGame();
user.setHasSavedGame(true);
} |
3ca1fcd0-3006-42a7-9c4e-8cac2a973877 | 7 | private String addSocialComponent(DialogState dialogState, String output) {
//String keyword = dialogState.getOutputKeyword();
JSONParser parser = new JSONParser();
boolean addBefore = true;
try {
//Location of sentences.json file
Object obj = parser.parse(new FileReader("resources/nlg/socialBefore.json"));
//Access to a sentence
//added
String dialogStateClass = dialogState.getClass().getCanonicalName();//getStateClassFromEnum(dialogState.getCurrentState());
//added
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonState = (JSONObject) jsonObject.get(dialogStateClass);
JSONArray jsonSentences = (JSONArray) jsonState.get(dialogState.getCurrentState().toString());
if(jsonSentences != null) {
Integer size = jsonSentences.size();
//selects social component randomly
String temp;
Random rn = new Random();
Integer randomNum = rn.nextInt(size);
temp = (String) jsonSentences.get(randomNum);
//search for a social component to be added after, in case there's no social component.
if (temp.equals("")) {
obj = parser.parse(new FileReader("resources/nlg/socialAfter.json"));
addBefore = false;
jsonObject = (JSONObject) obj;
jsonState = (JSONObject) jsonObject.get(dialogStateClass);
jsonSentences = (JSONArray) jsonState.get(dialogState.getCurrentState().toString());
rn = new Random();
randomNum = rn.nextInt(size);
temp = (String) jsonSentences.get(randomNum);
if (temp.equals("")) {
return output;
}
}
if(addBefore) { // add social component before the
output = temp + ". " + output;
} else {
output = output + ". " + temp;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return output;
} |
b5e718fb-2f4a-4cfc-83cc-18a792358aee | 0 | public static void setMaxAge(int newMAX_AGE)
{
MAX_AGE = newMAX_AGE;
} |
bf619def-7620-4f04-8641-c48cb3484c43 | 6 | @Override
public int hashCode() {
int result = benchmarkClass != null ? benchmarkClass.hashCode() : 0;
result = 31 * result + (benchmarkMethod != null ? benchmarkMethod.hashCode() : 0);
result = 31 * result + (heapMemoryFootprint != null ? heapMemoryFootprint.hashCode() : 0);
result = 31 * result + (nonHeapMemoryFootprint != null ? nonHeapMemoryFootprint.hashCode() : 0);
result = 31 * result + (memoryPoolFootprints != null ? memoryPoolFootprints.hashCode() : 0);
result = 31 * result + (gcUsages != null ? gcUsages.hashCode() : 0);
return result;
} |
b1aeb506-5660-4c39-9c0f-10ded3ad4029 | 8 | public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
DbfTable resultTable;
DbfViewer dbfViewer;
response.setCharacterEncoding("utf-8");
String file = request.getParameter("file");
String encoding;
int recordsOnPage = 0;
try{
recordsOnPage = Integer.parseInt(request.getParameter("recordsOnPage"));
}catch(NumberFormatException ex){
recordsOnPage = 50;
}
int pgNum = 1;
String pageNum = request.getParameter(PAGENUM);
if(pageNum == null){
try{
pageNum = request.getSession().getAttribute(CURRENTPAGE).toString();
}catch(NullPointerException ex){
pageNum = "1";
}
}
try{
pgNum = Integer.parseInt(pageNum);
request.getSession().setAttribute(CURRENTPAGE, pgNum);
}catch(NumberFormatException ex){
}
encoding = (String) request.getParameter(ENCODING);
if(encoding == null){
encoding = "cp866";
}
request.getSession().setAttribute(ENCODING, encoding);
//view full table, clear all filters
request.getSession().removeAttribute(FILTERMAP);
if(file == null){
file = DbfViewerUtils.findCookie(request.getCookies(), FILE);
}
if(file != null){
dbfViewer = new DbfViewer();
//resultTable = new DbfTable();
resultTable = dbfViewer.getTable(file, pgNum, (pgNum-1)*recordsOnPage, (pgNum)*recordsOnPage, encoding);
if(resultTable != null){
request.setAttribute(TABLE, resultTable);
request.setAttribute(FILE, file);
request.getSession().setAttribute(FILE, file);
request.getSession().setAttribute(TABLE, resultTable);
DbfViewerUtils.addCookie(FILE, file, response);
}
}
return mapping.findForward(INDEX);
} |
3c05922c-88ca-4b39-b9d2-467f156325cb | 6 | public static Stella_Object accessParametricTypeSpecifierSlotValue(ParametricTypeSpecifier self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Stella.SYM_STELLA_SPECIFIER_BASE_TYPE) {
if (setvalueP) {
self.specifierBaseType = ((Surrogate)(value));
}
else {
value = self.specifierBaseType;
}
}
else if (slotname == Stella.SYM_STELLA_SPECIFIER_PARAMETER_TYPES) {
if (setvalueP) {
self.specifierParameterTypes = ((List)(value));
}
else {
value = self.specifierParameterTypes;
}
}
else if (slotname == Stella.SYM_STELLA_SPECIFIER_DIMENSIONS) {
if (setvalueP) {
self.specifierDimensions = ((List)(value));
}
else {
value = self.specifierDimensions;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} |
03a32675-f378-4fad-af27-278d37d237da | 5 | @Override
public void setAge(int age) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
/* save all arguments into an array */
Object[] args = new Object[]{age};
Class<?>[] argsType = new Class<?>[]{int.class};
try {
super.invokeMethod(methodName, args, argsType);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return;
} |
98dc2dfe-c025-46cf-8b1b-caa6a2a54546 | 2 | public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).doubleValue()
: Double.parseDouble((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
} |
ff1d0c5f-6b8f-42bf-8cc3-6e0571f77699 | 3 | @Test
public void testOrdered()
{
// For reporting errors: an array of operations
ArrayList<String> operations = new ArrayList<String>();
// Add a bunch of values
for (int i = 0; i < 100; i++)
{
int rand = random.nextInt(1000);
ints.add(rand);
operations.add("ints.add(" + rand + ")");
} // for
if (!inOrder(ints.iterator()))
{
System.err.println("inOrder() failed");
for (String op : operations)
System.err.println(op + ";");
dump(ints);
fail("The instructions did not produce a sorted list.");
} // if the elements are not in order.
} // testOrdered() |
291fb631-46d9-430c-bc92-bbc42552eab1 | 8 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == this) {
this.faceUp();
}
else {
// the faceUp() method has a delay so the user can see the card, then this code block executes
selfTimer.stop();
Game.getThis().TimerRunning = false;
// Keep track if Herobrine was revealed before removing stuff
boolean needShuffle =
Child.getID() == Card.HEROBRINE ||
Game.getThis().FlippedCard.Child.getID() == Card.HEROBRINE;
// Keep track if the user goes again because of a match
boolean goAgain = false;
// Handle the FlippedCard property appropriately
if (Game.getThis().FlippedCard.getCard() == this.getCard()) {
// Got a match, go again
goAgain = true;
// Check consecutive point bonus
if (Game.getThis().ConsecutiveRun > 0) {
Game.getThis().thisTurn.givePoints(1);
}
// Increase consecutive increment
Game.getThis().ConsecutiveRun++;
// Remove matched cards from the game
Game.getThis().FlippedCard.clear();
this.clear();
}
else {
// Reset consecutive count
Game.getThis().ConsecutiveRun = 0;
// Flip cards back over
Game.getThis().FlippedCard.faceDown();
this.faceDown();
}
Game.getThis().FlippedCard = null;
// Shuffle if Herobrine was revealed
if (needShuffle) {
Game.getThis().shuffle();
}
if (!Game.getThis().gameOver()) {
if (!goAgain) {
// Change the player's turn
Game.getThis().thisTurn =
Game.getThis().thisTurn == Game.getThis().Player2
? Game.getThis().Player1
: Game.getThis().Player2;
}
}
// Tell the GamePanel to update
GamePanel.getThis().updateLabels();
}
} |
896c83c2-b4d5-4b7a-8be5-aee64380427c | 7 | private void updateMinMax(Instance ex) {
Instances insts = ex.relationalValue(1);
for (int j = 0;j < m_Dimension; j++) {
if (insts.attribute(j).isNumeric()){
for(int k=0; k < insts.numInstances(); k++){
Instance ins = insts.instance(k);
if(!ins.isMissing(j)){
if (Double.isNaN(m_MinArray[j])) {
m_MinArray[j] = ins.value(j);
m_MaxArray[j] = ins.value(j);
} else {
if (ins.value(j) < m_MinArray[j])
m_MinArray[j] = ins.value(j);
else if (ins.value(j) > m_MaxArray[j])
m_MaxArray[j] = ins.value(j);
}
}
}
}
}
} |
08431725-b2af-442f-860e-d7cdf43f5139 | 1 | public boolean hasNext() {
if (index < ballContainer.getCount()) {
return true;
} else {
return false;
}
} |
9e8880e9-0dbd-432d-b6d5-ce9e1dc04383 | 6 | public Result ValidarEdicionRol(Rol pRol)
{
StringBuilder sb = new StringBuilder();
sb.append((Common.IsMinorOrEqualsZero(pRol.getCodigoRol()))?".Código inválido\n":"");
sb.append((Common.IsNullOrEmpty(pRol.getNombreRol()))?".Nombre inválido\n":"");
sb.append((Common.IsNullOrEmpty(pRol.getDescripcionRol()))?".Descripción inválida\n":"");
sb.append((pRol.getModulos() == null || Common.IsMinorOrEqualsZero(pRol.getModulos().size())) ?".El rol no tiene módulos asignados\n":"");
if (!Common.IsMinorOrEqualsZero(sb.length()))
return new Result(ResultType.Error, "Valide los campos antes de modificar.", sb.toString());
else
return new Result(ResultType.Ok, "La validación pasó sin errores.", null);
} |
188e897d-8a60-48c4-9150-e99872b2ad56 | 0 | @Test
public void testConnected() {
assertThat(uf.connected(0, 1), is(false));
} |
3e75fc48-39e8-4dcc-b644-608f1230f6bc | 0 | public void setSpeaker(final Speaker speaker) {
this.speaker = speaker;
} |
e5d86790-ab5e-4168-b8e9-b75ea9e8aeb2 | 9 | @Override
public void update() {
if (!isRegistered) {
isRegistered = true;
pathID = TDPanel.registerPath(MonsterPath.getPatrol(patrolRad, (Point2D.Double) loc.clone()));
}
if (isFailing())
return;
if (!isReloading()) {
Mob closestMob = super.nextMob();
if (closestMob != null) {
SoundEffect.BASICSHOT.play();
Point2D.Double mobLoc = closestMob.getLoc();
//RainbowMob mob = new RainbowMob((Point2D.Double)loc.clone(), pathID, 1, 1, true);
//mob.setCityID(id);
//TDPanel.getMobHandler().add(mob);
lastShot = System.nanoTime()/1000000;
dir = Math.atan2(mobLoc.y-loc.y,mobLoc.x-loc.x); // sets tower facing direction
if (upg == 0)
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir, 3.5, dmg, splash, this, 0, faction));
else if(upg == 1) {
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir+.1, 3.5, dmg, splash, this, 1, faction));
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir-.1, 3.5, dmg, splash, this, 1, faction));
}
else if(upg == 2) {
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir+.1, 3.5, dmg, splash, this, 2, faction));
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir-.1, 3.5, dmg, splash, this, 2, faction));
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir+.2, 3.5, dmg, splash, this, 2, faction));
bh.add(new BasicBullet((Point2D.Double)loc.clone(), dir-.2, 3.5, dmg, splash, this, 2, faction));
}
else if (upg == 3) {
for (int i = 0; i < 16; i++) {
bh.add(new BasicBullet((Point2D.Double) loc.clone(), dir+.1*i-.8, 9.5, dmg, splash, this, 3, faction));
}
}
}
}
} |
8bd1453f-626a-4628-8c56-f439e87a50ff | 8 | public static double[][] rref(double[][] mat)
{
double[][] rref = new double[mat.length][mat[0].length];
/* Copy matrix */
for (int r = 0; r < rref.length; ++r)
{
for (int c = 0; c < rref[r].length; ++c)
{
rref[r][c] = mat[r][c];
}
}
for (int p = 0; p < rref.length; ++p)
{
/* Make this pivot 1 */
double pv = rref[p][p];
if (pv != 0)
{
double pvInv = 1.0 / pv;
for (int i = 0; i < rref[p].length; ++i)
{
rref[p][i] *= pvInv;
}
}
/* Make other rows zero */
for (int r = 0; r < rref.length; ++r)
{
if (r != p)
{
double f = rref[r][p];
for (int i = 0; i < rref[r].length; ++i)
{
rref[r][i] -= f * rref[p][i];
}
}
}
}
return rref;
} |
6a31b74c-ab13-4a65-99a6-731a80215abc | 4 | public void getInput(){
String userCommand;
Scanner inFile = new Scanner(System.in);
do {
this.display();
userCommand = inFile.nextLine();
userCommand = userCommand.trim().toUpperCase();
switch (userCommand) {
case "C":
this.optionsMenuControl.displayNumberCards();
break;
case "S":
this.optionsMenuControl.displayColorCards();
break;
case "Q":
break;
default:
new MemoryGameError().displayError(" You Entered an Invalid command. Please enter a valid command.");
continue;
}
} while (!userCommand.equals("Q"));
return;
} |
350ad200-35bd-46b4-94c8-74e9aa116813 | 7 | private Point[] drawSquare(Point center, double sideLength, Color color){
ArrayList<Point> changedPoints = new ArrayList<Point>();
int x = center.getX();
int y = center.getY();
if (sideLength == 0 && checkPointInBounds(center)){
board[x][y] = color;
Point[] singlePoint = {center};
return singlePoint;
}
for(int i = (int)-sideLength; i < Math.ceil(sideLength); i ++){
for(int j = (int)-sideLength; j < Math.ceil(sideLength); j ++){
if (checkPointInBounds(new Point(x+i, y + j))){
Color oldColor = board[x+i][y+j];
board[x+i][y+j] = color;
if (!color.equals(oldColor)){
changedPoints.add(new Point(x+i, y+j));
}
}
}
}
Point[] coloredPoints = new Point[changedPoints.size()];
for (int i = 0; i < changedPoints.size(); i ++){
coloredPoints[i] = changedPoints.get(i);
}
return coloredPoints;
} |
263a6aae-e7bc-4301-aafb-241adc9153de | 5 | public static double[] doLinearRegression(double[][] args) //input double[0]=array of day number
{ //input double[1]=array of prices
double[] answer = new double[3];
int n = 0;
double[] x = new double[args[0].length];
double[] y = new double[args[1].length];
for(int i=0;i<args[0].length;i++){x[i]=args[0][i];}
for(int i=0;i<args[0].length;i++){y[i]=args[1][i];}
double sumx = 0.0, sumy = 0.0;
for(int i=0;i<args[0].length;i++) {
sumx += x[i];
sumy += y[i];
n++;
}
double xbar = sumx / n;
double ybar = sumy / n;
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
for (int i = 0; i < n; i++) {
xxbar += (x[i] - xbar) * (x[i] - xbar);
yybar += (y[i] - ybar) * (y[i] - ybar);
xybar += (x[i] - xbar) * (y[i] - ybar);
}
double beta1 = xybar / xxbar;
double beta0 = ybar - beta1 * xbar;
//System.out.println("y = " + beta1 + " * x + " + beta0);
double ssr = 0.0;
for (int i = 0; i < n; i++) {
double fit = beta1*x[i] + beta0;
ssr += (fit - ybar) * (fit - ybar);
}
double R2 = ssr / yybar;
//System.out.println("R^2 = " + R2);
answer[0]=beta1; //returns m(gradient)
answer[1]=beta0; //returns c(y-intercept)
answer[2]=R2; //returns R-squared
return answer;
} |
e6368b01-defb-46e7-a20c-71cdb8749c9f | 7 | @Override
public boolean okMessage(Environmental oking, CMMsg msg)
{
if((oking==null)||(!(oking instanceof MOB)))
return super.okMessage(oking,msg);
final MOB mob=(MOB)oking;
if(msg.amITarget(mob)
&&(((msg.sourceMajor()&CMMsg.MASK_MOVE)>0)||((msg.sourceMajor()&CMMsg.MASK_HANDS)>0)))
{
if(!msg.amISource(mob))
sleepForTicks=0;
else
if(sleepForTicks>0)
{
mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SLEEPING);
return false;
}
}
return true;
} |
57837c1e-0fca-47ef-9fd7-4a7cee8b995e | 0 | public Iterator<Land> iterator() {
return laenderMap.values().iterator();
} |
78315549-55ee-447d-afa8-78d8210e078d | 5 | public String[] getColumnStr(int colNum)
{
int nRows = 0;
int i = 0;
String[] ret;
if(colNum > 0){
try {
//get amount of rows
while(result.next()){
nRows ++;
}
//Check if there are more then 0 rows
if(nRows == 0)
return null;
ret = new String[nRows]; //create the Stringarray with the now known size
result.first();
ret[i] = result.getString(colNum);
i ++;
while(result.next()){
ret[i] = result.getString(colNum);
i++;
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return ret;
}
else
{
return null;
}
} |
7d6d0014-0dbb-4b88-8d3c-42aa392012b5 | 4 | public short[] assemble(Map<String, Integer> labelMap) {
int op = 0;
if (this.opcode.isExtended()) {
op |= (this.opcode.getCode() & 0x3f) << 4;
op |= (this.b.getRawValue() & 0x3f) << 10;
if (this.b.getSize() > 0) {
return new short[] { (short)op, this.b.getNumber(labelMap) };
} else {
return new short[] { (short)op };
}
} else {
op |= (this.opcode.getCode() & 0x0f);
op |= (this.a.getRawValue() & 0x3f) << 4;
op |= (this.b.getRawValue() & 0x3f) << 10;
short[] res = new short[this.getSize()];
res[0] = (short)op;
int i = 1;
if (this.a.getSize() > 0) {
res[i++] = this.a.getNumber(labelMap);
}
if (this.b.getSize() > 0) {
res[i++] = this.b.getNumber(labelMap);
}
return res;
}
} |
832a3615-39b4-454d-9051-65d0077408fe | 2 | public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value != null)
{
ComboBoxInterface item = (ComboBoxInterface)value;
setText( item.getName() );
}
if (index == -1)
{
//ComboBoxInterface item = (ComboBoxInterface)value;
//setText( "None" );
}
return this;
} |
b3e3018d-e6ec-4330-a900-89aee26354ec | 5 | public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, ((Integer)value).intValue() + 1);
} else if (value instanceof Long) {
this.put(key, ((Long)value).longValue() + 1);
} else if (value instanceof Double) {
this.put(key, ((Double)value).doubleValue() + 1);
} else if (value instanceof Float) {
this.put(key, ((Float)value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} |
c6a08915-d3cf-4b00-839b-360495daa8f2 | 7 | static private int jjMoveStringLiteralDfa10_0(long old0, long active0, long old1, long active1)
{
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjStartNfa_0(8, old0, old1);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(9, active0, active1);
return 10;
}
switch(curChar)
{
case 69:
case 101:
return jjMoveStringLiteralDfa11_0(active0, 0x1000L, active1, 0L);
case 78:
case 110:
if ((active1 & 0x4L) != 0L)
return jjStartNfaWithStates_0(10, 66, 48);
break;
default :
break;
}
return jjStartNfa_0(9, active0, active1);
} |
53015e91-3f07-402d-a858-4cab29ac83df | 2 | @Override
public void handleRequest(int request) {
if (request == 3) {
System.out.println("ConcreteHandlerC handleRequest " + request);
} else if (mSuccessor != null) {
mSuccessor.handleRequest(request);
}
} |
8116f5e0-a855-4fd3-a96d-df27c2773a0e | 3 | private int findIndex(Object item){
int keyPosition = 0;
for (int i = 0; i < numItems; i++) {
if (items[i] != null && items[i].equals(item)){
keyPosition=i;
}
}
return keyPosition;
} |
d54b3a9e-95f6-4c29-a59a-adb5473a1ded | 0 | public static void main(String[] args)
{
String fileName = args[0];
int numCoefficient = Integer.parseInt(args[1]);
// /*---------------Test DCT----------------*/
// imageReader _image = new imageReader(new File(fileName), 512, 512);
// _image.ImageSetNormalColor();
// _image.DisPlayPic();
// _image.ImageSetDCT_Color(16);
// _image.DisPlayPic();
// /*-------------End Test DCT----------------*/
imageReader _imageDWT = new imageReader(new File(fileName), 512, 512);
// _imageDWT.ImageSetNormalColor();
// _imageDWT.DisPlayPic();
//512*512 = 262144
//512*128 = 131072
//128*128 = 16384
_imageDWT.ImageDWT_Color(16384);
//_imageDWT.ImageSetNormalColor();
_imageDWT.DisPlayPic("DWT", 100, 200);
}
// public static void main(String[] args) {
//
//
// String fileName = args[0];
// int numCoefficient = Integer.parseInt(args[1]);
//
// int width = 512;
// int height = 512;
//
// BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// byte[] bytes = null;
//
// double[][] rChannel=new double[height][width];
// double[][] gChannel=new double[height][width];
// double[][] bChannel=new double[height][width];
//
// try {
// File file = new File(args[0]);
// InputStream is = new FileInputStream(file);
//
// long len = file.length();
// bytes = new byte[(int)len];
//
// int offset = 0;
// int numRead = 0;
// while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
// offset += numRead;
// }
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// int ind = 0;
// for(int y = 0; y < height; y++){
//
// for(int x = 0; x < width; x++){
//
// byte a = 0;
// byte r = bytes[ind];
// byte g = bytes[ind+height*width];
// byte b = bytes[ind+height*width*2];
//
// //int pix = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
// int pix = ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
//
// //int pix = ((a << 24) + (r << 16) + (g << 8) + b);
// rChannel[x/8][x%8] = r;
// gChannel[x/8][x%8] = g;
// bChannel[y/8][x%8] = b;
//
// img.setRGB(x,y,pix);
// ind++;
// }
// }
//
// //split the picture into channels
// DCT _dct = new DCT();
// ArrayList<Block[][]> _blocks = new ArrayList<Block[][]>();
// Block[][] _rBlock = _dct.SplitChanneal(rChannel, width, height);
// Block[][] _gBlock = _dct.SplitChanneal(rChannel, width, height);
// Block[][] _bBlock = _dct.SplitChanneal(rChannel, width, height);
//
// _blocks.add(_rBlock);
// _blocks.add(_gBlock);
// _blocks.add(_bBlock);
//
// for(int k=0;k<3;k++){
// //Traverse the _tem to DCT every block.
// for(int i=0;i<height/8;i++){
// for(int j=0;j<width/8;j++){
// _blocks.get(k)[i][j].FDCT();
//
// //select the first m coefficients in a zig order for each 8x8 block
// _blocks.get(k)[i][j].block = _blocks.get(k)[i][j].ZigZag(8, numCoefficient);
// _blocks.get(k)[i][j].IDCT();
// }
// }
// }
//
//
//
//
//
//
//
//
//
// // Use a label to display the image
// JFrame frame = new JFrame();
// JLabel label = new JLabel(new ImageIcon(img));
// frame.getContentPane().add(label, BorderLayout.CENTER);
// frame.pack();
// frame.setVisible(true);
//
// } |
0aa3c6d2-0ff8-4df8-bcde-1a761492cc5f | 2 | private void dataMiningForProtonPatterns(){
ProtonPatternDetector protonPatternDetector;
for(int startRow=0;startRow<get_rows()-protonPatternEncoder.getRows();startRow++){
for(int startColumn=0;startColumn<get_columns()-protonPatternEncoder.getColumns();startColumn++){
protonPatternDetector = new ProtonPatternDetector();
protonPatternDetector.setXYCoordinates(startRow,startColumn);
protonPatternDetector.setImagePreprocessor(imagePreprocessor);
protonPatternDetector.setProtonEncoder(protonPatternEncoder);
protonPatternDetector.initialize();
protonDetectedPatterns.add(protonPatternDetector);
}
}
} |
e0167d4b-8885-4054-a430-46130157dc8d | 2 | protected void verifyPossibleDenotationalTerm(CycObject cycObject) throws IllegalArgumentException {
if (!(cycObject instanceof CycDenotationalTerm || cycObject instanceof CycList)) {
throw new IllegalArgumentException("cycObject must be a Cyc denotational term " + cycObject.cyclify());
}
} |
90b4315f-7916-481c-877b-d7c39d02f4a7 | 5 | @Override
public Event createEvent(Event event) {
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = ConnectionHelper.getConnection();
ps = cn.prepareStatement(QTPL_INSERT_EVENT,
new String[] { "event_id" });
ps.setString(1, event.getName());
ps.setString(2, event.getDescription());
ps.setString(3, event.getDate());
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
int eventId = rs.getInt(1);
event.setEventId(eventId);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
try { cn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
return event;
} |
c3fa8d3c-d64c-4cf8-bd5a-2ce452bb2e05 | 9 | public static boolean isAnagramms(String str1, String str2){
if( str1 == null ){
return str2 == null ? true : false;
}
final int str1Length = str1.length();
final int str2Length = str2.length();
if( str1Length != str2Length ){
return false;
}
Map<Character, Integer> charsMap = new IdentityHashMap<Character, Integer>();
Character ch;
for( int i =0; i < str1Length; i++ ){
ch = Character.valueOf(str1.charAt(i));
Integer counter = charsMap.get(ch);
if( counter == null ){
counter = Integer.valueOf(1);
}
else {
counter += 1;
}
charsMap.put( ch, counter );
}
for( int j = 0; j < str2Length; j++ ){
ch = Character.valueOf( str2.charAt(j) );
Integer counter = charsMap.get(ch);
if( counter == null || counter == 0 ){
return false;
}
counter -= 1;
if( counter > 0 ){
charsMap.put(ch, counter);
}
else {
charsMap.remove( ch );
}
}
return charsMap.isEmpty();
} |
2e73e9a7-6a63-4e37-b12f-b777d087814d | 6 | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
String command = cmd.getName();
if (command.equalsIgnoreCase("lteams")) {
return onLteamsCommand(sender, cmd, label, args);
}
else if (command.equalsIgnoreCase("leave")) {
return onLeaveCommand(sender, cmd, label, args);
}
else if (command.equalsIgnoreCase("join")) {
return onJoinCommand(sender, cmd, label, args);
}
else if (command.equalsIgnoreCase("capturetheflag") || command.equalsIgnoreCase("cf") || command.equalsIgnoreCase("ctf")) {
return onCTFCommand(sender, cmd, label, args);
}
return false;
} |
7714fbd0-67e3-4336-af42-411ad8a65416 | 8 | public void addQuizPermutation(String title,int quizId,ArrayList<String> imageList, ArrayList<Boolean> imageInventoryList,ArrayList<String> soundList,
ArrayList<Boolean> soundInventoryList, int narration,
String paragraphList, String preNote, String postNote, String goTo, int points,
String date, String wrong, int timestop, ArrayList<String> answerList)
{
Element quizModule = doc.createElement("quiz");
createQuiz(title,quizId,imageList,imageInventoryList,soundList,soundInventoryList,narration,paragraphList,preNote,postNote,quizModule);
Element answerModule = doc.createElement("answermodule");
quizModule.appendChild(answerModule);
Element answerElement = doc.createElement("answer");
createAnswerModule("Permutation",goTo,points,date,wrong,timestop,answerElement);
answerModule.appendChild(answerElement);
boolean shuffle[] = new boolean[answerList.size()];
for(int i=0;i<shuffle.length;i++)
{
shuffle[i]=false;
}
for(int i=0;i<answerList.size();i++)
{
Random generator = new Random();
int index = 0;
while(true)
{
index = generator.nextInt(answerList.size());
boolean end=true;
for(int t=0;t<shuffle.length;t++)
{
if(!shuffle[t])
{
end=false;
}
}
if(end)break;
if(!shuffle[index])
{
shuffle[index]=true;
break;
}
}
if(!answerList.get(index).equals(""))
{
Element optionElement = doc.createElement("option");
Attr attr = doc.createAttribute("index");
attr.setValue(Integer.toString(index+1));
optionElement.setAttributeNode(attr);
optionElement.appendChild(doc.createTextNode(answerList.get(index)));
answerElement.appendChild(optionElement);
}
else
{
answerList.remove(index-1);
index--;
}
}
} |
7268ec6b-d73f-4787-be9c-10452438126e | 0 | private static void comparableExanple() {
NextGenericExample<Person> o = new NextGenericExample<>();
o.setInternal(new Person());
} |
e196d6df-313b-4a68-a460-c0d2483b1afa | 6 | @Override
protected Class<?> loadClass(String name, boolean resolve)
{
try {
if ("offset.sim.Player".equals(name) ||
"offset.sim.Point".equals(name) || "offset.sim.Pair".equals(name) ||"offset.sim.movePair".equals(name))
return parent.loadClass(name);
else
return super.loadClass(name, resolve);
} catch (ClassNotFoundException e) {
return null;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.