text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void print() {
int printableHour; // hour value to be printed
String amPm; // am or pm value to be printed
if (error != null) {
System.out.println(error);
} else {
// convert 24h to 12 h
amPm = hour >= 12 ? "PM" : "AM"; // am or pm value to be printed
if (hour > 12) {
printableHour = hour - 12;
} else if (hour == 0) {
printableHour = 12;
} else {
printableHour = hour;
}
System.out.printf("%1$02d:%2$02d %3$s%n", printableHour, minute, amPm);
}
} | 4 |
static final public AbstractSyntaxTreeNode<DataTypeEnum,IValue> booleanFactorExpression() throws ParseException {
Token t;
AbstractSyntaxTreeNode<DataTypeEnum,IValue> node;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ID:
t = jj_consume_token(ID);
{if (true) return new Variable(t.image);}
break;
case LPAR:
jj_consume_token(LPAR);
node = booleanExpression();
jj_consume_token(RPAR);
{if (true) return node;}
break;
case TRUE:
jj_consume_token(TRUE);
{if (true) return new Constant<BooleanValue>(new BooleanValue(true));}
break;
case FALSE:
jj_consume_token(FALSE);
{if (true) return new Constant<BooleanValue>(new BooleanValue(false));}
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
} | 9 |
protected PoliLine pop(PoliLine master, Point first, Point last) {
Iterator<Point> cursor = master.iterator();
LinkedList<Point> poppedPoints = new LinkedList<Point>();
poppedPoints.add(first);
boolean started = false;
while (cursor.hasNext()) {
Point x = cursor.next();
if (started && x.equals(last)) {
break;
} else if (started) {
poppedPoints.add(x);
cursor.remove();
} else if (x.equals(first)) {
started = true;
} /* else {
continue;
} */
if (!cursor.hasNext() && started) {
cursor = master.iterator();
}
}
poppedPoints.add(last);
return new PoliLine(poppedPoints.toArray(new Point[poppedPoints.size()]));
} | 7 |
private boolean callInitMethods(final Plugin spawnedPlugin, final Method[] methods)
throws IllegalAccessException {
log("callinit/start", new OptionInfo("plugin", spawnedPlugin.getClass().getCanonicalName()));
for (final Method method : methods) {
log("callinit/method", new OptionInfo("method", method.getName()));
// Init methods will be marked by the corresponding annotation.
final Init annotation = method.getAnnotation(Init.class);
if (annotation != null) {
log("callinit/method/initannotation", new OptionInfo("method", method.getName()));
try {
final Object invoke = method.invoke(spawnedPlugin, new Object[0]);
if (invoke != null && invoke instanceof Boolean) {
// Check if any init method returns false.
if (((Boolean) invoke).booleanValue() == false)
return false;
}
} catch (final IllegalArgumentException e) {
log("callinit/exception/illegalargument",
new OptionInfo("method", method.getName()),
new OptionInfo("message", e.getMessage()));
log("callinit/end/abnormal", new OptionInfo("plugin", spawnedPlugin.getClass()
.getCanonicalName()));
e.printStackTrace();
return false;
} catch (final InvocationTargetException e) {
log("callinit/exception/invocationtargetexception", new OptionInfo("method",
method.getName()), new OptionInfo("message", e.getMessage()));
log("callinit/end/abnormal", new OptionInfo("plugin", spawnedPlugin.getClass()
.getCanonicalName()));
e.printStackTrace();
return false;
} catch (final Exception e) {
log("callinit/exception/exception", new OptionInfo("method", method.getName()),
new OptionInfo("message", e.getMessage()));
log("callinit/end/abnormal", new OptionInfo("plugin", spawnedPlugin.getClass()
.getCanonicalName()));
e.printStackTrace();
return false;
}
}
}
log("callinit/end", new OptionInfo("plugin", spawnedPlugin.getClass().getCanonicalName()));
return true;
} | 8 |
public int longestValidParentheses(String s) {
if (s == null || s.length() <= 1) {
return 0;
}
int longest = 0;
int[] longests = new int[s.length()];
longests[s.length() - 1] = 0;
for (int i = s.length() - 2; i >= 0; i--) {
longests[i] = 0;
if (s.charAt(i) == ')') {
longests[i] = 0;
} else {
int k = i + longests[i + 1] + 1;
if (k < s.length() && s.charAt(k) == ')') {
longests[i] = longests[i + 1] + 2;
if (k + 1 < s.length()) {
longests[i] += longests[k + 1];
}
}
}
if (longests[i] > longest) {
longest = longests[i];
}
}
return longest;
} | 8 |
public Object get(){
return stackList.removeLast();
} | 0 |
public static int indexer(char x)throws IllegalLineException{
//takes in a char and returns int to be used for indexing with Expression Checker's dictionary
//throws IllegalLineException when the char is not of expected type
//the final return of 100 is never reached.
switch(x){
case '|':case'&': return 0;
case '(': return 1;
case ')': return 2;
case '~': return 3;
case '=': return 5;
case '>': return 6;
default: if(!Character.isLetter(x)){
throw new IllegalLineException("***Invalid Expression: "+x);
}else{
return 4;
}
}
} | 8 |
public void run() {
try {
String line = reader.readLine();
while (line != null) {
if (isErrorStream)
System.err.println(line);
else
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
public Temporada buscarTemporada(int idTemporada){
Temporada solucion = null;
for (Temporada temporada : temporadas)
if (temporada.obtenerNumeroTemporada() == idTemporada)
solucion = temporada;
return solucion;
} | 2 |
public int depositAmount(int amount){
if(amount > 0)
{
bal += amount;
System.out.println("\nRs "+amount+" is deposited into your Account");
}
return bal;
} | 1 |
void initBlocks()
{
int xInicial=0;
int yMas=10;
switch(Level)
{
case 1:
xInicial=(screenWidth-(Block.width*VBlocks))>>1;
break;
case 2:
case 3:
xInicial=Block.width>>1;
}
for(int x=0;x<VBlocks;x++)
{
int yTmp=yMas;
for(int y=0;y<HBlocks;y++)
{
blocks[x][y]=new Block(xInicial,((y*Block.height)+10)+(Level==3?yTmp:0));
yTmp+=10;
}
xInicial+=Block.width+(Level>1?Block.width:0);
}
} | 7 |
protected void processGlobalResourceARList(Sim_event ev)
{
LinkedList regionalList = null; // regional GIS list
int eventTag = AbstractGIS.GIS_INQUIRY_RESOURCE_AR_LIST;
boolean result = false;
// for a first time request, it needs to call the system GIS first,
// then asks each regional GIS for its resource IDs.
if (globalResARList_ == null)
{
// get regional GIS list from system GIS first
regionalList = requestFromSystemGIS();
// ask a resource list from each regional GIS
result = getListFromOtherRegional(regionalList, eventTag);
if (result == true)
{
globalResARList_ = new ArrayList(); // storing global AR
numAR_ = regionalList.size() - 1; // excluding GIS itself
// then store the user ID
Integer id = (Integer) ev.get_data();
userARList_ = new ArrayList();
userARList_.add(id);
return; // then exit
}
}
// cache the request and store the user ID if it is already sent
if (numAR_ > 0 && userARList_ != null && userARList_.size() > 0)
{
Integer id = (Integer) ev.get_data();
userARList_.add(id);
return; // then exit
}
result = sendListToSender(ev, globalResARList_);
if (result == false)
{
System.out.println(super.get_name() +
".processGlobalResourceARList(): Warning - can't send a " +
"resource AR list to sender.");
}
} | 6 |
public MultiBufferTest(int numBuffers, GraphicsDevice device) {
try {
GraphicsConfiguration gc = device.getDefaultConfiguration();
mainFrame = new Frame(gc);
mainFrame.setUndecorated(true);
mainFrame.setIgnoreRepaint(true);
device.setFullScreenWindow(mainFrame);
if (device.isDisplayChangeSupported()) {
chooseBestDisplayMode(device);
}
Rectangle bounds = mainFrame.getBounds();
mainFrame.createBufferStrategy(numBuffers);
BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
for (float lag = 2000.0f; lag > 0.00000006f; lag = lag / 1.33f) {
for (int i = 0; i < numBuffers; i++) {
Graphics g = bufferStrategy.getDrawGraphics();
if (!bufferStrategy.contentsLost()) {
g.setColor(COLORS[i]);
g.fillRect(0,0,bounds.width, bounds.height);
bufferStrategy.show();
g.dispose();
}
try {
Thread.sleep((int)lag);
} catch (InterruptedException e) {}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
device.setFullScreenWindow(null);
}
} | 6 |
public void run(){
// If there is not word to recognized or the word is empty then do not recognize
if(word == null || word.trim().isEmpty()){
return;
}
// Get the highlighter
DefaultHighlighter.DefaultHighlightPainter highLighter = FileUtils.getInstance().getHighlighter();
// Get the word to highlight
word = word.trim().toLowerCase();
// Iterate through the document text
int lengthToRead = endPosition - startPosition;
if(lengthToRead > 0){
try {
String line = textPane.getDocument().getText(startPosition, lengthToRead).toLowerCase();
// Replace the non-alphabetical characters for spaces
line = FileUtils.getAlphabeticalChars(line);
// Split the words by space in store them in a list
List<String> words = Arrays.asList(line.split("\\s+"));
// If there's a match, then highlight it
if(words.contains(word)){
int indexInList = words.indexOf(word);
// If the word is the first token, then find the position of the word itself
// otherwise, add a space in front of the word.
// Avoid indexing the position of a word that contains another one. Ex.- 'Leather' contains 'the', 'Start' contains 'art'.
int offset = (indexInList == 0 ? line.indexOf(word+" ") : // Check if the word is located at the beginning
(indexInList == words.size()-1 ? // Check if the word is located at the end
line.indexOf(" "+word) :
line.indexOf(" "+word+" ")
)+1); //Advance the space that was included
// The new offset position is the actual position plus the offset (the position in the line)
offset += startPosition;
// Update the position to return it to the user
startPosition = offset + word.length();
// Highlight the word
textPane.getHighlighter().addHighlight(offset, startPosition, highLighter);
}
} catch (Exception e){
e.printStackTrace();
}
}
} | 7 |
public static Shape getShape(String color) {
Circle circle = (Circle) circleMap.get(color);
if (circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating Circle of " + color + " color.");
}
return circle;
} | 1 |
*/
private int stepCalc(int range) {
if (range < 10) {
return 1;
}
if (range < 20) {
return 2;
}
if (range < 50) {
return 5;
}
if (range < 100) {
return 10;
}
if (range < 250) {
return 25;
}
if (range < 500) {
return 50;
}
return 100;
} | 6 |
public int getAmountOfCitys(){
return amountOfCitys;
} | 0 |
public static void main(String[] args) throws SecurityException {
System.out.println(System.getProperty("java.runtime.version"));
SecurityManager testManager = System.getSecurityManager();
if (testManager == null)
{
//final Unsafe unsafe = Unsafe.getUnsafe();//Doesn't work - protected to throw a security error
final Unsafe unsafe = getUnsafe();
if(unsafe == null)
{
System.err.println("Failed to get the unsafe class with reflection");
System.exit(1);
}
else
{
System.out.println("Java byte version: "+System.getProperty("os.arch"));
if("amd64".equals(System.getProperty("os.arch"))) //checking if 64 bit - probably need to check for others as well later
{
//System.setSecurityManager(new SecurityManager());
testManager = System.getSecurityManager();
SecurityManager smArray[] = new SecurityManager[1];
smArray[0] = testManager;
long baseOffset = unsafe.arrayBaseOffset(SecurityManager[].class);
long addressOfSecurityManager = unsafe.getLong(smArray, baseOffset);
//unsafe.setMemory(addressOfSecurityManager, 8, (byte) 0); //8 bytes for 64 bit
Field security = null;
try {
security = System.class.getDeclaredField("security");
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long securityManagerOffset = 0;
if (security == null)
{
System.out.println("Security manager was not found");
}
else
{
securityManagerOffset = unsafe.objectFieldOffset(security);
}
unsafe.putAddress(addressOfSecurityManager+32, 0);
if (System.getSecurityManager()==null)
{
System.out.println("SecurityManager set to null");
}
else
{
System.out.println("SecurityManager still active");
}
}
else
{
System.err.println("Using other Java JVM bit version");
System.exit(1);
}
}
//long systemAddress =
}
else
{
System.err.println("Error - Security manager was already set before "
+ "running code");
System.exit(1);
}
} | 6 |
protected boolean test3 () { return true; } | 0 |
public void shiftLeft() {
point.setLocation(location);
point.translate(-1, 0);
if (assertLegal(pane, block, point, block, location)) {
free();
location.translate(-1, 0);
calcShadowDrop();
draw();
}
} | 1 |
public HashMap<BasicMana, Integer> getMap() {
HashMap<BasicMana, Integer> temp = new HashMap<BasicMana, Integer>();
if (this.black > 0) {
temp.put(BasicMana.BLACK, this.black);
}
if (this.blue > 0) {
temp.put(BasicMana.BLUE, this.blue);
}
if (this.red > 0) {
temp.put(BasicMana.RED, this.red);
}
if (this.green > 0) {
temp.put(BasicMana.GREEN, this.green);
}
if (this.white > 0) {
temp.put(BasicMana.WHITE, this.white);
}
if (this.neutral > 0) {
temp.put(BasicMana.NEUTRAL, this.neutral);
}
return temp;
} | 6 |
public int setxattr(ByteBuffer path, ByteBuffer name, ByteBuffer value, int flags, int position) {
if (xattrSupport == null) {
return handleErrno(Errno.ENOTSUPP);
}
String pathStr = cs.decode(path).toString();
String nameStr = cs.decode(name).toString();
if (log != null && log.isDebugEnabled()) {
log.debug("setxattr: path=" + pathStr + ", name=" + nameStr + ", value=" + value + ", flags=" + flags);
}
try {
return handleErrno(xattrSupport.setxattr(pathStr, nameStr, value, flags, position));
}
catch(Exception e) {
return handleException(e);
}
} | 4 |
public String getShortestExample(Boolean accept) {
String path = "";
Queue<ArrayList<Integer>> holder = new LinkedList();
List<ArrayList<Integer>> visited = new LinkedList();
Map<ArrayList<Integer>, ArrayList<Integer>> vertmap = new HashMap<ArrayList<Integer>, ArrayList<Integer>>();
ArrayList<Integer> cur = m_Start;
holder.add(cur);
while (!holder.isEmpty()) {
cur = holder.remove();
if (cur.equals(m_Final)) {
break;
} else {
for (ArrayList<Integer> vert : getConnectedVertices(cur)) {
if (!visited.contains(vert)) {
holder.add(vert);
visited.add(vert);
vertmap.put(vert, cur);
}
}
}
}
if (!(cur.equals(m_Final) && accept) || (cur.equals(m_Final) && accept)) {
ArrayList<Integer> prev = m_Final;
ArrayList<Integer> next;
for (next = m_Final; !next.equals(m_Start); next = vertmap.get(next)) {
path = path + getRoadActionChar(next, prev);
prev = next;
}
path = path + getRoadActionChar(next, prev);
path = new StringBuilder(path).reverse().toString();
return path;
}
return null;
} | 9 |
public void releaseBuffer(ByteBuffer bb){
if(this.createCount.intValue() > maxBufferPoolSize && (this.usableCount.intValue() > (this.createCount.intValue() / 2) ) ){
bb = null;
this.createCount.decrementAndGet();
}else{
this.queue.add(bb);
this.usableCount.incrementAndGet();
}
} | 2 |
private void loadConfig(){
properties[0] = "left";
properties[1] = "right";
properties[2] = "up";
properties[3] = "down";
properties[4] = "protect";
properties[5] = "shoot";
properties[6] = "shoot2";
properties[7] = "sound";
if(file.canRead())
try {
fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file), "UTF-8"));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] values = strLine.split(";");
if(values.length == 2) add(values);
}
in.close();
br.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
int key;
for(int i=0; i<config.length-1; i++){
key = config[0];
for(int j=i+1; j<config.length-1; j++){
if(config[j]==key)
config[j]=0;
}
}
} | 8 |
public void commit(){
Point p = GUI.getMousePosition();
if(GridWorldLife.brush){
Location l = GUI.panel.locationForPoint(p);
if((prevLoc != null && !prevLoc.equals(l)) || prevSize != GridWorldLife.brushSize){
stroke(l, GridWorldLife.brushSize);
prevLoc = l;
prevSize = GridWorldLife.brushSize;
}
}
} | 4 |
public DebateGUI(User user, Debate debate) {
super("Debate");
this.userLogin = user;
this.debateSelected = debate;
String[][] team = debateSelected.getTeam();
for (int i = 0; i < team.length; i++) {
for (int j = 0; j < team[i].length; j++) {
if (team[i][j].equals(userLogin.getName())) {
if ( i == 0 ) {
teamType = "A";
counterTeamType = "B";
} else {
teamType = "B";
counterTeamType = "A";
}
break;
}
}
}
this.fileName = "src/xml/Debate"+debateSelected.getId() + "/PrivateDialog" + teamType + ".xml";
this.publicFileName = "src/xml/Debate"+debateSelected.getId() + "/PublicDialog.xml";
initComponents();
} | 4 |
private static void launchServer() throws IOException {
InetSocketAddress addr = new InetSocketAddress(Integer.valueOf(conf.getProperty(PORT)));
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase(AppMonitoredConstant.GET)) {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html");
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write(Helper.loadFile(pathWebFile));
responseBody.close();
}
}
});
server.createContext("/" + ALL_ITEMS, new HttpHandler() {
public void handle(HttpExchange httpExchange) throws IOException {
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/json");
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
Collection<String> tranformed = Collections2.transform(appMonitoreds.values(), new Function<AppMonitored, String>() {
public String apply(AppMonitored appMonitored) {
return appMonitored.getJSon();
}
});
final OutputStream o = httpExchange.getResponseBody();
o.write(("[" + Joiner.on(',').join(tranformed) + "]").getBytes());
o.close();
}
});
HttpContext ctx = server.createContext("/" + CHECK, new HttpHandler() {
public void handle(HttpExchange httpExchange) throws IOException {
Headers responseHeaders = httpExchange.getResponseHeaders();
final String appKey = ((Map<String, String>) httpExchange.getAttribute(AppMonitoredConstant.PARAMS_KEY)).get(AppMonitoredConstant.URL_KEY);
AppMonitored current = appMonitoreds.get(appKey);
responseHeaders.set("Content-Type", "text/html");
String result = "OK";
try {
result = Helper.httpQuery(current.getUrl()) ? "OK" : "KO";
} catch (Exception e) {
e.printStackTrace();
}
httpExchange.sendResponseHeaders(HTTP_OK, 0);
final OutputStream o = httpExchange.getResponseBody();
o.write((result + "-" + current.getKey()).getBytes());
o.close();
}
});
ctx.getFilters().add(new Filter() {
@Override
public void doFilter(HttpExchange httpExchange, Chain chain) throws IOException {
final Map<String, String> params = Maps.newHashMap();
final URI currentUri = httpExchange.getRequestURI();
final String query = currentUri.getQuery();
Iterable<String> keyValues = Splitter.on('&').split(query);
for (String kv : keyValues) {
final Iterable<String> skv = Splitter.on('=').split(kv);
params.put(FluentIterable.from(skv).first().get(), FluentIterable.from(skv).last().get());
}
httpExchange.setAttribute(AppMonitoredConstant.PARAMS_KEY, params);
chain.doFilter(httpExchange);
}
@Override
public String description() {
return "catch parameters";
}
});
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080");
} | 4 |
@SuppressWarnings("unchecked")
@Override
public int compareTo(Node o) {
int toReturn;
if (o == null) {
toReturn = -1;
} else if (c == null && o.c == null) {
toReturn = 0;
} else if (c == null) {
toReturn = 1;
} else if (o.c == null) {
toReturn = -1;
} else {
toReturn = ((Comparable<E>) c).compareTo(o.getElement());
}
return toReturn;
} | 5 |
private void read(DataInputStream in) throws IOException {
accessFlags = in.readUnsignedShort();
name = in.readUnsignedShort();
descriptor = in.readUnsignedShort();
int n = in.readUnsignedShort();
attribute = new LinkedList();
for (int i = 0; i < n; ++i)
attribute.add(AttributeInfo.read(constPool, in));
} | 1 |
public int findIndexOfFileDescriptor(String filename, boolean delete) throws Exception {
for(int i = 0; i < 3; i++){
if(oft.readDiskToBuffer(0, i) == -1)
throw new Exception("Block not assigned");
byte[] memory = oft.getBuffer(0);
for(int j = 0; j < memory.length; j = j + DIRECTORY_ENTRY_SIZE_IN_BYTES){
boolean foundMatch = true;
for(int k = 0; k < filename.length(); k++){
if(((char) memory[j + k]) != (byte) filename.charAt(k))
foundMatch = false;
}
if(foundMatch){
int returnValue = unpack(memory, j + SIZE_OF_INT_IN_BYTES);
if(delete) {
for(int m = 0; m < 8; m++){
memory[j + m] = -1;
oft.writeByteArray(0, 0, memory);
}
}
return returnValue; //Return the 4th element, or the file descriptor index
}
}
}
throw new Exception("Could not find file descriptor index for a file that SHOULD exist");
} | 8 |
private List<LogicCell> next() {
List<LogicCell> resultList = new ArrayList<>();
for (LogicCell cell : currentStep) {
cell.neigbour = 0;
nextStep.put(cell, cell);
}
for (LogicCell c : currentStep) {
addNeighbors(c);
}
for (LogicCell cell : currentStep) {
if (cell.neigbour == 2 || cell.neigbour == 3) {
resultList.add(cell);
}
}
for (LogicCell c : nextStep.keySet()) {
if (!resultList.contains(c)) {
if (c.neigbour == 3) {
resultList.add(c);
}
}
}
nextStep.clear();
currentStep = resultList;
generation++;
return resultList;
} | 8 |
public void render(Graphics g) {
for (int y = 0; y < slots[0].length; y++) {
slots[slots.length - 1][y].render(g);
}
if (Main.screen.game.invOpen())
for (int y = 0; y < slots[0].length; y++) {
for (int x = 0; x < slots.length; x++) {
if (x != slots.length - 1)
slots[x][y].render(g);
}
}
} | 5 |
public void SetEngine(CoreEngine engine)
{
if(this.m_engine != engine)
{
this.m_engine = engine;
for(GameComponent component : m_components)
component.AddToEngine(engine);
for(GameObject child : m_children)
child.SetEngine(engine);
}
} | 3 |
public String getUsername()
{
return new String(probeData).trim();
} | 0 |
public void setLevel(int lvl){
if(Engine.DEBUG_MODE)
this.stats[PROGRESSION] = lvl;
rebuildStats();
} | 1 |
String unqualReason() {
String reason = "";
if (!this.qualifyTest()) {
reason = "Unqualified Reasons:\n";
}
if (this.getMajorCrd() < 45) {
reason = reason + "Less than 45 Major Credits\n";
}
if (this.getUpperCrd() < 45) {
reason = reason + "Less than 45 Upper Level Credits\n";
}
if (this.getTotalCrd() < 120) {
reason = reason + "Less than 120 Total Credits\n";
}
if (this.getMajorGPA() < 2.0) {
reason = reason + "Major GPA is less than 2.0\n";
}
if (this.getTotalGPA() < 2.0) {
reason = reason + "Total GPA is less than 2.0\n";
}
return reason;
}//End unqualReason() | 6 |
public final void setBiomeID(byte biomeID){
if(currentChunk == null)return;
currentChunk.setBiomeID((int)getX(), (int)getZ(), biomeID);
} | 1 |
@Override
public void rightMultiply(IMatrix other) {
// TODO Auto-generated method stub
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
copy[i][j]=0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
copy[i][j]=copy[i][j] + this.get(k, i) * other.get(j, k);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
this.set(j, i, copy[i][j]);
}
}
} | 7 |
@Override
public void mousePressed(MouseEvent ev) {
if (ev.getButton() == MouseEvent.BUTTON1 && !ev.isPopupTrigger() && !(ev.isShiftDown() && ev.isControlDown())) {
if ((ev.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK || (ev.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK) {
ListElement temp = data.getElementAtLocation(ev.getY());
if (temp != null) {
if (!temp.isSelected()) {
start = ev.getY();
}
temp.setSelected(!temp.isSelected());
display.repaint();
}
} else if ((ev.getModifiers() & InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
selectRange(ev);
} else {
start = ev.getY();
clearSelections();
setSelectedAt(start, true);
display.repaint();
}
}
} | 9 |
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
} | 2 |
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(Demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Demo.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 Demo().setVisible(true);
}
});
} | 6 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(otherSide)
return true;
if(msg.target()==affected)
{
if(!(affected instanceof MOB))
return true;
if((msg.source()!=msg.target())
&&(msg.tool() instanceof Ability)
&&(msg.tool().ID().equalsIgnoreCase("Skill_Convert")))
{
msg.source().tell((MOB)msg.target(),null,null,L("<S-NAME> is not interested in hearing your religious beliefs."));
return false;
}
}
return true;
} | 7 |
public static void binarySearch(int[] arr, int data) {
if (arr.length < 1) {
System.out.println("null?");
return;
}
if (arr.length == 1) {
if (data == arr[0]) {
System.out.println("success.\t" + data + " -> arr[0]");
return;
} else {
System.out.println("not in.");
return;
}
}
int left = 0;
int right = arr.length;
while (left <= right) {
int mid = (left + right) >> 2;
if (data == arr[mid]) {
System.out.println("success.\r" + data + " -> arr[" + mid + "]");
return;
}
if (data < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
System.out.println("not in.");
return;
} | 6 |
private boolean checkCommand(){
try{
CommandScanner commandscanner = new CommandScanner(StockGameCommandType.values(), descriptor);
commandscanner.checkCommandSyntax(shellreader);
return true;
}catch(WrongCommandException e){
shellwriter.println("Invalid Command");
shellwriter.flush();
return false;
}catch (IOException e) {
shellwriter.println("IO Exception failure !");
shellwriter.flush();
return false;
}
} | 2 |
public double weightedStandardDeviation_of_ComplexRealParts() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
boolean hold2 = Stat.nEffOptionS;
if (nEffReset) {
if (nEffOptionI) {
Stat.nEffOptionS = true;
} else {
Stat.nEffOptionS = false;
}
}
boolean holdW = Stat.weightingOptionS;
if (weightingReset) {
if (weightingOptionI) {
Stat.weightingOptionS = true;
} else {
Stat.weightingOptionS = false;
}
}
double varr = Double.NaN;
if (!weightsSupplied) {
System.out.println("weightedStandardDeviation_as_Complex: no weights supplied - unweighted value returned");
varr = this.standardDeviation_of_ComplexRealParts();
} else {
double[] cc = this.array_as_real_part_of_Complex();
double[] wc = amWeights.array_as_real_part_of_Complex();
varr = Stat.standardDeviation(cc, wc);
}
Stat.nFactorOptionS = hold;
Stat.nEffOptionS = hold2;
Stat.weightingOptionS = holdW;
return varr;
} | 7 |
public Object getField(Reference ref, Object obj)
throws InterpreterException {
Field f;
try {
Class clazz = TypeSignature.getClass(ref.getClazz());
try {
f = clazz.getField(ref.getName());
} catch (NoSuchFieldException ex) {
f = clazz.getDeclaredField(ref.getName());
}
} catch (ClassNotFoundException ex) {
throw new InterpreterException(ref + ": Class not found");
} catch (NoSuchFieldException ex) {
throw new InterpreterException("Constructor " + ref + " not found");
} catch (SecurityException ex) {
throw new InterpreterException(ref + ": Security exception");
}
try {
return fromReflectType(ref.getType(), f.get(obj));
} catch (IllegalAccessException ex) {
throw new InterpreterException("Field " + ref + " not accessible");
}
} | 5 |
void calcGravityForce() {
double scalar;
double dist;
for(int i = 0; i < mass.length; i++) {
dist = distances[i].length();
if(Math.abs(dist) > 0.001) {
scalar = PhysConstantEnum.gravitationalConstant.value() * weight * mass[i] /
(dist * dist * dist);
distances[i].scalarMul((float)scalar);
gravityForce.add(distances[i]);
}
}
} | 2 |
private void drawArena()
{
drawArenaLine(Engine.NUM_COLUMNS);
for(int y=Engine.NUM_LINES; y>=0; y--)
{
Util.print('#');
for(int x=0; x<Engine.NUM_COLUMNS; x++)
{
if( e.getCobra().isPosTrue(x,y) ) // Cobra
Util.print('-');
else if( e.getTocaPermanente().isPosTrue(x,y) ) // Toca Permanente
Util.print('+');
else if( e.getTocaTemporaria().isPosTrue(x,y) ) // Toca Temporária
Util.print( e.getTocaTemporaria().getNumRatos() );
else if( e.getObstaculos().isPosTrue(x,y) ) // Obstaculos
Util.print('/');
else
Util.print(' ');
}
Util.print('#');
Util.println();
}
drawArenaLine(Engine.NUM_COLUMNS);
} | 6 |
@Override
public int getScore(String p) {
if(p.equals(player1)) {
return this.score1;
}
else if (p.equals(player2)) {
return this.score2;
}
return 0;
} | 2 |
public void setLeft(PExp node)
{
if(this._left_ != null)
{
this._left_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._left_ = node;
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Clause other = (Clause) obj;
if (literals == null) {
if (other.literals != null)
return false;
} else if (!literals.equals(other.literals))
return false;
return true;
} | 6 |
protected boolean DelAccount(String accountFile, String id) throws ClassNotFoundException, IOException{
ArrayList<Account> accs = new ArrayList<Account>();
Account tempacc = null;
ArrayList<Account> newaccs = new ArrayList<Account>();
try {
obji = new ObjectInputStream(new FileInputStream(accountFile));
objo = new ObjectOutputStream(new FileOutputStream(accountFile));
Object temp = null;
try {
temp = obji.readObject();
} catch (IOException e) {
System.err.println("File Read Failed! @ DataFileHandler in DelAccount");
}
if (temp instanceof AccountList) {
accs = ((AccountList) temp).getAccs();
}
for(int i = 0; i < accs.size(); i++){
tempacc = accs.get(i);
if (tempacc.getUsername() == id) {
}else{
newaccs.add(tempacc);
}
}
new File(accountFile).delete();
objo.writeObject(newaccs);
objo.flush();
objo.close();
obji.close();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
obji.close();
objo.close();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
obji.close();
objo.close();
return false;
}
} | 6 |
@Basic
@Column(name = "PCA_USUARIO")
public String getPcaUsuario() {
return pcaUsuario;
} | 0 |
private boolean checkPsd() throws IOException {
byte[] a = new byte[24];
if (read(a) != a.length) {
return false;
}
final byte[] PSD_MAGIC = {0x50, 0x53};
if (!equals(a, 0, PSD_MAGIC, 0, 2)) {
return false;
}
format = FORMAT_PSD;
width = getIntBigEndian(a, 16);
height = getIntBigEndian(a, 12);
int channels = getShortBigEndian(a, 10);
int depth = getShortBigEndian(a, 20);
bitsPerPixel = channels * depth;
return (width > 0 && height > 0 && bitsPerPixel > 0 && bitsPerPixel <= 64);
} | 5 |
private static double computeCrc(int[][] squares) {
//calculate CR
double numerator = 0; //start by computing the numerator
for (int row = 0; row < 4; row++) {
double pi = 0; //nb of dots in this row divided by total number of dots
for (int col = 0; col < 4; col++) {
pi += squares[row][col];
}
pi = pi / 4;
if (pi != 0) {
numerator += pi * log2(1/pi); //avoid division by zero; we assume that 0 * Log₂0 = 0
}
}
double cr = 1 - numerator / log2(4);
//calculate CC
numerator = 0;
for (int col = 0; col < 4; col++) {
double pi = 0; //nb of dots in this col divided by total number of dots
for(int row = 0; row < 4; row++) {
pi += squares[row][col];
}
pi = pi / 4;
if (pi != 0) {
numerator += pi * log2(1/pi); //avoid division by zero; we assume that 0 * Log₂0 = 0
}
}
double cc = 1 - numerator / log2(4);
return 1 - (( 1 - cr ) * ( 1 - cc)); //return CRC
} | 6 |
private void send(String message, boolean isText) {
if (message.equals(""))
return;
if (isText) {
message = client.getName() + ": " + message;
message = "/m/" + message;
}
client.send(message.getBytes());
txtMessage.setText("");
} | 2 |
private boolean freeSpace() {
for (int i = 0; i < components.getLength(); i++) {
if (dropArea.intersects(components.get(i))) {
JOptionPane.showMessageDialog(this, FREE_SPACE);
return false;
}
}
return true;
} | 2 |
public void fDistributionProbabilityPlot(int nu1, int nu2){
this.lastMethod = 15;
// Check for suffient data points
this.fDistributionNumberOfParameters = 0;
if(this.numberOfDataPoints<3)throw new IllegalArgumentException("There must be at least three data points - preferably considerably more");
// Calculate Exponential order statistic medians
this.fDistributionOrderMedians = Stat.fDistributionOrderStatisticMedians(nu1, nu2, this.numberOfDataPoints);
// Regression of the ordered data on the F-distribution order statistic medians
Regression reg = new Regression(this.fDistributionOrderMedians, this.sortedData);
reg.linear();
// Intercept and gradient of best fit straight line
this.fDistributionLine = reg.getBestEstimates();
// Estimated erors of the intercept and gradient of best fit straight line
this.fDistributionLineErrors = reg.getBestEstimatesErrors();
// Correlation coefficient
this.fDistributionCorrCoeff = reg.getSampleR();
// Initialize data arrays for plotting
double[][] data = PlotGraph.data(2,this.numberOfDataPoints);
// Assign data to plotting arrays
data[0] = this.fDistributionOrderMedians;
data[1] = this.sortedData;
data[2] = fDistributionOrderMedians;
for(int i=0; i<this.numberOfDataPoints; i++){
data[3][i] = this.fDistributionLine[0] + this.fDistributionLine[1]*fDistributionOrderMedians[i];
}
// Create instance of PlotGraph
PlotGraph pg = new PlotGraph(data);
int[] points = {4, 0};
pg.setPoint(points);
int[] lines = {0, 3};
pg.setLine(lines);
pg.setXaxisLegend("F-distribution Order Statistic Medians");
pg.setYaxisLegend("Ordered Data Values");
pg.setGraphTitle("F-distribution probability plot: gradient = " + Fmath.truncate(this.fDistributionLine[1], 4) + ", intercept = " + Fmath.truncate(this.fDistributionLine[0], 4) + ", R = " + Fmath.truncate(this.fDistributionCorrCoeff, 4));
pg.setGraphTitle2(" nu1 = " + nu1 + ", nu2 = " + nu2);
// Plot
pg.plot();
this.fDistributionDone = true;
this.probPlotDone = true;
} | 2 |
public int getItemIcon(ItemStack par1ItemStack, int par2)
{
int var3 = super.getItemIcon(par1ItemStack, par2);
if (par1ItemStack.itemID == Item.fishingRod.shiftedIndex && this.fishEntity != null)
{
var3 = par1ItemStack.getIconIndex() + 16;
}
else
{
if (par1ItemStack.getItem().func_46058_c())
{
return par1ItemStack.getItem().func_46057_a(par1ItemStack.getItemDamage(), par2);
}
if (this.itemInUse != null && par1ItemStack.itemID == Item.bow.shiftedIndex)
{
int var4 = par1ItemStack.getMaxItemUseDuration() - this.itemInUseCount;
if (var4 >= 18)
{
return 133;
}
if (var4 > 13)
{
return 117;
}
if (var4 > 0)
{
return 101;
}
}
var3 = par1ItemStack.getItem().getIconIndex(par1ItemStack, par2, this, itemInUse, itemInUseCount);
}
return var3;
} | 8 |
public static void main(String[] args) {
Random rnd = new Random();
System.out.println("------------------------------------");
System.out.println("Demo class java.util.Random");
System.out.println("------------------------------------");
// rnd.nextInt(MAX) +1 = generer un nombre aleatoire entre 1 et MAX.
// Pourquoi +1 ? Parce que rnd.nextInt(MAX) -> genere un nb entre (0 et MAX -1)
System.out.printf("Nombre au hasard entre 1 et 20........: %d\n", rnd.nextInt(20) + 1);
System.out.printf("Nombre au hasard entre 1 et 1000......: %d\n", rnd.nextInt(1000) + 1);
// Code Ascii: http://www.ascii-code.com/
// 26 lettres alphabet [A-Z] (code Ascii 65 -> 90)
// Un nombre aleatoire entre (65, 90) = un nb aleatoire entre (0, 26) +65
int codeAsciiMaj = rnd.nextInt(26) + 65;
char charLettreMaj = (char) codeAsciiMaj; // convert int -> char
System.out.printf("Lettre Majuscule aleatoire (65 -> 90) : %s (Code Ascii: %d)\n", charLettreMaj, codeAsciiMaj);
// 26 lettres alphabet [a-z] (code Ascii 97 -> 122)
int codeAsciiMinus = rnd.nextInt(26) + 97;
char charLettreMinus = (char) codeAsciiMinus; // convert int -> char
System.out.printf("Lettre minuscule aleatoire (97 -> 122): %s (Code Ascii: %d)\n", charLettreMinus, codeAsciiMinus);
// 14 symboles simple (code Ascii 33 -> 47)
int codeAsciiSymbSimple = rnd.nextInt(14) + 33;
System.out.printf("Symbol simple #1 aleatoire (33 -> 47).: %s (Code Ascii: %d)\n", (char) codeAsciiSymbSimple, codeAsciiSymbSimple);
// 6 symboles simple (code Ascii 91 -> 96)
int codeAsciiSymbSimple2 = rnd.nextInt(6) + 91;
System.out.printf("Symbol simple #2 aleatoire (91 -> 96).: %s (Code Ascii: %d)\n", (char) codeAsciiSymbSimple2, codeAsciiSymbSimple2);
/*--------------------------------------------------------------------
Un symbol etendu = code 33 -> 255 (EXCLURE: chiffre, lettre Majuscule, minuscule)
--------------------------------------------------------------------*/
int codeAsciiSymbol = 0;
while (true) {
// Les caracteres ne sont affichables qu'a partir du code asci 33 -> 255
// Pour obtenir un nb aleatoire entre (33, 255) on fait (0, 223) +33
codeAsciiSymbol = rnd.nextInt(223) + 33;
// On accepte code Ascii obtenu QUE si le code N'EST PAS
// [0-9] = Code Ascii 48 -> 57
// [A-Z] = Code Ascii 65 -> 90
// [a-z] = Code Ascii 97 -> 122
// Condition 1: n'est pas [0-9]
if (!(codeAsciiSymbol >= 48 && codeAsciiSymbol <= 57)) {
// Condition 2: n'est pas [A-Z]
if (!(codeAsciiSymbol >= 65 && codeAsciiSymbol <= 90)) {
// Condition 3: n'est pas [a-z]
if (!(codeAsciiSymbol >= 97 && codeAsciiSymbol <= 122)) {
// maintenant on est sur que c'est un symbole
break; // quitter boucle WHILE
}
}
}
/*
Le meme test plus "pro" mais plus difficile a comprendre
if ( ! (codeAsciiSymbol >= 48 && codeAsciiSymbol <= 57) // 0-9
&& ! (codeAsciiSymbol >= 65 && codeAsciiSymbol <= 90) // A-Z
&& ! (codeAsciiSymbol >= 97 && codeAsciiSymbol <= 122) // a-z
) {
break; // quitter boucle WHILE
}
*/
}
char charSymbol = (char) codeAsciiSymbol; // convert int -> char
System.out.printf("Symbol etendu aleatoire...............: %s (Code Ascii: %d)\n", charSymbol, codeAsciiSymbol);
} | 7 |
public boolean newUser(User usertemp){
if(logUser(usertemp) == true)
return false;
return userList.add(usertemp);
} | 1 |
protected void log(String text, LogLevel logLevel) {
if (verbosity == LogLevel.ALL || logLevel == LogLevel.ERROR)
super.log(text);
else {
if (logLevel == verbosity)
super.log(text);
}
} | 3 |
public synchronized boolean replaceAllPossibleFailingParts(WorkSheet ws) {
if (ws.partsToReplace == null) {
// nothing to replace
ws.status = WorkSheet.Status.FINISHED;
return true;
}
for (Iterator<Part> it = ws.partsToReplace.iterator(); it.hasNext();) {
Part partToReplace = it.next();
PartType type = partToReplace.type;
Integer inStockQuantity = stock.get(type);
if (inStockQuantity != null && inStockQuantity > 0) {
inStockQuantity = inStockQuantity - 1;
stock.put(type, inStockQuantity);
if (ws.replacedParts == null) {
ws.replacedParts = new ArrayList<>();
}
ws.replacedParts.add(new ReplacedPart(type, partToReplace.name));
it.remove();
} else {
addOrderForMissingPart(type);
ws.status = WorkSheet.Status.WAITING_FOR_PARTS;
}
}
if (ws.partsToReplace.isEmpty()) {
ws.status = WorkSheet.Status.FINISHED;
return true;
} else {
return false;
}
} | 6 |
public static List<String> getAllLines(File file) throws IOException
{
List<String> strings = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e1) {}
String line;
try {
while ((line = reader.readLine()) != null) {
strings.add(line);
}
} catch (IOException e) {}
return strings;
} | 3 |
private void killEnemy(EnemyShip enemy) {
remaining--;
if (enemy.wasKilledByPlayer()) {
score += enemy.getScoreValue();
killedInLevel++;
ScorePopup popup = new ScorePopup(screen, enemy);
popup.setWorld(this);
if (level.isLastWave() && killedInLevel == spawnedInLevel &&
spawnedInWave == wave.getNumEnemies())
spawnPickup(enemy);
}
ships.remove(enemy);
} | 4 |
public static void export(ArrayList<HashSet<Integer>> clusterList) {
try {
File csv = new File("D:\\File\\Dropbox\\Project\\minHashedAuthors.csv");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true))) {
bw.newLine();
bw.write("aid" + "," + "clusterid");
for (int i = 0; i < clusterList.size(); i++) {
for (int j : clusterList.get(i)) {
bw.newLine();
bw.write((i + 1) + "," + j);
}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} | 4 |
public void removeEmployee(int id){
for(int i = 0; i < numEmployees; i ++){
if(employees[i].getId() == id){
for(int j = i; j < numEmployees; j ++){
employees[j] = employees[j+1];
}
numEmployees--;
}
}
} | 3 |
public void addDataPoints(String group, DataPoints dp)
{
if (dp==null || dp.isEmpty()) return;
group = group.toLowerCase();
if (!this.m_PointsSet.containsKey(group))
{
this.m_PointsSet.put(group, dp);
} else
{
for (DataPoint p: dp)
this.m_PointsSet.get(group).addPoint(p.getX(), p.getY());
}
// calculate min max values
calculateMinMax();
} | 4 |
public boolean canDo(char symbol) {
if (symbol == '{') return true;
return false;
} | 1 |
public double getDouble(Object key) {
Number n = get(key);
if (n == null) {
return (double) 0;
}
return n.doubleValue();
} | 1 |
public boolean isFresh() {
return (this.lastAnnounce != null &&
(this.lastAnnounce.getTime() + FRESH_TIME_SECONDS * 1000 >
new Date().getTime()));
} | 1 |
public String login(HttpServletRequest req, HttpServletResponse resp) {
try {
String queryString = req.getQueryString();
String name = queryString.split("&")[0];
String password = queryString.split("&")[1];
name = name.substring(10, name.length());
password = password.substring(14, password.length());
if (name.compareTo("") != 0 && password.compareTo("") != 0) {
name = "\"" + name + "\"";
UserDao userdao = new UserDao();
User newuser = userdao.getUserByEmail(name);
if (newuser.getPassword().compareTo(password) == 0) {
req.setAttribute("my-data2","Login Success");
} else {
req.setAttribute("my-data2","Login Failed");
}
} else {
req.setAttribute("my-data2","User Error");
}
} catch (Exception e) {
e.printStackTrace();
}
return "/logininfo.jsp";
} | 4 |
@Override
public void update() {
if (doc.isShowingAttributes()) {
AttributeContainer node = doc.tree.getEditingNode();
model.keys.clear();
model.values.clear();
model.readOnly.clear();
clearSelection();
Iterator it = node.getAttributeKeys();
if (it != null) {
while (it.hasNext()) {
String key = (String) it.next();
Object value = node.getAttribute(key);
boolean readOnly = node.isReadOnly(key);
model.keys.add(key);
model.values.add(value);
model.readOnly.add(new Boolean(readOnly));
}
}
if (isEditing()) {
getCellEditor().cancelCellEditing();
}
model.fireTableDataChanged();
}
} | 4 |
public void move(int xa, int ya) {
if(xa > 0) dir = 1;
if(xa < 0) dir = 3;
if(ya > 0) dir = 2;
if(ya < 0) dir = 0;
if(!collision()) {
x += xa;
y += ya;
}
} | 5 |
@Override
public void mouseReleased(MouseEvent me) {
int x = me.getX();
int y = me.getY();
if (this.drawable != null) {
// 最初の位置から変化があった場合のみmoveコマンドを実行する.
if (!((x == this.startX) && (y == this.startY))) {
// undoができるようにmoveコマンドを生成して実行する.
// undoした時にはドラッグの開始位置に戻すために,一旦,最初の位置まで戻して,moveコマンドを実行する.
this.drawable.move(- (this.lastX - this.startX), - (this.lastY - this.startY));
Command command = new CommandMove(this.canvas, this.drawable,
x - this.startX, y - startY);
this.canvas.execute(command);
}
}
// ドラッグは終了.
this.drawable = null;
this.updateCursorAt(x, y);
// ポップアップメニューを出すべきかチェックする.
if (me.isPopupTrigger()) {
this.handlePopupTrigger(me);
}
} | 4 |
public void actionPerformed(ActionEvent e){
String[] sa=new String[4];
if(e.getSource()==jbanalizar||e.getSource()==jmi1){
String cadaux=pa.getJtatexto().getText();
alva.analizar(cadaux);
if(tam>=0){
for(int i=0;i<tam;i++){
pa.getJttabla().setValueAt("",i,0);
pa.getJttabla().setValueAt("",i,1);
pa.getJttabla().setValueAt("",i,2);
pa.getJttabla().setValueAt("",i,3);
}
}
for(int i=0;i<alva.getAlstrings().size();i++){
sa=alva.getAlstrings().get(i);
pa.getJttabla().setValueAt(sa[0],i,0);
pa.getJttabla().setValueAt(sa[1],i,1);
pa.getJttabla().setValueAt(sa[2],i,2);
pa.getJttabla().setValueAt(sa[3],i,3);
}
tam=alva.getAlstrings().size();
alva=new AnalizadorLexico();
}
if(e.getSource()==jmi2)
System.exit(0);
if(e.getSource()==jmi3){
JDialog dlgHelp = new DialogAyuda( this,
"Tabla transicion LEN", "ttlen.txt" );
dlgHelp.setVisible( true );
}
if(e.getSource()==jmi4){
JDialog dlgAbout = new DialogAcercaDe(this);
dlgAbout.setVisible(true);
}
} | 8 |
public static void main(String[] args) {
// Объявим конcтанту для размера массива
int SIZE = 5;
// Создаем массив, в котором есть другие массивы
// Причем массивы не создаются - они равны NULL
char[][] graph = new char[SIZE][];
// Цикл по элементам массива - все они пока равны NULL
for (int i = 0; i < graph.length; i++) {
// Проверяем равенство NULL - это правда
System.out.println(graph[i] == null);
}
for (int i = 0; i < graph.length; i++) {
// Создаем случайное число от 25 до 75 для указания размера массива
int size = (int)(Math.round(Math.random()*50) + 25);
// Теперь создаем массив нужного размера
graph[i] = new char[size];
}
// Цикл по элементам массива - все они теперь проинициализированы
for (int i = 0; i < graph.length; i++) {
// Выводим размеры массивов, которые мы создали
System.out.println(graph[i].length);
}
} | 3 |
public void draw(Graphics g, Display d, int bottomPixelX, int bottomPixelY) {
if(filter != null){
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image, filter, bottomPixelX-image.getWidth(null)/2, bottomPixelY-image.getHeight(null));
} else {
Image i = getImage(d.getRotation());
if(i != null){
g.drawImage(i, bottomPixelX-image.getWidth(null)/2, bottomPixelY-image.getHeight(null), null);
}
}
if (world.showHealth() && isAttackable() && drawHealth) { // Attackable Structures have health bars
int tall = 10;
int hHeight = 3;
int hWidth = 16;
int barWidth = 10;
g.setColor(Color.red);
g.fillRect(bottomPixelX - barWidth , bottomPixelY - tall - TILE_HEIGHT, hWidth + barWidth, hHeight);
g.setColor(Color.green);
g.fillRect(bottomPixelX - barWidth , bottomPixelY - tall - TILE_HEIGHT, (int)((hWidth + barWidth) * currentHealth / (float)maxHealth), hHeight);
}
} | 5 |
public static boolean isRobotSafe(URL url) {
String strHost = url.getHost();
// form URL of the robots.txt file
String strRobot = "http://" + strHost + "/robots.txt";
URL urlRobot;
try {
urlRobot = new URL(strRobot);
} catch (MalformedURLException e) {
// something weird is happening, so don't trust it
return false;
}
String strCommands;
try {
InputStream urlRobotStream = urlRobot.openStream();
// read in entire file
byte b[] = new byte[1000];
int numRead = urlRobotStream.read(b);
strCommands = new String(b, 0, numRead);
while (numRead != -1) {
numRead = urlRobotStream.read(b);
if (numRead != -1) {
String newCommands = new String(b, 0, numRead);
strCommands += newCommands;
}
}
urlRobotStream.close();
} catch (IOException e) {
// if there is no robots.txt file, it is OK to search
return true;
}
String strURL = url.getFile();
int index = 0;
while ((index = strCommands.indexOf(DISALLOW, index)) != -1) {
index += DISALLOW.length();
String strPath = strCommands.substring(index);
StringTokenizer st = new StringTokenizer(strPath);
if (!st.hasMoreTokens())
break;
String strBadPath = st.nextToken();
// if the URL starts with a disallowed path, it is not safe
if (strURL.indexOf(strBadPath) == 0)
return false;
}
return true;
} | 7 |
public ArrayList<E>floyd (E saleDe, E vaA){
int[][] path=hacerMatrizPath();
for(int i=0; i<cantNodos; i++){
for(int j=0; j<cantNodos; j++){
System.out.print(path[j][i]+" ");
}
System.out.println("\n");
}
System.out.println("\n");
int[][] adj=hacerMatrizAdj();
int[][] resultadoPath;
int[][] resultadoAdj;
ArrayList<int[][]> lista=shortestpath(adj, path);
resultadoAdj=lista.get(0);
resultadoPath=lista.get(1);
for(int i=0; i<cantNodos; i++){
for(int j=0; j<cantNodos; j++){
System.out.print(resultadoPath[j][i]+" ");
}
System.out.println("\n");
}
int sale=tabla.get(saleDe);
int llega=tabla.get(vaA);
ArrayList<Integer> resInt=new ArrayList<Integer>();
resInt.add(sale);
while(resultadoPath[sale][llega]!=0){
if(resultadoPath[sale][llega]==-1){
return null;
}
int nuevoSale=resultadoPath[sale][llega];
sale=nuevoSale;
resInt.add(nuevoSale);
}
resInt.add(llega);
ArrayList<E> listaFinal=new ArrayList<E>();
for(int i=0;i<resInt.size();i++){
listaFinal.add(tablaInv.get(resInt.get(i)));
}
return listaFinal;
} | 7 |
public Object[] formatoTabela(Pesquisa pesquisa)
{
return new Object[] { pesquisa.getId(), pesquisa.getTitulo(),
pesquisa.getOrientador(),
pesquisa.getPesquisadorResponsavel(),
pesquisa.getColaboradores(), pesquisa.getAnoSubmissao(),
pesquisa.getTempoDuracao(), pesquisa.getTipo(),
pesquisa.getQualificacao(), pesquisa.getImpactoPesquisa(),
(pesquisa.isGerouPatente() == true ? "SIM" : "NÃO"),
pesquisa.getStatus(), pesquisa.getResultado(),
pesquisa.getInstituicaoSubmissao(),
pesquisa.getFonteFinanciamento(),
pesquisa.getAreaConhecimentoCNPq(),
pesquisa.getPalavrasChave(),
pesquisa.getInstituicoesCooperadoras(),
pesquisa.getLocais(),
pesquisa.getResumo() };
} | 1 |
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.getNext() == null || m == n) {
return head;
}
//create a preHead to comtrol the head node
ListNode preHead = new ListNode(0);
preHead.setNext(head);
head = preHead;
//before m, one node links by one
ListNode n1 = head;
int k = m - 1;
while (k > 0) {
n1 = n1.getNext();
k--;
}
//between m and n, reverse
preHead = n1;
n1 = n1.getNext();
k = n - m;
/**
* preHead -> 3,4,5,6 ->7
* preHead -> 4,3,5,6 ->7
* preHead -> 5,4,3,6 ->7
* preHead -> 6,5,4,3 ->7
*/
while (n1.getNext() != null && k > 0) {
//move the next "one"
ListNode temp = n1.getNext();
//link to the next.next
n1.setNext(temp.getNext());
//link to the head of the reverse
temp.setNext(preHead.getNext());
//link to the "one"
preHead.setNext(temp);
k--;
}
return head.getNext();
} | 6 |
private void analyseEndian(String line) throws AssemblerException {
if (line.trim().length() == 0)
return;
if(foundEndian)
throw new AssemblerException("Endian error: Endian already specified.");
foundEndian = true;
line = line.trim();
line = line.toLowerCase();
if (line.equals("big"))
data.setEndian("big");
else if (line.equals("little"))
data.setEndian("little");
else
throw new AssemblerException(
"Endian error: Endian not recognised, \"big\" or \"little\" expected.");
} | 4 |
protected static Ptg calcLog( Ptg[] operands ) throws CalculationException
{
if( operands.length < 1 )
{
return PtgCalculator.getNAError();
}
double[] dd = PtgCalculator.getDoubleValueArray( operands );
if( dd == null )
{
return new PtgErr( PtgErr.ERROR_NA );//20090130 KSC: propagate error
}
if( dd.length > 2 )
{
return PtgCalculator.getError();
}
double num1;
double num2;
if( dd.length == 1 )
{
num1 = dd[0];
num2 = 10;
}
else
{
num1 = dd[0];
num2 = dd[1];
}
double res = Math.log( num1 ) / Math.log( num2 );
PtgNumber ptnum = new PtgNumber( res );
return ptnum;
} | 4 |
private void initialize(Frame header)
throws DecoderException
{
// REVIEW: allow customizable scale factor
float scalefactor = 32700.0f;
int mode = header.mode();
int channels = mode==Frame.SINGLE_CHANNEL ? 1 : 2;
// set up output buffer if not set up by client.
if (output==null)
output = new SampleBuffer(header.frequency(), channels);
float[] factors = equalizer.getBandFactors();
filter1 = new SynthesisFilter(0, scalefactor, factors);
// REVIEW: allow mono output for stereo
if (channels==2)
filter2 = new SynthesisFilter(1, scalefactor, factors);
outputChannels = channels;
outputFrequency = header.frequency();
initialized = true;
} | 3 |
@Override
public void removeProductType(ProductType productType) {
tx.begin();
for (SubProcess sp : productType.getSubProcesses()) {
for (Stock s : sp.getStocks()) {
sp.removeStock(s);
}
em.merge(sp);
em.remove(sp);
}
em.remove(productType);
tx.commit();
} | 2 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
if (Double.compare(point.x, x) != 0) return false;
if (Double.compare(point.y, y) != 0) return false;
return true;
} | 5 |
@Override
public void run() {
this.Run = true;
while(Run)
{
try {
Thread.sleep(this.Intervall);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.Panel.repaint();
this.Panel.Update();
}
} | 2 |
public static void main(String[] args)
{
if(args == null || args.length < 1)
{
System.err.println
("usage: java org.mcuosmipcuter.dog4sql.text.RandomWordFactory <length> [allowed] [disallowed]");
System.exit(1);
}
String rw = "";
try
{
if(args.length == 1)
rw = getRandomWord(Integer.parseInt(args[0]));
if(args.length == 2)
rw = getRandomWord(Integer.parseInt(args[0]), args[1]);
if(args.length == 3)
rw = getRandomWord(Integer.parseInt(args[0]), args[1], args[2]);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("random word: " + rw);
} | 6 |
private int chkMycrds(){
int myrnk=0;
if(crd1!=null&&crd2!=null){
myrnk+=crd1.getRankID();
myrnk+=crd2.getRankID();
if(crd1.getRankID()==crd2.getRankID()){
myrnk+=40;
}else if(crd1.getRankID()-1==crd2.getRankID()||crd1.getRankID()+1==crd2.getRankID()){
myrnk+=20;
}
if(crd1.getSuitID()==crd2.getSuitID()){
myrnk+=20;
}if(crd1.getRankID()==14||crd2.getRankID()==14){
myrnk+=30;
}
}
// window.getLblBlind().setText("value "+myrnk);
return myrnk;
} | 8 |
public void body()
{
// wait for a little while
// This to give a time for GridResource entities to register their
// services to GIS (GridInformationService) entity.
super.gridSimHold(GridSim.PAUSE);
LinkedList resList = super.getGridResourceList();
// initialises all the containers
int totalResource = resList.size();
int resourceID[] = new int[totalResource];
String resourceName[] = new String[totalResource];
// a loop to get all the resources available
int i = 0;
for (i = 0; i < totalResource; i++)
{
// Resource list contains list of resource IDs
resourceID[i] = ( (Integer) resList.get(i) ).intValue();
// get their names as well
resourceName[i] = GridSim.getEntityName( resourceID[i] );
}
////////////////////////////////////////////////
// SUBMIT Gridlets
// determines which GridResource to send to
int index = myId_ % totalResource;
if (index >= totalResource) {
index = 0;
}
// sends all the Gridlets
Gridlet gl = null;
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) list_.get(i);
write(name_ + ": Sending Gridlet #" + i + " to " +
resourceName[index]);
// send without an ack
super.gridletSubmit(gl, resourceID[index], 0, false, ToS_);
}
////////////////////////////////////////////////////////
// RECEIVES Gridlets back
// hold for few period
super.gridSimHold(GridSim.PAUSE);
// receives the gridlet back
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) super.receiveEventObject(); // gets the Gridlet
receiveList_.add(gl); // add into the received list
write(name_ + ": Receiving Gridlet #" +
gl.getGridletID() + " at time = " + GridSim.clock() );
}
////////////////////////////////////////////////////////
// ping functionality
InfoPacket pkt = null;
int size = Link.DEFAULT_MTU * 100;
// hold for few period
super.gridSimHold(GridSim.PAUSE);
// There are 2 ways to ping an entity:
// a. non-blocking call, i.e.
//super.ping(resourceID[index], size, 0, ToS_); // (i) ping
//super.gridSimHold(10); // (ii) do something else
//pkt = super.getPingResult(); // (iii) get the result back
// b. blocking call, i.e. ping and wait for a result
pkt = super.pingBlockingCall(resourceID[index], size, 0, ToS_);
// print the result
write("\n-------- " + name_ + " ----------------");
write(pkt.toString());
write("-------- " + name_ + " ----------------\n");
////////////////////////////////////////////////////////
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// don't forget to close the file
if (report_ != null) {
report_.finalWrite();
}
write(this.name_ + ": sending and receiving of Gridlets" +
" complete at " + GridSim.clock() );
} | 5 |
public static Population evolvePopulation(Population pop)
{
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism)
{
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism)
{
elitismOffset = 1;
} else
{
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++)
{
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++)
{
mutate(newPopulation.getIndividual(i));
}
return newPopulation;
} | 4 |
public static int max_min_number(int[][] grid) {
int path[][] = new int[grid.length][grid[0].length];
int col, row;
row = grid.length;
col = grid[0].length;
path[0][0] = grid[0][0];
for (int i = 1; i < row; i++)
path[i][0] = Math.min(path[i-1][0],grid[i][0]);
for (int j = 1; j < col; j++)
path[0][j] = Math.min(path[0][j-1],grid[0][j]);
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
path[i][j] = Math.min( Math.max(path[i-1][j], path[i][j-1]), grid[i][j]);
}
}
return path[row-1][col-1];
} | 4 |
public Object readConst(final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
case ClassWriter.CLASS:
return Type.getObjectType(readUTF8(index, buf));
// case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
} | 5 |
public void makePowerups()
{
Random rand = new Random();
/*Clear the powerup vector*/
powerups.clear();
/*Go through every brick and check which bricks should contain powerups*/
for(Brick brick : bricks)
{
/*The brick should contain a powerup*/
if(rand.nextFloat() <= POWERUP_PROB)
{
/*Add a random powerup*/
int powerupType = rand.nextInt(POWERUP_TYPES);
switch(powerupType)
{
case 0://Paddle size
powerups.add(new PaddleLengthPowerup(brick.x, brick.y, brick));
break;
case 1://Floor
powerups.add(new FloorPowerup(brick.x, brick.y, brick));
break;
case 2://Ball
powerups.add(new BallPowerup(brick.x, brick.y, brick, this));
break;
case 3://Shooter
powerups.add(new ShooterPowerup(brick.x, brick.y, brick));
break;
default:
System.err.println("Breakout: Unknown powerup type.");
System.exit(1);
}
}
}
} | 6 |
protected void readAttributes(XMLStreamReader in)
throws XMLStreamException {
String newTypeId = in.getAttributeValue(null, "unit");
if (newTypeId == null) {
newUnitType = null;
} else {
newUnitType = getSpecification().getType(newTypeId, UnitType.class);
turnsToLearn = getAttribute(in, "turnsToLearn", UNDEFINED);
if (turnsToLearn > 0) {
changeTypes.put(ChangeType.EDUCATION, 100);
}
// @compat 0.9.x
for (ChangeType type : ChangeType.values()) {
String value = in.getAttributeValue(null, tags.get(type));
if (value != null) {
if(value.equalsIgnoreCase("false")) {
changeTypes.put(type, 0);
} else if (value.equalsIgnoreCase("true")) {
changeTypes.put(type, 100);
} else {
changeTypes.put(type, Math.max(0,
Math.min(100, new Integer(value))));
}
}
}
// end compatibility code
}
} | 6 |
private static HashMap<String, List<Integer>> getTaxaMap( int level) throws Exception
{
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
BufferedReader reader = new BufferedReader(new FileReader(new File(
ConfigReader.getGoranOct2015Dir() + File.separator +
"PC_0016 Metagenomics Study Report" + File.separator + "PC_0016 Data"
+ File.separator + "PC_0016 Seq_data.txt")));
reader.readLine(); reader.readLine();
for(String s= reader.readLine(); s != null; s = reader.readLine())
{
String[] splits = s.split("\t");
String key = null;
if( level == 0 )
{
key = splits[0];
if( map.containsKey(key))
throw new Exception("No");
}
else
{
String[] rdpNames = splits[2].trim().replaceAll("\"", "").split(";");
if( rdpNames.length != 6)
throw new Exception("No");
key = rdpNames[level];
key = key.substring(0, key.indexOf("("));
}
List<Integer> list = map.get(key);
if( list == null)
{
list = new ArrayList<Integer>();
for( int x=3; x < splits.length; x++)
list.add(0);
map.put(key, list);
}
for( int x=3; x < splits.length; x++)
list.set(x-3, list.get(x-3) + Integer.parseInt(splits[x]));
}
reader.close();
return map;
} | 7 |
@Override
public void setAllMap(Map<? extends K, ? extends Collection<? extends V>> map) {
for (Map.Entry<? extends K, ? extends Collection<? extends V>> en : map.entrySet()) {
setAll(en.getKey(), en.getValue());
}
} | 7 |
final void close() throws IOException {
if (!closed) {
if (fieldsStream != null) {
fieldsStream.close();
}
if (isOriginal) {
if (cloneableFieldsStream != null) {
cloneableFieldsStream.close();
}
if (cloneableIndexStream != null) {
cloneableIndexStream.close();
}
}
if (indexStream != null) {
indexStream.close();
}
fieldsStreamTL.close();
closed = true;
}
} | 6 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.