method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
beea98f0-19fd-445a-9d9a-e365d4d3fe1e | 2 | public static <T extends DC> Set<Pair<T,PT<Integer>>> codom(Set<Pair<Pair<T,PT<Integer>>,Pair<T,PT<Integer>>>> phiMax)
{ if(phiMax!=null)
{ if(phiMax.getNext()!=null)
{ return new Set(phiMax.getFst().snd(),codom(phiMax.getNext()));
}
else
{ return new Set(phiMax.getFst().snd(),null);
}
}
else
{ return null;
}
} |
72446b5f-ad5b-40ed-8dc8-c0b86d93caa9 | 3 | @Override
public boolean sureUzat(int siraID, int saat, int dakika) {
try {
/*
HbmIslemler hbm = new HbmIslemler();
Sira siraBilgisi = (Sira) hbm.bilgiGetir(siraID , this.getClass());
* */
Sira siraBilgisi = siraBul(siraID);
if(siraBilgisi == null)
return false;
saat += Integer.parseInt(siraBilgisi.getBaslangicSaat().split(":")[0]);
dakika += Integer.parseInt(siraBilgisi.getBaslangicSaat().split(":")[1]);
if(dakika > 59){
saat ++;
dakika -= 60;
}
siraBilgisi.setBaslangicSaat(saat + " : " + dakika);
return this.bilgiGuncelle(siraBilgisi, siraID);
} catch (HibernateException e) {
throw e;
}
} |
2e776648-4c5e-475e-9219-1bca5f5bfe0c | 9 | private void parseModuleImport() throws XPathException {
QueryModule thisModule = (QueryModule)env;
Import mImport = new Import();
String prefix = null;
mImport.namespaceURI = null;
mImport.locationURIs = new ArrayList(5);
nextToken();
if (t.currentToken == Token.NAME && t.currentTokenValue.equals("namespace")) {
t.setState(Tokenizer.DEFAULT_STATE);
nextToken();
expect(Token.NAME);
prefix = t.currentTokenValue;
nextToken();
expect(Token.EQUALS);
nextToken();
}
if (t.currentToken == Token.STRING_LITERAL) {
String uri = URILiteral(t.currentTokenValue);
checkProhibitedPrefixes(prefix, uri);
mImport.namespaceURI = uri;
if (mImport.namespaceURI.length() == 0) {
grumble("Imported module namespace cannot be \"\"", "XQST0088");
mImport.namespaceURI = "http://saxon.fallback.namespace/line" + t.getLineNumber(); // for error recovery
}
if (importedModules.contains(mImport.namespaceURI)) {
grumble("Two 'import module' declarations specify the same module namespace", "XQST0047");
}
importedModules.add(mImport.namespaceURI);
((QueryModule)env).addImportedNamespace(mImport.namespaceURI);
nextToken();
if (isKeyword("at")) {
do {
nextToken();
expect(Token.STRING_LITERAL);
mImport.locationURIs.add(URILiteral(t.currentTokenValue));
nextToken();
} while (t.currentToken == Token.COMMA);
}
} else {
grumble("After 'import module', expected 'namespace' or a string-literal");
}
if (prefix != null) {
try {
thisModule.declarePrologNamespace(prefix, mImport.namespaceURI);
} catch (XPathException err) {
err.setLocator(makeLocator());
reportError(err);
}
}
// // Check that this import would not create a cycle involving a change of namespace
// if (!disableCycleChecks) {
// if (!mImport.namespaceURI.equals(((QueryModule)env).getModuleNamespace())) {
// QueryModule parent = (QueryModule)env;
// if (!parent.mayImport(mImport.namespaceURI)) {
// StaticError err = new StaticError("A module cannot import itself directly or indirectly, unless all modules in the cycle are in the same namespace");
// err.setErrorCode("XQST0073");
// throw err;
// }
// }
// }
moduleImports.add(mImport);
} |
80521a19-103e-46be-a4a3-a969b75ab62f | 1 | public void dumpInstruction(TabbedPrintWriter writer)
throws java.io.IOException {
/*
* Only print the comment if jump null, since otherwise the block isn't
* completely empty ;-)
*/
if (jump == null)
writer.println("/* empty */");
} |
1f058e7a-bf5d-4315-ae2b-b1a9f6e2076e | 6 | public void addCategory(Category c) {
Connection conn = null;
PreparedStatement ps = null;
//Do nothing if category is not properly instantiated
if(c == null)
return;
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
//Insert attributes from category into table
if(c.getIdNumber() != null) {
ps = conn.prepareStatement("INSERT INTO Category(idNumber,name,superCategoryId) VALUES(?,?,?)");
ps.setInt(1, c.getIdNumber());
ps.setString(2, c.getName());
ps.setObject(3, c.getSuperCategoryId());
} else {
ps = conn.prepareStatement("INSERT INTO Category(idNumber,name,superCategoryId) VALUES(?,?)");
ps.setString(1, c.getName());
ps.setInt(2, c.getSuperCategoryId());
}
ps.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
try {
if(conn != null)
conn.close();
if(ps != null)
ps.close();
} catch (Exception e) { }
}
} |
e14df306-4961-4e8f-a698-765220c4dcb0 | 1 | public void info(String message)
{
if (this.logLevel >= Logger.INFO)
{
log(" INFO ", message);
}
} |
e3ec6da2-1fbd-44ee-9df6-5c1ccbcdfa36 | 5 | private void button4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button4MouseClicked
if(numberofpins < 4)
{
if(numberofpins == 0)
{
Login_form.setString1("0");
}
if(numberofpins == 1)
{
Login_form.setString2("0");
}
if(numberofpins == 2)
{
Login_form.setString3("0");
}
if(numberofpins == 3)
{
Login_form.setString4("0");
}
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_button4MouseClicked |
4fcaecce-3ef0-4c4f-8a27-32a7d12a055a | 2 | public Tiedote validateID() throws ValidointiPoikkeus {
// luodaan wrapper virheiden kuljettamista varten
ValidointiVirheet virheet = new ValidointiVirheet();
// luodaan validoija
Validator validoija = new Validator();
Tiedote tiedote = new Tiedote();
// tiedoteID:n validointi
if (validoija.validateInt(this.tiedoteId, "id", "Id-numero", true,
false)) {
System.out.println(tiedoteId);
tiedote.setTiedoteId(Integer.parseInt(tiedoteId));
}
// kutsutaan virhe Map jos virheitä on ja lähetetään ne poikkeusluokalle
if (validoija.getVirheet().size() > 0) {
virheet = validoija.getVirheet();
throw new ValidointiPoikkeus(virheet);
} else {
return tiedote;
}
} |
dd161ad5-1d79-43f1-9507-6c38f9755ddd | 0 | public void setCbLabo(JComboBox cbLabo) {
this.jComboBoxLabo = cbLabo;
} |
d017fe10-6b73-460c-8339-a4c266c2a966 | 1 | private Item Itemvalidate(Item item){
if(!paidTransaction(Accesscreate(),item) )
return null;
return item;
} |
4792e533-3fd5-4317-8863-82001528890a | 4 | private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
if((!txtFrnd.getText().equals(""))){
try {
String frnIP = database.getFrndIp(txtFrnd.getText());
switch(chat.getFriend(frnIP, txtFrnd.getText())){
case "yes":
chat.setVisible(true);
this.setVisible(false);
break;
case "no":
JOptionPane.showMessageDialog(this, "Not Available!");
break;
default:
txtFrnd.setText("");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "User doesn't exist");
}
}
}//GEN-LAST:event_btnConnectActionPerformed |
91032de6-bd88-4db0-a30e-202641b836c7 | 7 | private void transcribeVerticesAndTriangles(HashMap<Integer, MarchingCubes.Node3f> vertexMap, ArrayList<MarchingCubes.Triangle> triangleList)
{
int idIter = 0;
Iterator<Entry<Integer, MarchingCubes.Node3f>> mapIterator = vertexMap.entrySet().iterator();
Entry<Integer, MarchingCubes.Node3f> currentEntry;
Iterator<MarchingCubes.Triangle> vecIterator = triangleList.iterator();
MarchingCubes.Triangle currentTri;
// Rename vertices.
while(mapIterator.hasNext())
{
currentEntry = mapIterator.next();
currentEntry.getValue().id = idIter;
idIter++;
}
// Now rename triangles.
while(vecIterator.hasNext())
{
currentTri = vecIterator.next();
currentTri.n0 = vertexMap.get(currentTri.n0).id;
currentTri.n1 = vertexMap.get(currentTri.n1).id;
currentTri.n2 = vertexMap.get(currentTri.n2).id;
}
// Copy all the vertices and triangles into two arrays so that they
// can be efficiently accessed.
// Copy vertices.
mapIterator = vertexMap.entrySet().iterator();
vertices = new Point3f[vertexMap.size()];
for(int i = 0; i < vertices.length; i++)
{
currentEntry = mapIterator.next();
vertices[i] = new Point3f( currentEntry.getValue().x + offs[0],
currentEntry.getValue().y + offs[1],
currentEntry.getValue().z + offs[2]);
}
// Copy vertex indices which make triangles.
vecIterator = triangleList.iterator();
triangles = new int[triangleList.size() * 3];
for(int i = 0; i < triangles.length; i += 3)
{
currentTri = vecIterator.next();
currentTri.copyTo(i, triangles);
}
// Calculate normals.
Vector3f vec1 = new Vector3f();
Vector3f vec2 = new Vector3f();
Vector3f normal = new Vector3f();
int id0;
int id1;
int id2;
normals = new Vector3f[vertices.length];
// Set all normals to 0.
for(int i = 0; i < normals.length; i++)
{
normals[i] = new Vector3f(0, 0, 0);
}
// Calculate normals.
for(int i = 0; i < triangles.length; i += 3)
{
id0 = triangles[i];
id1 = triangles[i + 1];
id2 = triangles[i + 2];
vec1.sub(vertices[id1], vertices[id0]);
vec2.sub(vertices[id2], vertices[id0]);
normal.cross(vec2, vec1);
normals[id0].add(normal);
normals[id1].add(normal);
normals[id2].add(normal);
}
// Normalize normals.
for(int i = 0; i < normals.length; i++)
{
normals[i].normalize();
}
} |
25caf6f5-c1b4-44f1-8036-831daf59c2b4 | 4 | private void findPathes() {
if(MAZE.getHeight() == 0 || MAZE.getWidth() == 0 || !MAZE.isRoad(0, 0)){
log("No pathes");
return;
}
List<List<? extends Point>> pathes = findPathesRecursive();
log("Found: " + pathes);
log("Count: " + pathes.size());
} |
49b55398-b6f9-4efe-b072-319662da1b11 | 3 | private void removeMobs(){
for(ListIterator<Mob> i = mobs.listIterator(); i.hasNext();){
Mob mob = i.next();
if(mob.isDead()){
((HostileMob)mob).getSpawner().remove(1);
i.remove();
for(int j = 0; j < 5; j++) addParticle(new BloodParticle(getParticles().size(), mob.getX(), mob.getY(), 0xff6E2120, 8, 1.1, this, random));
items.add(new Gold(items.size(), mob.getX(), mob.getY(), mob.getInventory().getGold(), this, random));
getPlayer().addScore(mob.getScore());
continue;
}
}
} |
da645981-b713-4839-8f37-83c59f06a51d | 2 | @Override
public void run() // read server messages and act on them.
{
try {
DatagramSocket socket = new DatagramSocket(udpPort);
serverReceiveThread = new ServerReceiveThread(registry, gameController, socket, udpPort);
serverReceiveThread.start();
} catch (IOException e) {
gameController.showMessage("Error", "Couldn't accept connection...");
return;
}
doServer();
if (serverReceiveThread != null) {
serverReceiveThread.setRunning(false);
}
return;
} |
d6f668fd-5544-474c-bb57-0027e6a25f75 | 2 | private boolean ifStatement()
{
if (accept(NonTerminal.IF_STATEMENT))
{
enterScope();
expression0();
statementBlock();
if (accept(Token.Kind.ELSE))
{
statementBlock();
}
exitScope();
}
return false;
} |
8a58dbdb-510b-4555-bab4-2dcc63d6829c | 1 | public static synchronized SkiPassSystem getInstance() {
if (instance == null) {
instance = new SkiPassSystem();
}
return instance;
} |
7210af3e-09c2-46de-9f65-a004319db871 | 1 | @Override
public void run() {
while(true){
repaint();
}
} |
29ddffaa-3ae1-4963-85c5-7189b77ff082 | 7 | public int maxSubArray(int[] A) {
int max = 0;
int NegetiveMax = Integer.MIN_VALUE;
int len = A.length;
boolean allNegetive = true;
for(int i=0;i<len;i++) {
if(A[i] > 0) {
allNegetive = false;
} else {
if(A[i] > NegetiveMax) {
NegetiveMax = A[i];
}
}
}
if(allNegetive) {
return NegetiveMax;
} else {
int tmpSum = 0;
for(int i=0;i<len;i++) {
tmpSum = tmpSum + A[i];
if(tmpSum <= 0) {
tmpSum = 0;
} else {
if(tmpSum > max) {
max = tmpSum;
}
}
}
return max;
}
} |
00d1a50e-4357-40e2-83de-514bfbc9098d | 7 | private List<Pregunta> corregirExamen(HttpServletRequest request, HttpServletResponse response) {
List<Pregunta> questList = new ArrayList<Pregunta>();
String listId = request.getParameter("listId");
String[] ids = listId.split(",");
for (int i = 0; i < ids.length; i++) {
int id = Integer.parseInt(ids[i]);
Pregunta p = PreguntaDAO.buscaID(id);
questList.add(p);
}
List<Integer> respuestas = respuestasExamen(request, response, questList);
int buenas = 0, sinContestar = 0, fallidas = 0;
for (int i = 0; i < respuestas.size(); i++) {
if (questList.get(i).getRespuestaCorrecta() == respuestas.get(i)) {
buenas++;
} else if (respuestas.get(i) == -1) {
sinContestar++;
} else {
fallidas++;
}
}
request.setAttribute("fallidas", fallidas);
request.setAttribute("buenas", buenas);
request.setAttribute("sin", sinContestar);
request.setAttribute("corregir", true);
HttpSession session = request.getSession();
Usuario user = (Usuario) session.getAttribute("currentUser");
ResultadoExamen resultado = new ResultadoExamen(buenas, fallidas, sinContestar, user.getDni());
ResultadoExamenDAO.insertaResultadoExamen(resultado);
for (int i = 0; i < respuestas.size(); i++) {
ResultadoPregunta r = new ResultadoPregunta();
r.setExamen(ResultadoExamenDAO.ultimo());
r.setPregunta(questList.get(i).getId());
if (questList.get(i).getRespuestaCorrecta() == respuestas.get(i)) {
r.setResultado(0);
} else if (respuestas.get(i) == -1) {
r.setResultado(2);
} else {
r.setResultado(1);
}
ResultadoPreguntaDAO.insertaResultadoPregunta(r);
}
return questList;
} |
ae44aeec-a59b-4e97-b775-b67d26135092 | 9 | public String toString() {
// Number of items in each list to print
int n = 10;
String output = "The word list ";
output += isPruned ? "has been pruned:" : "has not been pruned:";
if (isPruned) {
output += "\n\tPruned word list: (showing first " + n + " items for each word length)";
for (Integer key : prunedWordList.keySet()) {
ArrayList<String> dictionarySubgroup = prunedWordList.get(key);
output += "\n\t\t";
output += key;
output += " [";
// Print first n elements of each dictionary subgroup
for (int i = 0; i < n; i++) {
output += dictionarySubgroup.get(i);
output += i < (n - 1) ? ", " : "";
}
output += (n < dictionarySubgroup.size()) ? ", ..." : "";
output += "]";
}
}
output += "\n\tFull word list: (showing first " + n + " items)";
output += "\n\t\t";
output += "[";
for (int i = 0; i < n; i++) {
output += wordList.get(i);
output += i < (n - 1) ? ", " : "";
}
output += (n < wordList.size()) ? ", ..." : "";
output += "]";
return output;
} |
8b921246-f9c0-48cf-b651-0cfa68445362 | 7 | @Override
public Feature[] analyze(String hpId, String mpId) {
String[] hpSyns = OntologyLoader.getHPSynonyms(hpId);
if(hpSyns.length == 0) return null;
String[] mpSyns = OntologyLoader.getMPSynonyms(mpId);
if(mpSyns.length == 0) return null;
int count = 0;
for(String hpSyn: hpSyns){
for(String mpSyn: mpSyns){
double score = SoftTFIDFBuilder.getIntance().score(hpSyn, mpSyn);
if(score >= THRESHOLD) count++;
}
}
if(count >= 2) return new Feature[]{new Feature(PREFIX_FEATURE + ":high")};
else if(count >= 1) return new Feature[]{new Feature(PREFIX_FEATURE + ":normal")};
else return new Feature[]{new Feature(PREFIX_FEATURE + ":none")};
} |
9428c5a4-4a49-46d8-b29e-777a62478b4b | 8 | public static Stella_Object access_PLProposition_Slot_Value(PLProposition self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == GuiServer.SYM_GUI_SERVER_PropositionName) {
if (setvalueP) {
self.PropositionName = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.PropositionName);
}
}
else if (slotname == GuiServer.SYM_GUI_SERVER_IsStrict) {
if (setvalueP) {
self.IsStrict = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.IsStrict);
}
}
else if (slotname == GuiServer.SYM_GUI_SERVER_IsAsserted) {
if (setvalueP) {
self.IsAsserted = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.IsAsserted);
}
}
else if (slotname == GuiServer.SYM_GUI_SERVER_IsRule) {
if (setvalueP) {
self.IsRule = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.IsRule);
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} |
cc2bc374-acfe-4de7-a764-61e6a036a330 | 7 | public int maxDepth(treeNode root) {
if (root == null)
return 0;
if (root.leftLeaf == null && root.rightLeaf == null)
return 1;
if (root.leftLeaf != null && root.rightLeaf != null) {
int maxLeft = maxDepth(root.leftLeaf);
int maxRight = maxDepth(root.rightLeaf);
return maxLeft <= maxRight ? (maxRight + 1) : (maxLeft + 1);
}
// rightLeaf only
if (root.leftLeaf == null) {
return maxDepth(root.rightLeaf) + 1;
} else {// leftLeaf only
return maxDepth(root.leftLeaf) + 1;
}
} |
87e09ba9-7685-4577-bcc7-8e7a4010355d | 6 | private void enableType(int type) {
bitsLbl.setEnabled(false);
arrayLbl.setEnabled(false);
enumLbl.setEnabled(false);
typeType.setEnabled(false);
array.setEnabled(false);
enumData.setEnabled(false);
switch (type) {
case TYPE_DISABLE:
break;
case TYPE_ARRAY: {
typeType.setEnabled(true);
arrayLbl.setEnabled(true);
array.setEnabled(true);
}
case TYPE_NONE: {
typeType.setEnabled(true);
if (typeType.getSelectedItem().equals(Type.INT)) {
bitsLbl.setEnabled(true);
bits.setEnabled(true);
} else {
bitsLbl.setEnabled(false);
bits.setEnabled(false);
}
break;
}
case TYPE_ENUM: {
enumData.setEnabled(true);
enumLbl.setEnabled(true);
break;
}
case TYPE_STRUCT:
break;
}
} |
1fc7d402-6ba7-4aff-b6a4-1ce2826fecb7 | 4 | protected Map<String, Long> writeFileList(String destination, long offset) {
Map<String, Long> filePathMap = new HashMap<String, Long>();
String innerPath, rawPath;
VDKRandomAccessFile raf = null;
try {
raf = new VDKRandomAccessFile(destination, "rw");
for(VDKInnerDirectory d : getChildren()) {
rawPath = destination.substring(0, destination.lastIndexOf("."));
innerPath = d.getSourcePath().substring(rawPath.length()+ 1);
filePathMap.put(innerPath, d.getOffset());
raf.writeString(innerPath, offset, VDK1FilePattern.FILE_PATH);
raf.writeUnsignedInt(d.getOffset(), offset, VDK1FilePattern.FILE_OFFSET);
if(!(d instanceof VDKInnerFile))
filePathMap.putAll(d.writeFileList(destination, offset));
offset += VDK1FilePattern.getPathNameBlockLength();
}
raf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return filePathMap;
} |
81c4b012-9bb1-406d-857e-43e8c13df64e | 2 | public void checkDialogs() {
if(dialogQueue.size() > 0) {
inputEnabled = false;
currentDialogBox = dialogQueue.remove();
} else {
inputEnabled = true;
currentDialogBox = null;
if(dialogCallback != null) {
dialogCallback.onClose();
}
}
} |
b403ed92-05e0-4fd9-a36e-d54ac184a74f | 1 | private static String addHTMLFontColor(final String text, final boolean isExceptional) {
return "<html><body><font color=" + (isExceptional ? "red" : "green") + ">" + text + "</font></body></html>";
} |
62532eca-d4ff-4771-82c9-199a05d30c19 | 7 | protected static Ptg calcRoundDown( Ptg[] operands ) throws CalculationException
{
if( operands.length < 1 )
{
return PtgCalculator.getNAError();
}
double[] dd = PtgCalculator.getDoubleValueArray( operands );
if( dd == null )
{
return new PtgErr( PtgErr.ERROR_NA );//20090130 KSC: propagate error
}
//if (dd.length != 2) return PtgCalculator.getError();
double num = dd[0];
double round = dd[dd.length - 1];
double res = 0;
if( round == 0 )
{//return an int
res = Math.round( num );
if( res > num )
{
res--;
}
}
else if( round > 0 )
{ //round the decimal that number of spaces
double tempnum = num * Math.pow( 10, round );
double tempnum2 = Math.round( tempnum );
if( tempnum2 > tempnum )
{
tempnum2--;
}
res = tempnum2 / Math.pow( 10, round );
}
else
{ //round up the decimal that numbe of places
round = round * -1;
double tempnum = num / Math.pow( 10, round );
double tempnum2 = Math.round( tempnum );
if( tempnum2 > tempnum )
{
tempnum2--;
}
res = tempnum2 * Math.pow( 10, round );
}
PtgNumber ptnum = new PtgNumber( res );
return ptnum;
} |
1b7025ad-ffe1-40ea-a856-0471fa4e3962 | 5 | public void dispose()
{
if (disposed)
return;
disposed = true;
charCache = null;
bufferPixels = null;
fontMetrics = null;
Graphics2D gfx = bufferGraphics;
if (gfx != null)
{
bufferGraphics = null;
try
{
gfx.dispose();
}
catch (Exception ex) { }
}
BufferedImage img = buffer;
if (img != null)
{
buffer = null;
try
{
img.flush();
}
catch (Exception ex) { }
}
} |
ecb31cbb-56c2-44b7-8545-c5fc9e96fa87 | 7 | public List<Employee> getTeamMembers(String managerId) {
String uniqueUserSql = SELECT_MANAGER_TEAM_DETAIL + managerId + "'";
Connection connection = new DbConnection().getConnection();
List<Employee> teamMembers = new ArrayList<Employee>();
ResultSet resultSet = null;
Statement statement = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(uniqueUserSql);
while (resultSet.next()) {
Employee employee = new Employee();
String employeeName = resultSet.getString("employee_name");
String employeeId = resultSet.getString("employee_id");
String email_id = resultSet.getString("email_id");
String designation = resultSet.getString("designation");
String manager_id = resultSet.getString("manager_id");
int deptt = resultSet.getInt("department");
employee.setDesignation(designation);
employee.setEmailId(email_id);
employee.setManagerId((manager_id));
employee.setEmployeeName(employeeName);
employee.setEmployeeId(employeeId);
employee.setDepartment(deptt);
if (!employee.getEmployeeId().equals(manager_id))
teamMembers.add(employee);
}
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
} finally {
try {
if (connection != null)
connection.close();
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
} catch (SQLException e) {
m_logger.error(e.getMessage(), e);
}
}
return teamMembers;
} |
ef4138ce-ef30-4e37-8961-ae3bc188643a | 1 | public void visit_iflt(final Instruction inst) {
stackHeight -= 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
} |
efba9bde-73e7-4bd4-9aa1-467c410dff96 | 8 | public void endRound() {
int winnersInd = 0;
numberOfRounds++;
cardsPlayedInRound = 0;
ItalianDeckCard winnersCard = currentStack[winnersInd];
int score = 0;
for (int i = 0; i < currentStack.length; i++) {
int comp = BriscaCardComparator.compare(winnersCard,
currentStack[i], this.life.getSuit());
if (comp > 0) {
winnersCard = currentStack[i];
winnersInd = i;
} else if (comp == 0) {
// TODO get players turns
}
score += currentStack[i].getRank().getValue();
}
int count = 0;
for (ItalianDeckCard card : playerStacks[winnersInd]) {
if (card == null)
break;
count++;
}
for (ItalianDeckCard card : currentStack)
playerStacks[winnersInd][count++] = card;
players[winnersInd].addScore(score);
// TODO END ROUND
// Set the player turns for next round to the right of the
// winner
for (int i = 0; i < turns.length; i++) {
int value = (i + winnersInd) % 4 + 1;
turns[i] = value;
}
isRoundOver = false;
if (numberOfRounds == MAX_NUMBER_OF_ROUNDS) {
isGameOver = true;
//TODO get winner
}
} |
6186c072-2351-457f-a665-c24db70507c2 | 4 | @Test
public void testTargetsAlongWalkways() {
// Initialize lists of where everything should be.
int[] targets4 = new int[] {307, 331, 333, 357, 381, 383, 405, 403, 429, 431, 455, 481, 457, 507, 483, 433, 409, 385, 411};
int[] targets3 = new int[] {190, 216, 242, 268, 196, 220, 170, 144, 118, 192, 168, 194, 218};
int[] targets2 = new int[] {204, 180, 156, 182, 208, 232, 256, 230};
int[] targets1 = new int[] {317, 341, 343, 367};
board.startTargets(13, 17, 1);
Set<BoardCell> actual1 = board.getTargets();
Assert.assertTrue(actual1.size() == targets1.length);
for(int i: targets1) {
Assert.assertTrue(actual1.contains(board.getCellAt(i)));
}
board.startTargets(16, 7, 4);
Set<BoardCell> actual4 = board.getTargets();
Assert.assertTrue(actual4.size() == targets4.length);
for(int i: targets4) {
Assert.assertTrue(actual4.contains(board.getCellAt(i)));
}
board.startTargets(7, 18, 3);
Set<BoardCell>actual3 = board.getTargets();
Assert.assertTrue(actual3.size() == targets3.length);
for(int i: targets3) {
Assert.assertTrue(actual3.contains(board.getCellAt(i)));
}
board.startTargets(8, 6, 2);
Set<BoardCell> actual2 = board.getTargets();
Assert.assertTrue(actual2.size() == targets2.length);
for(int i: targets2) {
Assert.assertTrue(actual2.contains(board.getCellAt(i)));
}
} |
0bcfb672-8749-4c99-b7e2-7f0a3f6c5151 | 8 | public void run()
{
try
{
// Wrapper for Threaded calling
System.out.println(this.clsName+","+this.mtdName);
Class<?> cls = Class.forName(this.clsName);
System.out.println("Class is "+cls);
Method[] mtds = cls.getMethods();
System.out.println("Methods are "+Arrays.deepToString(mtds));
Method mtd = cls.getMethod(this.mtdName);
System.out.println("mtd is "+mtd);
mtd.invoke(cls.newInstance(),null);
//Runnable - Adding implementation methods on initialisation
//Extends Thread - Adding implementation by overriding certain methods
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
} |
aef6512b-cb19-41e2-9e91-7468431a369f | 7 | private boolean isIdentifier(char c)
{
return (c > 47 && c < 58) // Zahl
|| (c > 64 && c < 91) // Groß A-Z
|| (c > 96 && c < 123) // Klein a-z
|| (c == '_') || (c == '$'); // Sonderzeichen
} |
03c555b3-1358-44ab-8350-b8881a31c4ff | 3 | public void setFullNameFromTextField(String fullName) {
String[] nameParts = fullName.split(" ");
if (nameParts.length > 0) {
Name.getInstance().setFirstName(nameParts[0]);
if (nameParts.length > 1) {
Name.getInstance().setMiddleName(nameParts[1]);
for (int index = 2; index < nameParts.length; index++) {
Name.getInstance()
.setLastName(
Name.getInstance().getLastName()
+ nameParts[index]);
}
}
}
} |
45d719a7-f549-4ada-b7a9-0a1342372f70 | 6 | @RequestMapping("/home")
public ModelAndView home(HttpServletRequest request) {
HttpSession session = request.getSession();
String currRole = session.getAttribute("currRole").toString();
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
if(currRole.equals("student"))
{
System.out.println("Student role");
ModelAndView mv = new ModelAndView("homepageStudent");
StudentsRegistrationDAO studentRegistrationDAO = ctx.getBean("studentsRegistrationDAO", StudentsRegistrationDAO.class);
List<StudentRegistration> registeredCourseId = studentRegistrationDAO.getRegisteredCoursesForId(session.getAttribute("currEmail").toString());
courseDAO courseD = ctx.getBean("courseDAO", courseDAO.class);
List<CourseGrade> registeredCourses = new ArrayList<CourseGrade>();
for(StudentRegistration sr:registeredCourseId ){
CourseGrade courseGrades = new CourseGrade();
Course courseInfo = courseD.getCourse(sr.getCourseID());
courseGrades.setCourseId(courseInfo.getCourseId());
courseGrades.setCourseName(courseInfo.getCourseName());
courseGrades.setCourseCategory(courseInfo.getCourseCategory());
courseGrades.setGrades(sr.getGrades());
registeredCourses.add(courseGrades);
}
mv.addObject("coursesList", registeredCourses);
System.out.println("Added object courseList");
return mv;
}
else if(currRole.equals("content manager")){
System.out.println("CM role");
ModelAndView mv = new ModelAndView("homepageCM");
return mv;
}
else {
System.out.println("Admin role");
ModelAndView mv = new ModelAndView("homepageAdmin");
ClassPathXmlApplicationContext obj = new ClassPathXmlApplicationContext("spring-config.xml");
UserDAO usersDAO = obj.getBean("userDAO", UserDAO.class);
List<User> studentList = usersDAO.getAllUsers();
List<User> cmList = new ArrayList<User>();
for (ListIterator<User> iter = studentList.listIterator(); iter.hasNext(); ) {
User element = iter.next();
if(element.getRole().equals("content manager"))
{
cmList.add(element);
iter.remove();
}
else if(element.getRole().equals("admin"))
{
iter.remove();
}
}
System.out.println(studentList.size() + " content managers");
System.out.println(cmList.size() + " students");
mv.addObject("studentList", studentList);
mv.addObject("cmList", cmList);
return mv;
}
//System.out.println("From session: " + session.getAttribute("currRole"));
} |
972b380b-4fea-49bb-9c9c-3ea1874f7897 | 5 | @Test
public void canDetermineTheCellFitnessOfAGrid() {
for (int sudokuPower = 1; sudokuPower < 10; sudokuPower++) {
// all cells are valid but the first one
for (int cellIndexX = 0, size = sudoku.getSudokuSize(); cellIndexX < size; cellIndexX++) {
for (int cellIndexY = 0; cellIndexY < size; cellIndexY++) {
if (cellIndexX == 0 && cellIndexY == 0)
continue;
sudoku.randomizeCell(cellIndexX, cellIndexY);
}
}
assertThat(sudoku.determineCellFitness()).isEqualTo((sudoku.getGridLength() - 1f) / sudoku.getGridLength());
}
} |
396481f6-efcf-4743-8589-6f0dcfca050f | 0 | public void setId(int id)
{
this.id = id;
} |
529029ca-8a19-49d1-b29d-74d827afeb33 | 6 | public void update() {
checkMove();
if (x == targetX)
xa = 0;
if (y == targetY)
ya = 0;
move(xa, ya);
if ((x <= targetX + 5 && x >= targetX - 5) && (y <= targetY + 5 && y >= targetY - 5)) {
checkHit();
this.removed = true;
}
} |
5a7cf991-89a0-4c04-a923-6c9990255f22 | 7 | public ArrayList<ArrayList<Move>> parseOpenings(){
ArrayList<ArrayList<Move>> allOpeningMoves = new ArrayList<ArrayList<Move>>();
List<PGNGame> games = null;
BufferedReader reader = null;
String pgn = "";
try {
reader = new BufferedReader(new FileReader(db));
int j = 0;
StringBuilder sb = new StringBuilder();
//50007
//120
while(reader.ready() && j<50007){
j++;
String line = reader.readLine();
sb.append(line+"\n");
}
pgn = sb.toString();
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
games = PGNParser.parse(pgn);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(PGNGame game: games){
Iterator<PGNMove> iterator = game.getMovesIterator();
ArrayList<Move> moves = new ArrayList<Move>();
int i = 0;
while(iterator.hasNext() && i<OPENINGMOVES){
i++;
PGNMove pgnmove = iterator.next();
Move move = parseMove(pgnmove);
moves.add(move);
}
allOpeningMoves.add(moves);
}
return allOpeningMoves;
} |
2f7e8976-454c-49db-bc7a-29af38e155fe | 8 | public double evaluateSolution(String solutionFileName) {
double score = 0.0;
BufferedReader br = null;
ArrayList<Double> locations = new ArrayList<Double>();
ArrayList<Boolean> validity = new ArrayList<Boolean>();
ArrayList<Boolean> flips = new ArrayList<Boolean>();
try {
br = new BufferedReader(new FileReader(solutionFileName));
String line = null;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber == 1) {
for(String splitLocation:line.split(" ")) {
double splitLoc = Double.parseDouble(splitLocation);
locations.add(splitLoc);
}
}
else {
String [] values = line.split(" ");
Boolean isTarget = (Integer.parseInt(values[0]) == 1) ? true : false;
Boolean isFlipped = false;
if(isTarget) {
isFlipped = (Integer.parseInt(values[1]) == 1) ? true : false;
}
moleculeValidity.add(isTarget);
flipList.add(isFlipped);
}
}
br.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
score += calculateFP(locations);
score += calculateFN(locations);
score += calculateHammingDistance(validity,flips);
return score;
} |
f26116a8-6322-448b-b16d-408e9bccae4f | 1 | public void setPos5(int val){ if (val == 1){p5 = true;} else { p5 = false; }} |
34d18240-d179-4625-b46a-3f9d2cc8f35b | 4 | public static String formatSceond(long second) {
long time = second / 1000;
if(time < 86400 && time >= 3600 ) {
long h = time / 3600;
long m = (time - (h * 3600)) / 60;
long s = time - h * 3600 - m * 60;
return h + "时" + m + "分" + s + "秒";
}
if(time < 3600 && time >= 60) {
long m = time / 60;
long s = time - m * 60;
return m + "分" + s + "秒";
}
return (double) second / 1000 + "秒";
} |
9ee40674-f04d-4bbc-8811-3524b1552ccc | 1 | private static boolean createUser(){
Prints.printWithColor("YELLOW","Usuario: ");
String user = rd.next();
if (searchUser(user) == null){
Prints.printWithColor("YELLOW","Contraseña: ");
String pass = rd.next();
Prints.printWithColor("YELLOW","Nombre Completo (Sin Espacios): ");
String nombre = rd.next();
Prints.printWithColor("YELLOW","Fecha Nacimiento (dd/mm/yy/): ");
String fecha = rd.next();
}else
Prints.printlnWithColor("RED","Usuario ya Existe\n");
return false;
} |
04e381b3-353d-462a-ba87-28a609929c14 | 4 | private static void rotateBilinear(int dd) {
ImageData imageData = original.getImageData();
int[][] matrix = new int[imageData.height][imageData.width];
for (int i = 0; i < imageData.height; i++) {
for (int j = 0; j < imageData.width; j++) {
matrix[i][j] = imageData.getPixel(j, i);
}
}
int[] pixels = ImageUtils.two2one(matrix);
int iw = imageData.width;
int ih = imageData.height;
int owh = (int) Math.sqrt(iw * iw + ih * ih);
int[] rotated = GT.rotate2Bilinear(pixels, dd, iw, ih, owh);
imageData = new ImageData(owh, owh, 8, imageData.palette);
int[][] rotatedMatrix = ImageUtils.one2two(rotated, owh, owh);
for (int i = 0; i < owh; i++) {
for (int j = 0; j < owh; j++) {
imageData.setPixel(j, i, rotatedMatrix[i][j]);
}
}
rotateBilinear = new Image(original.getDevice(), imageData);
rotateBilinearHisto = ImageUtils.analyzeHistogram(rotateBilinear.getImageData());
} |
373dd5fe-ca46-4073-bb1a-92bcba3c27a3 | 2 | private Vehicule rechercherVehicule(String immatriculation){
System.out.println("ModeleLocations::rechercherVehicule()") ;
Vehicule vehicule = null ;
for(Vehicule unVehicule : this.vehicules){
if(unVehicule.getImmatriculation().equals(immatriculation)){
vehicule = unVehicule ;
}
}
return vehicule ;
} |
4b51940c-c944-47d5-8682-488a4f3fd937 | 0 | public DocumentInfo getDocumentInfo() {
return this.docInfo;
} |
0321ab09-4ea6-41de-88db-fbeb884555cf | 9 | private void printData(Items providers){
for(Item provider : providers.getCloudProviders()){
System.out.println("PROVIDER: "+ provider.getName());
System.out.println(" - Category: "+ provider.getCategory());
System.out.println(" - license: "+ provider.getLicense());
System.out.println(" - monitoring: "+ provider.getMonitoring());
System.out.println(" - availability: "+ provider.getAvailability());
System.out.println(" - load_balancing: "+ provider.getLoad_balancing());
System.out.println(" - autoscaling: "+ provider.getAutoscaling());
System.out.println(" - logo: "+ provider.getLogo());
System.out.println(" - provider_url: "+ provider.getProvider_url());
System.out.println(" - control_Interface: ");
if (provider.getControl_Interface() != null){
for(String s : provider.getControl_Interface().getValue()){
System.out.println(" - "+ s);
}
}
System.out.println(" - languages: ");
if (provider.getLanguages() != null){
for(String s : provider.getLanguages().getValue()){
System.out.println(" - "+ s);
}
}
System.out.println(" - support_features: ");
if (provider.getSupport_features() != null){
for(String s : provider.getSupport_features().getValue()){
System.out.println(" - "+ s);
}
}
System.out.println(" - free_security_features: ");
if (provider.getFree_security_features() != null){
for(String s : provider.getFree_security_features().getValue()){
System.out.println(" - "+ s);
}
}
System.out.println("______________#########____________");
}
System.out.println("STATS:");
System.out.println("Number of Providers Imported: "+ providers.getCloudProviders().size());
} |
a72ca6b2-f445-4661-b0a1-40d7889beb10 | 1 | public void merge(List<String> inputFileNames, String fileNameDestination) {
try {
xmlWriter.write(xmlReader.read(inputFileNames), fileNameDestination);
} catch (IOException e) {
logger.error("error occurred during merge", e);
}
} |
76e8f535-d305-4145-9379-ac226e52eed8 | 1 | @Override
public String toString() {
StringBuilder res = new StringBuilder();
for (Map.Entry e : stats.entrySet()){
res.append("<");
res.append(e.getKey());
res.append(" = ");
res.append(e.getValue());
res.append(">");
}
return res.toString();
} |
13c1c746-197a-41ec-802e-54b7ea45d66d | 6 | public GUI(){
JPanel panel = new JPanel();
JFrame _frame = new JFrame();
Board _board = new Board();
JTextArea _box = new JTextArea("Player 1 :"+" Score: "+" Player 2: "+" Score: ");
JPanel board = new JPanel();
board.setLayout(new GridLayout(20,20));
panel.setLayout(new BorderLayout());
_frame.getContentPane().setLayout(new BorderLayout());
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (! ((i < _board.getNullColms() && j > (19 - _board.getNullRows())) || (i > (19 - _board.getNullColms()) && j < _board.getNullRows()))) {
ImageIcon image = new ImageIcon("Description/Tile.png");
JLabel jLabel = new JLabel(image);
board.add(jLabel);
} else {
board.add(new JLabel(" _"));
}
}
}
panel.add(_box,"Center");
_frame.add(panel,"North");
_frame.add(board,"Center");
_frame.setVisible(true);
_frame.setTitle("Scrabble");
_frame.pack();
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_frame.setLocation(_board.randomLocations(),_board.randomLocations());
_frame.setResizable(false);
} |
3a7f6963-0f62-4d21-a85f-b1d22fda8f8c | 4 | public int compareTo(Object other)
{
Location otherLoc = (Location) other;
if (getRow() < otherLoc.getRow())
return -1;
if (getRow() > otherLoc.getRow())
return 1;
if (getCol() < otherLoc.getCol())
return -1;
if (getCol() > otherLoc.getCol())
return 1;
return 0;
} |
ffaea2c1-4c83-4e53-a67e-dff94b940545 | 9 | @Override
public Node removeItem(int key) throws EmptyTreeException,
KeyNotFoundException, InvalidTreeOperation {
if (isEmpty())
throw new EmptyTreeException();
Node item = findItem(key);
Node next = nextInorder(item);
Node removedNode = null;
if (item == null)
throw new KeyNotFoundException("Key " + key + " not found !!!");
else {
removedNode = super.removeItem(key);
if (key == 63) {
if (DEBUG){
printTree();
System.out.println("Root: "+getRoot().getKey());
}
}
Node w = null;
if (item.getLeft() != null && item.getRight() != null)
w = next;
else
w = removedNode.getParent();
Node z = w;
while (z != null) {
if (DEBUG)
System.out.println("Checking for : "+ z.getKey());
Node temp = z.getParent();
if (z.calculateBalanceFactor() > 1)
restructure(z);
z = temp;
}
}
return removedNode;
} |
cbc0183b-b117-4887-addd-60ac5650d0cb | 0 | public String getSector() {
return addressCompany.getSector();
} |
aee8c278-6f5a-4742-b5e9-c7e196ed12f9 | 1 | @Override
public void paintComponent( Graphics g ) {
super.paintComponent( g );
if ( game_completed ) {
Font font = new Font( "Cooper black", Font.BOLD, 14 );
g.setFont( font );
g.drawString( "Game completed!", 130, 130 );
} else {
level.drawLevel( g );
}
g.drawLine(0, 63, 767, 63);
} |
9cd14979-08b0-41ef-aeda-a7ca6bde0ce5 | 2 | protected synchronized Runnable getTask()
throws InterruptedException
{
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
} |
df4b0dbf-2f07-42b4-8efe-7ce90718a388 | 9 | public void marshEffect(Player p){
int n = -1;
int lb = 0;
int ub = 3;
bansheeDamage();
spectralCloakShield(p);
String head;
String textBlock;
ArrayList<String> strList = new ArrayList<String>();
head = "Spectral Marsh";
if((p.inventory.contains(Card.gauntlet) || p.inventory.contains(Card.gauntletii)) && !spectralImmune(p)){
textBlock = "You notice thoughts in your mind that are not your own. Oddly enough you don't remember how you got here. The Gauntlet compels you to draw a Spectral Card...";
lb = 1;
}else{
textBlock = "You may use the mysterious energy in the air to either heal any player for 4 HP or deal 8 damage to any player. Alternatively you may try your chances at a spectral card. Everything has a price...";
strList.add("0: Decline");
strList.add("1: Deal 8 damage");
strList.add("2: Heal 4 HP");
}
strList.add("3: Spectral Card");
p.displayRender(head, textBlock, strList);
drawEvent(p, pturn);
do{
n = playerInput(p);
}while(n < lb || n > ub);
switch(n){
case 0 : declinedAreaEffects(p, Area.MARSH);
break;
case 1 :
spectralDamage(p);
break;
case 2 :
spectralHeal(p);
break;
case 3:
drawSpectralCard(p);
default : break;
};
} |
26b307d7-3945-450b-b812-d47b09e1ac14 | 3 | public static Account narrow (org.omg.CORBA.Object obj)
{
if (obj == null)
return null;
else if (obj instanceof Account)
return (Account)obj;
else if (!obj._is_a (id ()))
throw new org.omg.CORBA.BAD_PARAM ();
else
{
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
_AccountStub stub = new _AccountStub ();
stub._set_delegate(delegate);
return stub;
}
} |
47e50d17-fc95-4139-b38e-92c876a7415a | 5 | public void removeRegionRef(String id) {
if (members != null) {
GroupMember toRemove = null;
for (Iterator<GroupMember> it = members.iterator(); it.hasNext(); ) {
GroupMember member = it.next();
if (member instanceof RegionRef) {
if (((RegionRef)member).getRegionId().equals(id)) {
toRemove = member;
break;
}
}
}
if (toRemove != null)
members.remove(toRemove);
}
} |
2cad62ef-ad90-436d-812c-7577b1285510 | 4 | public static final int highNeighbour(int[] v, int x) {
int min=Integer.MAX_VALUE, n=0;
for(int i=0; i<v.length && i<x; i++) {
if(v[i]<min && v[i]>v[x]) {
min=v[i];
n=i;
}
}
return n;
} |
f2be4651-8bba-4c5e-941e-4898dee2ea37 | 5 | public boolean insert_Into_Inventory(Item item){
//is the item already in the inventory
//is the stack size not full
for(Slot slot : slots){
if(slot.getItem() == item && slot.getStack_Count() < item.getMax_Stack_Count()){
slot.setStack_Count(slot.getStack_Count()+1);
return true;
}
}
for(Slot slot : slots){
if(slot.getItem() == null){
slot.setItem(item);
slot.setStack_Count(1);
return true;
}
}
return false;
} |
88ca9e92-65d4-4ee1-a320-6a404190e182 | 8 | public static void loadPlugin(File dir) throws SlickException, ClassNotFoundException, FileNotFoundException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
Class<Plugin> plugin = null;
Properties properties = new Properties();
List<String> files = Arrays.asList(dir.list());
if(files.contains("res")){
File f = new File(dir.getPath() + dir.separatorChar + "res");
GraphicsLoader.loadResources(f, dir.getName());
}
for(File f : dir.listFiles()){
if(f.getName().equals("bin") && f.isDirectory()){
URL[] ul = {f.toURL()};
URLClassLoader loader = new URLClassLoader(ul, ClassLoader.getSystemClassLoader());
plugin = loadBinaries(f, dir.getName(), loader);
}
if(f.getName().equals("dat") && f.isDirectory()){
loadData(f, dir.getName());
}
if(FileType.plugin_info.isType(f) && f.isFile()){
properties.load(new FileInputStream(f));
}
}
Plugin initializedPlugin = plugin.getConstructor(Properties.class).newInstance(properties);
initializedPlugin.load();
loadedPlugins.add(initializedPlugin);
} |
1d23f6c9-a933-4bcb-a59d-97eacf88073f | 9 | @Override
//assumes that there is nothing in the buffer from other stuff
//make sure other methods accessing the streams
//are also synchronized
public void run() {
PrintWriter out;
InputStreamReader reader;
while(true) {
//wait until ONE client connects
synchronized(monitor) {
try {
// System.out.println("why waste the chanc?");
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//out = new PrintWriter(socket.getOutputStream(), true);
//reader = new InputStreamReader(socket.getInputStream());
char[] temp = new char[1];
while(true) {
//System.out.println("stop");
//synchronized(connectedClients) {
lock.lock();
// System.out.println("LOCKED");
// System.exit(0);
Iterator<ClientInfo> i = connectedClients.iterator();
ClientInfo clientInfo;
while(i.hasNext()) {
clientInfo = i.next();
// System.out.println("CLIENT NAME: " + clientInfo.getClientName());
out = new PrintWriter(clientInfo.getMainSocket().getOutputStream(), true);
reader = new InputStreamReader(clientInfo.getMainSocket().getInputStream());
out.write('a');
if(out.checkError()) {
//error so means the client has disconnected
//remove from the list of clients
System.out.println("\n" + clientInfo.getClientName() + " has disconnected!");
//CLOSE COMMAND SOCKET DON'T FORGET. EVEN IF IT ALREADY CLOSED YOU DON'T KNOW!
//actually WHEN PROGRAM DIES. ALL THESE SOCKETS ARE ASSUMED TO BE CLOSED.
//CUZ THEY ALL DEAD LOL.
//ALL OTHER SOCKETS ARE DEALT WITH ! :o
//STILL CLOSE COMMAND SOCKET JUST IN CASE!
//YOU KNOW MAIN SOCKET ALREADY DEAD ROFL CUZ U CAN'T WRITE FOR SHIT!
//MAIN IS BY DEFAULT ALREADY CLOSED. THAT IS NOW WE GOT HERE. LOL.
//EVERYTHING BELOW IS CLOSED JUST IN CASE. JUST FOR SAFE KEEPINGS.
clientInfo.closeCommandSocket();
clientInfo.closeAllSubSockets();
//FINALLY REMOVE FROM THE ARRAY BYE BYE!
i.remove(); //remove from the array
findAndDeleteRow(clientInfo);
} else { //success so read back so not mess up stream!
// out.flush();
// out.flush();
reader.read(temp);
}
// System.out.println("WELL GO HOME!");
// System.exit(0);
}
lock.unlock();
if(connectedClients.size() == 0) { //if size is zero, break and go enter that monitor synchronized block to wait until get notified.
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// out.close(); //resets
// reader.close();
// }
// for(ClientInfo clientInfo : clients) {
// out = new PrintWriter(clientInfo.getSocket().getOutputStream(), true);
// reader = new InputStreamReader(clientInfo.getSocket().getInputStream());
// out.write('a');
// if(out.checkError()) {
// //error so means the client has disconnected
// //remove from the list of clients
// clients.remove(clientInfo);
// } else { //success so read back so not mess up stream!
// reader.read(temp);
// }
// out.close(); //resets
// reader.close();
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// } catch (ConcurrentModificationException e) {
// //does nothing because there is no harm at all.
} catch(NullPointerException e) {
e.printStackTrace();
}
}
// return null;
// TODO Auto-generated method stub
// return null;
} |
d5b9df60-4968-48ae-8913-732dc34da6bf | 4 | @EventHandler
public void onCrazyMagicMove(PlayerMoveEvent pME) {
Player player = pME.getPlayer();
if(CrazyFeet.CrazyMagic.contains(player)) {
Location to = pME.getTo();
Location from = pME.getFrom();
Location loc = player.getLocation();
if(to.getX() != from.getBlockX() || to.getY() != from.getY() || to.getZ() != from.getZ()) {
loc.setY(loc.getY()-1);
player.getWorld().playEffect(loc, Effect.POTION_BREAK, 1, 100);
} else {
pME.setCancelled(false);
}
} else {
pME.setCancelled(false);
}
} |
a738808b-128b-4c81-9781-ddecb159aeb1 | 1 | public static boolean printQuickCount(StringBuilder saveAsText) {
String[] sections = saveAsText.toString().replaceAll("@", " ")
.split(" ");
StringBuilder build = new StringBuilder();
for (String s : sections) {
build.append(" " + s.split("_").length);
}
// System.out.println(build);
return build.toString().equals(" 2 36 44 9 9 9 9 9 9 9 9 9 9 1 1 1");
} |
97a8dd28-8028-405d-8f82-37cb867e93bd | 0 | public CheckResultMessage checkSum1(int i,int j){
return checkReport1.checkSum1(i,j);
} |
445619c4-0026-4548-9e45-cfab7ef39a1f | 4 | @SuppressWarnings("unchecked")
private void loadTheme()
{
try
{
final Class<? extends Theme> clazz = (Class<? extends Theme>) MCLauncher.class
.getClassLoader().loadClass(
config.getString("window.theme"));
final Constructor<? extends Theme> constructor = clazz
.getConstructor();
theme = constructor.newInstance();
System.out.println("Using custom theme '" + clazz.getSimpleName()
+ "'...");
}
catch (final Exception e)
{
theme = new SimpleTheme();
}
theme.onLoad(api);
} |
53a38b5b-794d-42f6-8ca9-3e1cb259890a | 9 | @Override
public boolean process(Player player) {
if (ingredients == Ingredients.TORSTOL && otherItem.getId() != VIAL) {
if (!player.getInventory().containsOneItem(15309)
|| !player.getInventory().containsOneItem(15313)
|| !player.getInventory().containsOneItem(15317)
|| !player.getInventory().containsOneItem(15321)
|| !player.getInventory().containsOneItem(15325)) {
stop(player);
return false;
}
}
if (!player.getInventory().containsItem(node.getId(), node.getAmount())
|| !player.getInventory().containsItem(otherItem.getId(),
otherItem.getAmount())) {
return false;
}
return true;
} |
87af52ea-c056-4917-8703-45869438a871 | 1 | public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("OK"))
System.exit(0);
} |
95ed07a8-b88e-47dc-bd30-2d9ff9e8cc07 | 8 | public void updateMouse() {
nextMB = Mouse.isButtonDown(0) ;
nextMP.x = Mouse.getX() ;
nextMP.y = Mouse.getY() ;
if (mouseB && (! nextMB)) {
mouseState = HOVERED ;
}
if ((! mouseB) && nextMB) {
mouseState = CLICKED ;
dragMP.setTo(nextMP) ;
}
if (mouseB && nextMB && (mouseState != DRAGGED)) {
mouseState = (dragMP.pointDist(nextMP) > DRAG_DIST) ? DRAGGED : PRESSED ;
}
mousePos.setTo(nextMP) ;
mouseB = nextMB ;
} |
899d7d81-b5ab-4628-a648-cd634b00aa38 | 5 | public void paint(Graphics g)
{
//screen dimensions 296,45,298,217
g.drawImage(my_gif,0,0,this);
if(track==99)
{
g.setFont(bigFont);
g.drawString("Press Play",350,150);
}
if(track==0)
{
g.setFont(bigFont);
g.drawImage(issues_cover,296,45,298,217,this);
g.drawString("King of Amarillo",302,414);
g.setFont(artist);
g.drawString("Issues",302,453);
g.setFont(bigFont);
g.drawString("Album:",302,547);
g.setFont(artist);
g.drawString("Black Diamonds",302,586);
}
if(track==1)
{
g.setFont(bigFont);
g.drawImage(adtr,296,45,298,217,this);
g.drawString("The Best of Me",302,414);
g.setFont(artist);
g.drawString("A Day to Remember",302,453);
g.setFont(bigFont);
g.drawString("Album:",302,547);
g.setFont(artist);
g.drawString("Common Courtesy",302,586);
}
if(track==2)
{
g.setFont(bigFont);
g.drawImage(rustie,296,45,298,217,this);
g.drawString("Slasherr",302,414);
g.setFont(artist);
g.drawString("Rustie",302,453);
g.setFont(bigFont);
g.drawString("Album:",302,547);
g.setFont(artist);
g.drawString("Slasherr Single",302,586);
}
if(track==3)
{
g.setFont(bigFont);
g.drawImage(xxyyxx,296,45,298,217,this);
g.drawString("About You",302,414);
g.setFont(artist);
g.drawString("XXYYXX",302,453);
g.setFont(bigFont);
g.drawString("Album:",302,547);
g.setFont(artist);
g.drawString("XXYYXX",302,586);
}
// g.fillRect(148,467,39,22);
// g.fillRect(216,467,39,22);
// g.fillRect(746,458,58,48);
// g.fillRect(803,418,15,15);
g.setColor(Color.red);
g.setFont(bigFont);
g.drawString("PLAY",733,492);
g.setFont(stopbutton);
g.drawString("Stop",801,432);
} |
8ed22923-c999-423a-bca4-1dad6daf7a76 | 7 | private void readyForTermination() {
addKeyListener( new KeyAdapter() {
public void keyPressed(KeyEvent e)
{ int keyCode = e.getKeyCode();
if ((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) ||
(keyCode == KeyEvent.VK_END) ||
((keyCode == KeyEvent.VK_C) && e.isControlDown()) ) {
running = false;
} else if(keyCode == KeyEvent.VK_P) {
if(theModel.isPaused()) {
theModel.resumeGame();
} else {
theModel.pauseGame();
}
}
}
});
} |
24366f0d-0ca7-438a-a656-e60e8e88722b | 8 | static String toUnsignedHex8String(long pValue)
{
String s = Long.toString(pValue, 16);
//force length to be eight characters
if (s.length() == 0) {return "00000000" + s;}
else
if (s.length() == 1) {return "0000000" + s;}
else
if (s.length() == 2) {return "000000" + s;}
else
if (s.length() == 3) {return "00000" + s;}
else
if (s.length() == 4) {return "0000" + s;}
else
if (s.length() == 5) {return "000" + s;}
else
if (s.length() == 6) {return "00" + s;}
else
if (s.length() == 7) {return "0" + s;}
else{
return s;
}
}//end of Log::toUnsignedHex8String |
5c3868ed-0083-42bc-a09f-a5fc23e6c3b7 | 8 | public void filter(Set<Item> usedItems, boolean filterTransitions) {
if (filterTransitions) {
Set<Transition> removeTrans = new ShareableHashSet<Transition>();
Set<Transition> usedTrans = new ShareableHashSet<Transition>();
for (Transition t : transitions) {
if (t.reverse.size() > 0) { // only derives and reduces
if (!t.used) {
removeTrans.add(t);
} else {
boolean noReverseUsed = true;
for (Transition r : t.reverse) {
if (r.used) {
noReverseUsed = false;
break;
}
}
if (noReverseUsed) {
removeTrans.add(t);
//System.out.println(t.toStringExt());
} else {
usedTrans.add(t);
}
}
}
}
removeTrans.removeAll(usedTrans);
removeTransitions(removeTrans);
}
if (clusters == null) {
Set<Item> remove = allItems();
remove.removeAll(usedItems);
removeItems(remove);
optimize(true); // now removes items of incomplete clusters
} else {
/*
// XXX some items can appear in multiple clusters (for instance with LALR)
// therefore we need to remove only the items not used in any cluster
Set<Item> remove = new ShareableHashSet<Item>();
Set<Item> used = new ShareableHashSet<Item>();
for (Set<Item> c : clusters) {
if (usedItems.containsAll(c)) {
used.addAll(c);
} else {
remove.addAll(c);
//System.out.println("rc: " + c);
}
}
// after a call to optimize, certain clusters might be removed partially
// again, remove incompletely used clusters
// taking into account items used in multiple clusters
int oldSize = 0;
while (items.size() != oldSize) {
oldSize = items.size();
remove.removeAll(used);
removeItems(remove);
optimize(true);
remove = new ShareableHashSet<Item>();
used = new ShareableHashSet<Item>();
for (Set<Item> c : clusters) {
int contained = 0;
for (Item i : c) {
if (items.contains(i)) {
++contained;
}
}
if (contained > 0) { // avoid removing the same clusters over and over again
if (contained == c.size()) {
used.addAll(c);
} else {
remove.addAll(c);
//System.out.println("rc: " + c);
}
}
}
}
computeClusters();
verify(); */
}
} |
94d77dd7-1c4a-4a24-b209-a6641aa9faee | 1 | public JScrollPane getGUI(){
JPanel p1=new JPanel();
getExam();
GroupLayout groupLayout=new GroupLayout(p1);
groupLayout.setAutoCreateContainerGaps(true);
groupLayout.setAutoCreateGaps(true);
GroupLayout.ParallelGroup horizontalGroup_P = groupLayout.createParallelGroup(GroupLayout.Alignment.CENTER);
GroupLayout.SequentialGroup verticalGroup_S = groupLayout.createSequentialGroup();
for (int i = 0; i < sections.size(); i++) {
SectionPanel_Preview sectionPanel=new SectionPanel_Preview(exam_ID);
sectionPanel.getGUI(((Section)sections.get(i)).getSection_ID());
horizontalGroup_P.addComponent(sectionPanel);
verticalGroup_S.addComponent(sectionPanel);
}
groupLayout.setHorizontalGroup(horizontalGroup_P);
groupLayout.setVerticalGroup(verticalGroup_S);
p1.setLayout(groupLayout);
JScrollPane scrollPane=new JScrollPane(p1);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
return scrollPane;
} |
f7e6863e-3732-4ca7-af60-a54d52b9acf0 | 8 | private boolean readFeed()
{
try
{
// Set header values intial to the empty string
String title = "";
String link = "";
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = read();
if(in != null)
{
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
while (eventReader.hasNext())
{
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement())
{
if (event.asStartElement().getName().getLocalPart().equals(TITLE))
{
event = eventReader.nextEvent();
title = event.asCharacters().getData();
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(LINK))
{
event = eventReader.nextEvent();
link = event.asCharacters().getData();
continue;
}
}
else if (event.isEndElement())
{
if (event.asEndElement().getName().getLocalPart().equals(ITEM))
{
// Store the title and link of the first entry we get - the first file on the list is all we need
versionTitle = title;
versionLink = link;
// All done, we don't need to know about older files.
break;
}
}
}
return true;
}
else
{
return false;
}
}
catch (XMLStreamException e)
{
plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
return false;
}
} |
dfc052fe-ce75-426c-9c3d-78188d1acb74 | 0 | public double getSpeedRpm() {
return _speedSensor.getSpeedRpm();
} |
b48cf1c0-fdcb-448a-b046-ff297718e95e | 7 | public static User getUserByXMLElem(XMLElement root) {
String username = new String("Username Not Specified");
String password = new String("Password Not Set");
String url = new String("URL missing");
int permission = IS_NORMAL;
if (root.attributeMap.containsKey("permission")) {
String permissionStr = root.attributeMap.get("permission");
if (permissionStr.equals("admin"))
permission = IS_ADMIN;
else if (permissionStr.equals("temp"))
permission = IS_TEMP;
}
for (int i = 0; i < root.childList.size(); i++) {
XMLElement elem = root.childList.get(i);
if (elem.name.equals("username")) {
username = elem.content;
} else if (elem.name.equals("password")) {
password = new Encryption().generateHashedPassword(elem.content);
} else if (elem.name.equals("homepageURL")) {
url = elem.content;
} else {
System.out.println("Field not recognized in user : " + elem.name);
}
}
return new User(username, password, url, permission);
} |
ed295c85-6c48-4dec-9dd0-90fb4f0178e9 | 0 | public String getClientId() {
return clientId;
} |
bf69612f-8c74-4f74-b348-009c903baa1a | 9 | private void button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button3ActionPerformed
if (order1code4tf.getText().equals("1001"))
{
o1c4destf.setText("Chicken Nugget");
}
if (order1code4tf.getText().equals("1002"))
{
o1c4destf.setText("Fries");
}
if (order1code4tf.getText().equals("1003"))
{
o1c4destf.setText("Salad");
}
if (order1code4tf.getText().equals("1004"))
{
o1c4destf.setText("Cheese Burger");
}
if (order1code4tf.getText().equals("1005"))
{
o1c4destf.setText("Bacon Cheese Burger");
}
if (order1code4tf.getText().equals("1006"))
{
o1c4destf.setText("Hamburger");
}
if (order1code4tf.getText().equals("1007"))
{
o1c4destf.setText("Soda");
}
if (order1code4tf.getText().equals("1008"))
{
o1c4destf.setText("Tea");
}
if (order1code4tf.getText().equals("1009"))
{
o1c4destf.setText("Coffee");
}
}//GEN-LAST:event_button3ActionPerformed |
6ce8891a-dab3-4b02-8235-e2f757e25b01 | 2 | public void cargarVentas() {
try {
String sql = "SELECT t1.idVentas AS id_venta, t2.nombre AS empleado, t1.precio_total "
+ "FROM ventas AS t1, empleados AS t2 "
+ "WHERE t1.empleados_idempleados = t2.idempleados";
Connection conn = Conexion.GetConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ventas = ps.executeQuery();
while (ventas.next()) {
String[] rows = {ventas.getString(1), ventas.getString(2), ventas.getString(3)};
tmVenta.addRow(rows);
}
jTableVentas.setModel(tmVenta);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
} |
ccd140c9-7a5a-4667-a361-b1be854c64d6 | 1 | private void writeInteger32ToByteArray(int value) {
//byte[] intBytes = new byte[4];
//I allocated the this buffer globally so the GC has less work
intBytes[3] = (byte)value; value >>>= 8;
intBytes[2] = (byte)value; value >>>= 8;
intBytes[1] = (byte)value; value >>>= 8;
intBytes[0] = (byte)value;
try {
stream.write(intBytes);
} catch (IOException ex) {
throw new RuntimeException("You're screwed:"
+ " IOException writing to a ByteArrayOutputStream", ex);
}
} |
30b3479e-b857-4663-af31-f75497bd61ba | 9 | @Override
protected int processRecord (int recordCounter, byte[] recordData, short recordAttributes, int recordUniqueID)
{
// local vars
int processResult = SUCCESS ;
int relations = 0 ;
String nodeTitle = null;
int titleLength = 0 ;
String nodeNote = null;
int noteLength = 0 ;
String nodeMisc = null;
int miscLength = 0 ;
NodeImpl node = null;
Integer wrappedLevel = null ;
// if it's not the first record ...
if (recordCounter > 0) {
// it's a data-containing node
// determine the node's level in the outline
// if it's the first node
if (recordCounter == 1) {
// nodeLevel is just 0
nodeLevel = 0 ;
} // end if we're the first node
// else it's not the first node
else {
// node's level was set by previous record
nodeLevel = nextNodeLevel ;
} // end else we're not the first node
// determine the node level of the next node
// grab current node's relations flags
relations = BitsAndBytes.unsignedShort(recordData, PDB_SP_RECORD_RELATIONS, BitsAndBytes.HI_TO_LO) ;
// note whether there's a sibling coming up
siblingAhead = ((relations & PDB_SP_RECORD_HAS_SIBLING) != 0) ;
// if current node has a child ...
if ((relations & PDB_SP_RECORD_HAS_CHILD) != 0) {
// that child is the next node
// children live one level deeper
nextNodeLevel = nodeLevel + 1 ;
// if there's a sibling ahead
if (siblingAhead) {
// siblings live at the same level
// push that onto the stack
wrappedLevel = new Integer(nodeLevel) ;
siblingAheadLevels.push(wrappedLevel);
} // end if there's a sibling ahead
} // end if current node has a child
// else if current node has no child, but does have a sibling
else if (siblingAhead) {
// that sibling is the next node
// siblings live at the same level
nextNodeLevel = nodeLevel ;
} // end else if current node has a sibling
// else current node has no siblings or children
// if there are more nodes, then next node is some kind of forebear
// we can find out if there are more nodes by checking the size of the stack
// if it's empty, there are no more nodes
else if (! siblingAheadLevels.empty()){
// the stack's NOT empty
//there's a next node, and it is a forebear
// pop its level off of the stack
wrappedLevel = (Integer) siblingAheadLevels.pop() ;
nextNodeLevel = wrappedLevel.intValue() ;
wrappedLevel = null ; // avoid memory leaks
} // end else current node has no siblings or children and stack's not empty
// else there are no more nodes
else {
// let's free the stack to avoid memory leaks
siblingAheadLevels = null ;
} // end else there are no more nodes
// phew
// if there's node text ...
// (Shadow Plan calls a node's text its title)
titleLength = BitsAndBytes.unsignedShort(recordData, PDB_SP_RECORD_TITLE_LENGTH, BitsAndBytes.HI_TO_LO) ;
if (titleLength > 0) {
// grab the node text as a string
nodeTitle = new String(recordData, PDB_SP_RECORD_FOOTER, titleLength) ;
// create a free-standing node with the proper contents
node = new NodeImpl(null, nodeTitle);
// set node attributes
// TBD
// add the node to the outline
ourContentHandler.addNodeToOutline(node, nodeLevel) ;
} // end if there's node text
// if the node has a note ...
noteLength = (int) BitsAndBytes.unsignedInt(recordData, PDB_SP_RECORD_NOTE_LENGTH, BitsAndBytes.HI_TO_LO) ;
if (noteLength > 0) {
// grab the note text as a string
nodeNote = new String(recordData,
PDB_SP_RECORD_FOOTER + titleLength+1, noteLength) ;
// create a free-standing node with the proper contents
node = new NodeImpl(null, nodeNote);
// set node attributes
// TBD
// create a free-standing node with the proper contents
node = new NodeImpl(null, SHADOW_PLAN_NOTE_START_MARKUP + nodeNote + SHADOW_PLAN_NOTE_STOP_MARKUP);
// set node attributes
// it's a Shadow Plan note node
// TBD
// for now, we encase in XMLian markup, as seen above
// add the note to the outline as a child of the current node
ourContentHandler.addNodeToOutline(node, nodeLevel + 1) ;
} // end if the node has a note
// if the node has misc stuff ...
miscLength = BitsAndBytes.unsignedShort(recordData, PDB_SP_RECORD_MISC_LENGTH, BitsAndBytes.HI_TO_LO) ;
if (miscLength > 0) {
// grab the misc text as a string
nodeNote = new String(recordData,
PDB_SP_RECORD_FOOTER + titleLength+noteLength + 2, miscLength) ;
// create a free-standing node with the proper contents
node = new NodeImpl(null, nodeNote);
// set node attributes
// TBD
// create a free-standing node with the proper contents
node = new NodeImpl(null, SHADOW_PLAN_MISC_START_MARKUP + nodeNote + SHADOW_PLAN_MISC_STOP_MARKUP);
// set node attributes
// it's a Shadow Plan misc stuff node
// TBD
// for now, we encase in XMLian markup, as seen above
// add the misc info to the outline as a child of the current node
ourContentHandler.addNodeToOutline(node, nodeLevel + 1) ;
} // end if the node has misc stuff
} // end if it's not the first record
// else it's the first record
else {
// the first record is special
// it contains meta data RE the outline
// more possibly TBD
// reset nodeLevel stuff for upcoming convolutions
nodeLevel = 0;
nextNodeLevel = 0 ;
siblingAhead = false ;
siblingAheadLevels = new Stack();
} // end else it's the first record
// return a result
// TBD make this real
// TBD while doing so, get a try/catch in here
return processResult ;
} // end protected method processRecord |
a6f815e7-a610-4b56-b2b9-17755e4fffcc | 7 | private ArrayList<SequencePart> parseDomainParts(List<String> lines,
String type) {
ArrayList<SequencePart> ret = new ArrayList<SequencePart>();
for (String line : lines) {
String fromStr = line.substring(15, 20).trim();
String toStr = line.substring(21, 27).trim();
if (fromStr.contains("?") || toStr.contains("?")) {
continue;
}
if (fromStr.startsWith("<") || fromStr.startsWith(">")) {
fromStr = fromStr.substring(1);
}
if (toStr.startsWith("<") || toStr.startsWith(">")) {
toStr = toStr.substring(1);
}
// -1 because the data file indexes letters in strings starting with 1
int from = Integer.parseInt(fromStr) - 1;
int to = Integer.parseInt(toStr) - 1;
ret.add(new SequencePart(from, to, type));
}
return ret;
} |
683696a2-f7ec-419c-9765-6db9b59d2751 | 3 | private void gameInit(){
score1 = 0;
score2 = 0;
level = startingLevel;
if (unlimitedLives){
if (isSinglePlayer){
player1 = new Player(screenWidth/2,screenHeight/2, 0,0,0,0,-1,0);
player2 = null;
}else{
player1 = new Player(screenWidth/4, screenHeight/2, 0,0,0,0,-1,0);
player2 = new Player(3*screenWidth/4, screenHeight/2, 0,0,0,0,-1,1);
}
}else{
if (isSinglePlayer){
player1 = new Player(screenWidth/2,screenHeight/2, 0,0,0,0,3,0);
player2 = null;
}else{
player1 = new Player(screenWidth/4, screenHeight/2, 0,0,0,0,3,0);
player2 = new Player(3*screenWidth/4, screenHeight/2, 0,0,0,0,3,1);
}
}
rogueSpaceship = null;
alienShip = null;
initAsteroids();
bullets = new ArrayList<Bullet>();
paused = false;
soundUtil = new SoundUtil();
} |
6fc65029-3f3c-405a-bde6-df21f1c866c3 | 2 | public Produto Abrir(int id) throws ErroValidacaoException, Exception{
try{
PreparedStatement comando = bd.getConexao()
.prepareStatement("SELECT * FROM produtos WHERE id = ? ");
comando.setInt(1, id);
ResultSet consulta = comando.executeQuery();
comando.getConnection().commit();
Produto tmp = null;
EstoqueDAO daoEstoque = new EstoqueDAO();
if(consulta.first()){
tmp = new Produto();
Estoque tmpE = daoEstoque.Abrir(id);
tmp.setDescricao(consulta.getString("descricao"));
tmp.setId(consulta.getInt("id"));
tmp.setNome(consulta.getString("nome"));
tmp.setValorUnidadeCompra(consulta.getDouble("valor_uni_Compra"));
tmp.setValorUnidadeVenda(consulta.getDouble("valor_uni_Venda"));
tmp.setEstoque(tmpE);
}
return tmp;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}
} |
fbf384a5-de6d-4a37-94c7-0f4d1fce7e56 | 8 | public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String host = null;
if (arg.length > 0) {
host = arg[0];
} else {
host = JOptionPane.showInputDialog("Enter username@hostname", System.getProperty("user.name")
+ "@localhost");
}
String user = host.substring(0, host.indexOf('@'));
host = host.substring(host.indexOf('@') + 1);
Session session = jsch.getSession(user, host, 22);
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
String command = JOptionPane.showInputDialog("Enter command, execed with sudo", "printenv SUDO_USER");
String sudo_pass = null;
{
JTextField passwordField = (JTextField) new JPasswordField(8);
Object[] ob = { passwordField };
int result = JOptionPane.showConfirmDialog(null, ob, "Enter password for sudo",
JOptionPane.OK_CANCEL_OPTION);
if (result != JOptionPane.OK_OPTION) {
System.exit(-1);
}
sudo_pass = passwordField.getText();
}
Channel channel = session.openChannel("exec");
// man sudo
// -S The -S (stdin) option causes sudo to read the password from the
// standard input instead of the terminal device.
// -p The -p (prompt) option allows you to override the default
// password prompt and use a custom one.
((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.out.println(e);
}
} |
59e3c502-0fc8-4353-8f23-b75087597350 | 0 | public Read(){
this.path = Params.testFolder + this.separator;
this.graf = new ArrayList<Long>();
} |
7974aee0-cb49-4107-a2ae-7e668ea50686 | 4 | @Override
public void actionPerformed(ActionEvent e) {
try {
BmTestManager bmTestManager = BmTestManager.getInstance();
GuiPackage guiPackage = GuiPackage.getInstance();
if (Utils.isTestPlanEmpty()) {
JMeterUtils.reportErrorToUser("Test-plan should have at least one Thread Group");
return;
}
if (guiPackage.getTestPlanFile() == null | guiPackage.isDirty()) {
Utils.saveJMX();
}
TestInfo testInfo = bmTestManager.getTestInfo();
if (testInfo.getNumberOfUsers() == 0) {
JMeterUtils.reportErrorToUser("Can't set up test with 0 users. " +
" '1' will be saved");
testInfo.setNumberOfUsers(1);
}
bmTestManager.updateTestSettings(bmTestManager.getUserKey(), bmTestManager.getTestInfo());
JMXUploader.uploadJMX();
} catch (NullPointerException npe) {
JMeterUtils.reportErrorToUser("Save test-plan locally before uploading");
}
} |
353dc8cb-b234-4082-b9b1-f554c5afd366 | 4 | private String lineStyle2Dot(Styles.LineStyle lineStyle) {
switch (lineStyle) {
case Dashed:
return "dashed";
case Dotted:
return "dotted";
case Bold:
return "bold";
case Solid:
default:
return "solid";
}
} |
83745c89-9364-498f-9bb1-9847a656c79f | 3 | public synchronized void addMessage(String paramString)
{
if ((this.LastMessage == null) || (paramString.compareTo(this.LastMessage) != 0))
{
this.LastMessage = paramString;
TextContainer localTextContainer = new TextContainer();
localTextContainer.setPackedHeight(true);
localTextContainer.setSize(140, 43);
localTextContainer.setLocation(0, 0);
localTextContainer.setFont(StatusPanel.TEXTFONT);
localTextContainer.setColor(Color.red);
localTextContainer.setHardSize(140, 43);
localTextContainer.setStreak(true, 8, 7, 50);
localTextContainer.addEffectsCompletionListener(this);
localTextContainer.setText(paramString);
add(localTextContainer);
doLayout();
this.CurrentMessages.addElement(localTextContainer);
return;
}
blinkLastMessage();
if (this.CurrentMessages.size() == 1)
{
this.TopMessageFinishedAt = System.currentTimeMillis();
}
} |
cd4d5f9b-c111-4da2-9d5b-5ccdb4fb139a | 3 | private void printSequenceRecursive(int k, int n, int position, int[] array){
if(position == array.length){
System.out.println(Arrays.toString(array));
return;
}
int startingNumber;
if(position == 0){
startingNumber = 1;
}
else{
startingNumber = array[position - 1] +1;
}
for(int i = startingNumber; i<=n; i++){
array[position] = i;
printSequenceRecursive(k, n, position+1, array);
}
} |
aec34cf6-946f-446e-bbe8-37e78f0e7b48 | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IndividualAgent other = (IndividualAgent) obj;
if (this.id != other.id) {
return false;
}
return true;
} |
bc131850-2035-4f59-bcee-dd621182e5cc | 5 | private static JToolBar buildToolbar(Item[] items)
{
JToolBar bar = new JToolBar();
for (Item item : items)
{
if (item == Item.SEPARATOR)
bar.add(new JToolBar.Separator());
else if (item.icon != null)
{
AbstractButton button = null;
if (item.setting != null)
{
JToggleButton tbutton = new JToggleButton(item.icon);
tbutton.setSelected(Settings.values.get(item.setting));
button = tbutton;
}
else
button = new JButton(item.icon);
if (item.tooltip != null)
button.setToolTipText(item.tooltip);
button.addActionListener(toolbarListener);
mapping.put(button, item);
item.buttonToolbar = button;
bar.add(button);
}
}
bar.setFloatable(false);
return bar;
} |
86418b3b-baa1-488c-bea4-c311be0e4ca1 | 3 | public boolean load() {
FileInputStream is = null;
File f = null;
try {
f = new File(FileLocation);
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
logger.info(e.getMessage() + ", creating new persistence file:" + f.getAbsolutePath());
save();
xmlHashMap = new HashMap<String, String>();
return false;
}
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(is);
xmlHashMap = (HashMap<String, String>) ois.readObject();
ois.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
} |
341ad6fb-1f92-4939-be2a-9945f9c02c35 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClassMetadata other = (ClassMetadata) obj;
if (qualifiedName == null) {
if (other.qualifiedName != null)
return false;
} else if (!qualifiedName.equals(other.qualifiedName))
return false;
return true;
} |
7e24cde9-6165-46b9-a52c-d8340516b769 | 1 | @Override
public JSONObject main(Map<String, String> params, Session session)
throws Exception {
JSONObject rtn = new JSONObject();
Venue[] aVenue = Venue.findAll();
rtn.put("rtnCode", this.getRtnCode(200));
{
JSONArray venueJa = new JSONArray();
for(int i=0; i<aVenue.length; i++) {
venueJa.put(aVenue[i].toJson());
}
rtn.put("aVenue", venueJa);
}
return rtn;
} |
778efae3-5c63-4fd8-929a-7718798cb444 | 3 | private boolean HLIDRoundTripConversionTest(Object obj) {
try {
String apiId = null;
if (obj instanceof String) {
apiId = CompactHLIDConverter.converter().toCompactHLId((String) obj);
} else if (obj instanceof Number) {
apiId = CompactHLIDConverter.converter().toCompactHLId((Number) obj);
}
Object roundTripObj = CompactHLIDConverter.converter().fromCompactHLId(apiId);
assertTrue(obj.equals(roundTripObj));
} catch (Throwable e) {
fail(e.toString());
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.