method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
b3fd66f5-8e19-465e-a140-0117f3731827
| 2
|
@WebResult(name = "GetAccountResponse", targetNamespace = "")
@RequestWrapper(localName = "GetAccountDetailRequest", targetNamespace = "http://xstore.com/wsdl", className="com.xstore.services.web.model.GetAccountDetailRequest")
@WebMethod(operationName = "GetAccountDetail")
@ResponseWrapper(localName = "GetAccountDetailResponse", targetNamespace = "http://xstore.com/wsdl", className="com.xstore.services.web.model.GetAccountDetailResponse")
public GetAccountResponse GetAccountDetail(
@WebParam(name = "GetAccountRequest", targetNamespace = "http://xstore.com/wsdl") GetAccountRequest getAccountRequest) throws XStoreException {
GetAccountResponse gResponse = new GetAccountResponse();
logger.info("Request - " + getAccountRequest);
try {
String accountID = getAccountRequest.getAccountId();
String clientID = getAccountRequest.getClientId();
// Find the list of orders
List<Order> orders = dataService.findOrder(accountID, clientID);
// Find the account details
Account account = dataService.findAccount(accountID, clientID);
gResponse.setAccountId(accountID);
gResponse.setAccountName(account.getAccountName());
gResponse.setClientId(clientID);
gResponse.setOrderCount(String.valueOf(orders.size()));
} catch (XStoreException e) {
throw new XStoreException(XStoreFault.getInstance(
"CLIENT_ACCOUNT_NOT_FOUND",
"Client or Account details not found"));
} catch (Exception e) {
logger.severe("Error occured - " + e.getMessage());
logger.severe("Stacktrace - \n" + ExceptionUtils.getStackTrace(e));
throw new XStoreException(e.getMessage(),
ExceptionUtils.getRootCauseMessage(e));
}
return gResponse;
}
|
461d64ad-61eb-4756-823d-dca66f9de209
| 4
|
public static ArrayList<Achievement> getAchievementsByUserID(int userID, int type) {
ArrayList<Achievement> achievements = new ArrayList<Achievement>();
String statement = new String("SELECT * FROM " + DBTable + " WHERE userid = ?");
PreparedStatement stmt;
try {
stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, userID);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Achievement achievement = Achievement.getAchievementByID(rs.getInt("aid"));
if (achievement.type != type && type != Achievement.ALL_TYPE)
continue;
achievements.add(achievement);
}
rs.close();
Collections.sort(achievements, new AchievementSortByID());
return achievements;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
|
4a7767f0-01dd-45ce-b4a1-a885de1d91ed
| 4
|
public Matrix plus(Matrix B) {
Matrix A = this;
if (B.M != A.M || B.N != A.N)
throw new RuntimeException("Illegal matrix dimensions.");
Matrix C = new Matrix(M, N);
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
C.data[i][j] = new DataNode((char) (A.data[i][j].value() + B.data[i][j].value()));
return C;
}
|
32b7e144-4058-4abe-9b9c-57755b7d1b06
| 4
|
public void writeToBalance(Kunde kunde){
if(kunde != null){
Double fullPrice = 0.00;
String productNames = "";
String pricelist = "";
for (model.Product product : kunde.getProducts()) {
fullPrice = fullPrice + product.getPrice();
if(pricelist == ""){
pricelist = Double.toString(product.getPrice());
}
else {
pricelist = pricelist + " , " + product.getPrice();
}
if(productNames == ""){
productNames = product.getName();
}
else {
productNames = productNames + " , " + product.getName();
}
}
lastProducts[0] = productNames;
lastProducts[1] = pricelist;
balance.addEntry(cashpointId,fullPrice,abgKunden,productNames,pricelist,waitingQueue.size());
}
else {
balance.addEntry(cashpointId, 0,abgKunden,lastProducts[0],lastProducts[1], waitingQueue.size());
}
}
|
6ef7a6ca-60ee-44f6-9bc8-02d5459013ee
| 1
|
public void actionPerformed(ActionEvent e) {
if(e.getSource() == beendenButton){
System.out.println("button clicked");
spiel.getAktuellerSpieler().setZugZuende(true);
lblNewLabel.setText("Aktueller Spieler: " + spiel.getAktuellerSpieler().toString());
repaint();
}
}
|
32040896-6cd9-4db0-9c02-e62e7339563d
| 0
|
public void setEmail(String email) {
this.email = email;
}
|
cf78bcdc-4613-40a6-8cf2-2326d2f5a20d
| 5
|
public DataBuffer getBuffer(CacheFileDescriptor descriptor) throws IOException
{
//System.out.println("Requesting file " + descriptor);
int expectedIndexID = descriptor.index().id() + 1;
DataBuffer fileBuffer = new DataBuffer();
int currentBlockID = descriptor.startBlock();
int remaining = descriptor.size();
int nextPartID = 0;
while (remaining > 0)
{
dataFile.seek(currentBlockID * DATA_SIZE);
byte[] tempData = new byte[DATA_HEADER_SIZE];
dataFile.read(tempData);
DataBuffer tempBuffer = new DataBuffer(tempData);
int currentFileID = tempBuffer.getShort();
int currentPartID = tempBuffer.getShort();
int nextBlockID = tempBuffer.getTribyte();
int nextIndexID = tempBuffer.get();
if (currentFileID != descriptor.id())
{
throw new IOException("Different file ID, index and data appear to be corrupt.");
}
else if (currentPartID != nextPartID)
{
throw new IOException("Block ID out of order or wrong file being accessed.");
}
else if (nextIndexID != expectedIndexID)
{
throw new IOException("Wrong index ID, must be a different type of file.");
}
byte[] block = new byte[remaining > DATA_BLOCK_SIZE ? DATA_BLOCK_SIZE : remaining];
dataFile.read(block);
fileBuffer.put(block);
remaining -= block.length;
currentBlockID = nextBlockID;
nextPartID++;
}
fileBuffer.flip();
return fileBuffer;
}
|
2d8f22ce-1c77-4b7b-9ace-20347a45de1f
| 9
|
private void rotate(){
if(stack.size() <= 1)
return;
else{
SplayNode n = stack.pop();
while(stack.size()>1){
SplayNode np = stack.pop();
SplayNode gp = stack.pop();
if((n == np.left && np == gp.left) || (n == np.right && np == gp.right))
n = zigzig(n, np, gp);
else
n = zigzag(n, np, gp);
if(stack.size() != 0){
SplayNode nd = stack.pop();
if(nd.left == gp)
nd.left = n;
else
nd.right = n;
stack.push(nd);
}
}
if(stack.size() == 1){
SplayNode np = stack.pop();
rotateTwoNodes(n, np);
}
root = n;
}
}
|
e9b5db9e-77d3-49ad-b388-a6fd902a2b5a
| 7
|
public int modificarOpcion(DTO.Opcion p) {
try {
if (con.isClosed()) {
con = bd.conexion();
}
Object ob = null;
if (p.getdespuesDeOpcion().getCodigo() != 0) {
ob = p.getdespuesDeOpcion().getCodigo();
}
String des = p.getDescripcionOpcion().replace("\\", "\\\\");
String consulta = "UPDATE opcion SET orden = '" + p.getOrden() + "', despuesDeOpcion = "+ ob + ", descripcionO = '"+des+"' WHERE idOpcion = '" + p.getCodigo() + "'";
Statement sta = con.createStatement();
int rs = sta.executeUpdate(consulta);
if (rs == 1 || rs == 4) {
return 1;
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error modificando opcion!. Error: " + ex);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException ignore) {
}
}
}
return 0;
}
|
d8fcac42-77a0-4e50-a3dc-1160da5e2865
| 7
|
public void close() {
try {
if (mResultSet != null && !mResultSet.isClosed()) {
mResultSet.close();
}
if (mStatement != null && !mStatement.isClosed()) {
mStatement.close();
}
if (mConnection != null && !mConnection.isClosed()) {
mConnection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
|
cc9aeebb-54d4-4eea-95b2-01a042bac6fb
| 2
|
private void setAdjacent(Node node1, Node node2) {
if (node1 == null || node2 == null) {
throw new IllegalArgumentException("Need two non-null Nodes");
}
// Create the Adjacent Nodes
Set<Node> aN = new HashSet<Node>();
aN.add(node1);
aN.add(node2);
// Set the Adjacent nodes
adjacentNodes = aN;
}
|
160b3cd4-8df5-4e4c-9afd-b5f4be2a01af
| 2
|
@Override
public void mousePressed(MouseEvent e) {
if (contains(e.getX(), e.getY()) && enabled) {
pressed = true;
}
}
|
64df4e6a-8460-4548-b40d-4614935e1399
| 7
|
public static TOObjectProperty setPropValue(TOObjectProperty prop, Object val, Integer type) {
try {
prop.setPropType(type);
switch (type) {
case TOPropertyType.TYPE_STR: {
prop.setStrval(String.valueOf(val));
}
break;
case TOPropertyType.TYPE_INT: {
prop.setIntval(Integer.valueOf(String.valueOf(val)));
}
break;
case TOPropertyType.TYPE_FLOAT: {
prop.setFloatval(Float.valueOf(String.valueOf(val)));
}
break;
case TOPropertyType.TYPE_TEXT: {
prop.setStrval(String.valueOf(val));
}
break;
case TOPropertyType.TYPE_DATE: {
prop.setDateval((Date) val);
}
break;
case TOPropertyType.TYPE_LIST: {
prop.setListval(Integer.valueOf(String.valueOf(val)));
}
break;
}
} catch (NumberFormatException e) {
}
return prop;
}
|
fecb0fc6-8802-4a42-9b0b-52a0b43844bf
| 6
|
public void addActive(Component folha) {
if (folha.getClass() != Job.class) {
if (!folha.getState().equalsIgnoreCase("closed")) {
this.addChild(folha);
}
} else {
Job newChild = new Job(folha.getName(),folha.getDescription());
for (Component child : ((Job) folha).getChildren()) {
if ((child.getClass() == Job.class && !child.getState().equalsIgnoreCase("closed")) ||
(!child.getState().equalsIgnoreCase("closed"))){
newChild.addActive(child);
}
}
this.addChild(newChild);
}
}
|
50770e48-0573-4912-86d6-597da6009587
| 5
|
public void calculateMoleculeID(int level, int val, int[] parentMolID){
initMoleculeID(level);
if(level>1){
for(int i=0; i<level-1; i++){
setMoleculeID(i, parentMolID[i]);
}
}
if(level!=0){
setMoleculeID(level-1, val); // Set child[0].moleculeID[last]=0
}
if( ! ((children.get(0).getID()==0)||(children.get(1).getID()==0)) ){
children.get(0).calculateMoleculeID(level+1, 0, MoleculeID);
children.get(1).calculateMoleculeID(level+1, 1, MoleculeID);
}
}
|
332ae0fd-991d-48bd-95f9-7b037fa44e80
| 2
|
public void replaceWith(Node replacement){
if (parent == null) return;
if (this == parent.left) parent.setLeftChild(replacement);
else parent.setRightChild(replacement);
}
|
e6507649-2355-48a3-afc5-8d4ea8d870d6
| 4
|
public static void set(Properties properties, String filePath) {
if (! filePath.endsWith(".properties")) {
filePath += ".properties";
}
try {
OutputStream output = new FileOutputStream(filePath); // Open the file we are saving to.
properties.store(output, ""); // Save the properties file to the output stream.
output.close(); // Close the file we're saving to.
if (propertiesMap.containsKey(filePath)) { // Check if the file we are saving is cached.
// If so, update the cache.
propertiesMap.put(filePath, properties);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
304306ed-358a-4d98-8184-75eb70bf4f06
| 4
|
@Override
public void process(Document doc) throws Exception {
super.process(doc);
this.subjects.clear();
if(doc != null) {
NodeList paramNodes = Utilities.selectNodes(doc, "/dc:DCTransaction/dc:GetDataBySubjectRq/dc:SubjectIDs/dc:SubjectID", XMLLabels.STANDARD_NAMESPACES);
for(int i = 0; i < paramNodes.getLength(); ++i) {
Node paramNode = paramNodes.item(i);
String value = paramNode.getTextContent();
String type = Utilities.getAttributeValue(paramNode, "type");
if(!Utilities.isNullOrWhitespace(type) && !Utilities.isNullOrWhitespace(value)) {
this.subjects.add(new SubjectID(type, value));
} else {
this.subjects.add(new SubjectID());
}
}
}
}
|
d1805cce-20ff-4674-a579-252e56f71b89
| 1
|
public void equip(){
isEquipped = true;
window.activeLevel.thisLevelsItems.remove(this);
createActionMessage();
if(this.itemType == 0){
panel.player.weapons[0] = this;
}else{
panel.player.equipment.add(this);
}
}
|
07457cc4-772f-43b0-a26c-7b2dded0589e
| 0
|
public static String getUsuario() {
return usuario;
}
|
25d3fb66-21d3-41e5-af5f-1a071d9195d0
| 7
|
public void ThinkDamnYou(players.Base ply) {
//TODO: Redesign it to allow the npc to grab if someone is in firing range faster and easier.
if (finished) {
finished = false;
DoneCities = DoneUnits = false;
UnitCount = CityCount = 0;
if (ply.power>=ply.level2) {ply.UsePower(false);}
else if (ply.power>=ply.level1) {ply.UsePower(true);}
}
NextUnit(Game.btl.currentplayer);
NextCities(Game.btl.currentplayer);
if (!DoneUnits) {
units.Base unit = Game.units.get(UnitCount);
UnitCount++;
if (unit.owner == Game.btl.currentplayer) {
HandleUnit(unit);
}
}
else if (!DoneCities) {
buildings.Base bld = Game.builds.get(CityCount);
CityCount++;
if (bld.owner == Game.btl.currentplayer) {
HandleBuilding(bld);
}
}
else {
finished = true;
Game.btl.EndTurn();
}
}
|
4b3e9fbb-f10e-4add-b4b2-6d45cc8ad568
| 7
|
public boolean pollInput()
{
if ((this.discoFlag) || (checkDisconnect(System.currentTimeMillis())))
{
System.out.println("client schließt verbindung");
disconnect();
return false;
}
int counter = 0;
try
{
for (; counter < messagesPerUpdate; ++counter)
{
ByteBuffer buf = ByteBuffer
.allocate(NETCONSTANTS.PACKAGELENGTH);
if (tcpConnection.read(buf) > 0)
{
this.incommingMessage(buf, true);
continue;
}
if (udpConnection.read(buf) > 0)
{
this.incommingMessage(buf, false);
continue;
}
break;
}
} catch (IOException e)
{
e.printStackTrace();
return false;
}
if (counter > 0)
{
this.lastHearthbeat = System.currentTimeMillis();
this.pongRequest = -1L;
}
return true;
}
|
76c068fe-c500-408a-83fb-38d7e97c3fee
| 0
|
public void run() {
carPhysics.run();
}
|
3b1e01ce-81c1-4a3e-8d7a-0f385ea846b5
| 7
|
public static Graph readGraph(InputStream is, int vertexNumber) {
Graph result = new Graph(vertexNumber);
Scanner fileScanner = new Scanner(is);
int i = 0;
while (fileScanner.hasNextLine() && i < vertexNumber) {
String str = fileScanner.nextLine();
Scanner lineScanner = new Scanner(str);//default delimiter is whitespace.
int v = -1;//suppose we have only positive numbers.
if (lineScanner.hasNext()) {
v = lineScanner.nextInt();
}
if (v != -1) {
//System.err.print("row " + v + ":");
while (lineScanner.hasNext()) {
String nextTuple = lineScanner.next();
if (nextTuple != null && !nextTuple.equals("")) {
//System.err.print(nextTuple + "|");
String[] pair = nextTuple.split(",");
int destV = Integer.parseInt(pair[0]);
int weight = Integer.parseInt(pair[1]);
result.addEdge(v, destV, weight);
}
}
}
//System.err.println();
lineScanner.close();
i++;
}
fileScanner.close();
return result;
}
|
81b3f4a5-ee05-44b3-b0f9-692e8ddc0a64
| 5
|
short check_data_content(String new_serial_data)
{
short ret = check_scg_command(new_serial_data);
if (MsgAnalyzerCmnDef.CheckSuccess(ret))
{
boolean highlight = false;
if (scg_command_status == SCG_COMMAND_STATUS.SCG_COMMAND_COMPLETE)
{
new_serial_data = scg_command_buf.toString();
highlight = true;
scg_command_status = SCG_COMMAND_STATUS.SCG_COMMAND_NONE;
}
ret = MsgAnalyzerCmnDef.parse_serial_parameter(new_serial_data, highlight, MsgAnalyzerCmnDef.SHOW_DEVICE_SYSLOG);
if (MsgAnalyzerCmnDef.CheckSuccess(ret))
ret = serial_analyzer.add_serial_data(new_serial_data, highlight); // Update the data
}
else
{
if (MsgAnalyzerCmnDef.CheckIgnoreData(ret) || MsgAnalyzerCmnDef.CheckWaitSCGCommand(ret))
ret = MsgAnalyzerCmnDef.ANALYZER_SUCCESS;
}
return ret;
}
|
6c74bf67-1a93-4f60-a1b2-7fefd455b20e
| 6
|
public void cancelMorphs() {
final LinkedList<MapleBuffStatValueHolder> allBuffs = new LinkedList<MapleBuffStatValueHolder>(effects.values());
for (MapleBuffStatValueHolder mbsvh : allBuffs) {
switch (mbsvh.effect.getSourceId()) {
case 5111005:
case 5121003:
case 15111002:
case 13111005:
return; // Since we can't have more than 1, save up on loops
default:
if (mbsvh.effect.isMorph()) {
cancelEffect(mbsvh.effect, false, mbsvh.startTime);
continue;
}
}
}
}
|
26f8600f-6d2c-4a42-b33a-af602a85809d
| 5
|
private boolean isPlayerKingInCheckFromPieceHorizontallyRight() {
for (int j=playerKingPiece.pieceColumn + 1; j<=8; j++){
BoardSquare boardSquare = chessBoard.getBoardSquare(playerKingPiece.pieceLine, j);
if (boardSquare.containsBoardPiece()){
if (j==playerKingPiece.pieceColumn+1){
if (boardSquare.containsOpponentKing(playerColor)){
return true;
}
}
if (boardSquare.containsOpponentRookOrQueen(playerColor)){
return true;
}else{
return false;
}
}
}
return false;
}
|
1b277552-d4c7-4055-b36d-18b88a57c75b
| 2
|
public void testPropertyCompareToSecond() {
TimeOfDay test1 = new TimeOfDay(TEST_TIME1);
TimeOfDay test2 = new TimeOfDay(TEST_TIME2);
assertEquals(true, test1.secondOfMinute().compareTo(test2) < 0);
assertEquals(true, test2.secondOfMinute().compareTo(test1) > 0);
assertEquals(true, test1.secondOfMinute().compareTo(test1) == 0);
try {
test1.secondOfMinute().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.secondOfMinute().compareTo(dt2) < 0);
assertEquals(true, test2.secondOfMinute().compareTo(dt1) > 0);
assertEquals(true, test1.secondOfMinute().compareTo(dt1) == 0);
try {
test1.secondOfMinute().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
|
565784fe-7e7e-4ce5-b774-44c264d2dfbc
| 3
|
private static double limitM( double m ){
if( m < 0 ){
return -limitM( -m );
}
if( m < 0.5 ){
return 0.5;
}
else if( m > 1.5 ){
return 1.5;
}
else{
return m;
}
}
|
59b78435-9ec5-45bb-ad37-270b7ef635f4
| 8
|
@Override
public Buildable create(Object name, Object value) {
if (name.equals("step")) {
Step step = new Step(steps.size() + 1);
steps.add(step);
return step;
} else if (name.equals("rounds")) {
rounds = (Integer) value;
if (rounds < 1) {
throw new ComponentException("Illegal 'rounds': " + rounds);
}
} else if (name.equals("calibration_start")) {
calib_start = Conversions.convert(value, Date.class);
} else if (name.equals("StartMonthOfYear")) {
startMonthOfYear = (Integer) value-1;
if ((startMonthOfYear<0) || (startMonthOfYear>11)) throw new ComponentException("StartMonthOfYear must be between 1-12 for Jan-Dec.");
} else if (name.equals("summary_file")) {
String fname = value.toString();
SW.setFile(fname);
} else {
return super.create(name, value);
}
return LEAF;
}
|
9e464988-2dfd-429e-8f75-dea6f3464a74
| 3
|
public void EliminaFinal ()
{
if ( VaciaLista())
System.out.println ("No hay elementos");
else
{
if (PrimerNodo == PrimerNodo.siguiente)
PrimerNodo = null;
else
{
NodosProcesos Actual =PrimerNodo;
while (Actual.siguiente.siguiente != PrimerNodo)
Actual = Actual.siguiente;
Actual.siguiente = PrimerNodo;
}
}
}
|
6c7ffc92-d81b-4552-821d-d53106ff9b90
| 7
|
public static void main(String[] args) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
for (String line; (line = in.readLine()) != null ; ) {
if(line.trim().isEmpty())
sb.append("\n");
else{
int sum = 0;
StringBuilder newAns = new StringBuilder();
for (int i = 0; i < line.length(); i++) {
char actual = line.charAt(i);
if(Character.isDigit(actual)){
sum+=Integer.parseInt(actual+"");
}
else if(actual == '!')
newAns.append("\n");
else {
for (int j = 0; j < sum; j++) {
if(actual == 'b')
newAns.append(" ");
else
newAns.append(actual);
}
sum = 0;
}
}
sb.append(newAns+"\n");
}
}
System.out.print(new String(sb));
}
|
4a89d472-1709-4f24-bfe7-8973951b6320
| 1
|
protected void changedServerName(){
for(ModelChangeListener mcl : listeners){
mcl.changedServerName(serv_name);
}
}
|
ce997d07-ca4b-4843-bfc1-e3eb772075d1
| 0
|
public void setJournal(Journal journal) {
this.journal = journal;
}
|
7fa054a5-ead6-4b0e-989c-3690f6c0c085
| 2
|
public synchronized void printProcesses() {
if (processes.size() == 0) {
System.out.println("No processes running.");
return;
}
for (int i = 0; i < processes.size(); i++) {
MigratableProcessWrapper cur = processes.get(i).getMPW();
System.out.println(cur.getName());
}
}
|
465bc5ff-a0c5-4862-b2db-e1e21672f7ad
| 6
|
public void actionPerformed(ActionEvent evt){
//receives the start button event from the startPanel
if (evt.getActionCommand().equals(START_APP_EVENT)) {
displayHoustonSearch();
//receives the next button event from the QuestionPanel
}else if (evt.getActionCommand().equals(QUE_NEXT_EVENT)){
((Question) questionPanel.getQuestion()).doAction();
questionPanel.setNextQuestion(((GasDecisionProcess)decisionProcess).getNextPanelQuestion());
//if it reached the final question.
if (((Question) questionPanel.getQuestion()).getID() == 4)
questionPanel.setNextButActionCommand(QUE_DONE_EVENT);
//receives the final button event from the QuestionPanel
}else if (evt.getActionCommand().equals(QUE_DONE_EVENT)){
((Question) questionPanel.getQuestion()).doAction();
displayHoustonResults();
//received the Austin search button event
}else if (evt.getActionCommand().equals(ONE_CLICK_EVENT)){
austinSearchPanel = new OneClickStatusPanel();
this.remove(toNextCityPanel);
austinSearchPanel.setSize(255,430);
this.add(austinSearchPanel);
this.pack();
boolean isMapReady = setAustinMap(austinMap);
austinSearchPanel.increaseProgressBar(10); //increase the progress bar size
//if successfully got the map, loads the Austin business XML file
if (isMapReady) {
setSPA_Austin(austinXML);
austinSearchPanel.increaseProgressBar(10);
setTitle("CityFinder (current task: finds gas-stations near the UT in Austin, Texas)");
oneClickAutomation();
}
}
}
|
30e7b79d-ff8d-4127-924b-22526ac629c7
| 9
|
public void fetchFiles() {
int returnVal = this.chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File[] directorys = this.chooser.getSelectedFiles();
for(int i = 0; i < directorys.length;i++){
if(directorys[i].isDirectory()){
String album = directorys[i].getName();
File[] dirFiles = this.chooser.getSelectedFile().listFiles();
for(int j = 0; j < dirFiles.length; j++ ){
if(dirFiles[j].isDirectory()==false){
/*find the pos of the . in the filename*/
int pos = dirFiles[j].getName().lastIndexOf(".");
/*get extension name and place into string ext*/
String end = dirFiles[j].getName().substring(pos + 1);
if (isValidFileExtension(end) && dirFiles[j].isFile()){
ImageObject imageObject;
if(dirFiles[j].isDirectory() == false){
imageObject = Metadata.getImageObject(dirFiles[j]);
imageObject.setAlbumName(album);
imageObject.setFileName(dirFiles[j].getName());
imageObject.setFilePath(dirFiles[j].getAbsolutePath());
this.imageObjects.add(imageObject);
}
}
}
}
}
else{
for(int k = 0; k < this.chooser.getSelectedFiles().length; k++){
ImageObject imageObject = Metadata.getImageObject(this.chooser.getSelectedFiles()[k]);
imageObject.setAlbumName(this.chooser.getSelectedFiles()[k].getParentFile().getName());
imageObject.setFileName(chooser.getSelectedFiles()[k].getName());
imageObject.setFilePath(this.chooser.getSelectedFiles()[k].getAbsolutePath());
this.imageObjects.add(imageObject);
}
}
}
}
}
|
4260d380-e42d-4b32-841d-dcd53b9c4822
| 1
|
private void startRun() {
try {
Thread.currentThread().getId();
levelLoader = new XMLLevelLoader();
frame = new TopFrame(this);
frame.initLWJGL();
RenderEngine.setupOpenGL();
needsResize = true;
SoundStore.get().init();
gameMusic = SoundStore.get().getOgg(Res.getResourceAsStream("res/music.ogg"));
gameMusic.playAsMusic(-10, 5, true);
setMusicPlaying(false);
renderer = new RenderEngine(this);
textFont = new TrueTypeFont(Res.getFont("res/DejaVuSans-Bold.ttf", 20f), true);
renderer.mgl.setFont(textFont);
camControl = new CameraController();
camControl.setCamera(renderer.cam);
frame.loadLevelResource("res/Level1.xml");
setPaused(true);
exec.execute(this);
} catch (Exception e) {
frame.setVisible(false);
frame.dispose();
GUtils.makePanicFrame(e);
}
}
|
b4cadfbe-6913-40c4-af2c-ab4da7d49f62
| 3
|
void parseJsonImageMap(String json) {
String imageSrc = null;
try {
ImageMap imagemap = getImageMapFromJSON(json);
createShapeList(shapeList, imagemap);
if (shapeList.size() == 0)
statusBar.setText("no imagemap found");
/*
if (imagemap.getImagesource_id() > -1) {
imageSrc = String.format("%simagesource/%d/", this.appURL,
imagemap.getImagesource_id());
String json_text = readUrl(imageSrc);
Gson gson = new Gson();
ImageSource imgsrc = gson
.fromJson(json_text, ImageSource.class);
imagemap.setSrc(imgsrc.getPath());
imagemap.setImagesource_id(imgsrc.getId());
} else */if (!(new File(getImagePath(imagemap.getSrc()))).exists()) {
// supports absolute paths D:\mydir\myyadda.ext
throw new Exception("ImageSource id and src not set");
}
if (loadViewImage(getImagePath(imagemap.getSrc()))) {
imagemap.setDimension(new Dimension(image.getWidth(null), image
.getHeight(null)));
// imagemapPanel.setImage(image);
jMenuItem_zoom1.setSelected(true);
jTextArea_json.setText(shapeList.get_json(imageMap));
imageMap = imagemap;
mapChanged = false;
}
} catch (Exception ex) {
reportError("Error parsing ImageMap: " + ex.getMessage());
}
}
|
2af61314-212f-4530-b221-7d930980db60
| 0
|
public void setLayoutMatchingMode(LayoutMatchingMode mode) {
this.layoutMatchingMode = mode;
}
|
ea9d15b9-feaa-4fe3-b01e-a26507128418
| 1
|
@Test
public void test_config_keys()
{
final StringBuffer s = new StringBuffer();
for (Iterator i = configKeys(); i.hasNext(); )
{
s.append("<" + i.next().toString() + ">");
}
Assert.assertEquals(s.toString(), "<b_remote_host><c_latency><b_latency><b_local_port><b_remote_port>");
}
|
c2d3a26a-3fb4-4fe5-9885-8d4b6e27adc9
| 7
|
public Collection<SpriteClip> getSpriteClips(BufferedImage image, BackgroundFilter filter) {
int h = image.getHeight();
int w = image.getWidth();
Label[][] labelSheet = new Label[h][w];
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
int currentPixel = image.getRGB(col, row);
if (filter.isForeground(currentPixel)) {
Label returnedLabel = labelFromNeighborhood(labelSheet, w, col, row);
labelSheet[row][col] = returnedLabel;
}
}
}
/* Now reduce the labels to their representatives and get pixels and bounding
boxes. */
Map<Label, SpriteClip> clipRegistry = new HashMap();
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
Label currentLabel = labelSheet[row][col];
if (currentLabel != null) { // then we have an object pixel at this loc.
Label rep = labelEquivalence.getRep(currentLabel);
if (!clipRegistry.containsKey(rep)) {
SpriteClip sc = new SpriteClip(image, row, col, rep.toString());
clipRegistry.put(rep, sc);
} else {
SpriteClip sc = clipRegistry.get(rep);
sc.addLocation(row, col);
}
}
}
}
/* Now we have all the SpriteClips stored in a map. Return them. */
//return (Collection<SpriteClip>) clipRegistry.values();
Set<SpriteClip> returnList = new HashSet();
returnList.addAll(clipRegistry.values());
return returnList;
}
|
09eb271b-acf3-4592-9c81-7b726458dc62
| 2
|
private void initView(Configuration[] configs, final Environment env,
boolean blockStep) {
this.setLayout(new BorderLayout());
// Set up the main display.
SelectionDrawer drawer = new SelectionDrawer(automaton);
AutomatonPane display = new AutomatonPane(drawer, true);
// Add the listener to the display.
ArrowDisplayOnlyTool arrow = new ArrowDisplayOnlyTool(display, drawer);
display.addMouseListener(arrow);
// Initialize the lower display.
JPanel lower = new JPanel();
lower.setLayout(new BorderLayout());
// Initialize the scroll pane for the configuration view.
JScrollPane scroller = new JScrollPane(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// Set up the configurations pane.
ConfigurationPane configurations = new ConfigurationPane(automaton);
configurations.setLayout(new GridLayout(0, 4));
for (int i = 0; i < configs.length; i++){
configurations.add(configs[i]);
}
// Set up the bloody controller device.
final ConfigurationController controller = new ConfigurationController(
configurations, simulator, drawer, display);
env.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (env.contains(SimulatorPane.this))
return;
env.removeChangeListener(this);
controller.cleanup();
}
});
ControlPanel controlPanel = new ControlPanel(controller);
controlPanel.setBlock(blockStep);
// Set up the lower display.
scroller.getViewport().setView(configurations);
lower.add(scroller, BorderLayout.CENTER);
lower.add(controlPanel, BorderLayout.SOUTH);
// Set up the main view.
JSplitPane split = SplitPaneFactory.createSplit(env, false, .6,
display, lower);
this.add(split, BorderLayout.CENTER);
}
|
97dc4c29-8c5d-4577-88e0-6f88ea2ca939
| 8
|
public static void findLongestSubPalindramic(String s) {
char[] arr = s.toCharArray();
int begin = -1;
int end;
int temp_begin;
int maxLength = -1;
boolean[][] table = new boolean[1000][1000];
for (int i = 0; i < table.length; i++) {
table[i][i] = true;
}
for (int i = 0; i < s.length() - 1; i++) {
if (arr[i] == arr[i + 1]) {
table[i][i + 1] = true;
begin = i;
maxLength = 2;
}
}
for (int len = 2; len < arr.length; len++) {
for (int i = 0; i < arr.length - len + 1; i++) {
int j = len + i - 1;
if (table[i + 1][j - 1] && (arr[i] == arr[j])) {
table[i][j] = true;
if (j - i + 1 > maxLength) {
begin = i;
maxLength = maxLength + 2;
}
}
}
}
System.out.println("begin:" + begin + ", length:" + maxLength);
}
|
45ff74af-e454-4c95-87a4-892f8ae780f3
| 9
|
public HexDumpOutputStream createHexDumpOutputStream() {
BasicType hexdumpFormat = this.getGlobalConfiguration().get( Constants.CKEY_HTTPCONFIG_HEXDUMP_FORMAT );
// System.out.println( "hexdumpFormat=" + hexdumpFormat );
int[] columns = null;
String str_hexdumpFormat = null;
if( hexdumpFormat != null
&& (str_hexdumpFormat = hexdumpFormat.getString()) != null
&& str_hexdumpFormat.length() != 0 ) {
try {
String[] splits = str_hexdumpFormat.split( "," );
int[] tmp_columns = CustomUtil.string2int( splits );
for( int i = 0; i < tmp_columns.length; i++ ) {
if( tmp_columns[i] < 0 )
throw new IllegalArgumentException( "Hexdump columns must not be negative (at index " + i + ": " +tmp_columns[i]+")." );
}
columns = tmp_columns;
} catch( NumberFormatException e ) {
this.logger.log( Level.WARNING,
getClass().getName() + ".createHexDumpOutputStream()",
"[NumberFormatException] " + e.getMessage() + " Going to use default column set." );
} catch( NullPointerException e ) {
this.logger.log( Level.WARNING,
getClass().getName() + ".createHexDumpOutputStream()",
"[NullPointerException] " + e.getMessage() + " Going to use default column set." );
} catch( IllegalArgumentException e ) {
this.logger.log( Level.WARNING,
getClass().getName() + ".createHexDumpOutputStream()",
"[IllegalArgumentException] " + e.getMessage() + " Going to use default column set." );
}
} else {
this.logger.log( Level.WARNING,
getClass().getName() + ".createHexDumpOutputStream()",
"No hexdump column format specified. Going to use default column set." );
}
if( columns == null ) {
columns = new int[]{ 8, 8,
0, // one separator column
8, 8,
0, 0, // two separator columns
8, 8,
0, // one separator column
8, 8 };
}
/*
System.out.println( "HEXDUMP COLUMNS: " );
for( int i = 0; i < columns.length; i++ )
System.out.print( " " + columns[i] );
System.out.println( "\n" );
*/
HexDumpOutputStream hexOut =
new HexDumpOutputStream( new OutputStreamWriter( System.out ),
columns );
return hexOut;
}
|
b08f3585-b854-40d4-8312-49d5be42e7e9
| 0
|
public RandomWords(int count) {
this.count = count;
}
|
73ec859d-c0c1-41a7-99e8-5adf2e6c6511
| 5
|
public boolean intersect(float i, float j, float k) {
return !(i <= x || i >= x + w || j <= y || j >= y + h || k <= z || k >= z + d);
}
|
302ae104-1968-4577-9737-8684ccf4f4e0
| 6
|
private final ArrayList<String> edits(String word)
{
ArrayList<String> result = new ArrayList<String>();
for(int i=0; i < word.length(); ++i)
result.add(word.substring(0, i) + word.substring(i+1));
for(int i=0; i < word.length()-1; ++i)
result.add(word.substring(0, i) + word.substring(i+1, i+2) + word.substring(i, i+1) + word.substring(i+2));
for(int i=0; i < word.length(); ++i)
for(char c='a'; c <= 'z'; ++c)
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i+1));
for(int i=0; i <= word.length(); ++i)
for(char c='a'; c <= 'z'; ++c)
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));
return result;
}
|
5ade77d4-5897-46c3-bdd7-c8c44e5a69dc
| 5
|
public void selectLevel(){
Menu myWorld = (Menu) getWorld();
switch(state){
case 0:
Greenfoot.setWorld(new Menu());
break;
case 1:
setImage("ShipCoordinatorInfo.png");
setLocation(500,300);
myWorld.removeOtherNewLevels(1);
myWorld.addObject(new PlayButton(1),700,500);
myWorld.addObject(new MenuButton(), 300,500);
break;
case 2:
setImage("CargoLifterInfo.png");
setLocation(500,300);
myWorld.removeOtherNewLevels(2);
myWorld.addObject(new PlayButton(2),700,500);
myWorld.addObject(new MenuButton(), 300,500);
break;
case 3:
setImage("XrayControlInfo.png");
setLocation(500,300);
myWorld.removeOtherNewLevels(3);
myWorld.addObject(new PlayButton(3),700,500);
myWorld.addObject(new MenuButton(), 300,500);
break;
case 4:
setImage("HarborPatrolInfo.png");
setLocation(500,300);
myWorld.removeOtherNewLevels(4);
myWorld.addObject(new PlayButton(4),700,500);
myWorld.addObject(new MenuButton(), 300,500);
break;
}
}
|
ba5d407f-e045-47b6-97ed-94091f07b290
| 2
|
public void testGetValue_int() {
LocalDateTime test = new LocalDateTime(ISO_UTC);
assertEquals(1970, test.getValue(0));
assertEquals(6, test.getValue(1));
assertEquals(9, test.getValue(2));
assertEquals(MILLIS_OF_DAY_UTC, test.getValue(3));
try {
test.getValue(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getValue(3);
} catch (IndexOutOfBoundsException ex) {}
}
|
943f9c5d-7188-4a05-bf18-6b4a790a014b
| 2
|
public boolean deleteCircle(Circle circle) {
if (this.next.data.equals(circle.data)) {
if (circle.data.equals(start.data)) {
start = next.next;
this.next = start;
return true;
} else {
this.next = next.next;
return true;
}
} else {
return this.next.deleteCircle(circle);
}
}
|
56e86ac3-bd53-4c3b-84d8-8ef427209944
| 9
|
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Province other = (Province) obj;
if (!Objects.equals(this.nom, other.nom)) {
return false;
}
if (this.faveur1 != other.faveur1) {
return false;
}
if (this.faveur2 != other.faveur2) {
return false;
}
if (this.faveur3 != other.faveur3) {
return false;
}
if (this.faveur4 != other.faveur4) {
return false;
}
if (this.nbtroupes != other.nbtroupes) {
return false;
}
if (!Objects.equals(this.troupe, other.troupe)) {
return false;
}
return true;
}
|
a4dcd2ae-8455-4357-a781-f420e1f42daa
| 1
|
public void addToIpMap(ChannelHandlerContext ctx) {
String clientIP = ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString();
synchronized (ipMap){
if (!ipMap.containsKey(clientIP)) {//if IP is new --> put it in map with default count 1 and current time
ipMap.put(clientIP, new IpData());
uniqueIpCount.incrementAndGet();
} else { // if IP is not new --> update time and increment count
ipMap.get(clientIP).incrementCount();
ipMap.get(clientIP).updateTime(); // in order to know the time of last request
}
}
}
|
42c9ca6a-dcf8-4e98-a4d7-264c21ea3f1b
| 9
|
public void bubblesort(){
int count = 1; //To pass the first while
while (count != 0){
count = 0;
for (int i = 0; i < number-1; i++) {
Class<? extends Object> c = objectsToSort[i].getClass();
Class[] cArg = new Class[1];
cArg[0] = objectsToSort[i].getClass();
Method lmethod;
try {
lmethod = c.getDeclaredMethod("compareTo", cArg);
Object[] vect = {objectsToSort[i+1]};
if((int)lmethod.invoke(objectsToSort[i], vect) > 0) {
Utils.exchangeObj(i, i+1, objectsToSort);
count++;
}
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
81f37f81-470c-46ab-a74b-8c71bc027d59
| 9
|
public StructuredFloat buildByType(boolean isNegative,
FloatNumberType doubleType, FloatNumberSpecialValue specialValue) {
switch (doubleType) {
case Nan:
normalizedExp = config.MaxExp + 1;
fraction = 1;
negative = isNegative;
break;
case Infinite: {
normalizedExp = config.MaxExp + 1;
fraction = 0;
negative = isNegative;
break;
}
case Normalized: {
switch (specialValue) {
case Zero:
normalizedExp = config.MinExp;
fraction = 0;
negative = isNegative;
break;
case MaxValue:
normalizedExp = config.MaxExp;
fraction = config.MaxFraction;
negative = isNegative;
break;
case MinNormal:
normalizedExp = config.MinExp;
fraction = 0;
negative = isNegative;
break;
default:
throw new IllegalArgumentException();
}
// Attetion
break;
}
case SubNormalized:
switch (specialValue) {
case MaxSubNormal:
normalizedExp = config.MinExp - 1;
fraction = config.MaxFraction;
negative = isNegative;
break;
case MinSubNormal:
normalizedExp = config.MinExp - 1;
fraction = 1;
negative = isNegative;
break;
default:
throw new IllegalArgumentException();
}
// Attetion
break;
}
buildSpecialValue();
return this;
}
|
1c39529e-2e68-4244-909d-2f4b23464608
| 0
|
@Override
public void init(List<String> argumentList) {
offset = Integer.parseInt(argumentList.get(0));
identifier = argumentList.get(1);
}
|
8f807367-686b-4512-935c-f5bf414932f1
| 8
|
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BloomFilter<E> other = (BloomFilter<E>) obj;
if (this.expectedNumberOfFilterElements != other.expectedNumberOfFilterElements) {
return false;
}
if (this.k != other.k) {
return false;
}
if (this.bitSetSize != other.bitSetSize) {
return false;
}
if (this.bitset != other.bitset && (this.bitset == null || !this.bitset.equals(other.bitset))) {
return false;
}
return true;
}
|
31192dda-da45-4e73-8f97-4e66be8d899a
| 7
|
public void paintPattern(Graphics2D g, Page parentPage) {
if (patternPaint == null) {
AffineTransform matrixInv = getInvMatrix();
Rectangle2D bBoxMod = matrix.createTransformedShape(bBox).getBounds2D();
int width = (int) bBoxMod.getWidth();
int height = (int) bBoxMod.getHeight();
// corner cases where some bBoxes don't have a dimension.
if (width == 0) {
width = 1;
}
if (height == 0) {
height = 1;
}
// create the new image to write too.
final BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D canvas = bi.createGraphics();
// apply current hints
canvas.setRenderingHints(g.getRenderingHints());
// copy over the rendering hints
// get shapes and paint them.
Shapes tilingShapes = getShapes();
if (tilingShapes != null) {
// setup resource parent
tilingShapes.setPageParent(parentPage);
canvas.setClip(0, 0, width, height);
// apply the pattern space
canvas.setTransform(matrix);
// move it back by any shear/rotation distance.
canvas.translate(matrixInv.getTranslateX(),
matrixInv.getTranslateY());
if (paintType == TilingPattern.PAINTING_TYPE_UNCOLORED_TILING_PATTERN) {
canvas.setColor(unColored);
}
// paint the pattern content stream.
tilingShapes.paint(canvas);
// do a little tiling if there is a shear so that we
// don't end up with any white space around the rotate
// pattern cell. Java texture paint can't take a transform
// when painting so this will have to do.
if (matrix.getShearX() > 0 ||
matrix.getShearY() > 0) {
canvas.translate(bBox.getWidth(), 0);
tilingShapes.paint(canvas);
canvas.translate(0, -bBox.getHeight());
tilingShapes.paint(canvas);
canvas.translate(-bBox.getWidth(), 0);
tilingShapes.paint(canvas);
canvas.translate(-bBox.getWidth(), 0);
tilingShapes.paint(canvas);
canvas.translate(0, bBox.getHeight());
tilingShapes.paint(canvas);
canvas.translate(0, bBox.getHeight());
tilingShapes.paint(canvas);
canvas.translate(bBox.getWidth(), 0);
tilingShapes.paint(canvas);
canvas.translate(bBox.getWidth(), 0);
tilingShapes.paint(canvas);
}
// release the page parent
tilingShapes.setPageParent(null);
}
// finally paint the graphic using the current gs.
patternPaint = new TexturePaint(bi, bBoxMod);
g.setPaint(patternPaint);
// show it in a frame
// final JFrame f = new JFrame("Test");
// f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// f.getContentPane().add(new JComponent() {
// @Override
// public void paint(Graphics g_) {
// super.paint(g_);
// g_.drawImage(bi, 0, 0, f);
// }
// });
// f.setSize(new Dimension(800, 800));
// f.setVisible(true);
// post paint cleanup
canvas.dispose();
bi.flush();
} else {
g.setPaint(patternPaint);
}
}
|
0b3f90c7-21d8-4db6-95cc-6e5892e933f2
| 1
|
private void resize(int capacity) {
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < next; i++) {
temp[i] = a[i];
}
this.a = temp;
}
|
af88f7b5-ec27-4ab0-9aaf-3e30722c0c21
| 0
|
@Test
public void testSchemaCreation() throws SQLException {
Star.setup();
}
|
51fde69b-5e7c-443d-8a93-6f5c76569309
| 0
|
public Upgrade getUpgrade(){
return upgrade;
}
|
0d40cdfa-f534-4d3c-a8f6-a338d8d52637
| 5
|
public void startAnimation() {
if(interval == -1) {return;}
if(animation == null) {
frameIndex.add(0);
animation = new Timer(interval, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0; i<entity.size(); i++) {
if(frameIndex.get(i) < frameTotal) {frameIndex.set(i, frameIndex.get(i)+1);}
else {frameIndex.set(i, 0);}
sendImage(i);
}
}
});
animation.setRepeats(true);
animation.start();
return;
}
if(animation.isRunning()) {return;}
else {animation.start();}
}
|
16e8d3cb-4cb2-49bd-9898-2a7a5e3ac0a4
| 4
|
@Override
public void remove() {
if(current == null) // empty iterator
return;
if(current.getPrev() != null)
current.getPrev().setNext(current.getNext());
if(current.getNext() != null)
current.getNext().setPrev(current.getPrev());
if(current.getPrev() == null)
s.root = current.getNext();
s.size--;
//current element has been removed
}
|
f8dc3e9f-b7fd-409a-af82-fcdb42f06744
| 2
|
public void removeBogusLegs() {
Iterator<Leg> it = legs.iterator();
while (it.hasNext()) {
Leg leg = it.next();
if (leg.isBogusWalkLeg()) {
it.remove();
}
}
}
|
aa405827-31bb-460d-b5fa-d188b8647567
| 9
|
private boolean salvarConfigsImpressoraCaixa() {
System.out.println("Configurando Impressora do Caixa:");
usarImpressoraCaixa = checkboxAtivarImpressoraCaixa.isSelected();
System.out.println("Usar impressora do caixa: " + usarImpressoraCaixa);
switch (comboboxModeloCaixa.getSelectedIndex()) {
case 0:
System.out.println("A opção selecionada é inválida!");
return false;
case 1:
System.out.println("Modelo selecionado: MP-4000 TH");
modeloImpressoraCaixa = 5;
break;
case 2:
System.out.println("Modelo selecionado: MP-4200 TH");
modeloImpressoraCaixa = 7;
break;
default:
System.out.println("Erro ao selecionar o modelo da impressora");
return false;
}
if (botaoRadioEthernetCaixa.isSelected()) {
interfaceImpressoraCaixa = "ethernet";
enderecoImpressoraCaixa = campoEnderecoCaixa.getText();
System.out.println("Interface selecionada: Ethernet");
System.out.println("Endereço IP: " + campoEnderecoCaixa.getText());
} else if (botaoRadioParalelaCaixa.isSelected()) {
interfaceImpressoraCaixa = "paralela";
enderecoImpressoraCaixa = "LPT1";
System.out.println("Interface selecionada: Paralela");
} else if (botaoRadioUsbCaixa.isSelected()) {
interfaceImpressoraCaixa = "usb";
enderecoImpressoraCaixa = "USB";
System.out.println("Interface selecionada: USB");
}
try {
salvou[0] = ManipulaConfigs.setProp("prop.impressora.caixa.ativa", String.valueOf(usarImpressoraCaixa));
salvou[1] = ManipulaConfigs.setProp("prop.impressora.caixa.modelo", String.valueOf(modeloImpressoraCaixa));
salvou[2] = ManipulaConfigs.setProp("prop.impressora.caixa.interface", interfaceImpressoraCaixa);
salvou[3] = ManipulaConfigs.setProp("prop.impressora.caixa.endereco", enderecoImpressoraCaixa);
} catch (IOException ex) {
Logger.getLogger(TelaConfiguracoes.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < 4; i++) {
if (salvou[i] == false) {
return false;
}
}
System.out.println("---------------------------------------------\n");
return true;
}
|
a639fe9c-14bd-40f5-af75-d86401baf791
| 4
|
private void add_s(Buffer lbuf, LuaString news, int soff, int e) {
int l = news.length();
for (int i = 0; i < l; ++i) {
byte b = (byte) news.luaByte(i);
if (b != L_ESC) {
lbuf.append((byte) b);
} else {
++i; // skip ESC
b = (byte) news.luaByte(i);
if (!Character.isDigit((char) b)) {
lbuf.append(b);
} else if (b == '0') {
lbuf.append(s.substring(soff, e));
} else {
lbuf.append(push_onecapture(b - '1', soff, e).strvalue());
}
}
}
}
|
5a09c14f-6fe6-4ed4-8df9-61e9a6e18772
| 7
|
public String genLargeDB() {
String nextLine;
URL url;
URLConnection urlConn;
InputStreamReader inStream;
BufferedReader buff;
this.largedb = "";
try {
for (NEOCP neocp : neocpData) {
url = new URL(
"http://scully.cfa.harvard.edu/cgi-bin/showobsorbs.cgi?Obj="
+ neocp.getTmpdesig() + "&orb=y");
urlConn = url.openConnection();
inStream = new InputStreamReader(
urlConn.getInputStream());
buff = new BufferedReader(inStream);
while (true) {
nextLine = buff.readLine();
if (nextLine != null) {
Pattern pattern = Pattern.compile("NEOCPNomin");
Matcher matcher = pattern.matcher(nextLine);
if (matcher.find()) {
//output = output + nextLine + (System.getProperty("line.separator"));;
Pattern splitPattern = Pattern.compile("^(.{7}) "
+ "(.{4}) (.{4}) (.{5}) (.{9}) (.{9}) "
+ "(.{9}) (.{9}) (.{9}) (.{10}) "
+ "(.{10})");
Matcher m = splitPattern.matcher(nextLine);
while (m.find()) {
String TmpDesig = m.group(1).trim();
Float H = Float.parseFloat(m.group(2).trim());
Float G = Float.parseFloat(m.group(3).trim());
String Epoch = m.group(4).trim();
Float M = Float.parseFloat(m.group(5).trim());
Float Peri = Float.parseFloat(m.group(6).trim());
Float Node = Float.parseFloat(m.group(7).trim());
Float Incl = Float.parseFloat(m.group(8).trim());
Float e = Float.parseFloat(m.group(9).trim());
Float n = Float.parseFloat(m.group(10).trim());
Float a = Float.parseFloat(m.group(11).trim());
this.largedb = this.largedb + String.format("%7s %5.2f %5.2f %5s "
+ "%9.5f %9.5f %9.5f %9.5f %9.7f %11.8f %11.7f"
+ " 0 NEOCP 10 1 1 days "
+ "0.00 Z72GUESS 0000 %-28s "
+ (System.getProperty("line.separator")), TmpDesig,
H, G, Epoch, M, Peri, Node, Incl,
e, n, a, TmpDesig);
}
break; // We're only taking the first orbit.
// So no point continuing to parse.
}
} else {
break;
}
}
}
} catch (MalformedURLException e) {
System.out.println("Please check the URL:"
+ e.toString());
} catch (IOException e1) {
System.out.println("Can't read from the Internet: "
+ e1.toString());
}
return (this.largedb);
}
|
72130249-7866-4c37-b1bc-e9d63df0af89
| 9
|
public final void setConfigValue(final String section, final String key,
final String value) {
synchronized (this.configOld) {
synchronized (this.configNew) {
if (value == null) {
if (getConfigValue(section, key, null) != null) {
final Map<String, String> map0 = this.configNew
.get(section);
if (map0 == null) {
final Map<String, String> map1 = new HashMap<>();
map1.put(key, null);
this.configNew.put(section, map1);
} else {
map0.put(key, null);
}
}
} else {
final Map<String, String> mapOld = this.configOld
.get(section);
final Map<String, String> map0 = this.configNew
.get(section);
if (mapOld != null) {
final String valueOld = mapOld.get(key);
if ((valueOld != null) && valueOld.equals(value)) {
if (map0 == null) {
return;
}
map0.remove(key);
if (map0.isEmpty()) {
this.configNew.remove(section);
}
return;
}
}
if (map0 != null) {
map0.put(key, value);
} else {
final Map<String, String> map1 = new HashMap<>();
map1.put(key, value);
this.configNew.put(section, map1);
}
}
}
}
}
|
45ea5025-c62e-4517-9888-1b73fa8ee76a
| 2
|
public void updateImage()
{
//we will update animation when delay counter reaches delay, then reset delay counter
delayCounter++;
if(delayCounter>delay)
{
delayCounter=0;
frameNumber++;//updates frame to next frame
//if surpass 3rd frame, back to frameNumber 0
if (frameNumber>=firstFrame+totalFrame)
{
frameNumber=firstFrame;
}
//sets image to specific frameNumber by multiplying width of the image
this.setImage(frameNumber*32+frameNumber+5,yLocationSpriteSheet,width,height ,newWidth, newHeight );
}
}
|
805b89e5-7fdd-4869-9c8d-08ca02cb26f8
| 8
|
public void parseString(String inputLine) {
System.out.println(inputLine);
String tagRegex = "(beat|accel|heartrate|eeg|pressure)=(.*)";
Pattern pattern = Pattern.compile(tagRegex);
Matcher matcher = pattern.matcher(inputLine);
if (matcher.matches()) {
String tag = matcher.group(1), value = matcher.group(2);
String multipleValueRegex = "([\\d]+\\.[\\d]+),(([\\d]+\\.[\\d]+),?)+";
pattern = Pattern.compile(multipleValueRegex);
matcher = pattern.matcher(value);
if(matcher.matches()) {
String[] floats = value.split(",");
switch(tag) {
case "accel":
mAccelerationValues[0] = Float.valueOf(floats[0]);
mAccelerationValues[1] = Float.valueOf(floats[1]);
mAccelerationValues[2] = Float.valueOf(floats[2]);
break;
case "eeg":
if (Float.valueOf(floats[0]) > 0) {
mEEGValues[0] = Float.valueOf(floats[1]);
mEEGValues[1] = Float.valueOf(floats[2]);
}
break;
}
} else {
switch(tag) {
case "beat":
mBeatValue = Float.valueOf(value);
break;
case "heartrate":
mHeartRateValue = Float.valueOf(value);
break;
case "pressure":
mPressureValue = Float.valueOf(value);
break;
}
}
}
}
|
e5c5309b-0184-45c6-ab27-8c0142d265fc
| 9
|
public void printBoard() {
System.out.print(" ");
for(int c = 0; c < 8; c++) {
if(flipped)
System.out.print((char)('h'-c) + " ");
else
System.out.print((char)(c + 'a') + " ");
}
System.out.println();
System.out.println(" _________________ ");
for(int r = 0; r < 8; r++) {
if(flipped)
System.out.print("" + (1+r) + " |");
else
System.out.print("" + (8-r) + " |");
for(int c = 0; c < 8; c++) {
Location loc = new Location(r,c);
if(get(loc) == null)
System.out.print("_|");
else
System.out.print(get(loc) + "|");
}
if(flipped)
System.out.println(" " + (1+r));
else
System.out.println(" " + (8-r));
}
System.out.println(" ----------------- ");
System.out.print(" ");
for(int c = 0; c < 8; c++) {
if(flipped) {
System.out.print((char)('h'-c) + " ");
} else
System.out.print((char)(c + 'a') + " ");
}
System.out.println();
System.out.println("Captured White Pieces: " + capturedWhitePieces);
System.out.println("Captured Black Pieces: " + capturedBlackPieces);
}
|
0ea292bc-3494-4a2c-af91-49bb038ab0b7
| 1
|
public String map2QcTestSetName(ISuite suite)
{
return (this.qcTestSetName != null ? this.qcTestSetName : suite.getName());
}
|
f66cd955-96bf-46e0-a7aa-0c413f3e9b39
| 2
|
public static CustomerGroup getByNumber(final String token, final Long number) {
JSONArray fetchByNumber = null;
try {
fetchByNumber = fetchByNumber(token, object, number);
} catch (IOException e) {
e.printStackTrace();
}
List<CustomerGroup> formatOutputs = formatOutputs(fetchByNumber);
if (formatOutputs.size() > 0)
return formatOutputs.get(0);
return null;
}
|
c75454c8-18a3-41d0-991a-ae82dc681992
| 9
|
public static List readWatchableObjects(DataInputStream var0) throws IOException {
ArrayList var1 = null;
for(byte var2 = var0.readByte(); var2 != 127; var2 = var0.readByte()) {
if(var1 == null) {
var1 = new ArrayList();
}
int var3 = (var2 & 224) >> 5;
int var4 = var2 & 31;
WatchableObject var5 = null;
switch(var3) {
case 0:
var5 = new WatchableObject(var3, var4, Byte.valueOf(var0.readByte()));
break;
case 1:
var5 = new WatchableObject(var3, var4, Short.valueOf(var0.readShort()));
break;
case 2:
var5 = new WatchableObject(var3, var4, Integer.valueOf(var0.readInt()));
break;
case 3:
var5 = new WatchableObject(var3, var4, Float.valueOf(var0.readFloat()));
break;
case 4:
var5 = new WatchableObject(var3, var4, Packet.readString(var0, 64));
break;
case 5:
short var9 = var0.readShort();
byte var10 = var0.readByte();
short var11 = var0.readShort();
var5 = new WatchableObject(var3, var4, new ItemStack(var9, var10, var11));
break;
case 6:
int var6 = var0.readInt();
int var7 = var0.readInt();
int var8 = var0.readInt();
var5 = new WatchableObject(var3, var4, new ChunkCoordinates(var6, var7, var8));
}
var1.add(var5);
}
return var1;
}
|
ed9d85a6-a099-460d-80ab-438ca1f1a46a
| 2
|
public Object unmarshal(InputStream xml) {
long start = System.currentTimeMillis();
Unmarshaller unmarshaller = unmarshallerPool.borrow();
try {
BufferedInputStream bufXml = new BufferedInputStream(xml);
SAXSource saxSource = new SAXSource(createNewXmlReader(), new InputSource(bufXml));
return unmarshaller.unmarshal(saxSource);
} catch (JAXBException e) {
throw new XmlTransformationException("Failed to unmarshal xml", e);
} finally {
unmarshallerPool.release(unmarshaller);
if (LOG.isDebugEnabled()) {
LOG.debug("Unmarshalled in : " + (System.currentTimeMillis() - start) + " ms");
}
}
}
|
d369987b-3265-47dd-95bc-9b259a729838
| 7
|
public static ArrayList<Object[][]> floydRoyWarshall(mxAnalysisGraph aGraph) throws StructuralException
{
Object[] vertices = aGraph.getChildVertices(aGraph.getGraph().getDefaultParent());
Double[][] dist = new Double[vertices.length][vertices.length];
Object[][] paths = new Object[vertices.length][vertices.length];
Map<Object, Integer> indexMap = new HashMap<Object, Integer>();
for (int i = 0; i < vertices.length; i++)
{
indexMap.put(vertices[i], i);
}
Object[] edges = aGraph.getChildEdges(aGraph.getGraph().getDefaultParent());
dist = initializeWeight(aGraph, vertices, edges, indexMap);
for (int k = 0; k < vertices.length; k++)
{
for (int i = 0; i < vertices.length; i++)
{
for (int j = 0; j < vertices.length; j++)
{
if (dist[i][j] > dist[i][k] + dist[k][j])
{
paths[i][j] = mxGraphStructure.getVertexWithValue(aGraph, k);
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
for (int i = 0; i < dist[0].length; i++)
{
if (dist[i][i] < 0)
{
throw new StructuralException("The graph has negative cycles");
}
}
ArrayList<Object[][]> result = new ArrayList<Object[][]>();
result.add(dist);
result.add(paths);
return result;
};
|
484ad097-4071-44d1-bd6e-9fba302a3d91
| 1
|
private void initialSpeciate(List<Organism> organisms) {
if (getSpecies().isEmpty()) {
/**
* In the first generation, since there are no preexisting species,
* NEAT begins by creating species 1 and placing the first genome
* into that species.
*/
getSpecies().add(new Species(organisms.get(0)));
organisms.remove(0);
speciate(organisms);
}
}
|
23eab445-15c7-4a62-af3f-e47eb9fd992d
| 4
|
public final A index(final int i) {
if (i < 0)
throw error("index " + i + " out of range on stream");
else {
Stream<A> xs = this;
for (int c = 0; c < i; c++) {
if (xs.isEmpty())
throw error("index " + i + " out of range on stream");
xs = xs.tail()._1();
}
if (xs.isEmpty())
throw error("index " + i + " out of range on stream");
return xs.head();
}
}
|
a99d466e-c99a-468f-a361-84e674fbe741
| 2
|
public void run() {
while (true) {
try {
disp = mon.getDisplayData();
HW.display(disp.ticket, disp.counter);
sleep(10000);
} catch (InterruptedException e) { break; }
}
}
|
556d43ff-0bcd-4e88-8180-f05a239439e7
| 4
|
public boolean existsBooking(Booking booking) {
List<Booking> bookings = this.getBookings();
Iterator<Booking> iter = bookings.iterator();
while (iter.hasNext()) {
Booking b = iter.next();
if (b.getDate().equals(booking.getDate())
&& b.getDiningHall().equals(booking.getDiningHall())
&& b.getStudent().equals(booking.getStudent()))
return true;
}
return false;
}
|
ad7f88d4-2faa-4320-a699-dceab02601be
| 7
|
public String toString()
{
String compoundString = "";
for(int k = 0; k < elements.length; k++)
{
if(elements[k] instanceof Compound && ((Compound)elements[k]).containsCompound())
compoundString += "[" + elements[k].toString() + "]" + ((subscripts[k] == 1)? "" : "" + subscripts[k]);
else if(elements[k] instanceof Compound)
compoundString += "(" + elements[k].toString() + ")" + ((subscripts[k] == 1)? "" : "" + subscripts[k]);
else
compoundString += elements[k].toString() + ((subscripts[k] == 1)? "" : "" + subscripts[k]);
}
return compoundString;
}
|
660bd2d2-a96e-4155-a457-f4d0c8371dfd
| 6
|
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<TreeNode> s = new ArrayList<TreeNode>();
if (root == null) {
return null;
}
s.add(root);
int[] cou = new int[Integer.MAX_VALUE];
int cur = 0;
int curcount = 0;
cou[0]++;
ArrayList<ArrayList<Integer>> returnArr = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
returnArr.add(temp);
while (!s.isEmpty()) {
if (curcount == cou[cur]) {
cur++;
curcount = 0;
temp = new ArrayList<>();
returnArr.add(temp);
}
curcount++;
TreeNode node = s.remove(0);
temp.add(node.getVal());
if (node.getLeft() != null) {
s.add(node.getLeft());
cou[cur + 1]++;
}
if (node.getRight() != null) {
s.add(node.getRight());
cou[cur + 1]++;
}
}
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
for (int i = 0; i < returnArr.size(); i++) {
ans.add(returnArr.remove(i));
}
return ans;
}
|
a7d2cff3-d94d-4c4e-b4be-0f0366cebfc7
| 0
|
private void initialize() {
GO = GUITreeLoader.reg.getText("goto_dialog_go");
GOTO_LINE_AND_COLUMN = GUITreeLoader.reg.getText("goto_dialog_line_and_column");
CANCEL = GUITreeLoader.reg.getText("cancel");
lineNumberTextField = new JTextField(10);
columnNumberTextField = new JTextField(10);
countDepthCheckBox = new JCheckBox(GUITreeLoader.reg.getText("goto_dialog_count_indents"));
goButton = new JButton(GO);
gotoLineAndColumnButton = new JButton(GOTO_LINE_AND_COLUMN);
cancelButton = new JButton(CANCEL);
// Create the layout
setResizable(false);
this.getContentPane().setLayout(new BorderLayout());
goButton.addActionListener(this);
gotoLineAndColumnButton.addActionListener(this);
cancelButton.addActionListener(this);
Box vBox = Box.createVerticalBox();
vBox.add(new JLabel(GUITreeLoader.reg.getText("goto_dialog_enter_column")));
vBox.add(columnNumberTextField);
vBox.add(countDepthCheckBox);
vBox.add(Box.createVerticalStrut(5));
vBox.add(new JLabel(GUITreeLoader.reg.getText("goto_dialog_enter_line")));
vBox.add(lineNumberTextField);
vBox.add(Box.createVerticalStrut(5));
Box hBox = Box.createHorizontalBox();
hBox.add(cancelButton);
hBox.add(Box.createHorizontalStrut(5));
hBox.add(gotoLineAndColumnButton);
hBox.add(Box.createHorizontalStrut(5));
hBox.add(goButton);
// Put it all together
this.getContentPane().add(vBox,BorderLayout.CENTER);
this.getContentPane().add(hBox,BorderLayout.SOUTH);
// Set the default button
getRootPane().setDefaultButton(goButton);
// This let's us actually set the focus in our modal dialog.
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
lineNumberTextField.requestFocus();
}
@Override
public void windowOpened(WindowEvent e) {
lineNumberTextField.requestFocus();
}
});
dialog.pack();
}
|
15537873-7667-47c1-bc7d-f46c4d651636
| 1
|
@Override
public void updateView() {
listModel.removeAllElements();
for (String s : controller.getModel().getSearchFormats()) {
listModel.addElement(s);
}
formatList.setModel(listModel);
}
|
493b763a-ca7e-49aa-9519-2b68098379aa
| 7
|
private FileLoaderCor() {
IMyProperties mp;
FileLoaderAbstract lastOne = null;
boolean ok = false;
try {
mp = MyPropertiesFactory.getInstance().getProp();
String[] classes = mp.getProperty("FileLoaderClasses").split(",");
for(int i = (classes.length-1); i > -1; --i) {
String curCl = classes[i].trim();
try {
Class<?> cl = Class.forName(curCl);
Constructor<?> ci = cl.getDeclaredConstructor(new Class<?>[]{ Class.forName("jMyCTMC.inputFiles.FileLoaderAbstract") });
FileLoaderAbstract fa = (FileLoaderAbstract) ci.newInstance(new Object[] { lastOne });
lastOne = fa;
ok = true;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
lastOne = new NullFileLoader(lastOne);
}
if(!ok) {
lastOne = new NullFileLoader(lastOne);
}
this.successor = lastOne;
}
|
1779f8e4-4140-4dc1-bca3-c539441bb73d
| 1
|
@SuppressWarnings("unchecked")
public Relationship usingId(Id id) {
if (this.id != null) {
throw new IllegalStateException("Id already assigned!");
}
this.id = id;
return this;
}
|
b2ac9995-b798-40b7-815b-17015c53a56f
| 2
|
public String toString() {
Object cl = null;
if (clref != null)
cl = clref.get();
return cl == null ? "<null>" : cl.toString();
}
|
864baecd-7635-4710-a946-d9017001a880
| 9
|
private Type getCommonType(Type t1, Type t2) {
if (!compatibleTypes(t1, t2)) {
return BasicType.NOTYPE;
}
if (t1 instanceof ListType) {
return t1;
}
if (t2 instanceof ListType ) {
return t2;
}
if (t1 == BasicType.FLOAT || t2 == BasicType.FLOAT) {
return BasicType.FLOAT;
}
if (t1 == BasicType.INT || t2 == BasicType.INT) {
return BasicType.INT;
}
if (t1 == BasicType.CHAR || t2 == BasicType.CHAR) {
return BasicType.CHAR;
}
return t1;
}
|
cd9297d3-567b-4f4d-89f1-bcc3e6c83c7f
| 3
|
private void collect(TreeNode root, String prefix, LinkedList<String> q){
if(root == null)return;
if(root.value != null)q.add(prefix);
for(char c = 0; c < R; c++){
collect(root.next[c], prefix + c, q);
}
}
|
9b333bd8-c7e1-4d4b-99e3-33f6619940a1
| 5
|
public static String getPrefix(final String name) {
try {
String s = "";
if (MonsterIRC.getHookManager() != null) {
if (MonsterIRC.getHookManager().getChatHook() != null) {
if (MonsterIRC.getHookManager().getChatHook().isEnabled()) {
if (MonsterIRC.getHookManager().getChatHook()
.getPlayerPrefix("", name) != null) {
s = MonsterIRC.getHookManager().getChatHook()
.getPlayerPrefix("", name);
}
}
}
}
return s;
} catch (final Exception e) {
return "";
}
}
|
b20485e5-3fe1-48f9-aa49-e11d5190a80b
| 1
|
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Library library = new Library();
request.setAttribute("patronResults",
library.getPatronList(0));
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("WEB-INF/patron-list.jsp").forward(request,
response);
}
|
632b1eee-7065-440a-a902-80f961177553
| 5
|
private void init() {
try {
setIconImage(new ImageIcon(AboutFrame.class.getResource("icon.png")).getImage());
} catch(NullPointerException e) {
controller.displayError(bundle.getString("error"),
e.getLocalizedMessage());
}
setTitle(Application.NAME + " " + Application.VERSION);
setSize(new Dimension(550, 225));
setResizable(true);
// setup components
btChoose.setText(bundle.getString("choose_file"));
btChoose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btChoose_actionPerformed(e);
}
});
btStegano.setText("Steganography");
btStegano.setActionCommand("Stegano");
btStegano.addActionListener(controller);
btEncrypt.setText(bundle.getString("encrypt"));
btEncrypt.setActionCommand("encrypt");
btEncrypt.addActionListener(controller);
btDecrypt.setText(bundle.getString("decrypt"));
btDecrypt.setActionCommand("decrypt");
btDecrypt.addActionListener(controller);
lbSource.setText(bundle.getString("source") + ": ");
lbSource.setVerticalAlignment(JLabel.CENTER);
lbSource.setHorizontalAlignment(JLabel.RIGHT);
lbAlgorithm.setText(bundle.getString("algorithm") + ": ");
lbAlgorithm.setVerticalAlignment(JLabel.CENTER);
lbAlgorithm.setHorizontalAlignment(JLabel.RIGHT);
lbCmpLevel.setText(bundle.getString("compression_level")+ ": ");
lbCmpLevel.setVerticalAlignment(JLabel.CENTER);
lbCmpLevel.setHorizontalAlignment(JLabel.LEFT);//TODO: fix this, should be RIGHT as the others
for(int i=0; i<10; i++)
cmbCompressionLevel.addItem(new Integer(i));
fchooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
btStop.setText(bundle.getString("stop"));
btStop.setActionCommand("stop");
btStop.addActionListener(controller);
btStop.setEnabled(false);
btAbout.setText(bundle.getString("about"));
btAbout.setActionCommand("about");
btAbout.addActionListener(controller);
btAlgInfo.setText(bundle.getString("algorithm_info"));
btAlgInfo.setActionCommand("alginfo");
btAlgInfo.addActionListener(controller);
pbCryptProgress.setMaximum(100);
// setup boxed layouts with panels
JPanel jpInput = new JPanel();
JPanel jpCompression = new JPanel();
JPanel jpCryptButtons = new JPanel();
JPanel jpProgress = new JPanel();
getContentPane().setLayout(new GridBagLayout());
getContentPane().add(jpInput, new GridBagConstraints(
0, 0, 1, 1, 1.0, 3.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,8,8,8), 0, 0
));
getContentPane().add(jpCompression, new GridBagConstraints(
0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0,0,0,0), 0, 0
));
getContentPane().add(jpCryptButtons, new GridBagConstraints(
0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,8,0,8), 0, 0
));
getContentPane().add(jpProgress, new GridBagConstraints(
0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,8,8,8), 0, 0
));
// add components to the panels
jpInput.setLayout(new GridBagLayout());
jpInput.add(lbSource, new GridBagConstraints(
0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0,0,0,8), 0, 0
));
jpInput.add(tfPath, new GridBagConstraints(
1, 0, 1, 1, 3.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0,0,0,8), 0, 0
));
jpInput.add(btChoose, new GridBagConstraints(
2, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0,0,0,0), 0, 0
));
jpInput.add(lbAlgorithm, new GridBagConstraints(
0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,8), 0, 0
));
jpInput.add(cmbAlgorithm, new GridBagConstraints(
1, 1, 1, 1, 3.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,8), 0, 0
));
jpInput.add(btAlgInfo, new GridBagConstraints(
2, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,0), 0, 0
));
jpInput.add(lbCmpLevel, new GridBagConstraints(
0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,-18), 0, 0
));
jpInput.add(cmbCompressionLevel, new GridBagConstraints(
1, 3, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,8), 0, 0
));
jpInput.add(btStegano, new GridBagConstraints(
2, 3, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,0), 0, 0
));
jpInput.add(Box.createRigidArea(new Dimension(btAlgInfo.getWidth(),5)), new GridBagConstraints(
2, 3, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(8,0,0,0), 0, 0
));
GridLayout cryptButtonsGrid = new GridLayout(1, 2);
cryptButtonsGrid.setHgap(8);
jpCryptButtons.setLayout(cryptButtonsGrid);
jpCryptButtons.add(btEncrypt);
jpCryptButtons.add(btDecrypt);
jpProgress.setLayout(new GridBagLayout());
jpProgress.add(pbCryptProgress, new GridBagConstraints(
0, 0, 1, 1, 25.0, 1.0, GridBagConstraints.WEST,
GridBagConstraints.BOTH, new Insets(0,0,0,0), 0, 0
));
jpProgress.add(btStop, new GridBagConstraints(
1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.EAST,
GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0
));
jpProgress.add(btAbout, new GridBagConstraints(
2, 0, 1, 1, 1.0, 1.0, GridBagConstraints.EAST,
GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0
));
DropTargetListener dropTargetListener =
new DropTargetListener() {
public void dragEnter(DropTargetDragEvent e) {}
public void dragExit(DropTargetEvent e) {}
public void dragOver(DropTargetDragEvent e) {}
public void drop(DropTargetDropEvent e) {
try {
Transferable tr = e.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
for (int i = 0; i < flavors.length; i++)
if (flavors[i].isFlavorJavaFileListType()) {
// Zun�chst annehmen
e.acceptDrop (e.getDropAction());
java.util.List files = (List)tr.getTransferData(flavors[i]);
File f = (File) files.get(0);
tfPath.setText(f.getAbsolutePath());
e.dropComplete(true);
return;
}
} catch (Throwable t) { t.printStackTrace(); }
// There was a problem
e.rejectDrop();
}
public void dropActionChanged(
DropTargetDragEvent e) {}
};
DropTarget dropTarget = new DropTarget(tfPath, dropTargetListener);
tfPath.setDropTarget(dropTarget);
//jpProgress.setLayout(new GridLayout(1, 1));
//jpProgress.add(pbCryptProgress);
//TODO: cmbAlgorithm.addItem(bundle.getString("add_algorithm"));
}
|
7934c599-48e4-4333-98a0-5f7e63b68d7f
| 0
|
public int getValue() {
return i.get();
}
|
68d0b91a-8e7a-456b-9a94-c9ad0f3b1972
| 9
|
public static void collectDirectSuperClasses(Stella_Class renamed_Class, List parents) {
{ List directsupertypes = renamed_Class.classDirectSupers;
List nondirectparents = List.newList();
{ Surrogate supertype = null;
Cons iter000 = directsupertypes.theConsList;
Cons collect000 = null;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
supertype = ((Surrogate)(iter000.value));
if (((Stella_Class)(supertype.surrogateValue)) != null) {
if (collect000 == null) {
{
collect000 = Cons.cons(((Stella_Class)(supertype.surrogateValue)), Stella.NIL);
if (parents.theConsList == Stella.NIL) {
parents.theConsList = collect000;
}
else {
Cons.addConsToEndOfConsList(parents.theConsList, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(((Stella_Class)(supertype.surrogateValue)), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
}
{ Stella_Class superclass = null;
Cons iter001 = parents.theConsList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
superclass = ((Stella_Class)(iter001.value));
{ Stella_Class othersuperclass = null;
Cons iter002 = parents.theConsList;
for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) {
othersuperclass = ((Stella_Class)(iter002.value));
if (!(othersuperclass == superclass)) {
if (superclass.classAllSuperClasses.memberP(othersuperclass)) {
nondirectparents.insert(othersuperclass);
}
}
}
}
}
}
{ Stella_Class p = null;
Cons iter003 = nondirectparents.theConsList;
for (;!(iter003 == Stella.NIL); iter003 = iter003.rest) {
p = ((Stella_Class)(iter003.value));
parents.remove(p);
}
}
nondirectparents.free();
}
}
|
93228207-abcf-40a0-9017-5686d16f47a1
| 9
|
private void exportFramedSameCatsSimStructVsMoa(String path, int level) throws Exception {
SmilesParser smilesParser = new SmilesParser(SilentChemObjectBuilder.getInstance());
DrugBank db = new DrugBank("data/tmp/drugbank.ser");
Brain atc = new Brain();
System.out.println("Learning ATC...");
atc.learn("data/atc.owl");
System.out.println("Learning done!");
//DrugBanks compounds in the FTC
List<String> drugs = brain.getSubClasses("FTC_C2", false);
List<String> drugBankIds = new ArrayList<String>();
//int iterations = 100;
int iterations = drugs.size();
//Gets only the compounds with a SMILES attached to them
//Get only the drugs that have a MoA (super classes > 4)
int notConsidered = 0;
for (int i = 0; i < iterations; i++) {
String drugId = drugs.get(i);
Drug drug = db.getDrug(drugId);
if(drug.getSmiles() != null){
if(brain.getSuperClasses(drugId, false).size() > 4){
drugBankIds.add(drugId);
}else{
notConsidered++;
}
}else{
notConsidered++;
}
}
System.out.println("number of compounds considered: " + drugBankIds.size() + " - Not considered: " + notConsidered);
List<SimilarityComparison> sims = new ArrayList<SimilarityComparison>();
for (int i = 0; i < drugBankIds.size(); i++) {
String id1 = drugBankIds.get(i);
System.out.println(i + "/" + drugBankIds.size());
for (int j = i + 1; j < drugBankIds.size(); j++) {
String id2 = drugBankIds.get(j);
//Actual sorting
boolean same = false;
try {
same = sameCategories(atc.getSubClasses(id1, true), atc.getSubClasses(id2, true), level);
} catch (ClassExpressionException exception){
same = false;
}
if(same){
String smiles1 = db.getDrug(id1).getSmiles();
String smiles2 = db.getDrug(id2).getSmiles();
IMolecule mol1 = smilesParser.parseSmiles(smiles1);
IMolecule mol2 = smilesParser.parseSmiles(smiles2);
HybridizationFingerprinter fingerprinter = new HybridizationFingerprinter();
BitSet bitset1 = fingerprinter.getFingerprint(mol1);
BitSet bitset2 = fingerprinter.getFingerprint(mol2);
float tanimoto = Tanimoto.calculate(bitset1, bitset2);
float jaccard = brain.getJaccardSimilarityIndex(id1, id2);
SimilarityComparison sim = new SimilarityComparison();
sim.firstSim = jaccard;
sim.secondSim = tanimoto;
try {
sim.id2 = getCategory(atc.getSubClasses(id2, true), level);
} catch (ClassExpressionException exception) {
sim.id2 = "NoCategory";
}
try {
sim.id1 = getCategory(atc.getSubClasses(id1, true), level);
} catch (ClassExpressionException exception) {
sim.id1 = "NoCategory";
}
sims.add(sim);
}
}
}
CSVWriter writer = new CSVWriter(path);
writer.write(sims);
atc.sleep();
}
|
58ea4c17-1b1d-4f53-aa9c-6371f58f53e2
| 3
|
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
}
|
856319fd-4b8e-4a35-be3a-a76a33a44155
| 6
|
public int convertShape( String shape )
{
defaultShape = 0;
if( shape.equals( "box" ) )
{
defaultShape = 0;
}
if( shape.equals( "cone" ) ) // 1 1
{
defaultShape = 257;
}
if( shape.equals( "coneToMax" ) ) // 1 2
{
defaultShape = 513;
}
if( shape.equals( "cylinder" ) ) // 1 0
{
defaultShape = 1;
}
if( shape.equals( "pyramid" ) ) // 0 1
{
defaultShape = 256;
}
if( shape.equals( "pyramidToMax" ) ) // 0 2
{
defaultShape = 512;
}
return defaultShape;
}
|
fd13edb7-24fa-46c4-8fad-578bf80108cb
| 0
|
@Test
public void itShouldSerializeAPointWithAltitude() throws Exception
{
Point point = new Point(100, 0, 256);
assertEquals("{\"coordinates\":[100.0,0.0,256.0],\"type\":\"Point\"}", mapper.toJson(point));
}
|
58a9f210-60b2-41e7-994c-90b2004a3924
| 5
|
private static void merge(int[] A, int left, int middle, int right) {
for (int i = left; i <= right; i++) {
temp[i] = A[i];
}
int leftEnd = middle - 1;
int k = left;
while (left <= leftEnd && middle <= right) {
if (temp[left] <= temp[middle]) {
A[k++] = temp[left++];
} else {
A[k++] = temp[middle++];
}
}
while (left <= leftEnd) {
A[k++] = temp[left++];
}
}
|
0215f84a-7833-4780-86fb-103aa5c4ee43
| 3
|
private void executeWaitForResultsJob(WaitForResultsJob job) throws IOException, JSchException {
updateable.send(new StatusUpdate("VM " + id + " waiting for mid results", id,
VMState.EXECUTING, JobType.WAITRESULT));
int expected = job.getExpectedCount();
while(new File("/").listFiles((new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".gif"); }
} )).length < expected){}
File folder = new File("");
synchronized (fileSystem){
if (!fileSystem.containsKey(job.getIP())){
fileSystem.put(job.getIP(), new HashMap<Integer, String>());
}
HashMap<Integer, String> fileMapping = fileSystem.get(job.getIP());
for (File i : folder.listFiles())
fileMapping.put(Integer.valueOf(i.getName().replaceAll("[:.]", "").replace("gif", "")), i.getAbsolutePath());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.