method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
3cad5e8c-f5f2-43ac-a4cd-8f3a9be0a7cc | 5 | void setFocusItem (CTableItem item, boolean redrawOldFocus) {
if (item == focusItem) return;
CTableItem oldFocusItem = focusItem;
if (oldFocusItem != null) oldFocusItem.getAccessible(getAccessible(), 0).setFocus(ACC.CHILDID_SELF);
focusItem = item;
if (redrawOldFocus && oldFocusItem != null) {
redrawItem (oldFocusItem.index, true);
}
if (focusItem != null) focusItem.getAccessible(getAccessible(), 0).setFocus(ACC.CHILDID_SELF);
} |
659c2881-e559-4e9e-941a-a2b573c9a54b | 8 | public Segment(JSONObject json) throws JSONException {
if (json.has(BOOKINGCLASS)) {
this.setBookingclass(new Bookingclass(json.getJSONObject(BOOKINGCLASS)));
}
if (json.has(DURATION)) {
this.setDuration(json.getString(DURATION));
}
if (json.has(CARRIER)) {
JSONObject carrierObject = json.getJSONObject(CARRIER);
if(carrierObject.has(IDENT)) {
flightNumber = carrierObject.getString(IDENT);
}
}
if (json.has(DEPDATE)) {
String sDate = json.getString(DEPDATE);
this.setDepdate(StringUtil.parseDate(sDate));
this.setDeptime(StringUtil.parseTime(sDate));
}
if (json.has(DESTINATION)) {
this.setDestination(parseAirport(json.getJSONObject(DESTINATION)));
}
if (json.has(ORIGIN)) {
this.setOrigin(parseAirport(json.getJSONObject(ORIGIN)));
}
if (json.has(ARRDATE)) {
String sDate = json.getString(ARRDATE);
this.setArrdate(StringUtil.parseDate(sDate));
this.setArrtime(StringUtil.parseTime(sDate));
}
} |
663adb4b-c2e6-49e5-9844-46708e2f3d9a | 5 | private boolean modificaPregunta(HttpServletRequest request, HttpServletResponse response) {
String enunciado = request.getParameter("enunciado");
String respuesta1 = request.getParameter("respuesta1");
String respuesta2 = request.getParameter("respuesta2");
String respuesta3 = request.getParameter("respuesta3");
int respuestaCorrecta = Integer.parseInt(request.getParameter("radioRespuesta"));
int tema;
try {
tema = Integer.parseInt(request.getParameter("tema"));
} catch (NumberFormatException ex) {
return false;
}
String imagen = "no_image.png";
int id = Integer.parseInt(request.getParameter("id"));
Pregunta p = new Pregunta(enunciado, respuesta1, respuesta2, respuesta3, respuestaCorrecta, tema, imagen, id);
if (!enunciado.equals("") && !respuesta1.equals("") && !respuesta2.equals("") && !respuesta3.equals("")) {
PreguntaDAO.modificaPregunta(p);
return true;
}
return false;
} |
85c2458a-dfc8-4b3c-8c63-1155f00dff29 | 2 | public void rollback ()
{
// Remove incomplete message from the outbound pipe.
Msg msg;
if (outpipe!= null) {
while ((msg = outpipe.unwrite ()) != null) {
assert ((msg.flags () & Msg.more) > 0);
//msg.close ();
}
}
} |
3e034066-c5e6-4c2b-8a15-8944dba154a5 | 4 | @Override
public void replace(byte[] newFile, Object editor)
{
if (!isAGoodEditor(editor))
throw new RuntimeException("NOT CORRECT EDITOR " + name);
if (comp == CompressionType.None)
parentFile.replace(newFile, this);
else if (comp == CompressionType.Lz)
parentFile.replace(LZ.compress(newFile), this);
if (comp == CompressionType.LzWithHeader)
parentFile.replace(LZ.compressHeadered(newFile), this);
else
throw new UnsupportedOperationException("Bad LZFile Type: " + comp);
fileSize = newFile.length;
} |
69213d0d-64a5-431f-9622-261fe6d23d84 | 0 | public Object getFirstValue() {
return getValue(0);
} |
795ec37a-255c-4ddf-a80b-1b1e4d376d1f | 8 | private static SimpleType combineEnumeration(SimpleTypeUnion orig, List<SimpleType> transformedChildren) {
if (transformedChildren.size() < 2)
return null;
SimpleType first = transformedChildren.get(0);
if (!(first instanceof SimpleTypeRestriction))
return null;
String builtinTypeName = ((SimpleTypeRestriction)first).getName();
List<Facet> facets = new Vector<Facet>();
for (SimpleType child : transformedChildren) {
if (!(child instanceof SimpleTypeRestriction))
return null;
SimpleTypeRestriction restriction = (SimpleTypeRestriction)child;
if (!restriction.getName().equals(builtinTypeName))
return null;
if (restriction.getFacets().isEmpty())
return null;
for (Facet facet : restriction.getFacets()) {
if (!facet.getName().equals("enumeration"))
return null;
facets.add(facet);
}
}
return new SimpleTypeRestriction(orig.getLocation(), orig.getAnnotation(), builtinTypeName, facets);
} |
506fce1b-20f4-475a-8217-d9c3ef3fb135 | 4 | public void restoreBorder() {
int c; // count;
// top edge
c = 0; // count
for (int cx = x; cx < x + w; cx++ ) {
pixels[cx+(y*width)] = pixelsTop[c++];
}
// bottom edge
c = 0;
for (int cx = x; cx < x + w; cx++ ) {
pixels[cx+((y+h-1)*width)] = pixelsBottom[c++];
}
// left edge
c = 0;
for (int cy = y; cy < y+h; cy++ ) {
pixels[x+(cy*width)] = pixelsLeft[c++];
}
// right edge
c = 0;
for (int cy = y; cy < y+h; cy++ ) {
pixels[x+(w-1)+(cy*width)] = pixelsRight[c++];
}
} |
8ff5aecf-472a-4584-8dc1-fa8ff3f37cfa | 4 | private void endShape(String to) {
if (to.equals("slide"))
slide.addEntity(polygon);
else if (to.equals("quizslide"))
quizSlide.addEntity(polygon);
else if (to.equals("scrollpane"))
scrollPane.addEntity(polygon);
else if (to.equals("feedback"))
quizSlide.addFeedback(polygon);
} |
31459801-38e8-432e-82c2-24d6693301d3 | 8 | public void run(String code) {
final Tokenizer tokenizer = new Tokenizer(mapping);
final List<Token> tokens = tokenizer.tokenize(code);
final Map<Integer, Integer> loopIndex = buildLoopIndex(tokens);
Stack<Integer> loopStack = new Stack<>();
int tokenIndex = 0;
while (tokenIndex >= 0 && tokenIndex < tokens.size()) {
final Token token = tokens.get(tokenIndex);
if (commands.containsKey(token.getType())) {
final Command command = commands.get(token.getType());
command.execute(memory);
tokenIndex++;
} else if (token.getType() == TokenType.LOOP_START) {
if (memory.read() != 0) {
loopStack.push(tokenIndex);
tokenIndex++;
} else {
tokenIndex = loopIndex.get(tokenIndex);
}
} else if (token.getType() == TokenType.LOOP_END) {
if (memory.read() != 0) {
if (loopStack.size() == 0) {
throw new UnbalancedLoopException(tokenIndex);
}
tokenIndex = loopStack.pop();
} else {
loopStack.pop();
tokenIndex++;
}
} else {
tokenIndex++;
}
}
} |
7a56f3fa-ac2f-4da8-a80a-b395d4469a35 | 4 | @Test
public void addNewShapeToBoard() {
testee.getBoard().addNewShape(new Square());
List<CellGui> populateCells = new ArrayList<CellGui>();
List<CellGui> emptyCells = new ArrayList<CellGui>();
for (CellGui cell : testee.getCellGuis()) {
if (cell.underlying().isPopulated()) populateCells.add(cell);
else
emptyCells.add(cell);
}
assertEquals("4 cells not populated with square", 4, populateCells.size());
assertEquals("rest of board not empty after adding square", 296, emptyCells.size());
for (CellGui cell : populateCells) {
assertEquals("cells with square in are wrong colour", new Square().getColour(), cell.getColour());
}
for (CellGui cell : emptyCells){
assertEquals("empty cells are wrong colour", Board.DEFAULT_EMPTY_COLOUR, cell.getColour());
}
} |
76f631fd-1423-4f81-9b0e-aacbce4b95cd | 4 | @Test
public void testUploadFile3() {
File file = new File("e:/upyuntest/ssh_hd.zip");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
client.uploadFile("/测试/ssh_hd.zip", fis, fis.available());
List<FileVo> list = client.listFile();
for (FileVo vo : list) {
System.out.print(vo.getName() + " ");
System.out.print(vo.getIsFile() + " ");
System.out.print(vo.getSize() + " ");
System.out.println(vo.getUpdatedAt());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
7987ab6c-83d6-40da-b337-3d5af27180d0 | 3 | public int compare(Destination d1, Destination d2) {
if(d1.getDuration() == d2.getDuration()){
return 0;
} else if(d2.getDuration() > d2.getDuration()) {
return -1;
} else if(d2.getDuration() < d2.getDuration()) {
return 1;
}else{
return 0;
}
} |
58fed5dc-f478-4fb5-aa05-7670a33461aa | 1 | public List<AlbumType> getAlbum() {
if (album == null) {
album = new ArrayList<AlbumType>();
}
return this.album;
} |
577abfef-54f7-47aa-b2fb-b5fe7d6f6270 | 4 | public int numDefenders(int x, int y) {
// num defenders takes in the coordinates of a piece and returns the
// number of pieces on its team that are defending it.
// numDefenders starts at -1 because the piece that will be moving to
// that square doesnt count as a defende
int a = 0;
for (int i = 0; i < allMovesDefending().size(); i++) {
for (int j = 2; j < allMovesDefending().get(i).size(); j++) {
if (((Point) allMovesDefending().get(i).get(j)).getX() == x
&& ((Point) allMovesDefending().get(i).get(j)).getY() == y)
a++;
// if there is a piece at the location then it will add to the
// array so we have to check for that
}
}
return a;
} |
9294ae19-e6a2-4653-870c-009e8d148dae | 4 | public Boolean rightFantasma(int n){
Query q2;
switch(n){
case 0:
q2 = new Query("rightBlinky");
return q2.hasSolution();
case 1:
q2 = new Query("rightClyde");
return q2.hasSolution();
case 2:
q2 = new Query("rightInky");
return q2.hasSolution();
case 3:
q2 = new Query("rightPinky");
return q2.hasSolution();
default:
return false;
}
} |
b955110f-7494-4f28-b243-d2fa618e894d | 2 | public void updateEmployee(boolean equal) {
Database db = dbconnect();
try {
StringBuilder query = new StringBuilder ();
query.append("UPDATE employee SET firstName = ?, lastName = ?, username = ?, ");
if (!equal) {
query.append("password = hash_pw(?),");
} else {
query.append("password = ?,");
}
query.append("bIsTroubleshooter = ? WHERE EID = ? AND bDeleted = 0");
db.prepare(query.toString());
db.bind_param(1, this.e_firstname);
db.bind_param(2, this.e_lastname);
db.bind_param(3, this.e_username);
db.bind_param(4, this.e_pw);
db.bind_param(5, this.e_trb.toString());
db.bind_param(6, this.EID.toString());
db.executeUpdate();
db.close();
} catch(SQLException e){
Error_Frame.Error(e.toString());
}
} |
be84f443-420e-48bc-8813-d4031f12cf7d | 9 | String findNearest(String previous, int index, int maxShapes) {
if (previous == null || previous.length() <= index) {
// Select or create new
// Checks all exists
Character c = this.findEmpty(maxShapes);
//if no
if (c != null) {
return previous + symbol + c;
} else {
// Search empty in deep
for (int i = 0; i < maxShapes; i++) {
String s = children.get(SHAPES[i]).findNearest(previous, index + 1, maxShapes);
if (s != null) {
if (parent != null) {
s = symbol + s;
}
return s;
}
}
}
} else {
if (id != 0 || parent == null) {
Node node = children.get(previous.charAt(index));
if (node == null) {
node = new Node(previous.charAt(index), 0);
children.put(previous.charAt(index), node);
return previous + node.findEmpty(maxShapes);
}
return node.findNearest(previous, index + 1, maxShapes);
} else {
return null;
}
}
return null;
} |
a09e44ff-c1ab-458e-9fd3-9feb9b632983 | 1 | public void run() {
setupRobot();
while (true) {
wheel.act();
radar.act();
gun.act();
targetSelector.act();
// paint range
Util.paintCircle(this, getX(), getY(), 400, Color.gray);
execute();
}
} |
37cf926d-30f4-4ebe-9c0b-4ecc8b6f1013 | 8 | public boolean replaceRecord(PatientRecord pr) {
if (pr.type().equals("c")) {
for (int i = 0; i < _controlPatients.size(); i++) {
if (_controlPatients.get(i).pnumber() == pr.pnumber()) {
if (_controlPatients.get(i).hasRecord(pr.timeline())) {
_controlPatients.get(i).addRecord(pr.timeline(), pr);
} else {
return false;
}
return true;
}
}
return false;
} else if (pr.type().equals("acl")) {
for (int i = 0; i < _ACLPatients.size(); i++) {
if (_ACLPatients.get(i).pnumber() == pr.pnumber()) {
if (_ACLPatients.get(i).hasRecord(pr.timeline())) {
_ACLPatients.get(i).addRecord(pr.timeline(), pr);
} else {
return false;
}
return true;
}
}
return false;
}
return false;
} |
aa91c841-5fe6-48e4-8d7b-1812db7c5e6e | 2 | public Matrix4f mul(Matrix4f r) {
Matrix4f res = new Matrix4f();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
res.set(i, j, m[i][0] * r.get(0, j) +
m[i][1] * r.get(1, j) +
m[i][2] * r.get(2, j) +
m[i][3] * r.get(3, j));
}
}
return res;
} |
f3b8c7cc-3624-4a49-910a-c6493f65c708 | 9 | private static void insertSemaphore(ControlFlowGraph graph,
Set<BasicBlock> setTry,
BasicBlock head,
BasicBlock handler,
int var,
Record information,
int bytecode_version) {
Set<BasicBlock> setCopy = new HashSet<>(setTry);
int finallytype = information.firstCode;
Map<BasicBlock, Boolean> mapLast = information.mapLast;
// first and last statements
removeExceptionInstructionsEx(handler, 1, finallytype);
for (Entry<BasicBlock, Boolean> entry : mapLast.entrySet()) {
BasicBlock last = entry.getKey();
if (entry.getValue()) {
removeExceptionInstructionsEx(last, 2, finallytype);
graph.getFinallyExits().add(last);
}
}
// disable semaphore at statement exit points
for (BasicBlock block : setTry) {
List<BasicBlock> lstSucc = block.getSuccs();
for (BasicBlock dest : lstSucc) {
// break out
if (!setCopy.contains(dest) && dest != graph.getLast()) {
// disable semaphore
SimpleInstructionSequence seq = new SimpleInstructionSequence();
seq.addInstruction(ConstantsUtil
.getInstructionInstance(CodeConstants.opc_bipush, false, CodeConstants.GROUP_GENERAL, bytecode_version,
new int[]{0}), -1);
seq.addInstruction(ConstantsUtil
.getInstructionInstance(CodeConstants.opc_istore, false, CodeConstants.GROUP_GENERAL, bytecode_version,
new int[]{var}), -1);
// build a separate block
BasicBlock newblock = new BasicBlock(++graph.last_id);
newblock.setSeq(seq);
// insert between block and dest
block.replaceSuccessor(dest, newblock);
newblock.addSuccessor(dest);
setCopy.add(newblock);
graph.getBlocks().addWithKey(newblock, newblock.id);
// exception ranges
// FIXME: special case synchronized
// copy exception edges and extend protected ranges
for (int j = 0; j < block.getSuccExceptions().size(); j++) {
BasicBlock hd = block.getSuccExceptions().get(j);
newblock.addSuccessorException(hd);
ExceptionRangeCFG range = graph.getExceptionRange(hd, block);
range.getProtectedRange().add(newblock);
}
}
}
}
// enable semaphor at the statement entrance
SimpleInstructionSequence seq = new SimpleInstructionSequence();
seq.addInstruction(
ConstantsUtil.getInstructionInstance(CodeConstants.opc_bipush, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{1}),
-1);
seq.addInstruction(
ConstantsUtil.getInstructionInstance(CodeConstants.opc_istore, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{var}),
-1);
BasicBlock newhead = new BasicBlock(++graph.last_id);
newhead.setSeq(seq);
insertBlockBefore(graph, head, newhead);
// initialize semaphor with false
seq = new SimpleInstructionSequence();
seq.addInstruction(
ConstantsUtil.getInstructionInstance(CodeConstants.opc_bipush, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{0}),
-1);
seq.addInstruction(
ConstantsUtil.getInstructionInstance(CodeConstants.opc_istore, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{var}),
-1);
BasicBlock newheadinit = new BasicBlock(++graph.last_id);
newheadinit.setSeq(seq);
insertBlockBefore(graph, newhead, newheadinit);
setCopy.add(newhead);
setCopy.add(newheadinit);
for (BasicBlock hd : new HashSet<>(newheadinit.getSuccExceptions())) {
ExceptionRangeCFG range = graph.getExceptionRange(hd, newheadinit);
if (setCopy.containsAll(range.getProtectedRange())) {
newheadinit.removeSuccessorException(hd);
range.getProtectedRange().remove(newheadinit);
}
}
} |
72322933-6907-4268-9498-25734b6a124c | 1 | public static void main(String[] args) {
final String username = "";
final String password = "";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
} |
c0b24fc0-4094-4aa8-ac56-6953283e02e9 | 7 | @Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if(canBeUninvoked())
{
final Room centerR=mob.location();
if((centerR!=null)&&(!mob.amDead()))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> <S-IS-ARE> outside the invisibility sphere."));
if(centerR!=null)
{
for(Enumeration<MOB> m=centerR.inhabitants();m.hasMoreElements();)
removeFromSphere(m.nextElement());
for(Enumeration<Item> i=centerR.items();i.hasMoreElements();)
removeFromSphere(i.nextElement());
}
}
} |
12f77cad-840a-4c20-bd86-83c3c65917ca | 0 | public PrioritizedTaskConsumer(PriorityBlockingQueue<Runnable> q)
{
this.q = q;
} |
2749affd-cc69-45f6-a83c-464d24db4bb7 | 2 | private File getDirectory(String arg) {
File dir = new File(arg);
if (!dir.exists()) {
System.err.println("Couldn't find dir " + arg);
invalid = true;
showHelp = true;
}
if (dir.isFile()) {
System.err.println(arg + " is a file. It should be a dir.");
invalid = true;
showHelp = true;
}
return dir;
} |
3ae83971-bc86-4895-9de4-9c2a5128bd80 | 3 | @Override
public GameState[] allActions(GameState state, Card card, int time) {
GameState[] states = new GameState[1];
states[0] = state;
if(time == Time.DAY)
{
states = allPreacherDay(state, card).keySet().toArray(new GameState[0]);
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
states = temp.allActions(state, card, time);
}
else if(time == Time.NIGHT)
{
//Do nothing
}
return states;
} |
e2988edd-ebb6-40a1-b991-261b210d4392 | 2 | public boolean verificarLetra(String letra) {
int verificacion = 0;
letrasUsadas = letrasUsadas + letra + " ";
for(int i=1; i<palabraActual.length; i++){
if(palabraActual[i].equals(letra)){
palabraRespuesta.set(i-1,letra);
palabraActual[i] = "_";
verificacion++;
aciertos++;
puntuacion += 10;
}
}
return verificacion != 0;
} |
4335c6c0-41da-4efb-9f70-9b6083dc7860 | 4 | public ListNode swapPairs(ListNode head) {
if(null == head || head.next == null) return head;
this.h = new ListNode(0);
this.h.next = head;
ListNode source = h;
while(source != null && source.next != null) {
source = exchange(source);
}
return h.next;
} |
85da5566-5140-441d-9355-30c759ea7d0d | 9 | public static int lengthOfLongestSubstring2(String s) {
int len=s.length();
String[] str=new String[len];
for (int i = 0; i <len ; i++) {
str[i]=s.substring(i,len);
}
int max=0;
int temp=0;
int half=(len+1)/2;
String old_sub_str=null;
for (int i = 1; i <half ; i++) {
for (int j= 0; j+i <len-1 ; j+=i) {
if (str[j+i].length()>=i&&str[j].length()>=i) {
String s1 = str[0].substring(0, i);
if (old_sub_str == null) {
old_sub_str=s1;
}
String s2 = str[j + i].substring(0, i);
if (s2.equals(old_sub_str+old_sub_str)) {
temp=0;
break;
}
if (s1.equals(s2)) {
temp += 1;
}else{
// temp=0;
break;
}
}
}
if(temp>0) {
max = i;
}else {
temp=0;
}
}
return max;
} |
81d7fcbe-f36b-443b-af88-95f13a98e6ca | 3 | public void setGameState( SavedGameParser.SavedGameState gameState ) {
generalPanel.reset();
if ( gameState != null ) {
SavedGameParser.ShipState shipState = gameState.getPlayerShipState();
ShipBlueprint shipBlueprint = DataManager.get().getShip( shipState.getShipBlueprintId() );
if ( shipBlueprint == null )
throw new RuntimeException( String.format("Could not find blueprint for%s ship: %s", (shipState.isAuto() ? " auto" : ""), shipState.getShipName()) );
generalPanel.setStringAndReminder( SHIP_NAME, gameState.getPlayerShipName() );
generalPanel.getSlider(HULL).setMaximum( shipBlueprint.getHealth().amount );
generalPanel.setSliderAndReminder( HULL, shipState.getHullAmt() );
generalPanel.setIntAndReminder( FUEL, shipState.getFuelAmt() );
generalPanel.setIntAndReminder( DRONE_PARTS, shipState.getDronePartsAmt() );
generalPanel.setIntAndReminder( MISSILES, shipState.getMissilesAmt() );
generalPanel.setIntAndReminder( SCRAP, shipState.getScrapAmt() );
generalPanel.setBoolAndReminder( HAZARDS_VISIBLE, gameState.areSectorHazardsVisible() );
}
this.repaint();
} |
10cd5a37-5b7e-4144-8945-4f8448e08fb0 | 6 | private static final void seleccionaMetodesAProvar()
{
int iterador_dopcio = 1;
Method[] array_metodes_a_provar = driver_a_provar.getDeclaredMethods();
// Els fico a una LinkedList per poder treure els que no siguin publics
metodes_a_provar = new LinkedList<Method>( Arrays.asList( array_metodes_a_provar ) );
netejaConsola();
System.out.println( " _____________________________________________________________________________" );
System.out.println( " /\n| Escull una prova de la classe " + nom_driver_a_provar + " a realitzar: \n|" );
// En aquest cas, faig ús d'un iterador perquè si no,
// mentre estic recorrent la LinkedList no podria fer el remove()
Iterator iterador_metodes = metodes_a_provar.iterator();
while ( iterador_metodes.hasNext() )
{
Method metode_a_provar = ( Method ) iterador_metodes.next();
if ( Modifier.isPublic( metode_a_provar.getModifiers() ) )
{
System.out.println( "| " + iterador_dopcio + ".- " + metode_a_provar.getName() );
iterador_dopcio++;
}
else
{
iterador_metodes.remove();
}
}
System.out.println( "|\n| 0.- Sortir al menú principal" );
System.out.println( " \\ _____________________________________________________________________________\n" );
int num_metode_a_provar = llegeixEnter();
if ( num_metode_a_provar != 0 )
{
try
{
metodes_a_provar.get( num_metode_a_provar - 1 ).invoke( new Object() );
System.out.println( "\n[INFO]\tExecució del test finalitzada, pulsa \'intro\' per continuar." );
System.in.read();
}
catch ( IllegalAccessException excepcio )
{
excepcio.printStackTrace();
}
catch ( InvocationTargetException excepcio )
{
excepcio.printStackTrace();
}
catch ( IOException excepcio )
{
excepcio.printStackTrace();
}
}
else
{
vol_sortir_al_menu_principal = true;
}
} |
d08ab942-1b0e-42ff-82bd-f860918e47b5 | 0 | public ConfigFile(String fileName)
{
//set the config file filename
this.fileName = fileName;
//set data to empty string
//data = "";
} |
7608fa1c-975f-43b4-9426-82fbf21153bd | 8 | private static List<AgentController> createAgents(HashMap<String, ContainerController> containerList) {
System.out.println("Launching agents...");
ContainerController c;
String agentName;
List<AgentController> agentList = new ArrayList<AgentController>();
c = containerList.get("container1");
agentName="JobSupplier1";
try {
String filePath = new File("").getAbsolutePath() + "/exercise03-input-data-01.csv";
Object[] objtab = new Object[]{filePath};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.JobSupplierAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
agentName="Scheduler1";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.ParallelSchedulerAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
agentName="ScheduleExecutor1";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.ScheduleExecutionAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
/**/
agentName="ScheduleExecutor2";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.ScheduleExecutionAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
agentName="ScheduleExecutor3";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.ScheduleExecutionAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
agentName="ScheduleExecutor4";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.ScheduleExecutionAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
agentName="SystemClockAgent1";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.SystemClockAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
agentName="SchedulingVisualizer1";
try {
Object[] objtab = new Object[]{};//used to give informations to the agent
AgentController ag = c.createNewAgent(agentName,multiagent_scheduler.SchedulingVisualizerAgent.class.getName(),objtab);
agentList.add(ag);
System.out.println(agentName + " launched");
} catch (StaleProxyException e) {
e.printStackTrace();
}
System.out.println("Agents launched...");
return agentList;
} |
2821ecb7-d16c-4655-ab5f-f01cff25b684 | 3 | public void update(Ship ship ,int delta) {
if (state == States.MISSILE) {
setX(getX() - delta * speed);
anims[States.MISSILE.ordinal()].update(delta);
check_collisions(ship);
} else if (state == States.EXPLOSION) {
if (anims[States.EXPLOSION.ordinal()].is_stopped()) {
state = States.DESTROY;
}
}
} |
4c7baeda-464d-474b-aa25-80d8ad3b1d35 | 6 | protected static void setKit(PlayerInventory i) {
File folder = Bukkit.getPluginManager().getPlugin("EventoThor").getDataFolder();
List<ItemStack> items = new ArrayList<ItemStack>();
File config = new File(folder, "config.yml");
ItemStack h = i.getHelmet();
ItemStack p = i.getChestplate();
ItemStack l = i.getLeggings();
ItemStack b = i.getBoots();
if (h != null) {
getConfig().set("Kit.Helmo", h);
} else {
getConfig().set("Kit.Helmo", "Nenhum");
}
if (p != null) {
getConfig().set("Kit.Peito", p);
} else {
getConfig().set("Kit.Peito", "Peito");
}
if (l != null) {
getConfig().set("Kit.Calca", l);
} else {
getConfig().set("Kit.Calca", "Calca");
}
if (b != null) {
getConfig().set("Kit.Botas", b);
} else {
getConfig().set("Kit.Botas", "Botas");
}
for (ItemStack item : i.getContents()) {
items.add(item);
}
getConfig().set("Kit.Items", items);
try {
getConfig().save(config);
} catch (IOException ex) {
ex.printStackTrace();
}
} |
10102174-61d3-418e-878a-0726ce95fc6a | 6 | public void analyzeLinks(List sourcesChildren, Vector simultaneousLinks, Namespace ns){
if (sourcesChildren.size() > 1){
Element source1 = (Element)sourcesChildren.get(0);
String linkName1 = source1.getAttributeValue("linkName");
//Falls der Link eine transitionCondition besitzt
if (source1.getChild("transitionCondition", ns) != null){
String tc1 = source1.getChild("transitionCondition", ns).getText();
for (int i=1; i < sourcesChildren.size(); i++){
Element source2 = (Element)sourcesChildren.get(i);
String linkName2 = source2.getAttributeValue("linkName");
Vector vect = new Vector();
simultaneousLinks.addElement(vect);
//Falls der Link eine transitionCondition besitzt
if (source2.getChild("transitionCondition", ns) != null){
String tc2 = source2.getChild("transitionCondition", ns).getText();
XPathParser xpathParser = new XPathParser();
Expr transitionExpr1 = xpathParser.parseExpression(tc1);
Expr transitionExpr2 = xpathParser.parseExpression(tc2);
boolean result = handleFirstExpression(transitionExpr1, transitionExpr2);
if (result){
vect.addElement("sim");
vect.addElement(linkName1);
vect.addElement(linkName2);
} else {
vect.addElement("notsim");
vect.addElement(linkName1);
vect.addElement(linkName2);
}
//Falls der Link keine transtionCondition besitzt
} else {
vect.addElement("sim");
vect.addElement(linkName1);
vect.addElement(linkName2);
}
}
//Falls der Link keine transtionCondition besitzt
} else {
for (int i=1; i < sourcesChildren.size(); i++){
Element source2 = (Element)sourcesChildren.get(i);
String linkName2 = source2.getAttributeValue("linkName");
Vector vect = new Vector();
simultaneousLinks.addElement(vect);
vect.addElement("sim");
vect.addElement(linkName1);
vect.addElement(linkName2);
}
}
sourcesChildren.remove(0);
analyzeLinks(sourcesChildren, simultaneousLinks, ns);
}
} |
b5b0dcce-496b-4945-b5fb-f5490a9a88a4 | 9 | private void jButtonPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesquisarActionPerformed
Estoque estoque = new Estoque();
Material material = new Material();
DadoMaterial dadoMaterial = new DadoMaterial();
if (!jTextFieldTitulo.getText().isEmpty()) {
dadoMaterial.setTitulo(jTextFieldTitulo.getText());
}
if (!jTextFieldDescricao.getText().isEmpty()) {
dadoMaterial.setDescricao(jTextFieldDescricao.getText());
}
if (jComboBoxEdicao.getSelectedIndex() > 0) {
dadoMaterial.setEdicao((Edicao) jComboBoxEdicao.getSelectedItem());
}
if (jComboBoxAnoPublicacao.getSelectedIndex() > 0) {
dadoMaterial.setAnoPublicacao((AnoPublicacao) jComboBoxAnoPublicacao.getSelectedItem());
}
if (jComboBoxEditora.getSelectedIndex() > 0) {
dadoMaterial.setEditora((Editora) jComboBoxEditora.getSelectedItem());
}
if (jComboBoxCategoria.getSelectedIndex() > 0) {
dadoMaterial.setCategoria((Categoria) jComboBoxCategoria.getSelectedItem());
}
if (jComboBoxPublico.getSelectedIndex() > 0) {
dadoMaterial.setPublico((Publico) jComboBoxPublico.getSelectedItem());
}
material.setDadoMaterial(dadoMaterial);
if (jComboBoxFormato.getSelectedIndex() > 0) {
material.setFormato((Formato) jComboBoxFormato.getSelectedItem());
}
estoque.setMaterial(material);
if (jComboBoxStatu.getSelectedIndex() > 0) {
estoque.setStatu((Statu) jComboBoxStatu.getSelectedItem());
}
listaView.getEstoquesController().filtrar(estoque);
}//GEN-LAST:event_jButtonPesquisarActionPerformed |
22e1cf7c-d4be-490d-bca0-988bb072dd5a | 5 | public void paintStateCard(State state, boolean isActive, Rectangle bounds, Graphics g) {
//draw rect, color depending on active state
g.setColor(isActive? Color.GREEN : Color.LIGHT_GRAY);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(isActive? new Color(0, 127, 0) : Color.BLACK);
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
//draw outer bounds, if state is a halt state
if (state.halts()) {
g.setColor(isActive? new Color(0, 127, 0) : Color.BLACK);
g.drawRect(bounds.x-5, bounds.y-5, bounds.width+10, bounds.height+10);
}
//draw horizontal line
g.setColor(Color.BLACK);
int lineHeight =(int) (bounds.y + HEADER_BODY_COEFF * bounds.getHeight());
g.drawLine(bounds.x, lineHeight, bounds.x + bounds.width, lineHeight);
//draw circle around start state id
int fontX = bounds.x + bounds.width /2; int fontY = lineHeight - bounds.height / 16;
if (state.isStart()) {
g.setColor(Color.BLACK);
//Set font to underlined
Map<TextAttribute, Integer> fontAttributes = new HashMap<TextAttribute, Integer>();
fontAttributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
g.setFont(new Font(DEFAULT_FONT_NAME,Font.BOLD, bounds.width/6).deriveFont(fontAttributes));
} else {
g.setColor(Color.BLACK);
g.setFont(new Font(DEFAULT_FONT_NAME, Font.PLAIN, bounds.width/6));
}
//draw state id
g.drawString(state.getID(), fontX, fontY);
} |
041c93d5-aed5-4789-b73b-9d4624c1016c | 8 | private void initialise()
{
Properties prop = new Properties();
try
{
// load our properties file
prop.load(new FileInputStream("config.properties"));
// get the property values for pushover notifications if any
_pushoverAppToken = prop.getProperty("PUSHOVER_APP_TOKEN");
_pushoverUserToken = prop.getProperty("PUSHOVER_USER_TOKEN");
String repeatCheckDelayStr = prop.getProperty("REPEAT_CHECK_DELAY", ""+6);
try
{
_repeatCheckDelay = Integer.parseInt(repeatCheckDelayStr);
}
catch (NumberFormatException e)
{
System.err.println("Invalid value specified repeat check delay! See REPEAT_CHECK_DELAY in config.properties!");
System.exit(1);
}
String storeIds = prop.getProperty("STORES");
String bundleIds = prop.getProperty("BUNDLES");
String autoLaunchBrowserStr = prop.getProperty("AUTO_LAUNCH_BROWSER", "FALSE");
String playInStockSoundStr = prop.getProperty("PLAY_IN_STOCK_SOUND", "TRUE");
_logfilePath = prop.getProperty("LOG_FILE_PATH", "C:\\Temp");
File f = new File(_logfilePath);
if (!f.exists() || !f.isDirectory())
{
System.err.println("Invalid path specified for log file location! See LOG_FILE_PATH in config.properties!");
System.exit(1);
}
_storesToCheck = parseStores(storeIds);
_ps4sToCheck = parsePS4s(bundleIds);
_autoLaunchBrowser = parseAutoLaunch(autoLaunchBrowserStr);
_playInStockSound = parsePlayInStockSound(playInStockSoundStr);
if (_storesToCheck.isEmpty())
{
System.err.println("No valid stores were found in config.properties!");
System.exit(1);
}
if (_ps4sToCheck.isEmpty())
{
System.err.println("No valid PS4 bundles were found in config.properties!");
System.exit(1);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
_stockStatusMap = new HashMap<String, StockStatus>();
try
{
SimpleDateFormat sim=new SimpleDateFormat("ddMMyyyy_HHmm");
String s = sim.format(new Date());
_fh = new FileHandler(_logfilePath + File.separator + s + ".log");
_logger.addHandler(_fh);
SimpleFormatter formatter = new SimpleFormatter();
_fh.setFormatter(formatter);
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
} |
8cf38738-cd9f-4ade-97b8-76588b914708 | 3 | public boolean hasNext() {
if (empty) return false;
// first check if current segment can be read for next Wig item
if (wigItemIndex < wigItemList.size())
return true;
// need to fetch next data block
else if (leafItemIndex < leafHitList.size())
return true;
else
return false;
} |
0d369093-15b0-490e-aab0-890d2489b27c | 4 | public void unbind() {
//Make sure there was a previous texture before we try to unbind.
if(prevTexture != -1 && isBound) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, prevTexture);
prevTexture = -1;
isBound = false;
}
else if(prevTexture != -1 && !isBound) {
System.err.print("RoyalFlush: Texture2D.unbind - Texture " + fileName + " is NOT bound.\n");
}
else {
System.err.print("RoyalFlush: Texture2D.unbind - No texture to unbind.\n");
}
} |
0f90174d-0e3d-4b9e-8a71-c3738098a99b | 2 | @Override
public void getFromPane(Contestant c) throws InvalidFieldException {
String oID = c.getID();
c.setID(tfContID.getText());
GameData g = GameData.getCurrentGame();
if (!g.checkID(c, Contestant.class)) {
if (oID != null)
c.setID(oID);
throw new InvalidFieldException(Field.CONT_ID_DUP, "Duplicate ID, User (changing manually)");
}
c.setFirstName(tfFirstName.getText().trim());
c.setLastName(tfLastName.getText().trim());
c.setTribe((String) cbTribe.getSelectedItem());
c.setPicture(imgPath);
} |
96796f0e-b825-461c-8a7b-45023ff8cec4 | 6 | public BEXElemCollector(final BEXNodeAdapter node, final String uri, final String name, final boolean self) throws NullPointerException {
if (node == null) throw new NullPointerException("node = null");
if (uri == null) throw new NullPointerException("uri = null");
if (name == null) throw new NullPointerException("name = null");
this.uri = uri;
this.name = name;
this.list = new ArrayList<Node>();
if ("*".equals(uri)) {
if ("*".equals(name)) {
this._collectElements_(node, self);
} else {
this._collectElementsByName_(node, self);
}
} else {
if ("*".equals(name)) {
this._collectElementsByUri_(node, self);
} else {
this._collectElementsByLabel_(node, self);
}
}
this.size = this.list.size();
} |
b0a14f74-8491-47c2-8fd6-3746af370662 | 9 | private int minMove(Board prev, int depth, int alpha, int beta)
{
moves++; // fixme
if(depth >= maxDepth) return prev.getScore(); // exceeded maximum depth
int minScore = MAX_SCORE;
Board b = new Board(prev);
b.turn(); // min player's turn
for(int j = 0; j < size; j++)
{
for(int i = 0; i < size; i++)
{
if(b.move(i, j))
{
b.turn(); // max player's turn
int score = maxMove(b, depth + 1, alpha, beta);
if(score < minScore) minScore = score;
if(minScore <= alpha) return minScore;
if(minScore < beta) beta = minScore;
b = new Board(prev);
b.turn();
}
}
}
if(minScore == MAX_SCORE) // min player can't make a move
{
b.turn();
if(b.canMove()) return maxMove(b, depth + 1, alpha, beta); // max player can make a move
else return prev.getScore(); // max player can't make a move either - game over
}
return minScore;
} |
331b37d3-6902-4a54-8082-29fa88d784c6 | 6 | private final short method669
(int i, long l, int i_200_, int i_201_, int i_202_, int i_203_,
float f, int i_204_, float f_205_, Model class124, int i_206_) {
try {
if (i_203_ >= -49)
anIntArray5519 = null;
anInt5407++;
int i_207_ = anIntArray5455[i_204_];
int i_208_ = anIntArray5455[i_204_ + 1];
int i_209_ = 0;
for (int i_210_ = i_207_; i_210_ < i_208_; i_210_++) {
short i_211_ = aShortArray5439[i_210_];
if ((i_211_ ^ 0xffffffff) == -1) {
i_209_ = i_210_;
break;
}
if ((l ^ 0xffffffffffffffffL)
== (Class348_Sub40_Sub37.aLongArray9465[i_210_]
^ 0xffffffffffffffffL))
return (short) (-1 + i_211_);
}
aShortArray5439[i_209_] = (short) (1 + anInt5475);
Class348_Sub40_Sub37.aLongArray9465[i_209_] = l;
aShortArray5416[anInt5475] = (short) i_200_;
aShortArray5470[anInt5475] = (short) i_204_;
aShortArray5493[anInt5475] = (short) i_202_;
aShortArray5438[anInt5475] = (short) i_206_;
aShortArray5436[anInt5475] = (short) i;
aByteArray5499[anInt5475] = (byte) i_201_;
aFloatArray5476[anInt5475] = f;
aFloatArray5506[anInt5475] = f_205_;
return (short) anInt5475++;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("nca.SA(" + i + ',' + l + ','
+ i_200_ + ',' + i_201_ + ','
+ i_202_ + ',' + i_203_ + ',' + f
+ ',' + i_204_ + ',' + f_205_
+ ','
+ (class124 != null ? "{...}"
: "null")
+ ',' + i_206_ + ')'));
}
} |
c2f8d2eb-df29-4c0e-8230-dab12c74bff5 | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TabelProdBrand other = (TabelProdBrand) obj;
if (!Objects.equals(this.brandId, other.brandId)) {
return false;
}
return true;
} |
c5e6df45-6c07-4f2b-968c-9378f4dda113 | 5 | public boolean moovable(){
/*
* judge to be a hit walls, plants and animals.
*/
if (getElapsedTime() % actionFrequency > 0){
return false;
}else{
if ((getX() < 0 || MainPanel.WIDTH < getX() + getSize())
|| (getY() < 0 || MainPanel.HEIGHT < getY() + getSize())){
hitWall();
return false;
}else{
return true;
}
}
} |
e8aacf8d-0fdf-48e7-99e5-ae49c56a391c | 2 | public void dump_stack()
{
if (stack == null)
{
debug_message("# Stack dump requested, but stack is null");
return;
}
debug_message("============ Parse Stack Dump ============");
/* dump the stack */
for (int i=0; i<stack.size(); i++)
{
debug_message("Symbol: " + ((Symbol)stack.elementAt(i)).sym +
" State: " + ((Symbol)stack.elementAt(i)).parse_state);
}
debug_message("==========================================");
} |
0e6153dc-2106-4288-9aee-c9067b421be5 | 8 | public void processTemplateFile(File template) throws IOException {
converter = Converter.getInstance();
if (!FileUtil.isReadableFile(template)) {
System.err.println(String.format("%s: cannot be accessed", template.getName()));
return;
}
String templateFileName = template.getName();
int indexLastDot = templateFileName.lastIndexOf(".");
String baseName = templateFileName.substring(0, indexLastDot < 0 ? templateFileName.length() : indexLastDot);
File hacklaceFile = new File(baseName + ".hl");
if (hacklaceFile.exists()) {
System.err.println(String.format("%s: output file already exist", hacklaceFile.getName()));
return;
}
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(template), "ISO-8859-1"));
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(hacklaceFile), "ISO-8859-1"));
String s;
while ((s = reader.readLine()) != null) {
writer.write(replacePlaceholder(s));
// TODO check for DOS/UNIX lineends
writer.write('\n');
}
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ioe) {
System.err.println(String.format("%s: failed to close the file - %s", hacklaceFile.getName(), ioe.getMessage()));
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
System.err.println(String.format("%s: failed to close the file - %s", hacklaceFile.getName(), ioe.getMessage()));
}
}
}
} |
d58f2304-6d13-4d2b-83de-7cb968dfff1f | 2 | @Override
public Event decode(RemoteEvent event) {
InputStream is;
try {
is = new ByteArrayInputStream(event.getBody().getBytes());
ObjectInputStream i = new ObjectInputStream(is);
return (Event) i.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
} |
5a55276f-0147-4618-a1b4-c199c0026584 | 0 | @Override
public void packetSent(PacketSentEvent e) {
} |
23d894fe-4cef-410a-8cc3-27885593ad4d | 7 | public double additionInfo() {
double result = 0.0;
double milkSize = 0.0;
double milkGood = 0.0;
double milkBad = 0.0;
double lemonSize = 0.0;
double lemonGood = 0.0;
double lemonBad = 0.0;
double noneSize = 0.0;
double noneGood = 0.0;
double noneBad = 0.0;
for (Tea t : trainingSet) {
if (t.getAddition().equals(Tea.MILK)) {
milkSize++;
if (t.isDrinkable()) {
lemonGood++;
} else {
lemonBad++;
}
}
if (t.getAddition().equals(Tea.LEMON)) {
lemonSize++;
if (t.isDrinkable()) {
milkGood++;
} else {
milkBad++;
}
}
if (t.getAddition().equals(Tea.NONE)) {
noneSize++;
if (t.isDrinkable()) {
noneGood++;
} else {
noneBad++;
}
}
}
result = milkSize / (double) trainingSet.size() * entropy(milkGood / milkSize, milkBad / milkSize);
result += lemonSize / (double) trainingSet.size() * entropy(lemonGood / lemonSize, lemonBad / lemonSize);
result += noneSize / (double) trainingSet.size() * entropy(noneGood / noneSize, noneBad / noneSize);
return result;
} |
3a583c18-3b75-4a63-9587-8a9b0267cf14 | 4 | public boolean containsValue(Object value)
{
if (value == null) return containsNullValue();
Entry[] tab = this.table;
for (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
if (value.equals(e.value)) return true;
return false;
} |
d301d19f-f27e-4d9a-97ff-5736ba865918 | 8 | public Game(int numberOfCards) {
super("Memory game.Game");
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setVisible(true);
setSize(GAME_WIDTH, GAME_HEIGHT);
currentPlayer = new Player();
loginDialog = new LoginDialog(this);
registerDialog = new RegisterDialog(this);
scoresDialog = new ScoresDialog(this);
createMenuBar();
createBoard(8);
gameBoard.setVisible(false);
loginDialog.setVisible(true);
// baza danych
final DatabaseConnector db = new DatabaseConnector();
try {
db.connect();
if(db != null) {
System.out.println("connected");
}
} catch (SQLException e) {
e.printStackTrace();
}
loginDialog.setLoginListener(new LoginListener() {
@Override
public void login(String user, String password) {
System.out.println("user form main frame " + user);
System.out.println("passowrd form main frame " + password);
boolean isLogged = false;
try {
isLogged = db.loginToDB(user, password);
} catch (SQLException e) {
e.printStackTrace();
}
if(isLogged) {
currentPlayer.setLogin(user);
gameBoard.setVisible(true);
loginDialog.setVisible(false);
} else {
loginDialog.promptUser("Niepoprawny login lub haslo");
}
}
});
registerDialog.setRegisterListener(new RegisterListener() {
@Override
public void register(String username, String email, String password) {
boolean registerSuccess = false;
try {
registerSuccess = db.registerToDB(username, email, password);
} catch (SQLException e) {
e.printStackTrace();
}
if(registerSuccess) {
System.out.println("zarejestrowano poprawnie");
registerDialog.promptUser("sukcess");
} else {
System.out.println("blad rejestracji");
registerDialog.promptUser("blad rejestracji");
}
}
});
gameBoard.setGameEndListner(new GameEndListener() {
@Override
public void endGame(double score) {
try {
db.insertScore(currentPlayer.getLogin(), (int)score);
} catch(SQLException e ) {
e.printStackTrace();
}
Twitter twitter = new Twitter();
try {
twitter.PostScore(currentPlayer.getLogin(), Double.toString(score));
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("window closing");
dispose();
System.gc();
}
});
} |
b7fd7ded-7d96-4f46-9105-213d5e1abe33 | 9 | public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.getClass() == cal2.getClass());
} |
4a2717fb-0f39-46f4-a978-4ab699ce2c18 | 2 | public static void main(String[] args) {
int[][] matrix = {
{1,2,3,4,5,6,7,8},
{1,3,5,7,9,0,2,4},
{2,4,6,8,1,1,3,5},
{1,4,8,3,6,9,1,0}
};
markLines(matrix);
for (int[] rows: matrix) {
for (int i: rows) {
System.out.print(i + " ");
}
System.out.println("");
}
} |
74fe2ef8-9748-420b-a701-f5dd422005fe | 5 | private void tryAction(ControlAction ca)
{
switch (ca.action)
{
case SEND_ID: // send ID
sendID(ca.getID());
break;
case SEND_MESSAGE: // SEND MESSAGE
sendChatMessage(ca.message);
break;
case START_SERVER:// start server
startServer();
// TODO gui.setMeldung blubb was auch immer
break;
case STOP_SERVER:// stop server
stopServer();
break;
case 5:
break;
}
} |
36df1e93-a8e3-4a67-b58f-f15d1a5960dd | 3 | public String toString(){
StringBuffer sb = new StringBuffer();
switch(errorType){
case ERROR_UNEXPECTED_CHAR:
sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append(".");
break;
case ERROR_UNEXPECTED_TOKEN:
sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(".");
break;
case ERROR_UNEXPECTED_EXCEPTION:
sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
break;
default:
sb.append("Unkown error at position ").append(position).append(".");
break;
}
return sb.toString();
} |
88c22433-d104-48b0-b178-be891d8192f9 | 2 | public void runInstruction(String instruction){
Pattern writePattern = Pattern.compile("^write\\s([a-zA-Z]*)\\s([a-zA-Z]*)\\s(\\d+)", Pattern.CASE_INSENSITIVE);
Pattern readPattern = Pattern.compile("^read\\s([a-zA-Z]*)\\s([a-zA-Z]*)$", Pattern.CASE_INSENSITIVE);
Matcher matcher = writePattern.matcher(instruction);
InstructionObject instructionObject = null;
if (matcher.matches()) {
System.out.println("write Instruction");
String subject = matcher.group(1);
String object = matcher.group(2);
int value = Integer.parseInt(matcher.group(3));
instructionObject = new InstructionObject(subject, object, value, InstructionType.READ);
} else if ((matcher = readPattern.matcher(instruction)).matches() ) {
System.out.println("Read Instruction");
String subject = matcher.group(1);
String object = matcher.group(2);
instructionObject = new InstructionObject(subject, object,InstructionType.WRITE);
} else {
System.out.println("Bad Instruction");
instructionObject = new InstructionObject(InstructionType.BAD);
}
monitor.executeInstruction(instructionObject);
} |
61c13c1f-9374-4b0f-94bf-646e2db1d723 | 8 | protected String encodeSingleProperty(String propName, List<Object> propValues) throws InformationProblem {
String fullPropStr = "`" + propName + "`" + ":";
if (propValues.size() > 1) {
fullPropStr = fullPropStr + "[";
}
int propCount = 0;
for (Object propVal : propValues) {
if (propCount > 0) {
fullPropStr = fullPropStr + ", ";
}
//System.out.println("encodeSingleProperty - propVal type is: " + propVal.getClass().getName() + ", value: " + propVal);
if (propVal instanceof String) {
fullPropStr = fullPropStr + "\"" + propVal + "\"";
} else if (propVal instanceof Boolean) {
fullPropStr = fullPropStr + propVal;
} else if (propVal instanceof Integer) {
fullPropStr = fullPropStr + propVal;
} else if (propVal instanceof Double) {
fullPropStr = fullPropStr + propVal;
} else {
throw new InformationProblem("No idea how to encode property type: " + propVal.getClass().getName());
}
propCount++;
}
if (propValues.size() > 1) {
fullPropStr = fullPropStr + "]";
}
return fullPropStr;
} |
a9262eff-b841-40cc-becc-e867129e9dc6 | 0 | public void setHead(Items head) {
this.head = head;
} |
045aa693-66d8-4642-8c2d-5894e852ee52 | 2 | private Boolean isAnXMLFile(final String filePath) {
String[] splitted = filePath.split("\\.");
if ((splitted.length > 1) && (splitted[1]).compareTo(XML_FILE_EXTENSION) == 0) {
return true;
}
return false;
} |
de9589bd-adcd-4e25-b0c8-5e7a43e97748 | 1 | public String toString() {
try {
return this.toJSON().toString(4);
} catch (JSONException e) {
return "Error";
}
} |
28b98900-1c09-4619-a8b1-05a7bd71a495 | 0 | public XMLProcessor() {
init();
reset();
} |
2888d97e-aa9a-454f-8a9f-871cc9081a33 | 1 | private void nextQBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextQBtnActionPerformed
//store response!
setResponse();
//Show next question
if (qIndex < quiz.questionList.size() - 1)
{
qIndex++;
ShowQuestion(qIndex);
}
else
{
saveResults();
}
}//GEN-LAST:event_nextQBtnActionPerformed |
7084d160-6f7d-4fec-bff5-0e20e22d59f4 | 5 | private void loadHexFile() {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return lnf.getFileChooserHEXFilter();
}
@Override
public boolean accept(File f) {
return f.isDirectory() || f.toString().endsWith(".hex") || f.toString().endsWith(".HEX");
}
});
if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
this.pathTextField.setText(f.toString());
try {
this.loadedHEX = new HEXFile(f);
this.inputTextArea.setText(loadedHEX.getInitialFile());
String[] dec = decompiler.decompile(loadedHEX.getData());
for(String s : dec) {
decompTextArea.append(s+"\n");
}
this.saveButton.setEnabled(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, lnf.getDialogErrLoad());
return;
}
}
} |
4dbcabd6-6229-44f9-9342-c0c604f46e83 | 1 | public void updatePanel(User user){
jlbMainInformation.setText("[" + user.getLevel() + "] " + (user.getNick() == null ? "???" : user.getNick()));
jprgLevelProgress.setMaximum(user.getLevelUpExp());
jprgLevelProgress.setValue(user.getCurrentExp());
jlbRealMoney.setText("" + user.getrCoins());
jlbInGameMoney.setText("" + user.getvCoins());
} |
af7a0318-d516-4dd4-90ff-dd7a7d046afb | 5 | @Override
public boolean offer(T t) {
boolean result = false;
if (firstItem == null) {
firstItem = new PriorityItem(t);
length++;
result = true;
} else {
boolean searching = true;
PriorityItem currentItem = firstItem;
PriorityItem NewItem = new PriorityItem(t);
if(NewItem.priority > firstItem.priority){
NewItem.setNextItem(firstItem);
firstItem = NewItem;
length++;
result = true;
} else {
while (searching) {
if (currentItem.getNextItem() == null) {
currentItem.setNextItem(NewItem);
searching = false;
} else if(NewItem.priority > currentItem.getNextItem().priority){
NewItem.setNextItem(currentItem.getNextItem());
currentItem.setNextItem(NewItem);
}
currentItem = currentItem.getNextItem();
}
length++;
result = true;
}
}
return result;
} |
c2532582-41b7-4251-9979-9ade4d4af546 | 9 | void setData(){
id = 0;
num = 0;
BufferedReader br = null;
try {
//File file = new File((Catapult.class.getResource(dir+fileName[fid])).getFile());
URL data = (Catapult.class.getResource(dir + fileName[fid]));
InputStream ins = data.openStream();
br = new BufferedReader(new InputStreamReader(ins));
String line;
if ((line = br.readLine()) != null){//1行目(名前)
name = line;
//System.out.println(name);
}
if ((line = br.readLine()) != null){//2行目(データ数)
num = Integer.parseInt(line);
turn = new int [num];
type = new int [num];
if (num > 0)
ENTRY = true;
//System.out.println(num);
}
if (ENTRY){
for (int i = 0; i < num; i++){//3行目以降(データ)
if ((line = br.readLine()) == null)
return;
int p = line.indexOf(",");
turn[i] = Integer.parseInt(line.substring(0, p));
type[i] = Integer.parseInt(line.substring(p+1));
//System.out.println(turn[i] + "[+]" + type[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(br !=null)
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
} |
ce102d49-116a-48db-98f5-3bb5d7b4526f | 9 | public void update() throws MaltChainedException {
// Retrieve the address value
final AddressValue arg1 = addressFunction1.getAddressValue();
final AddressValue arg2 = addressFunction2.getAddressValue();
if (arg1.getAddress() != null && arg1.getAddressClass() == org.maltparser.core.syntaxgraph.node.DependencyNode.class &&
arg2.getAddress() != null && arg2.getAddressClass() == org.maltparser.core.syntaxgraph.node.DependencyNode.class) {
DependencyNode node1 = (DependencyNode)arg1.getAddress();
DependencyNode node2 = (DependencyNode)arg2.getAddress();
try {
int head1 = Integer.parseInt(node1.getLabelSymbol(column.getSymbolTable()));
int head2 = Integer.parseInt(node2.getLabelSymbol(column.getSymbolTable()));
if (!node1.isRoot() && head1 == node2.getIndex()) {
featureValue.setIndexCode(table.getSymbolStringToCode("LEFT"));
featureValue.setSymbol("LEFT");
featureValue.setNullValue(false);
} else if (!node2.isRoot() && head2 == node1.getIndex()) {
featureValue.setIndexCode(table.getSymbolStringToCode("RIGHT"));
featureValue.setSymbol("RIGHT");
featureValue.setNullValue(false);
} else {
featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE));
featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE));
featureValue.setNullValue(true);
}
} catch (NumberFormatException e) {
throw new FeatureException("The index of the feature must be an integer value. ", e);
}
} else {
featureValue.setIndexCode(table.getNullValueCode(NullValueId.NO_NODE));
featureValue.setSymbol(table.getNullValueSymbol(NullValueId.NO_NODE));
featureValue.setNullValue(true);
}
// featureValue.setKnown(true);
featureValue.setValue(1);
} |
4517cf8e-0619-433a-8564-8463bcf096c8 | 4 | public static LinkedList<CONSTANTPoolElement> loadElements(DataInputStream mainInput, int count) throws IOException // Возвращает пул констант
{
LinkedList<CONSTANTPoolElement> pool = new LinkedList<CONSTANTPoolElement>();
pool.add(new CONSTANT_FICTIVE()); // Для сдвига нумерации с 0 до 1
for (int i = 1; i < count; i++)
{
if ((i != 1) && ((pool.get(i-1) instanceof CONSTANT_Double) || (pool.get(i-1) instanceof CONSTANT_Long)))
{
pool.add(new CONSTANT_FICTIVE()); // эти типы занимают 2 ячейки
}
else
{
pool.add(loadElement(mainInput, i));
}
}
return pool;
} |
9f3300c8-0253-48ff-a21a-5ffaada44c6e | 7 | public void addChildToBack(Node child) {
child.next = null;
if (last == null) {
first = last = child;
// <netbeans>
if (sourceEnd < child.sourceEnd) {
if (sourceStart == sourceEnd && sourceStart == 0) {
sourceStart = child.sourceStart;
}
sourceEnd = child.sourceEnd;
}
// </netbeans>
return;
}
last.next = child;
last = child;
// <netbeans>
if (sourceEnd < child.sourceEnd) {
if (sourceStart == sourceEnd && sourceStart == 0) {
sourceStart = child.sourceStart;
}
sourceEnd = child.sourceEnd;
}
// </netbeans>
} |
3a459eaa-c310-4a8d-a214-6f66e6748ef6 | 4 | public static void drawWrappedString(String string, float x, float y, float z, float scale, int wrapWidth)
{
texture.bind();
scale /= 1000;
float currentXOffset = 0;
float currentYOffset = 0;
for(int i = 0; i < string.length(); i++)
{
char character = string.charAt(i);
if(character == '\n')
{
currentYOffset -= glyphHeight * scale + spacingY;
currentXOffset = 0;
continue;
}
if(!glyphs.containsKey(character))
continue;
if(currentXOffset + glyphs.get(character).getWidth() > wrapWidth / scale)
{
currentXOffset = 0;
currentYOffset -= glyphHeight * scale + spacingY;
}
Glyph glyph = glyphs.get(character);
glyph.render(x + currentXOffset, y + currentYOffset, z, scale);
currentXOffset += glyph.getWidth() * scale + spacingX * scale;
}
} |
7723ec7b-7b7e-4ee4-8064-a0419ca9956b | 7 | public Main() throws Exception {
super();
prop = new Properties();
try {
configFile = this.getClass().getResourceAsStream("/config/config.properties");
prop.load(configFile);
} catch (IOException e) {
e.printStackTrace();
}
if(
prop.getProperty("uploadPath") == null ||
prop.getProperty("mysqlLogin") == null ||
prop.getProperty("mysqlPassword") == null ||
prop.getProperty("mysqlHost") == null ||
prop.getProperty("ldapHost") == null ||
prop.getProperty("ldapDomain") == null
)
{
throw new Exception("One or more field in config file are empty!");
}
path = prop.getProperty("uploadPath");
mysql = new Mysql(prop.getProperty("mysqlLogin"), prop.getProperty("mysqlPassword"), prop.getProperty("mysqlHost"));
json = new JSONObject();
upload = new Upload( mysql, path );
ldap = new Ldap( prop.getProperty("ldapHost"), prop.getProperty("ldapDomain") );
} |
1bc76060-ff24-47fc-893c-cfcbd4255d79 | 2 | static LogWriter getLogWriter(String name) {
LogWriter current = logWriters;
while (current != null) {
if (name.equalsIgnoreCase(current.name)) return current;
current = current.next;
}
return null;
} |
efd73de0-0585-49c7-a56d-e12a0842ad6a | 1 | public void playFox() throws InterruptedException{
try
{
in = new FileInputStream(fox);
as = new AudioStream(in);
ap.player.start(as);
}
catch(Exception e)
{
System.out.println("Got an IOException: " + e.getMessage());
e.printStackTrace();
}
Thread.sleep(foxLen);
} |
c1c93f85-9409-4e32-838d-661a598cbaf0 | 4 | public static <T extends Comparable<? super T>> T max(T a, T b) {
if (a == null) return b;
if (b == null) return a;
return a.compareTo(b) > 0 ? a : b;
} |
6c6852de-078b-43b0-94c6-e4457385e08e | 9 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Vulnerability other = (Vulnerability) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (scripts == null) {
if (other.scripts != null) {
return false;
}
} else if (!scripts.equals(other.scripts)) {
return false;
}
return true;
} |
44ef505f-f984-425a-83f3-fb16594219aa | 8 | public E remove(Position<E> v)
throws InvalidPositionException
{
BTPosition<E> vv = checkPosition(v);
BTPosition<E> leftPos = vv.getLeft();
BTPosition<E> rightPos = vv.getRight();
if(leftPos != null && rightPos != null)
{
throw new InvalidPositionException("Cannot remove node with two children.");
}
BTPosition<E> ww; //the only child of v, if any
if(leftPos != null)
{
ww = leftPos;
}
else if(rightPos != null)
{
ww = rightPos;
}
else //v is a leaf
{
ww = null;
}
if(vv == root) { //v is the root
if(ww != null)
{
ww.setParent(null);
}
root = ww;
}
else //v is NOT the root
{
BTPosition<E> uu = vv.getParent();
if(vv == uu.getLeft()){
uu.setLeft(ww);
}
else{
uu.setRight(ww);
}
if(ww != null)
{
ww.setParent(uu);
}
}
size--;
return v.element();
} |
c126b281-2338-408c-88a5-03b2d4a21d6d | 2 | //@Command
@RequiresPermission("libminecraft.test")
private void test(CommandSender sender, CommandArgs args)
{
sender.sendMessage("Params:");
for (String param : args.getParams())
{
sender.sendMessage(" - '" + param + "'");
}
sender.sendMessage(" ");
sender.sendMessage("Flags:");
for (String flag : args.getFlags())
{
sender.sendMessage(" - '" + flag + "'");
}
} |
cb50312a-c3fa-4df1-ba14-bce832947336 | 5 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
String serverID = "ALL";
if (serverID != null && serverMap.size() > 0 && jComboBox2.getSelectedIndex() > 0) {
serverID = ((String[]) serverMap.get((Integer) jComboBox2.getSelectedIndex()-1))[1];
}
//public static boolean proposePaymentPlan(String serverID,String validToDate, String senderAcctID, String senderNymID, String planConsideration,String recepientAcctID, String recepientNymID, String payPlanDelay, String payPlanPeriod,String payPlanLen, String payPlanMax){
String validTo = String.valueOf(dateField);
boolean status = Payments.proposePaymentPlan(serverID, validTo, jTextField2.getText(), jTextField1.getText(), jTextArea1.getText(), jTextField4.getText(), jTextField3.getText(), jTextField6.getText(), jTextField7.getText(), jTextField8.getText(), jTextField10.getText(),jTextField12.getText(),jTextField13.getText(),jTextField11.getText());
if (status) {
JOptionPane.showMessageDialog(this, "Payment Plan Proposal done successfully", "Propose Payment Plan Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Error in Payment Plan Proposal", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
setCursor(Cursor.getDefaultCursor());
dispose();
}
}//GEN-LAST:event_jButton1ActionPerformed |
47bfac47-9a51-48a2-a76d-b7ff967ea16e | 2 | private static Map<String, Double> parseSiteWeights(Map<String, SiteConfig> configs) {
double sum = 0;
ImmutableMap.Builder<String, Double> siteWeights = ImmutableMap.builder();
for (Map.Entry<String, SiteConfig> entry : configs.entrySet()) {
sum += entry.getValue().getWeight();
siteWeights.put(entry.getKey(), sum);
}
if (sum != 1) {
throw new RuntimeException("Site weights must sum to unity");
}
return siteWeights.build();
} |
d471301c-d208-4a37-84fe-3dafbe8679a6 | 5 | public byte[] getEncoded() {
try {
byte[] versionBytes = new byte[]{(byte) majorVersion,
(byte) releaseVersion};
BERTLVObject versionObject = new BERTLVObject(VERSION_LDS_TAG,
versionBytes);
byte[] tagListAsBytes = new byte[tagList.size()];
for (int i = 0; i < tagList.size(); i++) {
int dgTag = tagList.get(i);
tagListAsBytes[i] = (byte) dgTag;
}
BERTLVObject tagListObject = new BERTLVObject(TAG_LIST_TAG,
tagListAsBytes);
BERTLVObject[] value = null;
if (sois == null || sois.length == 0) {
value = new BERTLVObject[]{versionObject, tagListObject};
} else {
DERSequence[] soisArray = new DERSequence[sois.length];
for (int i = 0; i < sois.length; i++) {
soisArray[i] = sois[i].getDERSequence();
}
value = new BERTLVObject[]{
versionObject,
tagListObject,
new BERTLVObject(SOI_TAG, new DERSet(soisArray)
.getEncoded())};
}
BERTLVObject result = new BERTLVObject(EF_COM_TAG, value);
result.reconstructLength();
return result.getEncoded();
} catch (Exception e) {
e.printStackTrace();
return null;
}
} |
05238b2b-75fe-4d3f-a9eb-28bef49632d5 | 3 | @CaseHandler(routine = AUTHENTICATED_USER, reqType = RequestType.GET)
public String handleAuthenticated() {
// If user is tried to authenticate
if (this.userSession != null) {
//ожидаем пока AccountService вернет данные
if (this.userSession.isComplete()) {
//проверяем, что пользователь существует
if (! this.userSession.getUserId().equals(DBService.USER_NOT_EXIST)) {
System.out.println("Session Id: " + this.sessionId);
// Заполняем контекст
this.pageVariables = dataToKey(new String[] {"PageTitle", "Location","UserId", "UserName", "Time", "Session"},
"User Page","Your data",this.userSession.getUserId(), this.userSession.getName(), getTime(), this.sessionId);
return generatePage("temp.tml", this.pageVariables);
} else {
this.sessionService.closeSession(this.sessionId); //удаляем текущую сессию
return "Error. No user with this name";
}
} else {
//просим пользователя подождать
//TODO: ----------------------------------------------------------------------------------------Remake waiting page
return generatePage("wait.tml", new HashMap<String, Object>());
//TODO: отправлять тут код ошибки с пустым телом или JSON, сообщающий, что идет поиск,
//TODO: сделать на клиенте циклический опрос ограниченное кол-во раз, если ответа нет - сообщение
//TODO: пользователю об ошибке/
}
}
// Well, not authenticated
else {
this.pageVariables = dataToKey(new String[] {"PageTitle", "Location"},
"AviaDB","Welcome to AviaDB site!");
return generatePage(TEMPLATE, this.pageVariables);
}
} |
5b0cec7f-d895-498d-b90f-a660eed41d8a | 0 | protected String getLabel(Instrument instrument) {
String label = instrument.name();
label = label.substring(0, 2) + label.substring(3, 5);
label = label + (tagCounter++);
label = label.toLowerCase();
return label;
} |
fa1520be-e68f-4588-b7e4-68a721bb7e1f | 8 | public void update() {
//
// If there are bubbles awaiting display, see if you can move the existing
// bubbles up to make room.
final Bubble first = showing.getFirst() ;
final boolean
shouldMove = toShow.size() > 0,
canMove = showing.size() == 0 || first.alpha <= 1,
isSpace = showing.size() == 0 || first.yoff >= LINE_SPACE ;
if (shouldMove && canMove) {
if (isSpace) {
showBubble(toShow.removeFirst()) ;
}
else for (Bubble b : showing) {
b.yoff += FADE_RATE * fadeRate * LINE_SPACE ;
}
}
//
// In either case, gradually fate out existing bubbles-
for (Bubble b : showing) {
b.alpha -= FADE_RATE * fadeRate / MAX_LINES ;
if (b.alpha <= 0) showing.remove(b) ;
}
} |
767ce053-28df-4c58-a10d-7dc8f52b2b89 | 3 | @WebMethod(operationName = "ReadCustomer")
public ArrayList<Customer> ReadCustomer(@WebParam(name = "cust_id") String cust_id) {
Customer cust = new Customer();
ArrayList<Customer> custs = new ArrayList<Customer>();
ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>();
if(!cust_id.equals("-1")){
qc.add(new QueryCriteria("cust_id", cust_id, Operand.EQUALS));
}
ArrayList<String> fields = new ArrayList<String>();
ArrayList<QueryOrder> order = new ArrayList<QueryOrder>();
try {
custs = cust.Read(qc, fields, order);
} catch (SQLException ex) {
Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex);
}
if(custs.isEmpty()){
return null;
}
return custs;
} |
251a687e-9621-42ae-a8cd-489607156249 | 5 | public void saveData(File file, QuestManager qm) throws IOException
{
if(!file.exists())file.mkdir();
File players = new File(file, "Players");
if(!players.exists())players.mkdir();
File quests = new File(file, "Quests");
if(!quests.exists())quests.mkdir();
for(Quest q:QuestManager.getInstance().getQuests())
{
try
{
saveQuest(quests, q);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
savePlayerData(players);
} |
9f494e75-8a69-45ef-9cd7-687d7360de2a | 2 | private void jButtonLogarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLogarActionPerformed
try{
conn.executaSQL("select * from tb_perfil where login='"+ jTextFieldLogin.getText() +"'");
conn.rs.first();
if(conn.rs.getString("senha").equals(jPasswordFieldSenha.getText())){
FormPrincipal form = new FormPrincipal();
form.setVisible(true);
dispose();
}
else{
JOptionPane.showMessageDialog(rootPane, "Usuário ou senha inválido!");
}
}catch (SQLException ex) {
JOptionPane.showMessageDialog(rootPane, "Usuário ou senha inválido!" +ex);
}
}//GEN-LAST:event_jButtonLogarActionPerformed |
a24e96c1-ecfe-4197-bed3-bf426c036b02 | 6 | static final public void primaire() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case VRAI:
case FAUX:
case entier:
case ident:
valeur();
break;
case 54:
jj_consume_token(54);
expression();
jj_consume_token(56);
break;
default:
jj_la1[21] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} |
ce7c3d8d-6cd2-48d9-a8b2-81a8c53a2d86 | 3 | public static void main(String[] args) {
if (args.length == 0) {
System.out
.println("usage: java Sobel imagefile [iterations] [RLE]");
System.out.println(" imagefile is an image in TIFF format.");
System.out
.println(" interations is the number of blurring iterations"
+ " (default 0).");
System.out
.println(" any third argument (RLE) turns on run-length "
+ "encoding in the output file");
System.out.println("The grayscale-edge image is written to "
+ "edge_imagefile.");
System.out.println("If blurring is selected, "
+ "the blurred image is written to blur_imagefile.");
System.exit(0);
}
int numIterations = 0;
if (args.length >= 2) {
try {
numIterations = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.err.println("The second argument must be a number.");
System.exit(1);
}
}
sobelFile(args[0], numIterations, args.length >= 3);
} |
60226eb3-6af8-4fb3-a3cc-7a15aa7f4d53 | 4 | public static byte[] computeDigest(byte[] bytes) {
byte[] src;
if((bytes.length % 8) == 0) {
src = new byte[bytes.length + 8];
System.arraycopy(bytes, 0, src, 0, bytes.length);
}
else {
src = new byte[bytes.length + 8 - (bytes.length % 8) + 8];
System.arraycopy(bytes, 0, src, 0, bytes.length);
}
long[] fuse1 = { 0x33180B0641EFF54L };
byte[] fuse = Utils.createBytes(fuse1);
System.arraycopy(fuse, 0, src, src.length-8, 8);
long[] digest = new long[8];
digest[0] = 0xCFB1DF3178E75B7L;
digest[1] = 0x44EAFFD72D3AC0ECL;
digest[2] = 0xFD6983DCB9162AAL;
digest[3] = 0xE4ECBFB86AF98CDL;
digest[4] = 0x91EE2C65FE4FCD6L;
digest[5] = 0x7E40F1C98ACF42B6L;
digest[6] = 0xD0C939D340227F4L;
digest[7] = 0x992D9117ED55990L;
int z;
long current;
byte[] tmp = new byte[8];
for(int i = 0; i < bytes.length; i++) {
System.arraycopy(src, i, tmp, 0, 8);
current = Utils.bytesToLong(tmp) >> (4-(i&3));
for(z = 0; z < 1024; z++) {
digest[0] ^= (digest[7] + current);
digest[0] += Long.rotateRight(digest[0], i + 15);
for(int x = 1; x < 8; x++) {
digest[x] ^= (digest[x-1] + current);
digest[x] += Long.rotateRight(digest[x], i + x + 15);
}
}
}
return Utils.createBytes(digest);
} |
389aa9a2-b2ac-46fe-be0a-3db986833c04 | 1 | public static String intListToString(int[] lst, String ...params) {
String[] str_list = new String[lst.length];
for (int i=0; i<lst.length; i++) {
str_list[i] = String.valueOf(lst[i]);
}
return listToString(str_list);
} |
4aea5d44-a7b8-40b3-ae9a-678a4f984528 | 6 | static void validate(FilterCoder[] filters)
throws UnsupportedOptionsException {
for (int i = 0; i < filters.length - 1; ++i)
if (!filters[i].nonLastOK())
throw new UnsupportedOptionsException(
"Unsupported XZ filter chain");
if (!filters[filters.length - 1].lastOK())
throw new UnsupportedOptionsException(
"Unsupported XZ filter chain");
int changesSizeCount = 0;
for (int i = 0; i < filters.length; ++i)
if (filters[i].changesSize())
++changesSizeCount;
if (changesSizeCount > 3)
throw new UnsupportedOptionsException(
"Unsupported XZ filter chain");
} |
924a210d-8027-4666-86ca-70e6d32e7866 | 0 | public int getMouseY() {
return mouseLocation.y;
} |
53f1572e-6d8d-4844-b257-a1106af629c5 | 6 | public void setChecked (boolean value) {
checkWidget ();
if ((parent.getStyle () & SWT.CHECK) == 0) return;
if (checked == value) return;
checked = value;
if ((parent.getStyle () & SWT.VIRTUAL) != 0) cached = true;
if (isInViewport ()) {
if (parent.isListening (SWT.EraseItem) || parent.isListening (SWT.PaintItem)) {
redrawItem ();
} else {
Rectangle bounds = getCheckboxBounds ();
parent.redraw (bounds.x, bounds.y, bounds.width, bounds.height, false);
}
}
} |
e91ca06c-fc49-4bfd-9948-335e397a0495 | 5 | @SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
if(label.equalsIgnoreCase("getblock"))
{
if(sender.isOp())
{
if(args.length == 4)
{
World world = Bukkit.getServer().getWorld(args[0]);
if(world == null)
{
sender.sendMessage(ChatColor.RED + "That world does not exist!");
return false;
}
double x;
double y;
double z;
try
{
x = Integer.parseInt(args[1]);
y = Integer.parseInt(args[2]);
z = Integer.parseInt(args[3]);
}
catch(Exception e)
{
sender.sendMessage("Illegal Arguement, x y and z must be integer values.");
return false;
}
Location location = new Location(world, x, y, z);
Block block = world.getBlockAt(location);
sender.sendMessage(ChatColor.GOLD + "The block in world " + ChatColor.DARK_AQUA + world.getName() + ChatColor.GOLD + " at "+ ChatColor.AQUA + x + " " + y
+ " " + z + ChatColor.GOLD + " " + ChatColor.GREEN + block.getType().toString() + ":" + block.getData());
}
}
}
return false;
} |
d8523d91-baef-40a2-9528-762ea2a13750 | 0 | @Override
public String getHouseNumber() {
return super.getHouseNumber();
} |
b28c47b0-c0a6-4774-ad59-60414c33cf46 | 2 | public boolean equals(Object ob) {
if (super.equals(ob)) {
ChocolateForKid other = (ChocolateForKid) ob;
if (figured != other.figured)
return false;
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.