method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
0d9c3397-c1aa-4503-bca0-e6bddd34f46f | 0 | Bishop(int t, boolean w, int x, int y){
super(t,w,x,y);
dist = 7;
int[][] ex = {{1, 1}, {-1, 1}, {-1, -1}, {1, -1}};
moves = ex;
} |
61370d77-8eae-45b8-aa1a-469ad89b8e2a | 1 | public String stringOfScanProduct() {
StringBuilder products = new StringBuilder();
for (String s : scanProducts) {
products.append(s);
}
return products.toString();
} |
db20b57b-7bad-45c3-8b0d-3ea50ba2aaed | 3 | public double randomFunction(double x, double y){
switch(randomFunc){
case 0:
random = Math.sin(Math.PI*nextNode.randomFunction(x,y));
break;
case 1:
random = Math.cos(Math.PI*nextNode.randomFunction(x,y));
break;
case 2:
random = ((nextNode.randomFunction(x,y)) + (nextNode2.randomFunction(x,y)) )/2;
break;
default:
random = 0;
break;
}
return random;
} |
ef3bba7b-5bfa-40f4-a70f-24789187aa85 | 2 | public static Mask buildEdgeEnhancementMask(int width, int height) {
Mask mask = new Mask(width, height);
double pixelAmount = width * height;
for (int i = -mask.getWidth() / 2; i <= mask.getWidth() / 2; i++) {
for (int j = -mask.getHeight() / 2; j <= mask.getHeight() / 2; j++) {
mask.setPixel(i, j, -1);
}
}
mask.setPixel(0, 0, (pixelAmount - 1));
return mask;
} |
e294a93e-786b-4cc7-8f3a-75c60b37d1f3 | 8 | private void searchWithFilter(IndexReader reader, Weight weight,
final Filter filter, final Collector collector) throws IOException {
assert filter != null;
Scorer scorer = weight.scorer(reader, true, false);
if (scorer == null) {
return;
}
int docID = scorer.docID();
assert docID == -1 || docID == DocIdSetIterator.NO_MORE_DOCS;
// CHECKME: use ConjunctionScorer here?
DocIdSet filterDocIdSet = filter.getDocIdSet(reader);
if (filterDocIdSet == null) {
// this means the filter does not accept any documents.
return;
}
DocIdSetIterator filterIter = filterDocIdSet.iterator();
if (filterIter == null) {
// this means the filter does not accept any documents.
return;
}
int filterDoc = filterIter.nextDoc();
int scorerDoc = scorer.advance(filterDoc);
collector.setScorer(scorer);
while (true) {
if (scorerDoc == filterDoc) {
// Check if scorer has exhausted, only before collecting.
if (scorerDoc == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
collector.collect(scorerDoc);
filterDoc = filterIter.nextDoc();
scorerDoc = scorer.advance(filterDoc);
} else if (scorerDoc > filterDoc) {
filterDoc = filterIter.advance(scorerDoc);
} else {
scorerDoc = scorer.advance(filterDoc);
}
}
} |
bb027554-9077-46c2-823f-08d91a524b61 | 9 | public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} |
6cb90539-fc0c-4f81-9207-d360c12cb947 | 9 | @Override
public Void doInBackground() {
if (deriv == null || eqn == null || iterations == 0) {
return null;
}
int counter = 0;
double currentX = initialStart;
double newX = 0;
if (eqn.computeFor(currentX) == 0) {
root = currentX;
return null;
}
while (true) {
newX = currentX
- (eqn.computeFor(currentX) / deriv
.computeFor(currentX));
synchronized (lock){
tangentPoints.add(new Point2D.Double(currentX, eqn
.computeFor(currentX)));
}
// drawTangent (g,currentX, eqn.computeFor (currentX));
if (counter == iterations - 1 || eqn.computeFor(newX) == 0
|| Math.abs(currentX - newX) < 0.00001
|| eqn.computeFor(currentX) == eqn.computeFor(newX)) {
//System.out.println("Root at " + nf.format(newX));
root = newX;
break;
}
currentX = newX;
counter++;
}
return null;
} |
a68e580b-812a-4481-a2b3-f837f4618e28 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfoAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfoAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfoAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfoAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI_GestorInfoAdmin().setVisible(true);
}
});
} |
8efe8327-2514-4414-b3c0-177ae06107a2 | 7 | public int print(LineNumberPanel lineNumPanel, Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
// TODO: Because of banded printing the OS and printer driver may actually call this method
// two or more times for the same page, the first time is to help the printer determine extents.
// http://stackoverflow.com/questions/1943556/why-does-the-java-printables-print-method-get-called-multiple-times-with-the-sa
// It may be possible to get away with generating an array of BufferedImage for each page when
// pg.print(); is fired and just have this function look up the already rastered pages.
// - Robert B. Colton
int pageLines = (int) Math.floor(pf.getImageableHeight() / lineHeight);
int pageCount = (int) Math.ceil((float)getLineCount() / (float)pageLines);
if (pageIndex >= pageCount) return Printable.NO_SUCH_PAGE;
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.translate (pf.getImageableX(), pf.getImageableY());
Object map = Toolkit.getDefaultToolkit().getDesktopProperty(
"awt.font.desktophints"); //$NON-NLS-1$
if (map != null) {
graphics2D.addRenderingHints((Map<?, ?>) map);
}
// Editors like Studio and Eclipse usually do not paint background colors to avoid wasting the
// users ink.
// Fill background
//g.setColor(getBackground());
//g.fillRect(0, 0, pf.getImageableWidth(), pf.getImageableHeight());
// Draw each line
int insetY = lineLeading + lineAscent;
int lastLines = pageIndex * pageLines;
int lineCount = getLineCount();
if (lineNumPanel != null) {
lineNumPanel.printLineNumbers(g,lastLines,Math.min(pageLines,lineCount - lastLines),
lineNumPanel.getLineNumberWidth(lineCount));
graphics2D.translate(lineNumPanel.getLineNumberWidth(lastLines + lineCount),0);
}
for (int lineNum = 0; lineNum < pageLines && lineNum + lastLines < lineCount; lineNum++) {
drawLine(g, lineNum + lastLines, insetY + lineNum * lineHeight);
}
return Printable.PAGE_EXISTS;
} |
f2a2ba7c-955d-4cce-90d4-5d1bc18ced24 | 8 | public void processPackets() {
if(left())
return;
try {
DataInputStream din = getInputStream();
if (din.available() >= 2) {
short id = din.readShort();
Packet p = Packet.newPacket(id, this);
if (p != null)
p.handlePacket();
else
kick("Invalid Packet");
}
if (getSocket().isClosed())
leave("Socket closed");
long now = System.currentTimeMillis();
if(lastPacket == 0)
lastPacket = System.currentTimeMillis();
if (now - this.getLastPacketTime() >= 2100) {
PacketHeartbeat heartbeat = new PacketHeartbeat(this);
heartbeat.response = false;
byte[] bytes = new byte[43];
new Random().nextBytes(bytes);
heartbeat.payload = bytes;
heartbeat.send();
}
} catch (Exception e) {
leave(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
}
} |
884f1542-0a43-47ed-b648-3759b389029d | 6 | public void insert(Comparable item) {
current = parent = grand = header;
nullNode.element = item;
while (current.element.compareTo(item) != 0) {
great = grand;
grand = parent;
parent = current;
current = item.compareTo(current.element) < 0 ? current.left
: current.right;
// Check if two red children; fix if so
if (current.left.color == RED && current.right.color == RED)
handleReorient(item);
}
// Insertion fails if already present
if (current != nullNode)
return;
current = new RedBlackNode(item, nullNode, nullNode);
// Attach to parent
if (item.compareTo(parent.element) < 0)
parent.left = current;
else
parent.right = current;
handleReorient(item);
} |
8a088a1b-d1de-4688-8a4e-e90e42eb4e7d | 9 | private static int extractInt(int[] data, int startBit, int length) {
if (data == null) {
throw new IllegalArgumentException("data == null");
}
if (startBit < 0) {
throw new IllegalArgumentException("startBit < 0");
}
if (length <= 0) {
throw new IllegalArgumentException("length <= 0");
}
if (length > 31) {
throw new IllegalArgumentException("length > 31");
}
if ((length + startBit) > (data.length * 8)) {
throw new IllegalArgumentException("(length + startBit) > (data.length * 8)");
}
// create an int array where each entry represents a single bit
int[] bits = new int[data.length * 8];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 8; j++) {
bits[(i * 8) + j] = (data[i] >>> (7 - j)) & 1;
}
}
// extractInt the bits needed for the return value
int[] returnBits = new int[length];
for (int i = 0; i < returnBits.length; i++) {
returnBits[i] = bits[startBit + i];
}
// convert the return bits into an integer
// this loop could be combined with the loop in the previous step, but is kept separate for better readability
int returnInt = 0;
for (int i = 0; i < returnBits.length; i++) {
returnInt |= (returnBits[i] << ((returnBits.length - 1) - i));
}
return returnInt;
} |
f6438441-00e4-4051-9607-f1bef9b626cf | 9 | @Override
public int classDurationModifier(MOB myChar,
Ability skill,
int duration)
{
if(myChar==null)
return duration;
if((((skill.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_CRAFTINGSKILL)
||((skill.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_BUILDINGSKILL))
&&(myChar.charStats().getCurrentClass().ID().equals(ID()))
&&(!skill.ID().equals("FoodPrep"))
&&(!skill.ID().equals("Cooking"))
&&(!skill.ID().equals("Herbalism"))
&&(!skill.ID().equals("Weaving"))
&&(!skill.ID().equals("Masonry")))
return duration*2;
return duration;
} |
e70b7ab0-1279-4617-9818-e3aa52b28df2 | 8 | static final int method473(byte i, int i_25_, LobbyWorld class110_sub1,
int i_26_, boolean bool, boolean bool_27_,
LobbyWorld class110_sub1_28_) {
try {
anInt5257++;
int i_29_
= Class239_Sub8.compareLobbyWorlds(class110_sub1_28_, class110_sub1,
bool, i_25_, (byte) -30);
if (i_29_ != 0) {
if (!bool)
return i_29_;
return -i_29_;
}
if ((i_26_ ^ 0xffffffff) == 0)
return 0;
if (i >= -42)
return -65;
int i_30_
= Class239_Sub8.compareLobbyWorlds(class110_sub1_28_, class110_sub1,
bool_27_, i_26_, (byte) -30);
if (bool_27_)
return -i_30_;
return i_30_;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("o.B(" + i + ',' + i_25_ + ','
+ (class110_sub1 != null ? "{...}"
: "null")
+ ',' + i_26_ + ',' + bool + ','
+ bool_27_ + ','
+ (class110_sub1_28_ != null
? "{...}" : "null")
+ ')'));
}
} |
b8ab68a4-eafb-4800-a731-6f78240f7a77 | 8 | public static int getIndirectBufferByteOffset(Buffer buffer) {
if (buffer == null) {
return 0;
}
int i = buffer.position();
if (!(buffer instanceof ByteBuffer)) {
if (buffer instanceof FloatBuffer) {
return 4 * (((FloatBuffer) buffer).arrayOffset() + i);
}
if (!(buffer instanceof IntBuffer)) {
if (buffer instanceof ShortBuffer) {
return (((ShortBuffer) buffer).arrayOffset() + i) * 2;
}
if (buffer instanceof DoubleBuffer) {
return (((DoubleBuffer) buffer).arrayOffset() + i) * 8;
}
if (buffer instanceof LongBuffer) {
return (((LongBuffer) buffer).arrayOffset() + i) * 8;
}
if (buffer instanceof CharBuffer) {
return 2 * (((CharBuffer) buffer).arrayOffset() + i);
} else {
throw new RuntimeException("Unknown buffer type " + buffer.getClass().getName());
}
} else {
return 4 * (((IntBuffer) buffer).arrayOffset() + i);
}
} else {
return ((ByteBuffer) buffer).arrayOffset() + i;
}
} |
74afa0e5-6add-45cb-a72b-1d278f8d4470 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MLibros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MLibros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MLibros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MLibros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MLibros(null).setVisible(true);
}
});
} |
55f05824-33f9-4f64-a1aa-7035ef0f0417 | 2 | @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if(user != null) {
UserModel usermod = DataStore.getUser(user.getUserId());
if(usermod==null) response.sendRedirect(userService.createLogoutURL("/"));
request.setAttribute("user",usermod);
}
RequestDispatcher dispatch = request.getRequestDispatcher("/jsp/pages/HomePage.jsp");
dispatch.forward(request, response);
} |
81a8c06a-3e4d-4fea-b7e9-c1e646a929bf | 6 | private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
Packet packet = null;
switch (type) {
default:
case INVALID:
break;
case LOGIN:
packet = new Packet00Login(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] "
+ ((Packet00Login) packet).getUsername() + " has connected...");
PlayerMP player = new PlayerMP(game.level, 100, 100, ((Packet00Login) packet).getUsername(), address, port);
this.addConnection(player, (Packet00Login) packet);
break;
case DISCONNECT:
packet = new Packet01Disconnect(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] "
+ ((Packet01Disconnect) packet).getUsername() + " has left...");
this.removeConnection((Packet01Disconnect) packet);
break;
case MOVE:
packet = new Packet02Move(data);
this.handleMove((Packet02Move) packet);
break;
case HEALTH:
packet = new Packet03Health(data);
this.handleHealthChange((Packet03Health) packet);
break;
case DEATH:
packet = new Packet04Death(data);
this.handleDeath((Packet04Death) packet);
}
} |
a2bed850-3075-4dab-aaec-ed59b545fc1e | 1 | public void visit_dup2_x1(final Instruction inst) {
stackHeight -= 3;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 5;
} |
b8b4a6c8-b99b-4c75-8af8-23c73dd208aa | 5 | public void inputDigits(String sval) {
this.clear(); // clear all current digits
Vector<Unsigned> vtmp = new Vector<Unsigned>();
// parse string for spaces
Scanner scan = new Scanner(sval);
while(scan.hasNext()) {
try {
int n = scan.nextInt();
if(n >= base_) {
System.err.println("ERROR: Digit " + n + " too large for base " + base_);
System.exit(1);
}
vtmp.add(new Unsigned(n));
}
catch(InputMismatchException e) {
System.err.println("ERROR: Invalid symbol while parsing digits \"" + scan.next() + "\"");
System.exit(1);
}
}
scan.close();
// store with lowest base digits first
int cnt = vtmp.size();
for(int i = 0; i < cnt; i++) {
setDigit(i, vtmp.get(cnt - i - 1));
}
if(this.length() >= MAX_LENGTH_ / 2)
System.err.println("WARNING: Using a " + this.length() + " digit BigInt may cause overflow when multiplied.");
} |
a8fc6834-b859-462a-9ca1-b598c793a61b | 8 | private static int nfaMenu(EpsilonNFA nfa){
String menu = nfa.toString()+"\n\n"+
"1. Compute the Epsilon Closure\n"+
"2. Enter words\n"+
"3. Print out Alphabet\n"+
"4. Convert to DFA\n"+
"5. Print GRAIL format transitions\n"+
"6. Back\n"+alwaysMenu();
Scanner nfaScan = new Scanner(System.in);
int input;
String answer;
do{
System.out.println(menu);
input = nfaScan.nextInt();
switch(input){
case 1:
System.out.println(nfa.eCloseAutomaton());
break;
case 2:
System.out.print("Please enter a word: ");
nfaScan.nextLine();
String word = nfaScan.nextLine();
System.out.println();
System.out.println(nfa.containsWord(word));
break;
case 3:
System.out.println(nfa.alphabet);
break;
case 4:
DFA dfa = nfa.convertToDFA();
if(dfaMenu(dfa)==0)
input = 0;
break;
case 5:
System.out.println(nfa.grailFormat());
break;
default:
break;
}
}while(input!=0 && input != 6);
//can't close? makes sc in main throw an error
//nfaScan.close();
return input;
} |
699fc074-2f7a-49aa-92b6-958f2ab6ae59 | 1 | private void doInit() {
if (getConnections() == null) setConnections(new CopyOnWriteArrayList<ISocketServerConnection>());
serverStartListenerList = new EventListenerList();
serverStopListenerList = new EventListenerList();
clientConnectListenerList = new EventListenerList();
clientDisconnectListenerList = new EventListenerList();
receiveDataOnServerListenerList = new EventListenerList();
serverExceptionListenerList = new EventListenerList();
setInitial(true);
} |
d83f1087-39e3-4166-83d0-53e2f7ccd57e | 9 | protected void setBehaviorAsStateRule(Boolean state)
{
// set visible
if ( stateRule.isVisible() != null )
{
try {
affectedWidget.setVisible( !( stateRule.isVisible() ^ state ) );
}
catch(Exception e) {
e.printStackTrace();
}
}
// enabled and value setting rules are only valid if not in
// Cancel Replace mode
if ( cxlReplaceMode && affectedWidget.getParameter() != null && !affectedWidget.getParameter().isMutableOnCxlRpl() )
{
affectedWidget.setEnabled( false );
}
else
{
// set enabled
if ( stateRule.isEnabled() != null ){
affectedWidget.setEnabled( !( stateRule.isEnabled() ^ state ) );
}
// set value
if ( stateRule.getValue() != null )
{
if ( state )
{
String value = stateRule.getValue();
affectedWidget.setValueAsString( value );
}
// -- state arg is false and value involved is VALUE_NULL_INDICATOR --
else if ( Atdl4jConstants.VALUE_NULL_INDICATOR.equals( stateRule.getValue() ) )
{
// -- This resets the widget (other widgets than value="{NULL}") to non-null --
affectedWidget.setNullValue( Boolean.FALSE );
}
}
}
} |
bf754ebc-3b97-41dd-8b00-2acdf2384d44 | 8 | final public void AnonymousFunction() throws ParseException {/*@bgen(jjtree) AnonymousFunction */
SimpleNode jjtn000 = (SimpleNode)SimpleNode.jjtCreate(this, JJTANONYMOUSFUNCTION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
jj_consume_token(FUN);
Variable();
jj_consume_token(ARROW);
SingleExpression();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
} |
e32f6032-ba91-4ae7-a73c-3a1daefef23a | 9 | @SuppressWarnings("unchecked")
public boolean execute(int columnIndex) {
RowSorter<?> sorter = table.getRowSorter();
if(sorter instanceof DefaultRowSorter<?, ?>) {
RowFilter<Object, Object> parentFilter = (RowFilter<Object, Object>) ((DefaultRowSorter<?, ?>) sorter).getRowFilter();
if(!(parentFilter instanceof TableRowFilter)) {
filter.setParentFilter(parentFilter);
}
((DefaultRowSorter<?, ?>) sorter).setRowFilter(filter);
table.getTableHeader().repaint();
return true;
}
return false;
} |
ba20dd13-4b22-4e7a-bd2b-d67d648c180d | 7 | public void cargarTabla(){
//borra toda la tabla primero
for(int i=0;i<((DefaultTableModel)estrategyT.getModel()).getRowCount();){
((DefaultTableModel)estrategyT.getModel()).removeRow(i);
}
//agrega lo que haya en el arraylist
for(int i=0;i<contenedorEstrategia.getEstrategias().size();i++){
Estrategia c = contenedorEstrategia.getEstrategias().get(i);
String file = c.getFile();
String name = c.getNombre();
String status = c.isEstatus()?"Active":"Inactive";
boolean fullBackup = c.isFullBackup();
boolean archive = c.isArchive();
boolean used = c.isUsado();
//ArrayList<String> ts = c.getTablespaces();
ArrayList<Horario> hs = c.getHorarios();
String backup = "";
if(fullBackup){
backup="Full Backup";
}
else{
backup = "Partial";
}
if(c.incremental){
backup+=" Incremental";
}
String horarios="";
if(hs.size()>0){
horarios+=hs.get(0).getDia();
for(int j=1;j<hs.size();j++){
horarios+=","+hs.get(j).getDia();
}
}
((DefaultTableModel)estrategyT.getModel()).addRow(new Object[]{name,file,backup,horarios,status});
}
} |
53187a74-158e-486f-860d-edd0b7458886 | 1 | public NewMultiArrayExpr(final Expr[] dimensions, final Type elementType,
final Type type) {
super(type);
this.elementType = elementType;
this.dimensions = dimensions;
for (int i = 0; i < dimensions.length; i++) {
dimensions[i].setParent(this);
}
} |
639f5c80-9c8f-4792-9030-c405e25bbd90 | 5 | private void fillInElementsLists(int projectID){
listOfElementsToApprove.clear();
listOfElementsApproved.clear();
if (projectID >=1){
try{
ResultSet elementsOnProjectListResultSet = null;
Statement statement;
statement = connection.createStatement();
elementsOnProjectListResultSet = statement.executeQuery("SELECT Element.elementID, Element.elementName, Element.approved, SetOFElements.ProjectID FROM Element INNER JOIN SetOFElements ON Element.[elementID] = SetOFElements.[elementID] WHERE ProjectID="+ projectID +";");
int elementID;
String elementName;
boolean approved;
while(elementsOnProjectListResultSet.next())
{
elementID = elementsOnProjectListResultSet.getInt("elementID");
elementName = elementsOnProjectListResultSet.getString("elementName");
approved = elementsOnProjectListResultSet.getBoolean("approved");
Element element = new Element(elementID,elementName,approved);
if (approved == false){
listOfElementsToApprove.add(element);
listElementsToApproveList.setListData(listOfElementsToApprove);
}else{
listOfElementsApproved.add(element);
listElementsAprovedList.setListData(listOfElementsApproved);
}
ProjectElementsListCellRenderer renderer = new ProjectElementsListCellRenderer(); //custom cell renderer to display property rather than useless object.toString()
listElementsToApproveList.setCellRenderer(renderer);
listElementsAprovedList.setCellRenderer(renderer);
}
}catch(SQLException err)
{
System.out.println("ERROR: " + err);
JOptionPane.showMessageDialog(null,"* Cannot connect to database! *");
System.exit(1);
}
}else{
listOfElementsToApprove.clear();
listElementsToApproveList.setListData(listOfElementsToApprove);
listElementsToApproveList.repaint();
listOfElementsApproved.clear();
listElementsAprovedList.setListData(listOfElementsApproved);
listElementsAprovedList.repaint();
}
if (listOfElementsToApprove.isEmpty())
btnApprove.setEnabled(false);
else
btnApprove.setEnabled(true);
} |
b7f37d8b-a1cf-4695-b619-909774814f66 | 0 | public String getVoornaam() {
return voornaam;
} |
3401d714-5fec-4289-b293-1c5b5b6fa4da | 3 | public void addListener() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
super.windowOpened(e);
RandomHeader();
UpdateLookandFeel();
checkPatchState();
}
});
infoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Info(gui).setVisible(true);
}
});
consoleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
con.Fader(fader);
}
});
Play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
url = "http://signup.leagueoflegends.com/?ref=4cee835d0d9ba939041141";
Misc.OpenLink(url);
}
});
mntmMenuitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Misc.OpenLink("Logs\\");
}
});
// mntmCheckForUpdates.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// new Update(gui).setVisible(true);
// }
// });
mntmInfo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Info(gui).setVisible(true);
}
});
mntmHowToCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
url = "http://www.youtube.com/watch?v=36VrROBQ85Q";
Misc.OpenLink(url);
}
});
mntmHowToUse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
url = "http://www.youtube.com/watch?v=n0V0VvsGPSg";
Misc.OpenLink(url);
}
});
mnTutorials.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
mnTutorials.setBackground(Color.LIGHT_GRAY);
}
});
mntmGerThread.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
url = "http://euw.leagueoflegends.com/board/showthread.php?t=74443";
Misc.OpenLink(url);
}
});
mntmUsThread.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
url = "http://na.leagueoflegends.com/board/showthread.php?t=2140185";
Misc.OpenLink(url);
}
});
oeffnen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
url = "http://euw.leagueoflegends.com/board/showthread.php?t=473081";
Misc.OpenLink(url);
}
});
headerLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
RandomHeader();
UpdateLookandFeel();
}
});
ButtonPatch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
selectedSoundpack.getArchiveFile().patch();
} catch (AlreadyModdedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
checkPatchState();
}
});
btnUnpatch.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
selectedSoundpack.getArchiveFile().unpatch();
} catch (notModdedExcption e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
checkPatchState();
}
});
regionCombobox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
manager.switchRegion(regionCombobox.getSelectedItem()
.toString());
checkPatchState();
}
});
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
checkPatchState();
}
});
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String test = RADSSoundPatcher.Find.Tools.GetLoLFolder();
try {
manager.setLeagueOfLegendsBasePath(test);
lolPath.setText(test);
loadOtherRegion();
checkPatchState();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
} |
f08f2cdc-43d5-421f-aa24-a2c4e2269089 | 5 | int unpack(Buffer opb){
int vendorlen=opb.read(32);
if(vendorlen<0){
clear();
return (-1);
}
vendor=new byte[vendorlen+1];
opb.read(vendor, vendorlen);
comments=opb.read(32);
if(comments<0){
clear();
return (-1);
}
user_comments=new byte[comments+1][];
comment_lengths=new int[comments+1];
for(int i=0; i<comments; i++){
int len=opb.read(32);
if(len<0){
clear();
return (-1);
}
comment_lengths[i]=len;
user_comments[i]=new byte[len+1];
opb.read(user_comments[i], len);
}
if(opb.read(1)!=1){
clear();
return (-1);
}
return (0);
} |
58bee77d-a215-4fbb-9625-4f148bfa85e7 | 6 | public static String idlCreateCharacterSubstitutionTable() {
{ StringBuffer table = edu.isi.stella.javalib.Native.makeMutableString(256, '_');
{ int code = Stella.NULL_INTEGER;
int iter000 = (int) '0';
int upperBound000 = (int) '9';
boolean unboundedP000 = upperBound000 == Stella.NULL_INTEGER;
for (;unboundedP000 ||
(iter000 <= upperBound000); iter000 = iter000 + 1) {
code = iter000;
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '=', code);
}
}
{ int code = Stella.NULL_INTEGER;
int iter001 = (int) 'A';
int upperBound001 = (int) 'Z';
boolean unboundedP001 = upperBound001 == Stella.NULL_INTEGER;
for (;unboundedP001 ||
(iter001 <= upperBound001); iter001 = iter001 + 1) {
code = iter001;
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '=', code);
}
}
{ int code = Stella.NULL_INTEGER;
int iter002 = (int) 'a';
int upperBound002 = (int) 'z';
boolean unboundedP002 = upperBound002 == Stella.NULL_INTEGER;
for (;unboundedP002 ||
(iter002 <= upperBound002); iter002 = iter002 + 1) {
code = iter002;
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '=', code);
}
}
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '=', ((int) '_'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) ' '));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'X', ((int) '!'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '"'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'H', ((int) '#'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'B', ((int) '$'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'R', ((int) '%'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'A', ((int) '&'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'Q', ((int) '\''));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '('));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) ')'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'O', ((int) '*'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'I', ((int) '+'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) ','));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '-'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'D', ((int) '.'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'S', ((int) '/'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'C', ((int) ':'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) ';'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'L', ((int) '<'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'E', ((int) '='));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'G', ((int) '>'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'P', ((int) '?'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'M', ((int) '@'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '['));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '\\'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) ']'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'U', ((int) '^'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '`'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '{'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'V', ((int) '|'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, '_', ((int) '}'));
edu.isi.stella.javalib.Native.mutableString_nthSetter(table, 'T', ((int) '~'));
return (table.toString());
}
} |
47f3f26f-1459-487a-a88f-48c4393dd837 | 2 | private boolean isCredentialMatch() {
for (String credential : credentialsList()) {
if (basicAuthCredentials.equals(credential)) {
return true;
}
}
return false;
} |
2684beb3-5caa-4330-8b93-76dae0f6c247 | 8 | public void newMixer( Mixer m )
{
if( myMixer != m )
{
try
{
if( clip != null )
clip.close();
else if( sourceDataLine != null )
sourceDataLine.close();
}
catch( SecurityException e )
{}
myMixer = m;
if( attachedSource != null )
{
if( channelType == SoundSystemConfig.TYPE_NORMAL
&& soundBuffer != null )
attachBuffer( soundBuffer );
else if( myFormat != null )
resetStream( myFormat );
}
}
} |
4fc6caf6-00f6-4ab7-8860-cc4dcb1dddb3 | 5 | private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length) throws IOException {
assert(buffer != this.buffer);
try {
do {
int read = inflater.inflate(buffer, offset, length);
if(read <= 0) {
if(inflater.finished()) {
throw new EOFException();
}
if(inflater.needsInput()) {
refillInflater(inflater);
} else {
throw new IOException("Can't inflate " + length + " bytes");
}
} else {
offset += read;
length -= read;
}
} while(length > 0);
} catch (DataFormatException ex) {
throw (IOException)(new IOException("inflate error").initCause(ex));
}
} |
b024cff8-e94e-4e60-9965-a545a23a758c | 7 | @Override
protected void mutate(Individual i) {
Expression ex = (Expression)i;
Random r = new Random();
int depth =r.nextInt(ex.depth()>0?ex.depth():1);
while(!ex.isLeaf()&&depth>0){
ex= ((Operator)ex).expressions[r.nextInt(ex.getArity())];
depth--;
}
if (!ex.isLeaf()){
Operator op = (Operator) ex;
if (op instanceof If){
Expression aux = op.expressions[1];
op.expressions[1]=op.expressions[2];
op.expressions[2]=aux;
} else if (op instanceof Or){
op = new And(op.expressions);
} else if (op instanceof And){
op = new Or(op.expressions);
}
} else {
((Leaf) ex).rebuild();
}
ex.recalcule();
} |
0671b8ea-0b25-4b0f-a24d-0d7280068dd4 | 7 | public void loadMathStyle(Reader re) throws IOException {
StreamTokenizer tok = new StreamTokenizer(re);
tok.resetSyntax();
tok.whitespaceChars(0, 32);
tok.wordChars(33, 255);
tok.ordinaryChars('(', ')');
// commentChar('/');
tok.commentChar(';');// 59 is ';'
// tok.quoteChar('"');
// quoteChar('\''); // tok.eolIsSignificant(true);
SchemeNodeModel node = (SchemeNodeModel) getRoot();
while (tok.nextToken() != StreamTokenizer.TT_EOF) {
if (tok.ttype == 40) { // "("
// System.out.println("Token starts with (");
SchemeNodeModel newNode = new SchemeNodeModel(getFrame(), this);
insertNodeInto(newNode, node, node.getChildCount());
node = newNode;
} else if (tok.ttype == 41) { // ")"
// System.out.println("Token starts with )");
if (node.getParent() != null) {// this should not be necessary,
// if this happens, the code is
// wrong
node = (SchemeNodeModel) node.getParent();
}
} else if (tok.ttype == StreamTokenizer.TT_WORD) {
String token = tok.sval.trim();
if (node.toString().equals(" ") && node.getChildCount() == 0) {
node.setUserObject(token);
} else {
SchemeNodeModel newNode = new SchemeNodeModel(getFrame(),
this);
insertNodeInto(newNode, node, node.getChildCount());
newNode.setUserObject(token);
}
}/*
* else if (tok.ttype == tok.TT_NUMBER) { String token =
* Double.toString(tok.nval);
*
* if (node.toString().equals("")) { node.setUserObject(token); }
* else { SchemeNodeModel newNode = new SchemeNodeModel(getFrame());
* insertNodeInto(newNode,node,node.getChildCount());
* newNode.setUserObject(token); } }
*/
}
} |
a772f43e-e8fe-4d81-a76d-2496981af5f1 | 1 | public void PESQUISADepartamentos() {
DepartamentoDAO departamento = new DepartamentoDAO();
try {
tblDepartamentos.setModel(DbUtils.resultSetToTableModel(departamento.PesquisaNaTabelaDepartamentos(txtPesquisaDepartamento.getText())));
} catch (SQLException ex) {
}
} |
f30e2d52-e05f-41e7-b8a2-6480ab3ae25c | 3 | private void collision (LinkedList<GameObject> object){
for (int i=0;i< obbjectHandler.object.size();i++){
GameObject tempObject = obbjectHandler.object.get(i);
if(tempObject.getId() == ObjectId.Test){
if(getBounds().intersects(tempObject.getBounds())){
y = tempObject.getY()-height;
velocityY = 0;
jumping = false;
falling = false;
}
else
falling = true;
}
}
} |
cdf46c97-6510-4e8e-8950-88f84a12dda9 | 8 | @Override
public void handleClient(ObjectInputStream input, ObjectOutputStream output) {
try {
while(true){
Object obj = input.readObject();
if (obj instanceof String) {
if ((((String) obj)).equalsIgnoreCase("exit")) {
break;
}else{
System.out.println("Current obj: "+(String)obj);
}
}else if (obj instanceof Model){
model = (Model) obj;
}else if(obj instanceof Solver){
solver = (Solver) obj;
}
if (model != null && solver != null){
Integer val = new Integer(solver.calculator(model));
output.writeObject(val);
model = null;
}
}
// System.out.println(solver.getClass());
input.close();
output.close();
}catch (ClassNotFoundException | IOException e) {
System.out.println("CLASS OR IO, Nevermore8");
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
1c0da79e-0265-42cd-a85e-05678fd85a6b | 1 | public void testCycListVisitor() {
System.out.println("\n*** testCycListVisitor ***");
CycListParser.verbosity = 0;
try {
CycList cycList2000 = getCyc().makeCycList("(1 . 24)");
CycList cycList2001 = getCyc().makeCycList("(1 . 23)");
assertFalse(cycList2001.equals(cycList2000));
CycList cycList1 = getCyc().makeCycList("()");
Enumeration e1 = cycList1.cycListVisitor();
assertFalse(e1.hasMoreElements());
CycList cycList2 = getCyc().makeCycList("(1 \"a\" :foo #$Brazil)");
Enumeration e2 = cycList2.cycListVisitor();
assertTrue(e2.hasMoreElements());
Integer integer1 = Integer.valueOf(1);
Object nextObject = e2.nextElement();
assertTrue(nextObject instanceof Integer);
assertTrue(((Integer) nextObject).intValue() == integer1.intValue());
assertTrue(((Integer) nextObject).intValue() == 1);
assertTrue(e2.hasMoreElements());
assertEquals("a", e2.nextElement());
assertTrue(e2.hasMoreElements());
assertEquals(CycObjectFactory.makeCycSymbol(":foo"), e2.nextElement());
assertTrue(e2.hasMoreElements());
assertEquals(getCyc().makeCycConstant("#$Brazil"),
e2.nextElement());
assertFalse(e1.hasMoreElements());
CycList cycList3 = getCyc().makeCycList("((()))");
Enumeration e3 = cycList3.cycListVisitor();
assertFalse(e3.hasMoreElements());
CycList cycList4 = getCyc().makeCycList("(()())");
Enumeration e4 = cycList4.cycListVisitor();
assertFalse(e4.hasMoreElements());
CycList cycList5 = getCyc().makeCycList("(\"a\" (\"b\") (\"c\") \"d\" \"e\")");
Enumeration e5 = cycList5.cycListVisitor();
assertTrue(e5.hasMoreElements());
assertEquals("a", e5.nextElement());
assertTrue(e5.hasMoreElements());
assertEquals("b", e5.nextElement());
assertTrue(e5.hasMoreElements());
assertEquals("c", e5.nextElement());
assertTrue(e5.hasMoreElements());
assertEquals("d", e5.nextElement());
assertTrue(e5.hasMoreElements());
assertEquals("e", e5.nextElement());
assertFalse(e5.hasMoreElements());
CycList cycList6 = getCyc().makeCycList("(\"a\" (\"b\" \"c\") (\"d\" \"e\"))");
Enumeration e6 = cycList6.cycListVisitor();
assertTrue(e6.hasMoreElements());
assertEquals("a", e6.nextElement());
assertTrue(e6.hasMoreElements());
assertEquals("b", e6.nextElement());
assertTrue(e6.hasMoreElements());
assertEquals("c", e6.nextElement());
assertTrue(e6.hasMoreElements());
assertEquals("d", e6.nextElement());
assertTrue(e6.hasMoreElements());
assertEquals("e", e6.nextElement());
assertFalse(e6.hasMoreElements());
} catch (Exception e) {
failWithException(e);
}
System.out.println("*** testCycListVisitor OK ***");
} |
b2280e0b-e980-4e2c-9a67-72b3efe580de | 4 | private void dealtDamage(int getX, int getY, int getWidth, int getLength, int getTime, int getDelay, double getDamage,int applyForce)
{
if (character.equals("P1"))
{
if (movementDirection)
{
getWorld().addObject(new P1AttackArea(x + getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,movementDirection),x + getX, y + getY);
}
else
{
getWorld().addObject(new P1AttackArea(x - getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,movementDirection),x - getX, y + getY);
}
}
else if (character.equals("P2"))
{
if (movementDirection)
{
getWorld().addObject(new P2AttackArea(x + getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,movementDirection),x + getX, y + getY);
}
else
{
getWorld().addObject(new P2AttackArea(x - getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,movementDirection),x - getX, y + getY);
}
}
} |
fa9f86cf-f302-48b6-ba55-11b9f0c183c7 | 3 | private void destroyBricks() throws IOException {
int line, col;
BrickExplosion explosion;
for(int i = 0; i < 8; i++) {
if(blaster[i][2] == 1) {
line = blaster[i][1] / 40;
col = blaster[i][0] / 40;
//Retirer la brique de la map
if(gameModel.getMap().getMapTab()[line][col] == 1) {
gameModel.getMap().getMapTab()[line][col] = 3;
//Ajouter une explosion à la liste du gameModel et lancer l'animation
explosion = new BrickExplosion(GameModel.getExplosionCount(), blaster[i][0], blaster[i][1], gameModel);
gameModel.addExplosion(explosion);
explosion.start();
}
}
}
} |
fcbcc8b6-b570-4ed4-993e-da818cecf77e | 0 | public void removeByAppointment(Appointment appt, int dayOffset) {
this.removeBySpan(DateUtil.transposeToDay(appt.startTime,
this.startOfDay + dayOffset*DateUtil.DAY_LENGTH), DateUtil.transposeToDay(appt.endTime,
this.startOfDay + dayOffset*DateUtil.DAY_LENGTH));
} |
981aeedb-8554-426d-8e89-f6d6fa08a2dc | 3 | private void ConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConnectActionPerformed
UserDAO cdao = new UserDAO();
clients=cdao.findUserByLogin(login.getText());
boolean there = cdao.Authentification(login.getText(), pwd.getText());
if(there)
{
if(login.getText().equals("admin") && pwd.getText().equals("admin"))
{
AffichageUserGui a= new AffichageUserGui();
a.setVisible(true);
this.dispose();
}
else {
ProfilClient b=new ProfilClient();
b.setVisible(true);
this.dispose();
}
}else
{
JOptionPane.showMessageDialog(this,"Login OR Password unvalid");
}
}//GEN-LAST:event_ConnectActionPerformed |
fd46395e-1ebc-4688-a1f9-f17afe036684 | 6 | public Token getTokenList(Segment text, int initialTokenType, int startOffset) {
resetTokenList();
this.offsetShift = -text.offset + startOffset;
prevState = YYINITIAL;
// Start off in the proper state.
int state = YYINITIAL;
switch (initialTokenType) {
case INTERNAL_INTAG_START:
state = INTAG_START;
break;
case INTERNAL_INTAG_ELEMENT:
state = INTAG_ELEMENT;
break;
case INTERNAL_INTAG_ATTLIST:
state = INTAG_ATTLIST;
break;
default:
if (initialTokenType<-1024) { // INTERNAL_IN_COMMENT - prevState
int main = -(-initialTokenType & 0xffffff00);
switch (main) {
default: // Should never happen
case INTERNAL_IN_COMMENT:
state = COMMENT;
break;
}
prevState = -initialTokenType&0xff;
}
else { // Shouldn't happen
state = YYINITIAL;
}
}
start = text.offset;
s = text;
try {
yyreset(zzReader);
yybegin(state);
return yylex();
} catch (IOException ioe) {
ioe.printStackTrace();
return new DefaultToken();
}
} |
4e48ca90-79b2-470c-8115-8e8f7322a119 | 8 | public Application getApplication() {
if (this.application == null) {
Class clazz = null;
try {
clazz = this.getClass().getClassLoader().loadClass
("org.apache.shale.test.mock.MockApplication12");
this.application = (MockApplication) clazz.newInstance();
} catch (NoClassDefFoundError e) {
clazz = null; // We are not running in a JSF 1.2 environment
} catch (ClassNotFoundException e) {
clazz = null; // Same as above
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
if (clazz == null) {
try {
clazz = this.getClass().getClassLoader().loadClass
("org.apache.shale.test.mock.MockApplication");
this.application = (MockApplication) clazz.newInstance();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
}
}
return this.application;
} |
4957b2a9-c098-4b4e-af30-7270df92ae9c | 0 | public DecreaseThread(SampleCalc sample)
{
this.SampleCalc = sample;
} |
a92b69d2-f650-43a4-84a5-cc437e78acfd | 5 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coordinate that = (Coordinate) o;
if (x != that.x) return false;
if (y != that.y) return false;
return true;
} |
253f5499-8265-42aa-b9e4-1ab073c15f87 | 2 | public void setDocument(Document doc, long start) {
try {
if(doc != null) {
this.textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
String contents = stringify(doc);
this.textArea.setText(contents);
setStats(start);
}
} catch(Exception e) {
setContents(e.getMessage() + "\n" + Utilities.getStackTrace(e), start);
}
} |
f035655c-2239-47a0-81b0-e7d29cc8993a | 5 | public boolean isWonderBow(ItemStack item) {
if (item != null && item.getType() == Material.BOW) {
ItemMeta meta = item.getItemMeta();
if (meta != null && meta.getDisplayName().equals(this.metaBow.getDisplayName())) {
List<String> lore = meta.getLore();
if (lore.size() > this.metaBow.getLore().size()) {
return lore.subList(0, this.metaBow.getLore().size()).equals(this.metaBow.getLore());
}
}
}
return false;
} |
7100ab40-3103-40d8-a78f-b914fb497b5c | 5 | @Command(command = "deletewarp",
arguments = {"warp name"},
description = "Deletes a given warp",
permissions = "delete.self")
public static boolean deleteWarp(CommandSender sender, String warpName) throws EssentialsCommandException {
// try to get that warp
// get a resultset of all our warps
ArrayList<HashMap<String, Object>> results = null;
if(!PermissionsManager.playerHasPermission(sender, "warp.delete.any")) {
results = DatabaseManager.accessQuery(
"select * from warps where name=? and (public=? or owner=?) limit 1;",
warpName,
true,
sender.getName());
if(results.size() == 0) {
throw new EssentialsCommandException("&eThe warp '%s' doesn't exist!", warpName);
}
}
else {
results = DatabaseManager.accessQuery(
"select * from warps where name=? limit 1;",
warpName);
if(results.size() == 0) {
throw new EssentialsCommandException("&eThe warp '%s' doesn't exist!", warpName);
}
}
// make sure we have it
if(results.size() != 1) {
throw new EssentialsCommandException("&eThe warp '%s' doesn't exist!", warpName);
}
// ok, we have it
// build a location
HashMap<String, Object> result = results.get(0);
// delete it!
int numRowsDeleted = DatabaseManager.updateQuery("delete from warps where id=?",
result.get("id"));
if(numRowsDeleted == 0) {
throw new EssentialsCommandException("Failed to delete the warp! Please contact an administrator!");
}
ColourHandler.sendMessage(sender, "&aWarp '%s' deleted!", warpName);
return true;
} |
15f1757a-9a92-40d2-be48-abda2cad07c4 | 9 | public void keyPressed(int key) {
if(key == KeyEvent.VK_A || key == KeyEvent.VK_LEFT){
player.setLeft(true);
}
if(key == KeyEvent.VK_D || key == KeyEvent.VK_RIGHT){
player.setRight(true);
}
if(key == KeyEvent.VK_W || key == KeyEvent.VK_SPACE || key == KeyEvent.VK_UP){
player.setJumping(true);
}
if(key == KeyEvent.VK_SHIFT){
player.setSprint(true);
}
if(key == KeyEvent.VK_ESCAPE){
gameStateControl.setPaused(gameStateControl.getGameState()); //this allows us to "save" the current state of the game
gameStateControl.setGameState(LevelType.PAUSE); //Pause screen
}
} |
eb0676b4-1a29-4030-8f78-c87f8852f3a4 | 1 | public void dispose() {
for (Animation ani : animations) {
ani.stop();
}
} |
7e61c951-b7e0-4249-b0ac-aab711101c98 | 0 | public CheckResultMessage check14(int day) {
return checkReport.check14(day);
} |
a5e5764c-45fd-408b-a14b-fd7b354f3368 | 1 | @Override
public String execute() {
if (databaseContext.table != null) {
return Integer.toString(databaseContext.table.rollback());
} else {
return "no table";
}
} |
4c0d754a-ac4b-4271-a809-f5e3476cb758 | 3 | public static void print(TreeNode root) {
if (null != root) {
System.out.println(root.val + "[" + (null == root.left ? "null" : root.left.val) + "," + (null == root.right ? "null" : root.right.val) + "]");
print(root.left);
print(root.right);
}
} |
3dcee6d9-a7f1-46ae-bc8f-41056b5aed84 | 8 | public void visitVarInsn(final int opcode, final int var) {
Type type;
switch (opcode) {
case Opcodes.LLOAD:
case Opcodes.LSTORE:
type = Type.LONG_TYPE;
break;
case Opcodes.DLOAD:
case Opcodes.DSTORE:
type = Type.DOUBLE_TYPE;
break;
case Opcodes.FLOAD:
case Opcodes.FSTORE:
type = Type.FLOAT_TYPE;
break;
case Opcodes.ILOAD:
case Opcodes.ISTORE:
type = Type.INT_TYPE;
break;
default:
// case Opcodes.ALOAD:
// case Opcodes.ASTORE:
// case RET:
type = OBJECT_TYPE;
break;
}
mv.visitVarInsn(opcode, remap(var, type));
} |
ac6e3618-5515-496c-b703-3c7877971532 | 2 | public boolean contains( long testID ) {
for ( int i = 0; i < numIDs; i++ ) {
if ( statusIDs[i] == testID ) return true;
}
return false;
} |
9a5cee0b-8ea5-491d-aa27-81a43f5e5fe2 | 4 | public static void main(String[] args) {
try {
//lezen
JAXBContext jc = JAXBContext.newInstance(World.class);
World ls = (World) jc.createUnmarshaller().unmarshal(World.class.getResource("Wereld.xml"));
for(Person p : ls.getPersons()){
System.out.println(p.getName());
System.out.println(p.getRadius());
System.out.println(p.getZin());
}
System.out.println("----");
for(Item i : ls.getItems()){
System.out.println(i.getName());
System.out.println(i.getHeight());
}
for(Building b : ls.getBuildings()){
System.out.println(b.getName());
}
} catch (JAXBException ex) {
System.err.println(ex);
}
} |
ea249944-4327-4ac5-b790-0128b9a96acc | 3 | public File findCard(Card c) {
String name = c.getFileName();
String set = c.getSet();
if(set == null) {
set = map.get(name);
if(set == null) return null;
}
File f = new File(new File(CubeMaker.cacheDir, set), name + ".jpg");
if(f.exists()) {
return f;
} else {
return null;
}
} |
5bff0a0e-3082-4847-8d07-64c4087885ee | 3 | private void setUserDirs() {
homeDirs = new HashMap<>();
List<String> names = null;
String base = new File("").getAbsolutePath();
try {
names = UserStatementMaker.getUserNameList();
} catch (SQLException e) {
Logger.logError(e);
e.printStackTrace();
}
names.forEach(n -> {
String sandbox = base + "/storage/" + n;
setUserHomeDir(n, sandbox);
homeDirs.put(n, sandbox);
if (new File(sandbox).mkdirs())
Logger.log("Created new User Storage Folder for " + n + " at " + sandbox);
else
Logger.log("Opened existing sandbox for " + n + " at " + sandbox);
});
setUserHomeDir("Guest", base + "/storage/Guest");
homeDirs.put("Guest", base + "/storage/Guest");
if (new File(base + "/storage/Guest").mkdirs())
Logger.log("Created new User Storage Folder for Guest");
else
Logger.log("Opened existing sandbox for Guest");
setDefaultHomeDir(new File("").getAbsolutePath() + "/");
} |
df5cead9-8a44-488e-9301-03dd836e0760 | 0 | @Override
public void log(String str){
System.out.println("MyClass logging::"+str);
} |
d2328594-f2bd-4f82-8cbb-177dc95b2bf4 | 7 | public void updateScrollBars()
{
if(tm.getTiles().size()>0)
{
verticalScrollbar.update();
if(verticalScrollbar.isSelected() && !tm.isTileSelected() || verticalScrollbar.isKeyboardInput())
{
//System.out.println("vert bar selected: "+verticalScrollbar.isSelected()+", "+verticalScrollbar.isKeyVert());
tm.updateVert((int)verticalScrollbar.getDisplacement());
}
horizontalScrollbar.update();
if(horizontalScrollbar.isSelected() && !tm.isTileSelected() || horizontalScrollbar.isKeyboardInput())
{
//System.out.println("horiz bar selected: "+horizontalScrollbar.isSelected()+ ", "+horizontalScrollbar.isKeyHoriz());
tm.updateHoriz((int)horizontalScrollbar.getDisplacement());
}
}
} |
22e2d438-1b85-4474-b1d6-6d4d21d319ce | 4 | public boolean saveBooking() {
boolean commitSuccess = false;
boolean doubleBooking = false;
bookingList = DBFacade.getBookingsFromDB();
notSavedBookings = new ArrayList<>();
ArrayList<Booking> bookingsForSaving = DBFacade.getBookingsFromUOF();
ArrayList<Booking> bookingsForSavingCopy = new ArrayList<>(bookingsForSaving);
Room newRoom = null;
//ConcurrentModificationException: man kan ikke kører løkken igennem og ændre på listen samtidig.
//Derfor har vi lavet en kopi af listen
for (Booking booking : bookingsForSavingCopy) {
for (int i = 0; i < roomList.size(); i++) {
if (roomList.get(i).getRoomNo() == booking.getRoomNo()) {
newRoom = roomList.get(i);
}
}
doubleBooking = checkForDoubleBooking(newRoom, booking.getCheckInDate(), booking.getCheckOutDate()); // Checker at rummet er ledigt i perioden.
if (doubleBooking) {
DBFacade.removeBookingFromUOF(booking); // Sletter rum fra vores UnitOfWork.
notSavedBookings.add(booking); // Bruges til at give brugeren besked på hvilke bookings der fejlede.
}
}
commitSuccess = commitTransaction();
return commitSuccess;
} |
f0c80f1e-995d-41b0-a8d1-228b8f46212b | 9 | public static void main (String args[])
throws Exception {
String host ="omnimail1.omnifax.xerox.com";
String username ="edi";
String password ="ediedi";
// Get session
Session session = Session.getInstance(
new Properties(), null);
// Get the store
Store store = session.getStore("imap");
store.connect(host,username,password);
// Get folder
Folder folder = store.getFolder("INBOX/AIG/EQ");
folder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader (
new InputStreamReader(System.in));
// Get directory
Message message[] = folder.getMessages();
for (int i = message.length-1,n=message.length;n>i&&i!=-1;i--) {
Date e = message[i].getSentDate();
System.out.println("Message Inbox date :"+e);
Address[] a;
if ((a=message[i].getFrom())!=null) {
for (int j=0;j<a.length;j++)
System.out.println("From : " +a[j].toString());
}
Calendar cal = Calendar.getInstance();
SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd 06:00:00" );
cal.add(Calendar.DATE,-15); //set to 17 days earlier date (15-31)
fmt1.setCalendar(cal); //set to date after 6am
String s2 =fmt1.format(cal.getTime()); //returns yesterday's date in string format
System.out.println("Yesterday's Date in string form before conversion :"+s2 );
SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date d2 = fmt2.parse(s2); //to convert the date in string to date form
System.out.println("Yesterday's date in date type is: "+d2);
if (e.after(d2)) {
Object content = message[i].getContent();
if (content instanceof Multipart) {
System.out.println("Multipart" + i);
if ((a=message[i].getFrom()) !=null) {
for (int j=0;j<a.length;j++) {
System.out.println("From : " +a[j].toString());
String t = ((a[j].toString()).substring(3,13));
String m = "AIG - TEST";
if (t.equals(m)==false)
handleMultipart((Multipart)content);
} //end of for (int j=0)
} //end of if(a=msg[i])
}
else {
System.out.println("ElseMultipart" + i);
handlePart(message[i]);
}
} // end of (if e.after d2)
else
System.out.println("Old message");
} // end of for loop
// Close connection
folder.close(false);
store.close();
} // end of main |
b48362bb-c3f9-4160-b10e-766579e8f899 | 9 | public void executeLdrt(InstructionARM inst, boolean exec) {
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getAddrMode2(inst);
int vaddr, paddr, rot, value;
if (!exec) {
printDisasm(inst,
String.format("ldrt%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getAddrMode2Name(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
//P ビットは必ず 0、ポストインデクス
vaddr = getReg(rn);
rot = vaddr & 0x3;
paddr = getMMU().translate(vaddr, 4, false, false, true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead_a32(paddr, 4)) {
raiseException(ARMv5.EXCEPT_ABT_DATA,
String.format("ldrt [%08x]", paddr));
return;
}
value = read32_a32(paddr);
switch (rot) {
case 0:
//do nothing
break;
case 1:
value = Integer.rotateRight(value, 8);
break;
case 2:
value = Integer.rotateRight(value, 16);
break;
case 3:
value = Integer.rotateRight(value, 24);
break;
default:
throw new IllegalArgumentException("Illegal address " +
String.format("inst:0x%08x, rot:%d.",
inst.getInst(), rot));
}
if (rd == 15) {
setPC(value & 0xfffffffe);
getCPSR().setTBit(BitOp.getBit32(value, 0));
} else {
setReg(rd, value);
}
//P ビットは必ず 0、W ビットは必ず 1、ベースレジスタを更新する
setReg(rn, offset);
} |
a65ec699-09c8-4923-98ab-6628ad1345e7 | 9 | private static void messageParser() throws IOException{
//Ok, lets use the potentially broken thing ot test the broken thing
//right?
MessageParser MP = new MessageParser();
ByteArrayOutputStream os=new ByteArrayOutputStream();
ByteArrayInputStream bis;
byte [] info = testGen(20);
byte [] id = testGen(20);
byte [] bitField = testGen(80);
MP.sendHandShake(os,info,id);
bis = new ByteArrayInputStream(os.toByteArray());
HandShake hs = MP.readHandShake(bis);
System.out.println(" Test 1: "+(Arrays.equals(info,hs.hashInfo)&&Arrays.equals(id,hs.peerID)));
//MP.bitfield(os, new byte[50]);
os.reset();
MP.choke(os);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
System.out.println(" Test 2: "+(MP.getNext().type==PeerMessage.Type.CHOKE));
os.reset();
MP.unchoke(os);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
System.out.println(" Test 3: "+(MP.getNext().type==PeerMessage.Type.UNCHOKE));
os.reset();
MP.interested(os);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
System.out.println(" Test 4: "+(MP.getNext().type==PeerMessage.Type.INTERESTED));
os.reset();
MP.not_interested(os);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
System.out.println(" Test 5: "+(MP.getNext().type==PeerMessage.Type.NOT_INTERESTED));
os.reset();
MP.bitfield(os,bitField);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
System.out.println(" Test 6: "+(Arrays.equals(bitField, MP.getNext().bitfield)));
os.reset();
MP.have(os,10241139);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
System.out.println(" Test 7: "+(MP.getNext().piece==10241139));
os.reset();
MP.request(os, 10199,10211,12311);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
PeerMessage p = MP.getNext();
System.out.println(" Test 8: "+(p.begin==10211&&p.index==10199&&p.length==12311&&p.type==PeerMessage.Type.REQUEST));
byte [] block = testGen(10234);
os.reset();
MP.piece(os, 0, 300, block);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
p = MP.getNext();
System.out.println(" Test 9: "+(Arrays.equals(block, p.block)&&p.index==0&&p.begin==300));
os.reset();
MP.cancel(os, 10199,10211,12311);
bis = new ByteArrayInputStream(os.toByteArray());
MP.readMessage(bis);
p = MP.getNext();
System.out.println(" Test 10: "+(p.begin==10211&&p.index==10199&&p.length==12311&&p.type==PeerMessage.Type.CANCEL));
} |
b4f9b9d0-4903-4cbe-8f6d-05f07b5d385c | 5 | @AfterGroups("Insertion")
@Test(groups = "AVL Tree")
public void testAVLTreeSearch() throws KeyNotFoundException {
Integer count;
Reporter.log("[ ** 2-3 Tree Search ** ]\n");
try {
timeKeeper = System.currentTimeMillis();
for (Integer i = 0; i < seed; i++) {
avlTree.search(i);
}
Reporter.log("Search -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
timeKeeper = System.currentTimeMillis();
count = 0;
for (Integer i = -seed; i < 0; i++) {
try {
avlTree.search(i);
} catch (KeyNotFoundException e) {
count++;
}
}
if (count == seed) {
Reporter.log("False search -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
} else {
throw new KeyNotFoundException();
}
} catch (KeyNotFoundException e) {
Reporter.log("Searching -- Failed!!!\n");
throw e;
}
} |
599bd119-dfc4-4c4b-9787-42c424d0db95 | 0 | @Provides
@Named("unmarshalContext")
public JAXBContext getUnmarshalContext() throws JAXBException {
return JAXBContext.newInstance(clazzezToBeBound);
} |
cc417273-56bc-4b53-a23a-46e24c45a8fb | 8 | private void tryToFall(World par1World, int par2, int par3, int par4)
{
int i = par2;
int j = par3;
int k = par4;
if (canFallBelow(par1World, i, j - 1, k) && j >= 0)
{
byte byte0 = 32;
if (fallInstantly || !par1World.checkChunksExist(par2 - byte0, par3 - byte0, par4 - byte0, par2 + byte0, par3 + byte0, par4 + byte0))
{
par1World.setBlockWithNotify(par2, par3, par4, 0);
for (; canFallBelow(par1World, par2, par3 - 1, par4) && par3 > 0; par3--) { }
if (par3 > 0)
{
par1World.setBlockWithNotify(par2, par3, par4, blockID);
}
}
else if (!par1World.isRemote)
{
EntityFallingSand entityfallingsand = new EntityFallingSand(par1World, (float)par2 + 0.5F, (float)par3 + 0.5F, (float)par4 + 0.5F, blockID);
par1World.spawnEntityInWorld(entityfallingsand);
}
}
} |
0b3c4132-04f9-4a4a-902b-56428641b2c6 | 7 | public void replaceSpace(char[] s, int length) {
if (s == null || length == 0) {
return;
}
int spaceCount = 0;
for (int i = 0; i < length; i++) {
if (s[i] == ' ')
spaceCount++;
}
int j = spaceCount;
for (int i = length - 1; i >= 0; i--) {
if (s[i] == ' ') {
j--;
s[i + j * 2] = '%';
s[i + 1 + j * 2] = '2';
s[i + 2 + j * 2] = '0';
} else if (j > 0) {
s[i + j * 2] = s[i];
} else {
break;
}
}
} |
bc73d1e9-d6f7-422e-ae30-de4ef7e7a9ee | 6 | public void advance(Territory territ, boolean all) {
if (territ == fromTerrit) {
if (toTerrit.units > 1) {
int toPlace = getTroopTransferCount(all, toTerrit.units - 1);
toTerrit.addUnits(-toPlace);
fromTerrit.addUnits(toPlace);
}
if (all)
endAdvance();
} else if (territ == toTerrit) {
if (fromTerrit.units > 1) {
int toPlace = getTroopTransferCount(all, fromTerrit.units - 1);
fromTerrit.addUnits(-toPlace);
toTerrit.addUnits(toPlace);
}
if (all)
endAdvance();
}
} |
e4b22e76-6a0a-4e7e-903b-30f4d640f9eb | 3 | public EntityUniqueIdentifier(Class<?> clazz, String uuid) {
if (clazz == null) {
throw new IllegalArgumentException("clazz musnt be null");
}
if (uuid == null) {
throw new IllegalArgumentException("uuid musnt be null");
}
this.clazz = clazz;
this.uuid = uuid;
} |
05915ed2-1ae4-4801-8ab1-f40678f90510 | 9 | @Override
public Object getValueAt(int row, int col)
{
Order o = info.get(row);
switch (col)
{
case 0 : return o.getOrderName();
case 1 : return o.printDate(o.getDueDate());
case 2 : return o.getSleeve().getMaterial().getName();
case 3 : return o.getSleeve().getCircumference();
case 4 : return o.getWidth();
case 5 : return o.getQuantity();
case 6 : return o.getConductedQuantity();
case 7 : return o.getStatus();
case 8 : return o.isUrgent();
}
return null;
} |
70034fd8-5628-4941-86a7-d981bf1a2647 | 3 | public int singleNumber(int[] A) {
int x = 0;
int result = 0;
for (int i = 0;i < 32 ; i++ ){
x = 0;
for (int j = 0;j < A.length;j++) {
if( (A[j] & (1 << i)) != 0)
x ++;
}
result = result |((x%3)<<(i));
}
return result;
} |
9ef70c09-e2ac-41d4-8fd7-8685f5e4fcaf | 5 | public String[] loadFromFile() {
String filename = "Database.ini";
Scanner textScan;
String[] params = new String[5];
System.out.print("Loading: " + filename + "...");
try {
File file = new File(filename);
textScan = new Scanner(file);
int count = 0;
while (textScan.hasNextLine() && count < 5) {
params[count] = textScan.nextLine().trim();
count++;
}
textScan.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bound: " + e.getMessage());
} catch (ArrayStoreException e) {
System.out.println("Wrong object: " + e.getMessage());
}
return params;
} |
25ba732b-7045-45bc-8511-4bec20659eaf | 5 | private void deleteSigns(String filename) throws Exception {
// check that the folder "filename" under the certificate folder is legal
String pathname = (Server.SERVERDIRECTORIES[2] + "/" + filename);
File file = new File(pathname);
// Signature folder doesn't exist or path doesn't exist
if(file == null || !file.exists()) {
System.out.println("Server: No signatures deleted for '" + filename + "'");
// Signature folder does exist
} else {
if(!file.isDirectory()) {
throw new IllegalArgumentException("ERROR: Certificates for filename '" + pathname + "' can't be deleted: '" +
pathname + "' is not a directory name.");
}
// Find all child files in the folder and delete them
System.out.println("Server: Deleting signatures for '" + filename + "'");
File[] fileSigns = file.listFiles();
boolean success = false;
for(File f: fileSigns) {
success = f.delete();
if(!success) {
throw new Exception("ERROR: Could not delete file '" + f.getAbsolutePath() + "' on Server");
}
}
}
} |
6126d1f2-9c31-418a-97b8-933a94e3c838 | 9 | public static TileMap loadMapFromFile(String path) throws IOException{
System.out.println(Functions.getTimeStamp()+" [MAPMANAGER] : Parsing data from "+path+"...");
InputStreamReader in = new InputStreamReader(ClassLoader.getSystemResourceAsStream(path));
BufferedReader inputreader = new BufferedReader(in);
String line = null;
boolean found = false;
TileMap tilemap = null;
int x=0,y=0;
while ( (line = inputreader.readLine()) != null) {
if (line.compareTo("<spritelayer>") == 0){
tilemap = new TileMap();
found = true;
} else if ( line.compareTo("</spritelayer>") == 0) {
found = false;
} else if (found) {
if (line.startsWith("[") && line.endsWith("]")){
ArrayList<Tile> tileset = new ArrayList<Tile>();
String data = line.substring(1, line.length()-1);
String[] dataarray = data.split(",");
for (int i=0; i<dataarray.length;i++){
tileset.add(new Tile(x, y, tilesize,
TextureManager.getSpriteFromSpriteSheet(TextureManager.WORLD, Integer.valueOf(dataarray[i]))));
x+=tilesize;
if ((x / tilesize) > 19) x = 0;
}
tilemap.addTileSet(tileset);
y+=tilesize;
if ((y / tilesize) > 14) y = 0;
}
} else {
System.out.println(Functions.getTimeStamp()+" [MAPMANAGER] : Unknown/invalid line. Can't parse this line:"+line);
}
}
inputreader.close();
in.close();
return tilemap;
} |
c477c21d-a106-4409-bb0a-267eae480f81 | 1 | public static double multiplicativeMean(double[] values)
{
int size = values.length;
double product = values[0];
for (int i = 1; i < size; i++) {
product *= values[i];
}
return Math.pow (product, (1.0f / size));
} |
2212eca0-3c4a-409d-b6ed-0f21655cc5e5 | 4 | private void renderSubset(ModelSubset sub) {
processSubsetFlag(sub.getFlags());
Material mat = sub.getMaterial();
setMaterial(mat);
Texture tex = null;
if (mat.getTextureID() == -1) {
if (_currentTexID != -1) {
_currentTex.disable();
_currentTex.dispose();
_currentTexID = -1;
_currentTex = null;
}
} else if (_currentTexID != mat.getTextureID()) {
if (_currentTexID != -1) {
_currentTex.dispose();
}
tex = TextureIO.newTexture(mat.getTexData());
tex.enable();
tex.bind();
tex.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
tex.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
_currentTexID = mat.getTextureID();
_currentTex = tex;
}
sub.render(gl);
} |
f40554e8-f009-470b-8e5c-dcf64f033ced | 9 | public FwySegment(LpLink ml_link,LpLink or_link,LpLink fr_link, FundamentalDiagram fd, Actuator actuator){
// link references
ml_link_id = ml_link==null?null:ml_link.getId();
or_link_id = or_link==null?null:or_link.getId();
fr_link_id = fr_link==null?null:fr_link.getId();
fr_node_id = fr_link==null?null: fr_link.getBegin().getId();
ml_link_length = ml_link==null?null:ml_link.getLength();
or_link_length = or_link==null?null:or_link.getLength();
or_lanes = or_link==null?null:or_link.getLanes();
double ml_lanes = ml_link.getLanes();
// fundamental diagram
f_max = fd.getCapacity()*ml_lanes;
vf = fd.getFreeFlowSpeed()/ml_link_length;
w = fd.getCongestionSpeed()/ml_link_length;
n_max = fd.getJamDensity()!=null ? fd.getJamDensity() : fd.getCapacity()*(1d/fd.getFreeFlowSpeed()+1d/fd.getCongestionSpeed()); // veh/meter/lane
n_max *= ml_lanes; // veh/meter
n_max *= ml_link_length; // veh/link
// metering
is_metered = actuator!=null;
has_on_ramp = or_link!=null;
has_off_ramp = fr_link != null;
if(is_metered){
Parameters P = actuator.getParameters();
r_max = get_parameter(P,"max_rate_in_vphpl",Double.POSITIVE_INFINITY)*or_lanes/3600d;
l_max = get_parameter(P,"max_queue_length_in_veh",Double.POSITIVE_INFINITY);
}
else{
r_max = Double.POSITIVE_INFINITY;
l_max = Double.POSITIVE_INFINITY;
}
this.no = 0d;
this.lo = 0d;
} |
a74cb1f7-6514-4757-977c-4a5603dda032 | 4 | public void fireAddNewMissilePressed() {
new Thread(new Runnable() {
@Override
public void run() {
// while (true) {
String id = txtId.getText();
String dest = txtDest.getText();
String damage = txtDamage.getText();
String flyTime = txtFlyTime.getText();
if (id.isEmpty() || dest.isEmpty() || damage.isEmpty()) {
JOptionPane.showMessageDialog(null,
"You must fill all details!");
return;
}
launchersPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
for (WarUIEventsListener l : allListeners) {
// sending missile details to the relevant GUI launcher
l.addMissileToUI(id, dest, damage, flyTime, launcherId);
}
closeFrame();
// }
}
}).start();
setVisible(false);
} |
f0d0f91d-5c28-45c3-abcd-1cfbbd048201 | 8 | public String runMachineStep() {
Character readSymb;
// On the first iteration
if(curReadSymb == null) {
curState = cmds.get(0).getCurState();
readSymb = tape.get(0);
}
// On the following iterations
else {
readSymb = curReadSymb;
}
// True, if such command was found
if(0 <= searchCommand(curState, readSymb)) {
// assign that command to temporary variable
Command tmpCurCmd = cmds.get(searchCommand(curState, readSymb));
// assign a new symbol to the current cell according to command
tape.set(idCurCell, tmpCurCmd.getNewSymb());
// If tape's head needs to move left and index of the current cell is the start of the ArrayList
// then need to increase our ArrayList to the left side
if((tmpCurCmd.getMoveDirection() == -1) && (idCurCell == 0)) {
tape.add(0, ' ');
}
// Else tape's head needs to move right and index of the current cell is the end of the ArrayList
// then need to increase our ArrayList to the right side
else if((tmpCurCmd.getMoveDirection() == 1) && (idCurCell == tape.size() - 1)) {
tape.add(' ');
idCurCell++;
}
// Otherwise
else {
if((tmpCurCmd.getMoveDirection() == -1)) {
idCurCell--;
}
else if((tmpCurCmd.getMoveDirection() == 1)) {
idCurCell++;
}
else {
// tape's head stays on the same cell (idCureCell doesn't change)
}
}
curReadSymb = tape.get(idCurCell);
curState = tmpCurCmd.getNextState();
}
else {
// Command wasn't found
}
return tape.toString();
} |
27a1dbcb-23c0-4130-897c-d2a42f6159e3 | 7 | Value getValue()
{
switch (type)
{
case NULL:
case UNDEFINED:
return (Value)objValue;
case BOOLEAN:
return new BooleanValue(value!=0);
case NUMBER:
return new NumberValue(value);
case STRING:
return new StringValue((String)objValue);
case OBJECT:
return (ObjectValue)objValue;
case FUNCTION:
return (FunctionValue)objValue;
}
throw new UnimplementedException();
} |
442703c1-be6e-44d7-9deb-8e052672c1f7 | 0 | @Override
public String toString() {
return name + " " + id;
} |
9b529f46-ca95-4cd7-88f5-2d77c44618c4 | 3 | public double getMiddleDirection()
{
if (leftNeighbour == null || rightNeighbour == null) return -1024;
double leftAngle = getDirection(leftNeighbour);
double rightAngle = getDirection(rightNeighbour);
if (rightAngle < leftAngle) rightAngle += Math.PI * 2;
return (leftAngle + rightAngle) / 2;
} |
2be1059c-a731-4a67-8829-718e36ccbb17 | 3 | public void add(int index, MatterInterval element) {
if (index < 1 && fictitiousRegionReady) {
throw new IndexOutOfBoundsException("Index must be from 1 to " + intervals.size() + " to add to MatterStack, but "
+ index + " inserted");
}
processBack();
intervals.add(index, element);
if (!fictitiousRegionReady) {
addFictitiousInterval();
}
process();
} |
434e3692-940d-4817-bf28-06e846fb7851 | 8 | @Override
public Object getValueAt(Object node, int column) {
Object value = null;
if (node instanceof DefaultMutableTreeTableNode) {
DefaultMutableTreeTableNode mutableNode = (DefaultMutableTreeTableNode) node;
Object o = mutableNode.getUserObject();
if (o != null && o instanceof Material) {
Material bean = (Material) o;
switch (column) {
case 0:
value = bean.getLiaohao();
break;
case 1:
value = bean.getXunhao();
break;
case 2:
value = bean.getYouxianji();
break;
case 3:
value = bean.getMiaoshu();
break;
case 4:
value = bean.getTidaixiangmuzu();
break;
}
}
}
return value;
} |
65947c4f-79e5-44c5-8831-478d83ffae43 | 5 | public static void main(String[] args) throws Exception {
if (args.length != 3 && args.length !=4) {
System.err.println("usage: java edu.berkeley.nlp.classical.ChartParser [-verbose] lexiconFileName grammarFileName \"sentence to parse\"");
System.exit(0);
}
if (args[0].equalsIgnoreCase("-verbose") || args[0].equalsIgnoreCase("-v"))
verbose = true;
String lexiconFileName = args[args.length-3];
String grammarFileName = args[args.length-2];
String sentenceString = args[args.length-1];
Lexicon lexicon = new Lexicon(new BufferedReader(new FileReader(lexiconFileName)));
Grammar grammar = new Grammar(new BufferedReader(new FileReader(grammarFileName)));
List<String> sentence = Arrays.asList(sentenceString.split("\\s+"));
ChartParser parser = new ChartParser(lexicon, grammar);
parser.parse(sentence);
List<Tree<String>> parses = parser.getParses();
for (int parseNum = 0; parseNum < parses.size(); parseNum++) {
Tree<String> parse = (Tree<String>) parses.get(parseNum);
parse = cleanTree(parse);
System.out.println("PARSE "+(parseNum+1));
System.out.print(Trees.PennTreeRenderer.render(parse));
}
} |
6d7a6520-864b-44ac-b4c7-e8b49e63e70c | 8 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == pagoFacturaGui.getAceptar()) {
if (pagoFacturaGui.getMonto().getText().equals("")) {
JOptionPane.showMessageDialog(pagoFacturaGui, "Por favor ingrese el monto", "Error!", JOptionPane.ERROR_MESSAGE);
} else {
abrirBase();
String clienteId = cli.getString("id");
int idCliente = cli.getInteger("id");
BigDecimal entrega = new BigDecimal(pagoFacturaGui.getMonto().getText());
Pago pago = new Pago();
pago.set("fecha", pagoFacturaGui.getCalendarioText().getText());
pago.set("monto", entrega);
pago.set("cliente_id", idCliente);
pago.saveIt();
String pagoId = Pago.findFirst("fecha = ? and monto = ? and cliente_id = ?", pagoFacturaGui.getCalendarioText().getText(), entrega, idCliente).getString("id");
BigDecimal cuentaCliente = new BigDecimal(cli.getString("cuenta"));
entrega = entrega.add(cuentaCliente);
Iterator<Venta> itrVenta = cargarDeuda(clienteId).iterator();
Venta ventaAPagar = null;
boolean sePuedePagar = true;
BigDecimal montoVentaAPagar = new BigDecimal(0);
BigDecimal aux;
ABMVenta ambV = new ABMVenta();
while (sePuedePagar) {
sePuedePagar = false;
while (itrVenta.hasNext()) {
String ventaId = itrVenta.next().getString("id");
aux = montoVentaNoAbonada(ventaId);
if (entrega.compareTo(aux) >= 0) {
sePuedePagar = true;
if (montoVentaAPagar.compareTo(aux) <= 0) {
ventaAPagar = Venta.findById(ventaId);
montoVentaAPagar = new BigDecimal(aux.toString());
}
}
}
if (sePuedePagar) {
abrirBase();
entrega = entrega.subtract(montoVentaAPagar);
ambV.pagar(ventaAPagar, montoVentaAPagar);
ventaAPagar.set("pago_id", pagoId);
ventaAPagar.saveIt();
itrVenta = cargarDeuda(clienteId).iterator();
montoVentaAPagar = new BigDecimal(0);
aux = null;
ventaAPagar = null;
}
}
cli.set("cuenta", entrega);
cli.saveIt();
JOptionPane.showMessageDialog(apgui, "¡Cobro registrado exitosamente!");
cerrarBase();
}
}
pagoFacturaGui.dispose();
try {
this.finalize();
} catch (Throwable ex) {
Logger.getLogger(RealizarPagoVentaControlador.class.getName()).log(Level.SEVERE, null, ex);
}
} |
03e078c6-c2ad-4651-9c2f-e02d3161a168 | 2 | private void createWindow() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(880, 550);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{30, 815, 30, 5}; // SUM = 880
gbl_contentPane.rowHeights = new int[]{50, 460, 40}; // SUM = 550
gbl_contentPane.columnWeights = new double[]{1.0, 1.0};
gbl_contentPane.rowWeights = new double[]{1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
history = new JTextArea();
history.setEditable(false);
JScrollPane scroll = new JScrollPane(history);
caret = (DefaultCaret)history.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.insets = new Insets(0, 0, 5, 5);
scrollConstraints.fill = GridBagConstraints.BOTH;
scrollConstraints.gridx = 0;
scrollConstraints.gridy = 0;
scrollConstraints.gridwidth = 3;
scrollConstraints.gridheight = 2;
scrollConstraints.insets = new Insets(0, 5, 0, 0);
contentPane.add(scroll, scrollConstraints);
txtMessage = new JTextField();
txtMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
send(txtMessage.getText(), true);
}
}
});
GridBagConstraints gbc_txtMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(0, 0, 0, 5);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
contentPane.add(txtMessage, gbc_txtMessage);
txtMessage.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
send(txtMessage.getText(), true);
}
});
GridBagConstraints gbc_btnSend = new GridBagConstraints();
gbc_btnSend.insets = new Insets(0, 0, 0, 5);
gbc_btnSend.gridx = 2;
gbc_btnSend.gridy = 2;
contentPane.add(btnSend, gbc_btnSend);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
String disconnect = "/d/" + client.getID() + "/e/";
send(disconnect, false);
running = false;
client.close();
}
});
setVisible(true);
txtMessage.requestFocusInWindow();
} |
02192e7e-7e7b-4a13-8e52-0713ea4028cd | 2 | public List<Player> getKickerList() throws IOException, ParseException {
List<String> csvPlayers = retriveData(K_PROJECTION_LINK);
List<Player> players = new ArrayList<Player>();
for (String playerString : csvPlayers) {
String[] split = playerString.split("\t");
if (split.length == 10) {
Player tempPlayer = new Player();
// hand mapped values
tempPlayer.setName(split[0]);
tempPlayer.setTeam(split[1]);
tempPlayer.setRushingAttempts(prepareDouble(split[2]));
tempPlayer.setRushingYards(prepareDouble(split[3]));
tempPlayer.setRushingTouchdowns(prepareDouble(split[4]));
tempPlayer.setReceptions(prepareDouble(split[5]));
tempPlayer.setRecievingYards(prepareDouble(split[6]));
tempPlayer.setRecievingTouchdown(prepareDouble(split[7]));
tempPlayer.setFumbles(prepareDouble(split[8]));
tempPlayer.setPosition(Position.K);
players.add(tempPlayer);
}
}
return players;
} |
0ddaf5f7-1c7d-4668-a8bc-79ce15508ac0 | 2 | public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray) object).put(value));
} else {
throw new JSONException("JSONObject[" + key
+ "] is not a JSONArray.");
}
return this;
} |
5200bf5f-982a-4db5-a130-a60cd1e7fcb9 | 2 | @Override
public void init(IViewSite site) throws PartInitException {
super.init(site);
initializeColorRegistry();
createActions();
createToolBars();
ResourcesPlugin.getWorkspace().addResourceChangeListener(new IResourceChangeListener() {
@Override
public void resourceChanged(IResourceChangeEvent e) {
if (e.getDelta() != null && e.getDelta().getResource() != null) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(ResourcesPlugin.getWorkspace().getRoot());
viewer.expandAll();
}
});
}
}
});
} |
998d4f0e-a256-4787-9974-08e6591e2867 | 8 | private static int pivot(int[] a, int low, int high) {
int i1 = low, i2 = high - 1, i3 = (low + high) / 2;
int a1 = a[i1], a2 = a[i2], a3 = a[i3];
int n = (a1 > a2) ? a1 : a2;
int m = (a2 > a3) ? a2 : a3;
if (m > n) {
return (a1 > a2) ? i1 : i2;
} else if (n > m) {
return (a2 > a3) ? i2 : i3;
} else if (n == m) {
return (a1 > a3) ? i1 : i3;
}
return -1;
} |
903b1a67-24eb-4230-bb36-96a5d5e93f29 | 3 | protected void loadXRefStmIfApplicable() {
if (m_CrossReferenceStream == null) {
long xrefStreamPosition = library.getLong(entries, "XRefStm");
if (xrefStreamPosition > 0L) {
// OK, this is a little weird, but basically, any XRef stream
// dictionary is also a Trailer dictionary, so our Parser
// makes both of the objects.
// Now, we don't actually want to chain the trailer as our
// previous, but only want its CrossReferenceStream to make
// our own
PTrailer trailer = library.getTrailerByFilePosition(xrefStreamPosition);
if (trailer != null)
m_CrossReferenceStream = trailer.getCrossReferenceStream();
}
}
} |
b6324629-f721-407f-a147-665b478071b6 | 6 | public static void SetNames(){
String[] PlayerNames = new String[NumPlayers];
int[] RandOrd = RunFileGame.getRandomOrdering(NumPlayers);
for(int i = 0; i < NumPlayers; i++){
int n = RandOrd[i];
boolean BadName = false;
String Name;
do{
Name = ui.inputName();
BadName = false;
if(Name.equals("NONE")){
BadName = true;
ui.displayError("FUCK OFF THAT NAMES RESERVED");
} else if(Name.equals("")){
BadName = true;
ui.displayError("FUCK OFF NOBODYS CALLED THAT");
}
for(int j = 0; j < i; j++){
if(Name.equals(PlayerNames[RandOrd[j]])) {
BadName = true;
ui.displayError("FUCK OFF YOUVE ALREADY DONE THEM");
}
}
}while(BadName);
PlayerNames[n] = Name;
}
Players = PlayerNames;
} |
e3bc7085-765d-4afb-ae4b-5c0723e5a6f6 | 3 | @Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.user");
try {
Criteria criteria = new Criteria();
User currUser = (User) request.getSessionAttribute(JSP_CURRENT_USER);
if (currUser == null) {
throw new TechnicalException("message.errorNullEntity");
}
criteria.addParam(DAO_ID_USER, currUser.getIdUser());
User user = (User) request.getSessionAttribute(JSP_USER);
if (user != null) {
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
criteria.addParam(DAO_ROLE_NAME, type);
} else {
criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE));
}
AbstractLogic userLogic = LogicFactory.getInctance(LogicType.USERLOGIC);
Integer resIdUser = userLogic.doDeleteEntity(criteria);
request.setParameter(JSP_SELECT_ID, resIdUser.toString());
currUser.setStatus(DELETED);
page = new ShowUser().execute(request);
} catch (TechnicalException ex) {
request.setAttribute("errorDeleteReason", ex.getMessage());
request.setAttribute("errorDelete", "message.errorDeleteData");
request.setSessionAttribute(JSP_PAGE, page);
}
return page;
} |
9e53b7a4-943e-46ad-837e-1d4bb432bbc4 | 0 | public String getEncoding() {
return encoding;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.