method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
03c14cd5-0b55-49e3-89f5-12a13dc68502 | 1 | private static int[] genPref()
{
int[] pref = new int[FRUIT_NAMES.length];
for (int i = 0; i != pref.length; ++i)
pref[i] = i + 1;
shuffle(pref);
return pref;
} |
00515dc3-e19c-46c7-81e9-43eb818a870d | 3 | public static int getPassengerCount(SimpleTrain train) {
if(train == null){
LOG.error("Train is null");
throw new IllegalArgumentException("Train is null");
}
int count = 0;
for (AbstractCarriage ac : train) {
if (ac instanceof AbstractPassengerCarriage) {
count += ((AbstractPassengerCarriage) ac).getPassengerCurCount();
}
}
return count;
} |
3c4bfcbf-89e5-4a9a-b2df-e1fc1498a4d3 | 9 | public RegisterViewHelper getRegisterViewHelper(HttpServletRequest req)
throws UnsupportedEncodingException {
RegisterViewHelper registerViewHelper = new RegisterViewHelper();
if (req.getParameter("forename") != null) {
registerViewHelper.setForename(new String(req.getParameter("forename")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("surname") != null) {
registerViewHelper.setSurname(new String(req.getParameter("surname")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("email") != null) {
registerViewHelper.setEmail(new String(req.getParameter("email")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("password") != null) {
registerViewHelper.setPassword(new String(req.getParameter("password")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("conf-password") != null) {
registerViewHelper.setConfPassword(new String(req.getParameter("conf-password")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("card-num") != null) {
registerViewHelper.setCardNum(new String(req.getParameter("card-num")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("house-num") != null) {
registerViewHelper.setHouseNum(new String(req.getParameter("house-num")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("street") != null) {
registerViewHelper.setStreet(new String(req.getParameter("street")
.getBytes("iso-8859-1"), "UTF-8"));
}
if (req.getParameter("postcode") != null) {
registerViewHelper.setPostcode(new String(req.getParameter("postcode")
.getBytes("iso-8859-1"), "UTF-8"));
}
return registerViewHelper;
} |
76b18611-84f8-47aa-9ada-a4d08cd081ee | 0 | public String getFrameIdentifier() {
return frameIdentifier;
} |
e27d6d5b-1b87-479d-8d26-a2676976f8de | 1 | public void render(){
texture.bind();
int xChange = (change-1) % 2;
int yChange = (change-1) / 2;
if(!isDead()){
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(xChange * 0.5f,yChange * 0.5f + 0.5f);
GL11.glVertex2f(x, y);
GL11.glTexCoord2f(xChange * 0.5f + 0.5f,yChange * 0.5f + 0.5f);
GL11.glVertex2f(x+32, y);
GL11.glTexCoord2f(xChange * 0.5f + 0.5f,yChange * 0.5f);
GL11.glVertex2f(x+32, y+32);
GL11.glTexCoord2f(xChange * 0.5f,yChange * 0.5f);
GL11.glVertex2f(x, y+32);
GL11.glEnd();
}else{
renderItemBag();
}
} |
adf3fb4e-84d0-40f2-958b-a53977c39e3a | 5 | private void button7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button7MouseClicked
if(numberofpins < 4)
{
if(numberofpins == 0)
{
Login_form.setString1("6");
}
if(numberofpins == 1)
{
Login_form.setString2("6");
}
if(numberofpins == 2)
{
Login_form.setString3("6");
}
if(numberofpins == 3)
{
Login_form.setString4("6");
}
numberofpins +=1;
jLabel2.setText(Integer.toString(numberofpins));
}
else
{
System.out.print(Timetable_main_RWRAF.checkDelete());
JOptionPane.showMessageDialog(null,"You've already entered your 4 digit pin!", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE);
}// TODO add your handling code here:
}//GEN-LAST:event_button7MouseClicked |
aa4152af-b032-4eff-b04a-8d4db2f06061 | 8 | @java.lang.Override
public boolean isValidMove(int MoveToX,int MoveToY,int MoveFromX,int MoveFromY) {
if (((MoveFromX-MoveToX)==1||(MoveFromX-MoveToX)==-1)&&((MoveFromY-MoveToY)==2||(MoveFromY-MoveToY)==-2)){
return true;
}
if (((MoveFromX-MoveToX)==2||(MoveFromX-MoveToX)==-2)&&((MoveFromY-MoveToY)==1||(MoveFromY-MoveToY)==-1)){
return true;
}
else
return false;
} |
f7ae65c6-0cb0-43ac-af3a-fbee1dab9e46 | 2 | public void reset() {
double[][] map = new double[_source.length][_source[0].length];
double scale = 1023.0 / (double) _maxValue;
for (int i = 0; i < map.length; i++) {
double[] row = map[i];
for (int j = 0; j < row.length; j++) {
map[i][j] = _source[i][j] * scale;
}
}
_map = map;
} |
55822223-2d2b-4428-bb83-f5a07776e1ba | 2 | public static boolean buyProduct(Integer id) {
Session session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("from Product where id = :id");
query.setParameter("id", id);
Product product = (Product)query.uniqueResult();
if(product!=null && product.getAmount()>0) {
product.setAmount(product.getAmount()-1);
Transaction transaction = session.beginTransaction();
session.update(product);
transaction.commit();
return true;
}
return false;
} |
1d281304-2ae0-424c-b69b-8d7961ac57f2 | 0 | public void tick() {
} |
09001b52-07f6-4607-a320-39895eab2bd3 | 9 | private void write(Map<String,Map<String,SerAnnotatedElement>> output, Map<String,Collection<Element>> originatingElementsByAnn) {
for (Map.Entry<String,Map<String,SerAnnotatedElement>> outputEntry : output.entrySet()) {
String annName = outputEntry.getKey();
try {
Map<String,SerAnnotatedElement> elements = outputEntry.getValue();
try {
FileObject in = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", METAINF_ANNOTATIONS + annName);
// Read existing annotations, for incremental compilation.
InputStream is = in.openInputStream();
try {
ObjectInputStream ois = new ObjectInputStream(is);
while (true) {
SerAnnotatedElement el;
try {
el = (SerAnnotatedElement) ois.readObject();
} catch (ClassNotFoundException cnfe) {
throw new IOException(cnfe.toString());
}
if (el == null) {
break;
}
if (!elements.containsKey(el.key())) {
elements.put(el.key(), el);
}
}
} finally {
is.close();
}
} catch (FileNotFoundException x) {
// OK, created for the first time
}
FileObject out = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT,
"", METAINF_ANNOTATIONS + annName,
originatingElementsByAnn.get(annName).toArray(new Element[0]));
OutputStream os = out.openOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(os);
for (SerAnnotatedElement el : elements.values()) {
oos.writeObject(el);
}
oos.writeObject(null);
oos.flush();
} finally {
os.close();
}
out = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT,
"", METAINF_ANNOTATIONS + annName + ".txt",
originatingElementsByAnn.get(annName).toArray(new Element[0]));
Writer w = out.openWriter();
try {
w.write("# informational; use java -jar sezpoz.jar to see authoritative contents\n");
for (SerAnnotatedElement el : elements.values()) {
w.write(el.toString());
w.write('\n');
}
} finally {
w.close();
}
} catch (IOException x) {
processingEnv.getMessager().printMessage(Kind.ERROR, x.toString());
}
}
} |
9582c911-38cb-448c-bb12-07f16d95ffc4 | 2 | @Override
public int compareTo(ValueIndexPair o) {
return sum < o.sum ? -1 : (sum > o.sum ? 1 : 0);
} |
d8bad654-d762-40ff-9dc9-f9d7482c8c13 | 4 | * @return The column, or <code>null</code> if none is found.
*/
public Column overColumn(int x) {
int pos = getInsets().left;
int count = mModel.getColumnCount();
for (int i = 0; i < count; i++) {
Column col = mModel.getColumnAtIndex(i);
if (col.isVisible()) {
pos += col.getWidth() + (mDrawColumnDividers ? 1 : 0);
if (x < pos) {
return col;
}
}
}
return null;
} |
3c23cfd8-1c21-4b3d-9b68-ecddb3f09d81 | 0 | Errors(String name) {
this.value = name;
} |
fd4cfb8b-3d9d-45ad-9c5c-c12dc3e2d630 | 8 | @Override
public synchronized Message process(ClientState state, Message request)
{
String xmlString;
Model model = Model.getInstance();
Message response = null;
Node child = request.contents.getFirstChild();
String myKey = child.getAttributes().getNamedItem("key").getNodeValue();
// check the key and if it is wrong we need a failure
if (!model.checkKey(myKey))
{
xmlString = new String(Message.responseHeader(request.id(),
"Invalid key") + "<forceResponse numberAffected='0'/></response>");
}
else if (child.getAttributes().getNamedItem("id") != null)
{
// get ID of event and the DLE
String eventID = new String(child.getAttributes()
.getNamedItem("id").getNodeValue());
DecisionLineEvent dle = model.getDecisionLineEvent(eventID);
if (dle==null){
dle = DatabaseSubsystem.readDecisionLineEvent(eventID);
if (dle!=null){
model.getDecisionLineEvents().add(dle);
}
}
// validate that this DLE exists
if (dle != null)
{
// finish the DLE
dle.setType(EventType.FINISHED);
dle.getFinalOrder();
// write to database
DatabaseSubsystem.writeDecisionLineEvent(dle);
// generate the success message
xmlString = new String(Message.responseHeader(request.id())
+ "<forceResponse numberAffected='1'/></response>");
}
else
{
xmlString = new String(Message.responseHeader(request.id(),
"Invalid Event Id") + "<forceResponse numberAffected='0'/></response>");
}
// TODO Needs to be broadcasted to all users of the dle
}
else
{
int daysOld = new Integer(child.getAttributes()
.getNamedItem("daysOld").getNodeValue());
int count = 0;
Date currentDate = new java.util.Date();
Date deleteByDate = new java.util.Date(
currentDate.getTime() - 1000 * 3600 * 24 * daysOld);
// get the DLE list from Model
ArrayList<DecisionLineEvent> dles = model.getDecisionLineEvents();
// iterate through each DLE in memory
for (DecisionLineEvent dle : dles)
{
// check whether it is older than daysOld
if (dle.getDate().before(deleteByDate))
{
// check whether it has been finished
if (!dle.getEventType().equals(EventType.FINISHED))
{
// finish the DLE
dle.setType(EventType.FINISHED);
dle.getFinalOrder();
// write to database
DatabaseSubsystem.writeDecisionLineEvent(dle);
count++;
}
}
}
// finish any DLEs not in memory
DatabaseSubsystem.finishDLEBasedOnDate(deleteByDate);
xmlString = new String(Message.responseHeader(request.id())
+ "<forceResponse numberAffected='" + count + "'/></response>");
}
response = new Message(xmlString);
return response;
} |
2090344a-31e0-4b79-a47c-c204a6a32541 | 3 | public static boolean eval(String expression) {
if (expression == null) return false;
String[] comparitors = new String[] {"<=",">=","<>","!",">","<","="};
int i;
for (i=0; i < comparitors.length; i++) {
if (expression.contains(comparitors[i])) {
String[] split = expression.split(comparitors[i]);
return compares(split[0], split[1], comparitors[i]);
}
}
return false;
} |
106e00c4-b742-451c-99ee-628f4958d247 | 1 | public void save() {
try {
file.openWr(dir + "\\" + getNick() + ".txt");
file.write(hpass);
file.write(getWins());
file.write(getLoses());
file.close();
} catch (Exception e) {
empty();
ExceptionLog.println("Ошибка: Не удалось записать в файл пользователя " + getNick());
}
} |
d88fa11e-626f-4777-b64d-e47af5e82725 | 0 | public Employee(String n, double s)
{
name = n;
salary = s;
hireDay = new Date();
} |
469fec59-d51e-4b08-9ce6-dac52873454e | 6 | private void populateCombos() {
String imgQuality = device.getProperty(Device.IMAGE_QUALITY);
String pollRate = device.getProperty(Device.POLLING_RATE);
int qualityPosition = 0;
int pollPosition = 0;
if (imgQuality == null) {
imgQuality = Integer
.toString(IConnectionConstants.DEFAULT_IMAGE_QUALITY);
}
if (pollRate == null) {
pollRate = Long.toString(IConnectionConstants.DEFAULT_FRAME_DELAY);
}
int i = 0;
for (String rate : IConnectionConstants.pollingRates.keySet()) {
reverseRateMap.put(IConnectionConstants.pollingRates.get(rate),
rate);
pollingRateCombo.addItem(IConnectionConstants.pollingRates
.get(rate));
if (rate.equals(pollRate)) {
pollPosition = i;
}
i++;
}
i = 0;
for (String quality : IConnectionConstants.qualities.keySet()) {
reverseQualityMap.put(IConnectionConstants.qualities.get(quality),
quality);
imageQualityCombo.addItem(IConnectionConstants.qualities
.get(quality));
if (quality.equals(imgQuality)) {
qualityPosition = i;
}
i++;
}
pollingRateCombo.setSelectedIndex(pollPosition);
imageQualityCombo.setSelectedIndex(qualityPosition);
} |
04dd5509-7b81-4327-9311-2d61b20d1f1c | 1 | public List<String> getString() {
if (string == null) {
string = new ArrayList<String>();
}
return this.string;
} |
b0e7472e-da24-494e-ac9f-18e8f2bee71b | 0 | @Before
public void setUp() {
} |
31a63be5-19a0-4f85-8e2f-6916feb51e5e | 1 | @Override
public void run() {
Thread.currentThread().setName("Shutdown");
try {
LOG.info("The \"UCP and SMMP Proxy\" is shutting down");
// Do whatever has to be done here to cleanup the module before complete shutdown
LOG.info("The \"UCP and SMMP Proxy\" shutted down");
} catch (Throwable throwable) {
LOG.error("The \"UCP and SMMP Proxy\" shutdown encountered a problem: ", throwable);
}
} |
6c23d6ff-2600-4866-8399-1bec54901df1 | 9 | private void renderFormalTypeParameters(JavaBytecodeSyntaxDrawer sd, Imports ia, List<FormalTypeParameter> typeParams) {
boolean displayExtendsObject = SystemFacade.getInstance().getPreferences().isSettingTrue(Settings.DISPLAY_EXTENDS_OBJECT);
if (typeParams != null && typeParams.size() > 0) {
sd.drawDefault("<");
boolean isFirstTypeParam = true;
for (FormalTypeParameter typeParam : typeParams) {
if (isFirstTypeParam) {
isFirstTypeParam = false;
} else {
sd.drawDefault(", ");
}
sd.drawDefault(typeParam.getIdentifier());
List<GenericJavaType> union = typeParam.getTypeUnion();
if (union.size() == 1 && union.get(0).getBaseType().equals(JavaType.JAVA_LANG_OBJECT)) {
// special case where there's just extends Object
if (displayExtendsObject) {
sd.drawKeyword(" extends ");
sd.drawDefault(ia.getShortName(JavaType.JAVA_LANG_OBJECT.toString()));
}
} else {
sd.drawKeyword(" extends ");
boolean isFirstType = true;
for (GenericJavaType gjt : union) {
if (isFirstType) {
isFirstType = false;
} else {
sd.drawDefault(" & ");
}
renderGenericJavaType(sd, ia, gjt);
}
}
}
sd.drawDefault(">");
}
} |
69c78f46-c854-4f75-965f-8c9d7bff5627 | 0 | public void setDescription(String description) {
this.description = description;
} |
c57bbaf1-c0b1-4dab-b969-46fc82cf97f9 | 0 | public EntityServlet() {
super();
} |
5b9a898b-2f97-42da-a824-2b301e28afcf | 6 | public void combat(Unit attacker, Unit defender, int round) {
if (round < 100) {
if (attacker.range > defender.range)
// Prüfen ob der Verteidiger sich wehren kann
{
defender.setHP(defender.hp - r.nextInt(attacker.attack) * attacker.hp / 100);
// ranged Schadensberechnung wip
return;
} else {
if (r.nextInt(81) >= strikechance(attacker, defender)) {
defender.setHP(defender.hp - 1);
}
// Rng Wert muss ausgerechneten Wert überschreiten um für 1 zu
// striken
if (r.nextInt(81) >= strikechance(defender, attacker)) {
attacker.setHP(attacker.hp - 1);
}
System.out.println("round " + round + " defhp " + defender.hp + " atkhp " + attacker.hp);
// Nur zu Testzwecken wird später noch entfernt
}
if (defender.hp > 0 && attacker.hp > 0) {
combat(attacker, defender, round + 1);
}
}
} |
bc061fd0-7ada-4f8e-b251-e730fa4314cd | 6 | public static ArrayList<Book> checkBookReservation(ArrayList<BookCopy> bookList) {
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Book> foundReservations = new ArrayList<Book>();
Statement stmnt = null;
String sql = "";
ResultSet res = null;
for(Book b : bookList) {
try {
stmnt = conn.createStatement();
sql = "SELECT * FROM Reservations WHERE product_id = " + b.getBookID() + " AND type = 'boek'";
res = stmnt.executeQuery(sql);
if(res.next())
foundReservations.add(b);
} catch (SQLException e) {
System.out.println(e);
}
}
return foundReservations;
} |
07508e2b-77f3-4030-936b-e6bf5d24b7b4 | 0 | public ProblemList getProblemList() {
return problemList;
} |
3f178196-1899-412e-b38d-e3b1f50cf3cc | 8 | TermInfosReader(Directory dir, String seg, FieldInfos fis, int readBufferSize, int indexDivisor)
throws CorruptIndexException, IOException {
boolean success = false;
if (indexDivisor < 1 && indexDivisor != -1) {
throw new IllegalArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try {
directory = dir;
segment = seg;
fieldInfos = fis;
origEnum = new SegmentTermEnum(directory.openInput(segment + "." + IndexFileNames.TERMS_EXTENSION,
readBufferSize), fieldInfos, false);
size = origEnum.size;
//read in bloom filter.... here if it exists...
BloomFilter filter = TermInfosCache.getFromCache(getRealDir(directory), segment);
if (filter == null && bloomFilterEnabled) {
if (directory.fileExists(segment + "." + IndexFileNames.BLOOM_FILTER_EXTENSION)) {
IndexInput openInput = directory.openInput(segment + "." + IndexFileNames.BLOOM_FILTER_EXTENSION);
if (openInput.readLong() != -1L) {
openInput.seek(0);
bloomFilter = new BloomFilter();
bloomFilter.read(openInput);
openInput.close();
}
}
}
if (indexDivisor != -1) {
// Load terms index
totalIndexInterval = origEnum.indexInterval * indexDivisor;
final SegmentTermEnum indexEnum = new SegmentTermEnum(directory.openInput(segment + "." + IndexFileNames.TERMS_INDEX_EXTENSION,
readBufferSize), fieldInfos, true);
try {
index = new TermInfosReaderIndex(directory,segment);
index.build(indexEnum, indexDivisor, (int) dir.fileLength(segment + "." + IndexFileNames.TERMS_INDEX_EXTENSION));
indexLength = index.length();
} finally {
indexEnum.close();
}
} else {
// Do not load terms index:
totalIndexInterval = -1;
index = null;
}
success = true;
} finally {
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success) {
close();
}
}
} |
461fa0f0-a478-4d7b-a1c9-18e822d89769 | 4 | @SuppressWarnings("unchecked")
public void add(int index, T theElement)
{
if(index < 0 || index > size)
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
if(size == element.length)
{
T[] old = element;
element = ( T[] ) new Object[2 * size];
System.arraycopy(old, 0, element, 0, size);
}
for(int i = size - 1; i >= index; i--)
element[i + 1] = element[i];
element[index] = theElement;
size++;
} |
53ff43e4-a3ce-445a-b588-cfa02255a3a1 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(SecurityJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SecurityJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SecurityJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SecurityJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SecurityJDialog dialog = new SecurityJDialog(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);
}
});
} |
89befd03-fa60-451a-b544-2bdbcb2b3d08 | 3 | public int trimaLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 30;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod-1;
} |
36e81fae-017e-45f3-8eca-8cec79e38c4c | 3 | public void close(){
try {
acceptthread.stop();
if (s != null) {
s.close();
for (Client c: clients) {
c.close();
}
}
gui.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
0ce20b74-ed68-473d-92ea-7dfd2a378b9e | 9 | public void renderTopFace(Block block, double d, double d1, double d2, int i) {
Tessellator tessellator = Tessellator.instance;
if (this.overrideBlockTexture >= 0) {
i = this.overrideBlockTexture;
}
int j = (i & 15) << 4;
int k = i & 240;
double d3 = ((double) j + block.minX * 16.0D) / 256.0D;
double d4 = ((double) j + block.maxX * 16.0D - 0.01D) / 256.0D;
double d5 = ((double) k + block.minZ * 16.0D) / 256.0D;
double d6 = ((double) k + block.maxZ * 16.0D - 0.01D) / 256.0D;
if (block.minX < 0.0D || block.maxX > 1.0D) {
d3 = (double) (((float) j + 0.0F) / 256.0F);
d4 = (double) (((float) j + 15.99F) / 256.0F);
}
if (block.minZ < 0.0D || block.maxZ > 1.0D) {
d5 = (double) (((float) k + 0.0F) / 256.0F);
d6 = (double) (((float) k + 15.99F) / 256.0F);
}
double d7 = d4;
double d8 = d3;
double d9 = d5;
double d10 = d6;
if (this.field_31083_k == 1) {
d3 = ((double) j + block.minZ * 16.0D) / 256.0D;
d5 = ((double) (k + 16) - block.maxX * 16.0D) / 256.0D;
d4 = ((double) j + block.maxZ * 16.0D) / 256.0D;
d6 = ((double) (k + 16) - block.minX * 16.0D) / 256.0D;
d9 = d5;
d10 = d6;
d7 = d3;
d8 = d4;
d5 = d6;
d6 = d9;
} else if (this.field_31083_k == 2) {
d3 = ((double) (j + 16) - block.maxZ * 16.0D) / 256.0D;
d5 = ((double) k + block.minX * 16.0D) / 256.0D;
d4 = ((double) (j + 16) - block.minZ * 16.0D) / 256.0D;
d6 = ((double) k + block.maxX * 16.0D) / 256.0D;
d7 = d4;
d8 = d3;
d3 = d4;
d4 = d8;
d9 = d6;
d10 = d5;
} else if (this.field_31083_k == 3) {
d3 = ((double) (j + 16) - block.minX * 16.0D) / 256.0D;
d4 = ((double) (j + 16) - block.maxX * 16.0D - 0.01D) / 256.0D;
d5 = ((double) (k + 16) - block.minZ * 16.0D) / 256.0D;
d6 = ((double) (k + 16) - block.maxZ * 16.0D - 0.01D) / 256.0D;
d7 = d4;
d8 = d3;
d9 = d5;
d10 = d6;
}
double d11 = d + block.minX;
double d12 = d + block.maxX;
double d13 = d1 + block.maxY;
double d14 = d2 + block.minZ;
double d15 = d2 + block.maxZ;
if (this.enableAO) {
tessellator.setColorOpaque_F(this.colorRedTopLeft, this.colorGreenTopLeft, this.colorBlueTopLeft);
tessellator.addVertexWithUV(d12, d13, d15, d4, d6);
tessellator.setColorOpaque_F(this.colorRedBottomLeft, this.colorGreenBottomLeft, this.colorBlueBottomLeft);
tessellator.addVertexWithUV(d12, d13, d14, d7, d9);
tessellator.setColorOpaque_F(this.colorRedBottomRight, this.colorGreenBottomRight, this.colorBlueBottomRight);
tessellator.addVertexWithUV(d11, d13, d14, d3, d5);
tessellator.setColorOpaque_F(this.colorRedTopRight, this.colorGreenTopRight, this.colorBlueTopRight);
tessellator.addVertexWithUV(d11, d13, d15, d8, d10);
} else {
tessellator.addVertexWithUV(d12, d13, d15, d4, d6);
tessellator.addVertexWithUV(d12, d13, d14, d7, d9);
tessellator.addVertexWithUV(d11, d13, d14, d3, d5);
tessellator.addVertexWithUV(d11, d13, d15, d8, d10);
}
} |
6973d35c-0a32-4575-a9a7-25d22effb37f | 4 | private String sourceLastUpdated() {
XPath xpath = XPathFactory.newInstance().newXPath();
String updated = "";
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse("service-names-port-numbers.xml");
updated = xpath.evaluate("/registry/updated", doc);
} catch (XPathExpressionException e) {
logger.log(Level.SEVERE, "Invalid XPath expression!", e);
} catch (SAXException e) {
logger.log(Level.SEVERE,
"Error parsing service-names-port-numbers.xml", e);
} catch (IOException e) {
logger.log(Level.SEVERE,
"Error processing service-names-port-numbers.xml", e);
} catch (ParserConfigurationException e) {
logger.log(
Level.SEVERE,
"Error creating DocumentBuilder which satisfies the configuration requested.",
e);
} finally {
}
return updated;
} |
58e45bca-feae-40a9-bca4-be1684762921 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Principal().setVisible(true);
}
});
} |
b2b2d70a-59e1-44b7-aab7-16b956f81f54 | 3 | public boolean allowScreenDownMode() {
if (!allowScreenOrPrintRenderingOrInteraction())
return false;
if (getFlagNoView() && !getFlagToggleNoView())
return false;
return !getFlagReadOnly();
} |
8a910d00-e13b-4e15-aef1-bf928c7fadf5 | 1 | @Test
public void testGreater2PowersExponent() {
logger.info("greater2PowersExponent");
int[] number = {0, 1,2, 3,4, 5,6,7,8, 9,10,11,12,13,14,15,16,17,18,19,20};
int[] expResult = {0, 0,1, 2,2, 3,3,3,3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5};
for (int i = 0; i < number.length; i++) {
logger.info("Trying "+i);
int result = PowersHelper.greater2PowersExponent(number[i]);
assertEquals(expResult[i], result);
}
} |
0ac43331-8117-47d0-8a6c-ab5d42f541f1 | 5 | public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number M: ");
int m = sc.nextInt();
System.out.println("Enter number N: ");
int n = sc.nextInt();
if (n < m) {
int helper = n;
n = m;
m = helper;
}
String numbersDivisibleBy3 = "";
String numbersDivisibleBy2 = "";
String numbersDivisibleBy5 = "";
for (int i = m; i <= n; i++) {
if (i % 3 == 0) {
numbersDivisibleBy3 += i + " ";
}
if (i % 2 == 0) {
numbersDivisibleBy2 += i + " ";
}
if (i % 5 == 0) {
numbersDivisibleBy5 += i + " ";
}
}
System.out.println("Numbers divisible by 3: " + numbersDivisibleBy3);
System.out.println("Numbers divisible by 2: " + numbersDivisibleBy2);
System.out.println("Numbers divisible by 5: " + numbersDivisibleBy5);
} |
2910b792-d944-44c9-b31e-9c7ec4c8f004 | 6 | public void setCurrentItemByPath(String relativePath){
File file = new File(ProjectMgr.getAssetsPath(), relativePath);
if(!file.exists()){return;}
List<File> files = new ArrayList<File>();
while(file.getParent() != null && !file.getParent().equals(ProjectMgr.getAssetsPath())){
files.add(file);
file = file.getParentFile();
}
if(file.getParent() == null){
return;
}
for(int i=files.size()-1; i>=0; i--){
file = files.get(i);
String relPath = Util.getRelativePath(file, new File(ProjectMgr.getAssetsPath()));
FilePathTreeItem item = getItemByPath(relPath);
if(i==0){
setCurrentItem(item);
}
else{
item.setExpanded(true);
}
}
} |
2b48c1df-2743-473b-b008-08cb6a0f1e67 | 3 | @Override
public boolean tallenna() {
try {
FileWriter kirjoitin = new FileWriter(rekisteri);
for (int i = 0; i < tyopaivat.size() - 1; i++) {
kirjoitin.write(tyopaivat.get(i).tallennusMuoto() + "\n");
}
if (!tyopaivat.isEmpty()) { // viimeisen turhan rivinvaihdon poisto
kirjoitin.write(tyopaivat.get(tyopaivat.size() - 1).tallennusMuoto());
}
kirjoitin.close();
} catch (Exception e) {
return false;
}
return true;
} |
30cca9d0-bdac-4cb0-b570-88787855a07e | 6 | public String getParamValue(String configKey, String paramKey) {
if (key.equalsIgnoreCase(configKey)) {//search own
for (Param param : params) {
String ret = param.get(paramKey);
if (ret != null) {
return ret;
}
}
} else {//search in tree
if (configs != null) {
for (Config cfg : configs) {
String ret = cfg.getParamValue(configKey, paramKey);
if (ret != null) {
return ret;
}
}
}
}
return null;
} |
6a60d1f0-671c-4cf7-b14f-c836ee9d311d | 8 | @Override
public void checkPropertyAccess(String key) {
// allow access to some harmless properties
switch (key) {
case "line.separator":
case "user.dir":
case "file.separator":
case "java.class.version":
case "file.encoding":
case "java.compiler":
case "user.timezone":
case "user.country":
return;
}
checkOrigin("System.getProperty(" + key + ")");
super.checkPropertyAccess(key);
} |
01f85eca-49ec-4016-b4cd-ad21eb6c94bc | 0 | public String getLabel() {
return label;
} |
3c5f24a4-4e27-49e6-836d-1ecdd2b77858 | 5 | public LookupSwitchInsnNode(final LabelNode dflt, final int[] keys,
final LabelNode[] labels) {
super(Opcodes.LOOKUPSWITCH);
this.dflt = dflt;
this.keys = new ArrayList(keys == null ? 0 : keys.length);
this.labels = new ArrayList(labels == null ? 0 : labels.length);
if (keys != null) {
for (int i = 0; i < keys.length; ++i) {
this.keys.add(new Integer(keys[i]));
}
}
if (labels != null) {
this.labels.addAll(Arrays.asList(labels));
}
} |
5ec85644-302e-4e79-a80d-e61b6d96ae6f | 9 | public Object getValueAt(int rowIndex, int columnIndex) {
if (dados != null && rowIndex < dados.size()) {
Cad_Produto_TO e = (Cad_Produto_TO) dados.get(rowIndex);
if (columnIndex == 0) {
return e.getTxt_produto();
}
if (columnIndex == 1) {
return e.getCad_fornecedor().getTxt_nomerazaosocial();
}
if (columnIndex == 2) {
return e.getCad_unidade_medida().getTxt_unidade_medida();
}
if (columnIndex == 3) {
return e.getValor_compra();
}
if (columnIndex == 4) {
return e.getValor_venda();
}
if (columnIndex == 5) {
return e.getNCM();
}
if (columnIndex == 6) {
return e.getObservacao();
}
}
return null;
} |
ae8fc116-1723-4b97-8366-34b8f0a683cc | 6 | public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(LauncherGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LauncherGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LauncherGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LauncherGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LauncherGUI().setVisible(true);
}
});
} |
e96e3b36-386a-430a-9e96-499c051aa24c | 7 | private CompanyCollection readAllCompaniesFromFile()
{
CompanyCollection allCompanies = new CompanyCollection();
try
{
CsvReader csvReader = new CsvReader(sourceFile);
if(csvReader.readHeaders() == true)
{
while(csvReader.readRecord()==true)
{
//apar_id,apar_name,address,place,province,Country_code,zip_code,telephone_1,comp_reg_no,acctype
// TODO : constants for each header ?
String id = csvReader.get("Customer ID");
String name = csvReader.get("Business Name 1");
String companyRegNo = csvReader.get("Local Registration Number");
CompanyType type = CompanyType.UNKNOWN;
Company c = new Company(id, name, type);
c.setCompanyRegistrationNumber(companyRegNo);
String dunsString = csvReader.get("DUNS");
if( dunsString.length()>0)
{
int dunsNumber = Integer.parseInt(dunsString);
DnBData data = new DnBData(dunsNumber);
String dnbName = csvReader.get("COMPANY_NAME");
data.setName(dnbName);
SICCode sic = SICCode.getSICFromCode(csvReader.get("PRIMARY_SIC"));
if(sic!=null)
data.setPrimarySicCode(sic);
c.setDunnBradstreetData(data);
}
allCompanies.add(c);
}
}
csvReader.close();
}
catch(FileNotFoundException fnfe)
{
logger.warning(fnfe.getMessage());
}
catch(IOException ioe)
{
logger.warning(ioe.getMessage());
}
catch(Exception e)
{
logger.warning(e.getMessage());
}
return allCompanies;
} |
eb1af88b-c94f-4a64-bfe7-d845a4cce7eb | 2 | public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add((int) (Math.random() * 100));
}
Collections.sort(list);
System.out.println("Sorted Array: " + list);
int testNumber = 10;
int index = Collections.binarySearch(list, testNumber);
if (index >= 0) {
System.out.println("Number " + testNumber + " found at index: "
+ index);
} else {
System.out.println("Number " + testNumber + " not found");
}
System.out.println("Max number: " + Collections.max(list));
System.out.println("Min number: " + Collections.min(list));
System.out.println("Frequency of " + testNumber + " : "
+ Collections.frequency(list, testNumber));
Set<Integer> sortedList = new HashSet<>();
sortedList.addAll(list);
System.out.println("Number of distinct elements:" + sortedList.size());
list.clear();
list.addAll(sortedList);
Collections.shuffle(list);
List<Integer> topTenList = list.subList(0, 10);
Collections.sort(topTenList);
System.out.println("Top 10: " + topTenList);
} |
66c2ec0c-473a-4d31-84bb-1a8bbe357e14 | 8 | public void simular(){
int i=0;
do{
if(te[0]<tr){ //CASO 1
t=te[0];
r=r+1;
if(r==s+1){
T=t;
System.out.println("\nEl sistema FALLO en instante "+T);
System.out.println("El algoritmo hizo "+i+" ciclos.");
break;
}
if(r<s+1){
te[0]=(int)(t+this.generarPF());
this.ordenarFallas();
this.mostrarFallas();
/*equivale a eliminar t1 y agregar al vector t+X.
* Lo hago de esta manera porque estoy usando un vector, No un ArrayList
*/
}
if(r==1){
tr=(int)(t+this.generarTR());
}
}
if(tr<=te[0]){
t=tr;
r=r-1;
if(r>0){
tr=(int)(t+this.generarTR());
}
if(r==0){
tr=(int)Float.POSITIVE_INFINITY;
}
}
i++;
System.out.print(" Hay "+r+" equipos en reparacion.");
System.out.print(" Hay "+s+" equipos de backup.");
}
while(t<9999999);
} |
99fc06bb-7b98-43ec-9dc8-3136b120956c | 1 | private float getValueAsFloat(String value, float defaultFloat) {
try {
return Float.valueOf(value);
} catch(NumberFormatException e) {
e.printStackTrace();
}
return defaultFloat;
} |
0df6e09d-196a-4579-bd69-9e7ee4853cc9 | 6 | public void searchRoundTripFlights() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
PreparedStatement ps = null;
Connection con = null;
ResultSet rs;
try {
con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940");
if (con != null) {
con.setAutoCommit(false);
String sql = "Create OR Replace view SearchResults(Name, FlightNo, DepTime, ArrTime, DepAirportID, ArrAirportID, LegNo, Class, fare, AirlineID)\n"
+ "as\n"
+ "SELECT DISTINCT R.Name, L.FlightNo, L.DepTime, L.ArrTime, L.DepAirportId, L.ArrAirportId, L.LegNo, M.Class, M.Fare, L.AirlineID\n"
+ "FROM Flight F, Leg L, Airport A , Fare M, Airline R\n"
+ "WHERE F.AirlineID = L.AirlineID AND F.FlightNo = L.FlightNo \n"
+ " AND (L.DepAirportId = ? OR L.ArrAirportId = ?) AND M.AirlineID = L.AirlineID \n"
+ "AND M.FlightNo = L.FlightNo AND R.Id = L.AirlineID AND M.FareType = 'Regular' \n"
+ "AND L.DepTime > ? AND L.DepTime < ? ";
ps = con.prepareStatement(sql);
ps.setString(1, flightTo);
ps.setString(2, flightFrom);
ps.setDate(3, new java.sql.Date(returning.getTime()));
ps.setDate(4, new java.sql.Date(returning.getTime() + +(1000 * 60 * 60 * 24)));
try {
ps.execute();
sql = "select Distinct A.Name, A.FlightNo, A.DepTime, B.ArrTime ,A.class, A.fare, A.DepAirportID, A.LegNo, A.AirlineID, B.ArrAirportID\n"
+ "From searchresults A, searchresults B\n"
+ "Where ((A.ArrAirportID = B.DepAirportID) OR (A.DepAirportID = ? AND B.ArrAirportID = ?))";
ps = con.prepareStatement(sql);
ps.setString(1, flightTo);
ps.setString(2, flightFrom);
ps.execute();
rs = ps.getResultSet();
flightReturnResults.removeAll(flightReturnResults);
int i = 0;
while (rs.next()) {
//flightResults.add()
flightReturnResults.add(new Flight(rs.getString("AirlineID"), rs.getString("Name"), rs.getInt("FlightNo"), rs.getTimestamp("DepTime"), rs.getTimestamp("ArrTime"),
rs.getString("Class"), rs.getDouble("fare"), rs.getString("DepAirportID"), rs.getString("ArrAirportID"), i, rs.getInt("LegNo")));
i++;
}
con.commit();
} catch (Exception e) {
con.rollback();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.setAutoCommit(true);
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
b2246ff7-c926-436b-b536-d604cb6e1e04 | 8 | public float unitize()
{
assert (vertices != null);
float maxx, minx, maxy, miny, maxz, minz;
float cx, cy, cz, w, h, d;
float scale;
/*
* get the max/mins
*/
maxx = minx = vertices[3 + 0];
maxy = miny = vertices[3 + 1];
maxz = minz = vertices[3 + 2];
for (int i = 1; i <= numvertices; i++)
{
if (maxx < vertices[3 * i + 0])
{
maxx = vertices[3 * i + 0];
}
if (minx > vertices[3 * i + 0])
{
minx = vertices[3 * i + 0];
}
if (maxy < vertices[3 * i + 1])
{
maxy = vertices[3 * i + 1];
}
if (miny > vertices[3 * i + 1])
{
miny = vertices[3 * i + 1];
}
if (maxz < vertices[3 * i + 2])
{
maxz = vertices[3 * i + 2];
}
if (minz > vertices[3 * i + 2])
{
minz = vertices[3 * i + 2];
}
}
/*
* calculate model width, height, and depth
*/
w = Math.abs(maxx) + Math.abs(minx);
h = Math.abs(maxy) + Math.abs(miny);
d = Math.abs(maxz) + Math.abs(minz);
/*
* calculate center of the model
*/
cx = (maxx + minx) / 2.0f;
cy = (maxy + miny) / 2.0f;
cz = (maxz + minz) / 2.0f;
/*
* calculate unitizing scale factor
*/
scale = 2.0f / Math.max(Math.max(w, h), d);
/*
* translate around center then scale
*/
for (int i = 1; i <= numvertices; i++)
{
vertices[3 * i + 0] -= cx;
vertices[3 * i + 1] -= cy;
vertices[3 * i + 2] -= cz;
vertices[3 * i + 0] *= scale;
vertices[3 * i + 1] *= scale;
vertices[3 * i + 2] *= scale;
}
return scale;
} |
3eed1db1-e2c1-46e2-af75-dffb3dba904d | 7 | public void saveAsIco(OutputStream out) throws IOException {
byte[] buffer = new byte[16];
int count = 0;
int[] sizes = new int[] { 256, 128, 64, 48, 32, 16 };
for (int size : sizes) {
if (hasImage(size)) {
count++;
}
}
EndianUtils.writeLEShort(0, buffer, 0);
EndianUtils.writeLEShort(1, buffer, 2);
EndianUtils.writeLEShort(count, buffer, 4);
out.write(buffer, 0, 6);
int totalImageBytes = 0;
List<byte[]> images = new ArrayList<>();
for (int size : sizes) {
if (hasImage(size)) {
buffer[0] = (byte) (size == 256 ? 0 : size);
buffer[1] = buffer[0];
buffer[2] = 0;
buffer[3] = 0;
EndianUtils.writeLEShort(1, buffer, 4);
EndianUtils.writeLEShort(32, buffer, 6);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!StdImage.writePNG(baos, getImage(size), 72)) {
throw new IOException(UNABLE_TO_CREATE_PNG);
}
byte[] bytes = baos.toByteArray();
images.add(bytes);
EndianUtils.writeLEInt(bytes.length, buffer, 8);
EndianUtils.writeLEInt(6 + buffer.length * count + totalImageBytes, buffer, 12);
out.write(buffer);
totalImageBytes = bytes.length;
}
}
for (byte[] bytes : images) {
out.write(bytes);
}
} |
fa72b946-89a1-41fe-becc-e727d18190f5 | 0 | @Override
public String toString() {
return "fleming.entity.Sintoma[ idSintomas=" + idSintomas + " ]";
} |
4a66d8e9-6223-4272-8629-408e38c72978 | 1 | public int getIndexOfChild(Object parent, Object child) {
Iterator iter = ((TreeElement) parent).getChilds().iterator();
int i = 0;
while (iter.next() != child)
i++;
return i;
} |
1e6c0972-2f32-4d66-b123-5761b9e1e012 | 6 | public Chess1(String title){
super(title);
Dimension boardSize = new Dimension(800, 800);
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );
int row = (i / 8) % 2;
if (row == 0)
square.setBackground( i % 2 == 0 ? Color.black : Color.white );
else
square.setBackground( i % 2 == 0 ? Color.white : Color.black );
}
JLabel piece = new JLabel( new ImageIcon("3.png") );
JPanel panel = (JPanel)chessBoard.getComponent(0);
panel.add(piece);
piece = new JLabel(new ImageIcon("5.png"));
panel = (JPanel)chessBoard.getComponent(1);
panel.add(piece);
piece = new JLabel(new ImageIcon("4.png"));
panel = (JPanel)chessBoard.getComponent(2);
panel.add(piece);
piece = new JLabel(new ImageIcon("2.png"));
panel = (JPanel)chessBoard.getComponent(3);
panel.add(piece);
piece = new JLabel(new ImageIcon("1.jpg"));
panel = (JPanel)chessBoard.getComponent(4);
panel.add(piece);
piece = new JLabel(new ImageIcon("4.png"));
panel = (JPanel)chessBoard.getComponent(5);
panel.add(piece);
piece = new JLabel(new ImageIcon("5.png"));
panel = (JPanel)chessBoard.getComponent(6);
panel.add(piece);
piece = new JLabel(new ImageIcon("3.png"));
panel = (JPanel)chessBoard.getComponent(7);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(8);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(9);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(10);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(11);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(12);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(13);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(14);
panel.add(piece);
piece = new JLabel(new ImageIcon("6.png"));
panel = (JPanel)chessBoard.getComponent(15);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(48);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(49);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(50);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(51);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(52);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(53);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(54);
panel.add(piece);
piece = new JLabel(new ImageIcon("12.png"));
panel = (JPanel)chessBoard.getComponent(55);
panel.add(piece);
piece = new JLabel(new ImageIcon("9.png"));
panel = (JPanel)chessBoard.getComponent(56);
panel.add(piece);
piece = new JLabel(new ImageIcon("11.png"));
panel = (JPanel)chessBoard.getComponent(57);
panel.add(piece);
piece = new JLabel(new ImageIcon("10.png"));
panel = (JPanel)chessBoard.getComponent(58);
panel.add(piece);
piece = new JLabel(new ImageIcon("8.png"));
panel = (JPanel)chessBoard.getComponent(59);
panel.add(piece);
piece = new JLabel(new ImageIcon("7.png"));
panel = (JPanel)chessBoard.getComponent(60);
panel.add(piece);
piece = new JLabel(new ImageIcon("10.png"));
panel = (JPanel)chessBoard.getComponent(61);
panel.add(piece);
piece = new JLabel(new ImageIcon("11.png"));
panel = (JPanel)chessBoard.getComponent(62);
panel.add(piece);
piece = new JLabel(new ImageIcon("9.png"));
panel = (JPanel)chessBoard.getComponent(63);
panel.add(piece);
board = new Board();
new King(board, false, new Position(4, 0));
new King(board, true, new Position(4, 7));
for (int i = 0; i<8; i++) {
new Pawn(board, false, new Position(i, 1));
}
for (int i = 0; i<8; i++) {
new Pawn(board, true, new Position(i, 6));
}
new Rook(board, false, new Position(0,0));
new Rook(board, false, new Position(7,0));
new Rook(board, true, new Position(0,7));
new Rook(board, true, new Position(7,7));
new Knight(board, false, new Position(1,0));
new Knight(board, false, new Position(6,0));
new Knight(board, true, new Position(1,7));
new Knight(board, true, new Position(6,7));
new Bishop(board, false, new Position(2,0));
new Bishop(board, false, new Position(5,0));
new Bishop(board, true, new Position(2,7));
new Bishop(board, true, new Position(5,7));
new Queen(board, false, new Position(3, 0));
new Queen(board, true, new Position(3, 7));
} |
87a94922-86b9-455a-b1c5-c306259b57ed | 0 | private int calculateNewDelay()
{
//core.setMessageDelay((long)(500/(1+500*Math.pow(2, messagesQueue.size() * 2))));
return (int)(500/(1+500*Math.pow(2, messagesQueue.size() * 2)));
} |
c292fab4-3274-4bbf-ba73-2cc50661d970 | 5 | public boolean disparar() throws ExceptionDisparo{
Logger.log(LogLevel.DEBUG, "Mina Retardad["+this.getPosicion().getX()+","+this.getPosicion().getY()+"]: turnos restantes: " + retardo);
if (this.retardo-- <= 0){
ArrayList<Posicion> posiciones = radioPosicion(posicion, this.radio);
ArrayList<Nave> naves;
if (posiciones.size() > 0){
for(Posicion pos: posiciones){
naves = juego.naveEnPosicion(pos);
if (naves.size() > 0){ //Si encontro alguna nave la da~na
for(Nave nave: naves){
nave.danar(this,pos);
}
}
}
}
Logger.log(LogLevel.DEBUG, "-->Mina Retardad: BUM! retardo: " + retardo);
this.disparo = true;
return true;
}
return false;
} |
2b89f5ac-bfe8-4330-9395-7ca90f2efa8b | 3 | @Override
public List<Funcionario> listAll() {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Funcionario> funcionarios = new ArrayList<>();
try {
con = ConnectionFactory.getConnection();
pstm = con.prepareStatement(LIST);
rs = pstm.executeQuery();
while (rs.next()) {
//nome = ?, login = ?, senha = ?, telefone = ?, celular = ?, cargo = ?,data_nascimento = ?, rg = ?
Funcionario f = new Funcionario();
f.setNome(rs.getString("nome"));
f.setCodigo(rs.getInt("codigo"));
f.setLogin(rs.getString("login"));
f.setSenha(rs.getString("senha"));
f.setTelefone(rs.getString("telefone"));
f.setCelular(rs.getString("celular"));
f.setCargo(rs.getString("cargo"));
f.setDataNascimento(rs.getDate("data_nascimento"));
f.setRg(rs.getString("rg"));
f.setEndereco(rs.getString("endereco"));
f.setCidade(rs.getString("cidade"));
f.setEstado(rs.getString("estado"));
funcionarios.add(f);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao listar funcionarios: " + e.getMessage());
} finally {
try {
ConnectionFactory.closeConnection(con, pstm, rs);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao fechar conexão de listar funcionarios: " + e.getMessage());
}
}
return funcionarios;
} |
0c90d08b-e89d-4f82-b303-1a777f9255fe | 0 | StarSystem(Ticker ticker) {
super(ticker);
world.setAmbientLight(100, 100, 100);
world.getLights().setRGBScale(Lights.RGB_SCALE_2X);
adapter = new AdapterPhysics(world);
} |
553b9c1e-16ab-4125-9db0-d2e8c1597452 | 5 | public int getNumAreaAtPosition(int x, int y) {
if (y > 660) {
return -1;
}
int widthWindow = AppliWindow.getInstance().getWidth();
int heightWindow = AppliWindow.getInstance().getHeight();
int xMap = x * this.widthMap / widthWindow;
int yMap = y * this.heightMap / heightWindow ;
if(xMap<0 || xMap >= this.widthMap || yMap < 0 || yMap >= this.heightMap) {
return -1;
}
return this.map[xMap][yMap];
} |
8556c2f4-0495-4535-b2f4-0abef6c2a7b8 | 0 | @Test
public void runTestAnonymousClass1() throws IOException {
InfoflowResults res = analyzeAPKFile("Callbacks_AnonymousClass1.apk");
Assert.assertNotNull(res);
Assert.assertEquals(1, res.size()); // loc + lat, but single parameter
} |
5705b7ed-d0df-4480-b27f-d302f05ffd95 | 7 | public static ArrayList<Polygon> getPolygonList()
{
try{
SAXBuilder sxb = new SAXBuilder();
try
{
// File reading
Document xmlFile = sxb.build("dbPattern.xml");
Element racine = xmlFile.getRootElement();
String patternName, position;
ArrayList<Vector> vectorList;
ArrayList<Position> positionList;
ArrayList<Polygon> polygonList = new ArrayList<Polygon>();
List<Element> listPatterns = racine.getChildren("pattern");
Iterator<Element> patternIterator = listPatterns.iterator();
while (patternIterator.hasNext())
{
Element current = (Element) patternIterator.next();
patternName = current.getChild("name").getText();
vectorList = new ArrayList<Vector>();
Element vectors = current.getChild("vectors");
if (vectors != null)
{
List<Element> tmp_listVector = vectors.getChildren("vector");
Iterator<Element> j = tmp_listVector.iterator();
while (j.hasNext()) {
Element currentVector = (Element) j.next();
position = currentVector.getText();
// Conversion string to double
vectorList.add(new Vector(Double.parseDouble(position
.split(",")[0]),
Double.parseDouble(position.split(",")[1])));
}
polygonList.add(new Polygon(patternName, vectorList));
}
positionList = new ArrayList<Position>();
Element positions = current.getChild("positionList");
if(positions!= null)
{
List<Element> tmp_listPosition = positions.getChildren("position");
Iterator<Element> j = tmp_listPosition.iterator();
while (j.hasNext()) {
Element currentPosition = (Element) j.next();
position = currentPosition.getText();
// Conversion string to double
positionList.add(new Position(Double.parseDouble(position
.split(",")[0]),
Double.parseDouble(position.split(",")[1])));
}
polygonList.add(new Polygon(positionList, patternName));
}
}
return polygonList;
}
catch(Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
} |
c4242944-05b4-466a-a951-58ca556bc24d | 9 | public byte[] getConsensusSequence() {
if (consensusPos!=-1) getConsensusBreakpointPosition();
StringBuilder consensus = new StringBuilder();
int pos = matrixStart;
for (int[] vote : votingMatrix) {
if (((increment==-1) && pos > consensusPos) || ((increment==1) && pos < consensusPos)) {
pos += increment;
continue;
}
int max_vote = -1;
int max_vote_idx = -1;
int tot_vote = 0;
for (int i=0; i<vote.length; i++) {
tot_vote += vote[i];
if (vote[i] > max_vote) {
max_vote = vote[i];
max_vote_idx = i;
}
}
if ( (float)max_vote/(float)tot_vote <= 0.5 ) max_vote_idx = 0;
char b = Utilities.indexToNucleotide(max_vote_idx);
consensus.append(b);
pos += increment;
}
votingMatrix = null;
return Utilities.stringToByte(consensus.toString());
} |
e489adb5-6926-45df-96aa-f151a97d7e4d | 8 | public void draw(BufferedImage canvas, boolean drawEdge, boolean drawCorners)
{
for (int y = 2; y < _height-2; y++)
for (int x = 2; x < _width-2; x++)
{
if (_image[y][x] == FILLED)
{
canvas.setRGB(x + _left, y + _top, ImageSegmenter._drawColor[_type]);
}
else if (drawEdge && _image[y][x] == EDGE)
{
canvas.setRGB(x+_left, y+_top, 0x000000);
}
}
if (drawCorners)
{
findLines();
if (_lines != null)
for (LineSegment line : _lines)
line.draw(canvas.createGraphics(), _left, _top);
}
} |
a6416565-986f-4832-b1d7-13c65cec00a9 | 4 | public static void main(String[] args)
{
if (args.length > 1)
{
try
{
BufferedImage image = ImageIO.read(new File(args[0]));
if (image != null)
{
ASCIIfier asciifier = new ASCIIfier(image);
if (args.length > 2)
{
float fontSize = Float.parseFloat(args[2]);
asciifier.setFontSize(fontSize);
}
asciifier.process(args[1].charAt(0));
ImageIO.write(asciifier.getProcessedImage(), "png", new File(args[0] + "_asciified.png"));
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}
else
{
System.out.println("Usage:");
System.out.println("java ASCIIfier IMAGE CHARACTER [FONT SIZE]");
}
} |
623ec23e-416c-40d7-8e0d-6938819fc140 | 9 | public List<T> getVoisinsNonNull(T[][] locations, int posX, int posY) {
List<T> voisins = new ArrayList<T>();
for (int i = ((posY - 1) < 0 ? 0 : posY - 1); i <= posY + 1
&& i < locations.length; i++) {
for (int j = ((posX - 1) < 0 ? 0 : posX - 1); j <= posX + 1
&& j < locations[0].length; j++) {
if ((i != posY || j != posX) && voisins != null) {
voisins.add(locations[i][j]);
}
}
}
return voisins;
} |
51393243-0443-4593-a46f-7d19affd160d | 1 | private void jButtonClientAjouterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonClientAjouterMouseClicked
String nom= jTextFieldClientNom.getText();
String prenom= jTextFieldClientPrenom.getText();
String email= jTextFieldClientEmail.getText();
Ville ville= (Ville) jComboBoxInterlocuteurVille.getSelectedItem();
Commercial commercial= (Commercial) jComboBoxInterlocuteurCommercial.getSelectedItem();
Service service= (Service) jComboBoxInterlocuteurService.getSelectedItem();
int id_ville=ville.getIdville();
int id_commercial =commercial.getIdCommercial();
int id_service =service.getIdservice();
try {
RequetesInterlocuteur.insertInterlocuteur(id_commercial, id_ville, id_service, nom, prenom, email);
} catch (SQLException ex) {
Logger.getLogger(VueInterlocuteur.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "Mise à jour interlocuteur "," Erreur ", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButtonClientAjouterMouseClicked |
9060cefc-f704-49f2-a9df-4c35f0dc85d1 | 5 | public static void main(String[] argv)
{
// Retrieve command line arguments
if (argv.length < 2) {
System.out.println("java DBEmployeeServer <EmployeeSurname> <EmployeeObjectName>");
return;
}
Connection dbConnection = null;
try {
// Establish connection with employee database
dbConnection = DBConnectionManager.getConnection();
// Retrieve all employees with given surname
DBEmployeeRetriever employeeRetriever = new DBEmployeeRetriever(dbConnection);
List<Employee> foundEmployees = employeeRetriever.getEmployees(argv[0]);
if (foundEmployees.isEmpty()) {
System.out.println("No employees were foudn with surname '" + argv[0] + "'. Could not bind employee.");
} else {
// Bind the first employee to the RMI registry
Employee employee = foundEmployees.get(0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(argv[1], employee); // rebind() so it doesn't matter if an object already exists with that name
// Inform invoker of server that object has been bound
System.out.println("Employee " + employee.getForename() + " "
+ employee.getSurname() + " has been bound with name "
+ argv[1] + ".");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// Ensure the connection to the database is closed
if (dbConnection != null) {
try {
dbConnection.close();
} catch (Exception closeError) {
// silently ignore connection close error
}
}
}
} |
d1ba9b5c-8504-470a-8f54-34d3671de71e | 5 | void processaDefunto()
{
int i, j;
for(i = 0; i < l; i++)
for(j = 0; j < c; j++)
if((mapa_atual[i][j].tipo == DEFUNTO)&&((mapa_prox[i][j].tipo == DEFUNTO)||(mapa_prox[i][j].tipo == NADA)))
{
//if(--mapa_atual[i][j].vida == 0)
// mapa_prox[i][j] = new Celula(NADA,0);
//else
mapa_prox[i][j] = new Celula(DEFUNTO, mapa_atual[i][j].vida);
}
} |
efe52901-8921-4c5d-908f-2addc54d8c38 | 2 | private void findMax() {
int m = 0;
for (int i = 1; i < array.length; ++i) {
if (array[i].getValue().compareTo(array[m].getValue()) > 0) {
m = i;
}
}
max = array[m];
} |
ccafe929-4824-4f55-899f-23d12e7089f0 | 5 | * @return True if it is, false if not.
*/
private boolean isEndingPunctuation(char input){
return input == '.' || input == '!' || input == '?' || input == ';' || input == ':' || input == '|';
} |
bd076614-7505-4ac0-9807-61552807f714 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(WycieczkaWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(WycieczkaWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(WycieczkaWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(WycieczkaWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WycieczkaWindow().setVisible(true);
}
});
} |
806b5488-8f28-42bf-ac95-96ae50e9c233 | 8 | public String toString() {
return (userID == null ? "" : userID + ", ") + (firstName == null ? "" : firstName + " ")
+ (lastName == null ? "" : lastName) + (klass == null ? "" : ", " + klass)
+ (institution == null ? "" : ", " + institution) + (state == null ? "" : ", " + state)
+ (country == null ? "" : ", " + country) + (emailAddress == null ? "" : ", " + emailAddress);
} |
b783fceb-fa19-40f0-8bc1-52fdca307981 | 2 | @Override
public PastMeeting getPastMeeting(int id) {
Meeting returnMeeting = getMeeting(id);
if(returnMeeting != null) {
if(returnMeeting.getDate().after(timeNow())) {
throw new IllegalArgumentException();
} else {
return (PastMeetingImpl) returnMeeting;
}
} else {
return null;
}
} |
50704651-52a4-49a2-86e3-9f51dcb6ddb7 | 9 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Mark)) {
return false;
}
Mark other = (Mark) object;
if ((this.idMark == null && other.idMark != null) || (this.idMark != null && !this.idMark.equals(other.idMark))) {
return false;
}
if ((this.nameMark == null && other.nameMark != null) || (this.nameMark != null && !this.nameMark.equals(other.nameMark))) {
return false;
}
return true;
} |
5a740525-cdf6-4b62-b43f-2b6058c8e765 | 6 | public static final void setMaximumPrecision(int p)
{
if(p == currMpipl)
return;
currMpipl = p;
mpmcr=MPMCRX;
mpird=1;
mpipl = currMpipl;
mpiou = 56;
mpiep = 10 - mpipl;
mpwds = (int)((mpipl / 7.224719896) + 1);
mp2 = mpwds + 2;
mp21 = mp2 + 1;
mpoud = mpiou;
mpnw = mpwds;
//const MPSize DEFAULTSIZE = MPSize(int((mpipl / 7.224719896) + 4));
// initializing mpuu1
int n = mpnw+1;
double t1, ti;
int j, i;
t1 = 0.75 * n;
int m = (int)(CL2 * Math.log (t1) + 1.0 - MPRXX); // *cast*
int mq = m + 2;
int nq = (int)(Math.pow(2, mq)); // *cast*
mpuu1 = new DComplex[nq];
mpuu1[0] = new DComplex(mq,0);
int ku = 1;
int ln = 1;
for(j = 1; j<= mq; j++)
{
t1 = PI / ln;
for (i = 0; i<= ln - 1; i++)
{
ti = i * t1;
mpuu1[i+ku] = new DComplex(Math.cos (ti), Math.sin (ti));
}
ku += ln;
ln *= 2;
}
// initializing mpuu2
double tpn;
int k;
t1 = 0.75 * n;
mpuu2 = new DComplex [mq+nq];
ku = mq + 1;
mpuu2[0] = new DComplex(mq,0);
int mm, nn, mm1, mm2, nn1, nn2, iu;
for (k = 2; k<= mq - 1; k++)
{
mpuu2[k-1] = new DComplex(ku,0);
mm = k;
nn = (int)(Math.pow(2, mm)); // *cast*
mm1 = (mm + 1) / 2;
mm2 = mm - mm1;
nn1 = (int)(Math.pow(2, mm1)); // *cast*
nn2 = (int)(Math.pow(2, mm2)); // *cast*
tpn = 2.0 * PI / nn;
for(j = 0; j<nn2; j++)
{
for(i = 0; i<nn1; i++)
{
iu = ku + i + j * nn1;
t1 = tpn * i * j;
mpuu2[iu-1] = new DComplex(Math.cos (t1), Math.sin (t1));
}
}
ku += nn;
}
} |
9bc6e692-cd02-469d-a635-cf5b0ceb2e6a | 5 | private ArrayList<Operadores> getListaOperadores() {
int usados = NUMEROS.size() - 1;
ArrayList<Operadores> operadores = new ArrayList<>();
for (int i = 0; i < usados; i++) {
int operador = NumeroAleatorio.generaNumero(1, Operadores.values().length);
if (Operadores.SUMA.getValue() == operador) {
operadores.add(Operadores.SUMA);
} else if (Operadores.RESTA.getValue() == operador) {
operadores.add(Operadores.RESTA);
} else if (Operadores.PRODUCTO.getValue() == operador) {
operadores.add(Operadores.PRODUCTO);
} else if (Operadores.COCIENTE.getValue() == operador) {
operadores.add(Operadores.COCIENTE);
}
}
return operadores;
} |
228ca073-1d1b-456b-9fa0-148af22d601d | 1 | void skipUntil(String delim) throws java.lang.Exception
{
while (!tryRead(delim)) {
readCh();
}
} |
756f08a6-447c-4451-98f5-2ad198d602ac | 1 | public void setupVertices(int width, int height) {
// We'll define our quad using 4 vertices of the custom 'TexturedVertex' class
VertexData v0 = new VertexData(); {
v0.setXYZ(0, 0, 0);
v0.setRGB(1, 0, 0);
v0.setST(0, 0);
}
VertexData v1 = new VertexData(); {
v1.setXYZ(0, height, 0);
v1.setRGB(0, 1, 0);
v1.setST(0, 1f);
}
VertexData v2 = new VertexData(); {
v2.setXYZ(width, height, 0);
v2.setRGB(0, 0, 1);
v2.setST(1f, 1f);
}
VertexData v3 = new VertexData(); {
v3.setXYZ(width, 0, 0);
v3.setRGB(1, 1, 1);
v3.setST(1f, 0);
}
vertices = new VertexData[] {v0, v1, v2, v3};
// Put each 'Vertex' in one FloatBuffer
verticesByteBuffer = BufferUtils.createByteBuffer(vertices.length *
VertexData.stride);
FloatBuffer verticesFloatBuffer = verticesByteBuffer.asFloatBuffer();
for (int i = 0; i < vertices.length; i++) {
// Add position, color and texture floats to the buffer
verticesFloatBuffer.put(vertices[i].getElements());
}
verticesFloatBuffer.flip();
byte[] indices = {
0, 1, 2,
2, 3, 0,
};
indicesCount = indices.length;
ByteBuffer indicesBuffer = BufferUtils.createByteBuffer(indicesCount);
indicesBuffer.put(indices);
indicesBuffer.flip();
// Create a new Vertex Array Object in memory and select it (bind)
vaoId = GL30.glGenVertexArrays();
GL30.glBindVertexArray(vaoId);
// Create a new Vertex Buffer Object in memory and select it (bind)
vboId = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboId);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verticesFloatBuffer, GL15.GL_STREAM_DRAW);
// Put the position coordinates in attribute list 0
GL20.glVertexAttribPointer(0, VertexData.positionElementCount, GL11.GL_FLOAT,
false, VertexData.stride, VertexData.positionByteOffset);
// Put the color components in attribute list 1
GL20.glVertexAttribPointer(1, VertexData.colorElementCount, GL11.GL_FLOAT,
false, VertexData.stride, VertexData.colorByteOffset);
// Put the texture coordinates in attribute list 2
GL20.glVertexAttribPointer(2, VertexData.textureElementCount, GL11.GL_FLOAT,
false, VertexData.stride, VertexData.textureByteOffset);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
// Deselect (bind to 0) the VAO
GL30.glBindVertexArray(0);
// Create a new VBO for the indices and select it (bind) - INDICES
vboiId = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboiId);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indicesBuffer,
GL15.GL_STATIC_DRAW);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
} |
bfa12478-f04a-4e48-b7e6-b72d9babcbdf | 4 | private String getLabelString() {
// Assumes relocation labels at beginning of instruction (in first path)
String label = null;
boolean foundLabel = false;
for (ArrayList<String> path : legitAssemblyOpTreePaths) {
for (String term : path) {
if (term.equals("LABEL"))
foundLabel = true;
if (foundLabel)
label = term;
}
break;
}
return label;
} |
ef2ea814-6181-46c4-a8b7-b154fa267947 | 8 | public synchronized void FileReader(){
String filePath = "C:/JavaFiles/QuizManager/QuizMasterFile.csv";
String playerFilePath="C:/JavaFiles/QuizManager/Players.csv";
String resultFilePath = "C:/JavaFiles/QuizManager/Results.csv";
File file = new File(filePath);
File playerFile = new File(playerFilePath);
File resultFile = new File(resultFilePath);
BufferedReader bufferedReader = null;
BufferedReader playerReader = null;
BufferedReader resultReader = null;
String searchChar = ",";
int quizId=0;
String title="";
int recordCount =0;
int totalQuestions=0;
String[] extractedRecord=null;
Set<Question> questionList =null;
try{
bufferedReader = new BufferedReader(new FileReader(file));
playerReader = new BufferedReader(new FileReader(playerFile));
resultReader = new BufferedReader(new FileReader(resultFile));
String recordInFile;
questionList = new HashSet<Question>();
playerList = new ArrayList<Player>();
quizList = new HashSet<Quiz>();
resultList = new ArrayList<Result>();
//reading the quiz master file
while ((recordInFile=bufferedReader.readLine()) != null){
extractedRecord = recordInFile.split(searchChar);
if(extractedRecord.length==3){
quizId=Integer.parseInt(extractedRecord[0]);
title = extractedRecord[1];
totalQuestions = Integer.parseInt(extractedRecord[2]);
}
else{
if(recordCount <= totalQuestions){
recordCount=recordCount+1;
//System.out.println("~~" +recordCount + " " + totalQuestions );
questionList.add(new QuestionImpl(Integer.parseInt(extractedRecord[0]),extractedRecord[1],extractedRecord[2],extractedRecord[3],extractedRecord[4],extractedRecord[5],Integer.parseInt(extractedRecord[6]),Integer.parseInt(extractedRecord[7])));
}
}
if(recordCount==totalQuestions){
quizList.add(new QuizImpl(questionList,title, quizId));
recordCount=0;
questionList = new HashSet<Question>();
}
}
extractedRecord=null;
recordInFile=null;
//get players data and store them in an ArrayList
while ((recordInFile=playerReader.readLine()) != null){
extractedRecord = recordInFile.split(searchChar);
int playerId =Integer.parseInt(extractedRecord[0]);
String playerName = extractedRecord[1];
String userName = extractedRecord[2];
String password = extractedRecord[3];
playerList.add(new PlayerImpl(playerId,playerName,userName,password));
}
extractedRecord=null;
recordInFile=null;
//get results data and store them in an ArrayList
while ((recordInFile=resultReader.readLine()) != null){
extractedRecord = recordInFile.split(searchChar);
int playerId =Integer.parseInt(extractedRecord[0]);
String playerName=extractedRecord[1];
int quizId1 = Integer.parseInt(extractedRecord[2]);
String quizName=extractedRecord[3];
int score=Integer.parseInt(extractedRecord[4]);
resultList.add(new ResultImpl(score,playerId,quizId1,quizName,playerName));
}
}
catch (FileNotFoundException ex) {
System.out.println("File " + file + " does not exist.");
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
closeReader(bufferedReader);
closeReader(playerReader);
closeReader(resultReader);
}
} |
420129be-d7dc-45d8-8535-ddfd458f1a63 | 1 | private static ArrayList<Character> rollCharacters()
{
// TODO create 100 Random Characters
// The Race's assigned should be pretty random
// Each Character's
// level must be 1-85
// strength, 0-100
// armour, 0-100
// find and fix the bug
ArrayList<Character> retval = new ArrayList<Character>();
for (int i = 0; i < 100; i++)
{
Race race = getRandomRace();
int level = getRandomLevel();
int strength = getRandomStrength();
int armour = getRandomArmour();
Character character = new Character(race, level, strength, armour);
retval.add(character);
}
return retval;
} |
afb10a3b-23e0-437d-b93e-88c6df376d47 | 5 | private void distinguishTour(SessionRequestContent request) {
List<Tour> list = (List<Tour>) request.getSessionAttribute(JSP_TOUR_LIST);
String selectId = request.getParameter(JSP_SELECT_ID);
Integer idTour = null;
if (selectId != null) {
idTour = Integer.decode(selectId);
} else {
Tour tour = (Tour) request.getSessionAttribute(JSP_CURRENT_TOUR);
if (tour != null) {
idTour = tour.getIdTour();
}
}
if (idTour != null) {
request.setSessionAttribute(JSP_CURRENT_TOUR, null);
for (Tour tour: list) {
if (Objects.equals(tour.getIdTour(), idTour)) {
request.setSessionAttribute(JSP_CURRENT_TOUR, tour);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = tour.getDepartDate();
String ds1 = formatter.format(d1);
request.setAttribute(JSP_CURR_DEPART_DATE, ds1);
Integer dn = tour.getDaysCount();
Calendar c = Calendar.getInstance();
c.setTime(d1);
c.add(Calendar.DATE, dn);
Date d2 = c.getTime();
String ds2 = formatter.format(d2);
request.setAttribute(JSP_CURR_ARRIVAL_DATE, ds2);
}
}
}
} |
f5a7fde4-6bd0-4bd2-a14f-6436359c95bd | 7 | final void addDisturbance(int radius, int chunkX, int chunkY, int chunkZ, double xVel, double yVel, double zVel)
{
// Limited to below the surface layer and above the thermocline layer
// For each depth in the range
for (int y = Math.max(1, chunkY - radius); y < Math.min(ySize - 2, chunkY + radius); y++)
// For every chunk at that depth within the range
for (int x = chunkX - radius; x < chunkX + radius; x++)
for (int z = chunkZ - radius; z < chunkZ + radius; z++)
{
int xIndex = x;
// y doesn't need to be checked as it doesn't wrap
int zIndex = z;
// wrap the coordinates if they go off the x or z axes
if (xIndex < 0)
xIndex += xSize;
if (xIndex >= xSize)
xIndex -= xSize;
if (zIndex < 0)
zIndex += zSize;
if (zIndex >= zSize)
zIndex -= zSize;
int index = getIndex(xIndex, y, zIndex);
this.xVel[index] += xVel;
this.yVel[index] += yVel;
this.zVel[index] += zVel;
// System.out.println("(" + this.xVel[index] + ", " + this.yVel[index] + ", " + this.zVel[index] + ")");
}
} |
75b46424-c935-483b-a159-00294200466a | 2 | private void afficherComptesRendus(){
if (ctrlMenu == null) {
VueMenu vueM = new VueMenu(ctrlA);
ctrlMenu = new CtrlMenu(vueM, vueA);
}
if (ctrlComptesRendus == null) {
VueComptesRendus vueCR = new VueComptesRendus(ctrlA);
ctrlComptesRendus = new CtrlComptesRendus(vueCR, vueA);
} else {
// si la le contrôleur et sa vue existent déjà
// il faut rafraîchir le contenu à partir de la base de données
ctrlComptesRendus.actualiser();
}
ctrlComptesRendus.getVue().setVisible(true);
} |
cf7073dc-f151-40ee-a3a3-46b92baddcb8 | 1 | public void start() {
// 下面的代码都是可以直接在Netty的官网里看到的,不仔细注释
_factory = new NioServerSocketChannelFactory(
// TODO: 需要写性能测试用例已验证cached thread pool是否够用?
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(_factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
// 这个就是发送消息包的Handler栈 - 虽然名字叫管道!
return Channels.pipeline(
new ObjectEncoder(),
new ObjectDecoder(
ClassResolvers.cacheDisabled(
getClass().getClassLoader())),
new QueryTrainServerHandler());
}
});
_channels.add(bootstrap.bind(new InetSocketAddress(_port)));
try {
// 如果eventbus因为日志\或者联系不上备份服务器而无法启动
// 那么就关闭Netty服务器
registerService();
EventBus.start();
_started = true;
} catch ( Exception e ) {
// TODO: 改成使用log4j之类的库来打印日志!
System.out.println("start server failed with: " + e);
e.printStackTrace();
stopNettyServer();
}
} |
0301c44e-421f-44c8-84f7-cf67e77f5d0b | 1 | private static void allSizes(String name, int children, MonteCarloNpv npv, StopWatch sw) {
int[] chunkSizes = { 100, 500, 1000, 2000 };
for (int i : chunkSizes) {
oneSize(name, children, i, npv, sw);
}
} |
85ba31e8-b14e-45f5-8dd1-3fedd960cc26 | 3 | private List<IArticle> loadArticles(Reader articlesFile) throws IOException {
List<IArticle> result = new ArrayList<>();
BufferedReader in = new BufferedReader(articlesFile);
String line;
while ((line = in.readLine()) != null) {
if (!EMPTY_LINE_PATTERN.matcher(line).matches()) {
try {
result.add(ArticleFactory.getArticle(new UrlWrapper(line)));
} catch (MalformedURLException e) {
LOG.warn(format("Пропускаю некорректную ссылку на статью: %s", line));
}
}
}
return result;
} |
a7904974-a5d3-4ae5-91a8-81c1a3a12288 | 0 | public void setColsCount(int colsCount) {
m_colsCount = colsCount;
fitVectorsToSize();
} |
7a60f639-1fbb-4ed4-a429-c7065743060f | 7 | public void removeRunningTask(Task task) {
for(Task t:taskQueue){
if(t.getJob().getID() == task.getJob().getID() && t.getTaskID() == task.getTaskID()){
if(t instanceof MapperTask &&task instanceof MapperTask)
taskQueue.remove(t);
if(t instanceof ReducerTask &&task instanceof ReducerTask)
taskQueue.remove(t);
}
}
} |
04d7719a-00f3-403a-a45b-dabc1e5f91f6 | 5 | public int getPaintImageIndex(int[][] currentBlockArray, BufferedImage[] images, int x, int z, int xMin, int xMax, boolean bottomLevel) {
int[][] pixels = null;
int i = -1;
int fit = 0;
int count = 0;
do {
i = Rand.getRange(0, images.length-1);
pixels = getImagePixels(images[i]);
fit = paintImageFit(currentBlockArray, pixels, x, z, xMin, xMax, bottomLevel);
count++;
} while(fit < 1 && count <= images.length);
if(fit == 2 && noExitImages.size() < 1 || count > images.length) {
i = -1;
}
//System.out.println("index: "+i+" fit: "+fit);
return i;
} |
c407c5e8-53c6-4d15-8107-8fea42615bbb | 6 | private static String filterToken(String s, int start, int end) {
StringBuffer sb = new StringBuffer();
char c;
boolean gotEscape = false;
boolean gotCR = false;
for (int i = start; i < end; i++) {
c = s.charAt(i);
if (c == '\n' && gotCR) {
// This LF is part of an unescaped
// CRLF sequence (i.e, LWSP). Skip it.
gotCR = false;
continue;
}
gotCR = false;
if (!gotEscape) {
// Previous character was NOT '\'
if (c == '\\') // skip this character
gotEscape = true;
else if (c == '\r') // skip this character
gotCR = true;
else // append this character
sb.append(c);
} else {
// Previous character was '\'. So no need to
// bother with any special processing, just
// append this character
sb.append(c);
gotEscape = false;
}
}
return sb.toString();
} |
b7ad6df5-1b94-4fcc-8eeb-6d1b5fe63263 | 0 | public boolean isEmpth()
{
return queueList.isEmpty();
} |
07e73bc7-491f-4018-ba45-b1af6dcd0e08 | 2 | private List<ProtectionEntry> listAllDependingEntries(ProtectionEntry entry, ConnectionWrapper cw) throws SQLException
{
List<ProtectionEntry> res = dependingCache.get(entry);
if (res==null)
{
res = new ArrayList<ProtectionEntry>();
StringBuilder statement = new StringBuilder(100);
statement.append("SELECT OWNER_TABLE, OWNER_ID FROM ");
statement.append(Defaults.HAS_A_TABLENAME);
statement.append(" WHERE PROPERTY_TABLE = ? AND PROPERTY_ID = ?");
PreparedStatement ps = cw.prepareStatement(statement.toString());
ps.setInt(1, entry.getPropertyTableNameId());
ps.setLong(2, entry.getPropertyId());
Tools.logFine(ps);
try
{
ResultSet rs = ps.executeQuery();
while (rs.next())
{
ProtectionEntry nuEntry = new ProtectionEntry(rs.getInt(1), rs.getLong(2));
res.add(nuEntry);
}
}
finally
{
ps.close();
}
dependingCache.put(entry, res);
}
return res;
} |
e91f26fe-8448-4820-b25a-e18749ab96c6 | 0 | public TransitionExpanderTool(AutomatonPane view, AutomatonDrawer drawer,
ConversionController controller) {
super(view, drawer);
this.controller = controller;
} |
23540b07-08ff-4f03-afe5-a2e14c3a160a | 5 | public boolean hasAlias(String alias) {
if (alias.equalsIgnoreCase(cmdName))
return true;
if (aliases == null || aliases.length == 0)
return false;
for (String s : aliases) {
if (alias.equalsIgnoreCase(s))
return true;
}
return false;
} |
a43bf089-37e9-4515-8748-df415b06db4d | 8 | private void playGame(Player player, Dealer dealer) {
String inputVal = "";
System.out.println(Constants.WELCOME_MESSAGE);
while (true) {
if (player.getNumChips() >= Constants.MIN_BET_CHIPS) {
System.out
.println(Constants.BET_MESSAGE + player.getNumChips());
inputVal = inputScanner.nextLine();
if ((inputVal.length() == 1)
&& (inputVal.charAt(0) == Constants.ACTION_KEY_QUIT))
break;
if (inputVal.equals("")) {
betChips = 1;
} else {
try {
betChips = Float.parseFloat(inputVal);
} catch (NumberFormatException nfe) {
System.out.println("Unrecognized number " + inputVal);
continue;
}
}
// invalid bet amount
if (betChips < Constants.MIN_BET_CHIPS
|| betChips > player.getNumChips()) {
System.out.println("Invalid bet size: " + betChips);
System.out.println("Bet must be between "
+ Constants.MIN_BET_CHIPS + " and "
+ player.getNumChips());
continue;
}
System.out.println("Your bet: " + betChips + " chip(s)\n");
newHand();
playAllHands();
calculateWinnings();
} else {
System.out
.println("\n *** You do not have enough chips to play another round! ***\n");
break;
}
}
inputScanner.close();
} |
004af1dd-10e7-421f-aab9-1fede4a28389 | 8 | private void manageGameStartMessage(int senderID, GameStartMessage msg) {
if (gameServer == null) {
console.displayMessage("Got game start message but game server is null. Dropping message.");
return;
}
for (int i = 0; i < clients.size(); i++) {
if (clients.get(i).getID() == senderID) {
//Client has no game
if (clients.get(i).getCurrentGame() == null) {
clients.get(i).setCurrentGame(msg.getGameName());
console.displayMessage("CLIENT STARTED GAME");
try {
gameServer.addPlayer(clients.get(i));
} catch (GameException ex) {
console.displayMessage(ex.getMessage());
}
//Client has a game but is not running it
} else if (!clients.get(i).isRunningGame()) {
//Second game start message
if (clients.get(i).getCurrentGame().equals(msg.getGameName())) {
clients.get(i).startGame();
console.displayMessage("CLIENT STARTED GAME");
try {
gameServer.addPlayer(clients.get(i));
} catch (GameException ex) {
console.displayMessage(ex.getMessage());
}
//Another game start message
} else {
clients.get(i).setCurrentGame(null);
}
//Client has a game and is running it
} else {
console.displayMessage("Got game start message but client is already running a game.");
}
return;
}
}
console.displayMessage("Did not find client with id '" + senderID + "'.");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.