text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void setName(String name) {
this.name = name;
} | 0 |
public void loadProperties(String xmlDataFile, String xmlSchemaFile)
throws InvalidXMLFileFormatException
{
String dataPath = getProperty(DATA_PATH_PROPERTY);
// ADD THE DATA PATH
xmlDataFile = dataPath + xmlDataFile;
xmlSchemaFile = dataPath + xmlSchemaFile;
// FIRST LOAD THE FILE
Document doc = xmlUtil.loadXMLDocument(xmlDataFile, xmlSchemaFile);
// NOW LOAD ALL THE PROPERTIES
Node propertyListNode = xmlUtil.getNodeWithName(doc, PROPERTY_LIST_ELEMENT);
ArrayList<Node> propNodes = xmlUtil.getChildNodesWithName(propertyListNode, PROPERTY_ELEMENT);
for(Node n : propNodes)
{
NamedNodeMap attributes = n.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Node att = attributes.getNamedItem(NAME_ATT);
String attName = attributes.getNamedItem(NAME_ATT).getTextContent();
String attValue = attributes.getNamedItem(VALUE_ATT).getTextContent();
properties.put(attName, attValue);
}
}
// AND THE PROPERTIES FROM OPTION LISTS
Node propertyOptionsListNode = xmlUtil.getNodeWithName(doc, PROPERTY_OPTIONS_LIST_ELEMENT);
if (propertyOptionsListNode != null)
{
ArrayList<Node> propertyOptionsNodes = xmlUtil.getChildNodesWithName(propertyOptionsListNode, PROPERTY_OPTIONS_ELEMENT);
for (Node n : propertyOptionsNodes)
{
NamedNodeMap attributes = n.getAttributes();
String name = attributes.getNamedItem(NAME_ATT).getNodeValue();
ArrayList<String> options = new ArrayList();
propertyOptionsLists.put(name, options);
ArrayList<Node> optionsNodes = xmlUtil.getChildNodesWithName(n, OPTION_ELEMENT);
for (Node oNode : optionsNodes)
{
String option = oNode.getTextContent();
options.add(option);
}
}
}
} | 5 |
void sort(int[] a) throws Exception {
for (int i = a.length; --i>=0; )
for (int j = 0; j<i; j++) {
if (stopRequested) {
return;
}
if (a[j] > a[j+1]) {
int T = a[j];
a[j] = a[j+1];
a[j+1] = T;
}
pause(i,j);
}
} | 9 |
public int getSelectionMode() {
return this.selectionMode;
} | 0 |
public boolean hasEntryPoint(Cell cell, int entryPointId){
String result = "";
char c = get(cell);
if(entryPointId == 1) {
return StringUtils.isOneOf(c, entryPoints1);
} else if(entryPointId == 2) {
return StringUtils.isOneOf(c, entryPoints2);
} else if(entryPointId == 3) {
return StringUtils.isOneOf(c, entryPoints3);
} else if(entryPointId == 4) {
return StringUtils.isOneOf(c, entryPoints4);
} else if(entryPointId == 5) {
return StringUtils.isOneOf(c, entryPoints5);
} else if(entryPointId == 6) {
return StringUtils.isOneOf(c, entryPoints6);
} else if(entryPointId == 7) {
return StringUtils.isOneOf(c, entryPoints7);
} else if(entryPointId == 8) {
return StringUtils.isOneOf(c, entryPoints8);
}
return false;
} | 8 |
public static void main(String[] args)
{
List v = (List)factory(new Vector());
System.out.println(v.getClass().getName());
v.add("new");
System.out.println("----------------------------");
v.add("old");
System.out.println(v);
v.remove(0);
System.out.println(v);
} | 0 |
public ArrayList<Patch> getNeighbors(){
ArrayList<Patch> neighbors = new ArrayList();
if (!topEdge()){
neighbors.add(getN());
if (!leftEdge()){
neighbors.add(getNW());
}
if (!rightEdge()){
neighbors.add(getNE());
}
}
if (!bottomEdge()){
neighbors.add(getS());
if (!leftEdge()){
neighbors.add(getSW());
}
if (!rightEdge()){
neighbors.add(getSE());
}
}
if (!leftEdge()){
neighbors.add(getW());
}
if (!rightEdge()){
neighbors.add(getE());
}
return neighbors;
} | 8 |
private boolean checkNorthEdge(EdgeLocation normEdgeLocation, ArrayList<Road> roads, int playerIndex) {
HexLocation thisHexLoc = normEdgeLocation.getHexLoc();
HexLocation NEHexLoc = normEdgeLocation.getHexLoc().getNeighborLoc(EdgeDirection.NorthEast);
HexLocation NWHexLoc = normEdgeLocation.getHexLoc().getNeighborLoc(EdgeDirection.NorthWest);
for (Road road : roads) {
if (road.getOwnerIndex() == playerIndex && road.getLocation().getNormalizedLocation().equals(new EdgeLocation(thisHexLoc, EdgeDirection.NorthEast))) {
return true;
}
else if (road.getOwnerIndex() == playerIndex && road.getLocation().getNormalizedLocation().equals(new EdgeLocation(thisHexLoc, EdgeDirection.NorthWest))) {
return true;
}
else if (road.getOwnerIndex() == playerIndex && road.getLocation().getNormalizedLocation().equals(new EdgeLocation(NEHexLoc, EdgeDirection.NorthWest))) {
return true;
}
else if (road.getOwnerIndex() == playerIndex && road.getLocation().getNormalizedLocation().equals(new EdgeLocation(NWHexLoc, EdgeDirection.NorthEast))) {
return true;
}
}
return false;
} | 9 |
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid==null){
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int [][]result = new int[m][n];
result [0][0] = (obstacleGrid[0][0]==0?1:0);
for (int i = 1; i<m;i++){
if (obstacleGrid[i][0]==0){
result [i][0] = result [i-1][0];
}
else {
result [i][0] = 0;
}
}
for (int i = 1; i<n;i++){
if (obstacleGrid[0][i]==0){
result [0][i] = result [0][i-1];
}
else {
result [0][i] = 0;
}
}
for (int i = 1;i<m;i++){
for (int j = 1;j<n;j++){
if (obstacleGrid[i][j]==0){
result [i][j] = result [i][j-1]+result [i-1][j];
}
else {
result [i][j] = 0;
}
}
}
return result[m-1][n-1];
} | 9 |
public Object getValue(String aggregate) {
if ("min".equals(aggregate)) {
return getMin();
}
if ("max".equals(aggregate)) {
return getMax();
}
if ("avg".equals(aggregate)) {
return getAverage();
}
if ("count".equals(aggregate)) {
return getCount();
}
if ("sum".equals(aggregate)) {
return getSum();
}
if (customAggregates != null) {
if (customAggregates.containsKey(aggregate)) {
return customAggregates.get(aggregate).getValue();
}
}
throw new RuntimeException(
"This aggregate can't provide value for \"" + aggregate + "\"");
} | 7 |
public static QuizResult getQuizResult(int QuizId, int UserId)
{
try
{
QuizResult qr = new QuizResult();
String statement = String.format("select qq.questionid ,coalesce(qr.ANSWERID, 0) AnswerID, q.questiontext, coalesce(qr.answertext, 'NONE') ANSWERTEXT, coalesce(qr.iscorrect, false) ISCORRECT, qca.answertext as correctanswer\n" +
"from quizquestion qq join question q on qq.QUESTIONID = q.QUESTIONID\n" +
"left outer join (select iq.QUESTIONID, iq.ANSWERID, iqa.AnswerText, iqa.iscorrect from quizresult iq \n" +
"join questionanswer iqa on iq.ANSWERID = iqa.ANSWERID and iq.QUESTIONID = iqa.QUESTIONID where userid = %d and quizid = %d) qr\n" +
"on qq.QUESTIONID = qr.QUESTIONID\n" +
"join (select answertext, questionid from questionanswer where iscorrect = true) qca\n" +
"on qq.QUESTIONID = qca.questionid\n" +
"where qq.quizid = %d" +
"", UserId, QuizId, QuizId);
ResultSet rs = getQueryResults(statement);
while (rs.next())
{
QuizResultRow qrr = new QuizResultRow();
qrr.questionText = rs.getString("QuestionText");
qrr.isCorrect = rs.getBoolean("isCorrect");
qrr.selectedAnswerText = rs.getString("Answertext");
qrr.correctAnswerText = rs.getString("CorrectAnswer");
qr.ResultRows.add(qrr);
}
return qr;
}
catch (SQLException ex)
{
return null;
}
} | 2 |
static public String convertResponseToString(Object response, Object command) {
if (!(response instanceof String)) {
throw new RuntimeException("Expected String but received ("
+ response.getClass() + ") " + response + "\n in response to command " + command);
}
return (String) response;
} | 1 |
public static void checkException(ExceptionGenerator exceptionGenerator, Class expectedException) {
try {
exceptionGenerator.generateException();
//no exception was caught
System.out.println("no exception; expected " + expectedException.getSimpleName());
} catch (Exception ex) {
if (expectedException.isInstance(ex)) { //expected exception is caught
System.out.println("caught expected " + expectedException.getSimpleName());
} else { //some exception is caught, but not the expected one
System.out.println("caught " + ex.getClass().getSimpleName() +
"; expected: " + expectedException.getSimpleName());
}
}
} | 2 |
public void init(int mode, byte[] key, byte[] iv) throws Exception{
String pad="NoPadding";
//if(padding) pad="PKCS5Padding";
byte[] tmp;
if(iv.length>ivsize){
tmp=new byte[ivsize];
System.arraycopy(iv, 0, tmp, 0, tmp.length);
iv=tmp;
}
if(key.length>bsize){
tmp=new byte[bsize];
System.arraycopy(key, 0, tmp, 0, tmp.length);
key=tmp;
}
try{
cipher=javax.crypto.Cipher.getInstance("DESede/CTR/"+pad);
/*
// The following code does not work on IBM's JDK 1.4.1
SecretKeySpec skeySpec = new SecretKeySpec(key, "DESede");
cipher.init((mode==ENCRYPT_MODE?
javax.crypto.Cipher.ENCRYPT_MODE:
javax.crypto.Cipher.DECRYPT_MODE),
skeySpec, new IvParameterSpec(iv));
*/
DESedeKeySpec keyspec=new DESedeKeySpec(key);
SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DESede");
SecretKey _key=keyfactory.generateSecret(keyspec);
cipher.init((mode==ENCRYPT_MODE?
javax.crypto.Cipher.ENCRYPT_MODE:
javax.crypto.Cipher.DECRYPT_MODE),
_key, new IvParameterSpec(iv));
}
catch(Exception e){
cipher=null;
throw e;
}
} | 4 |
@Override
public void run() {
while(true) {
synchronized (timers) {
for(Timer timer : timers){
if((timer.isWorking())&&(timer.update())){
timer.stop();
}
}
}
try {
sleep(1000);
} catch (InterruptedException e) {}
}
} | 5 |
public void insertElement(IndexPair pair) throws IOException {
// If there is no block yet, allocate one and insert the element.
if (firstBlock == null) {
firstBlock = createNewBlock();
firstBlock.insertElement(pair);
} else {
SignatureStoringBlock block = getBlockFor(pair.getBitSignature());
if (block == null) {
// If there is no block that might contain the pair, all blocks
// have a greater start key.
// So add to the first block.
block = firstBlock;
}
if (block.getSize() < block.getCapacity()) {
block.insertElement(pair);
} else {
// Split the block and add the elements:
// 1. Create a new block and link it right after the current
// block.
SignatureStoringBlock newBlock = createNewBlock();
newBlock.setPreviousBlock(block);
newBlock.setNextBlock(block.getNextBlock());
block.setNextBlock(newBlock);
if (newBlock.getNextBlock() != null) {
newBlock.getNextBlock().setPreviousBlock(newBlock);
}
// 2. Retrieve all elements and spread them over the new blocks.
IndexPair[] pairs = block.getElements();
int splitIndex = pairs.length / 2 + 1;
block.bulkLoad(pairs, 0, splitIndex);
newBlock.bulkLoad(pairs, splitIndex, pairs.length - splitIndex);
// 3. Find the target block for the new element and add it.
if (BitSignatureUtil.COMPARATOR.compare(pair.getBitSignature(),
newBlock.getStartKey()) < 0) {
block.insertElement(pair);
} else {
newBlock.insertElement(pair);
}
}
}
} | 5 |
public static void main(String[] args) throws InterruptedException {
EasyPost.apiKey = "cueqNZUb3ldeWTNX7MU3Mel8UXtaAMUi";
try {
Map<String, Object> fromAddressMap = new HashMap<String, Object>();
fromAddressMap.put("name", "Simpler Postage Inc");
fromAddressMap.put("street1", "388 Townsend St");
fromAddressMap.put("street2", "Apt 20");
fromAddressMap.put("city", "San Francisco");
fromAddressMap.put("state", "CA");
fromAddressMap.put("zip", "94107");
fromAddressMap.put("phone", "415-456-7890");
Address fromAddress = Address.create(fromAddressMap);
Map<String, Object> parcelMap = new HashMap<String, Object>();
parcelMap.put("weight", 22.9);
parcelMap.put("height", 12.1);
parcelMap.put("width", 8);
parcelMap.put("length", 19.8);
Parcel parcel = Parcel.create(parcelMap);
// Customs info - this is required for international destinations
Map<String, Object> customsItem1Map = new HashMap<String, Object>();
customsItem1Map.put("description", "EasyPost T-shirts");
customsItem1Map.put("quantity", 2);
customsItem1Map.put("value", 23.56);
customsItem1Map.put("weight", 18.8);
customsItem1Map.put("origin_country", "us");
customsItem1Map.put("hs_tariff_number", "610910");
Map<String, Object> customsItem2Map = new HashMap<String, Object>();
customsItem2Map.put("description", "EasyPost Stickers");
customsItem2Map.put("quantity", 11);
customsItem2Map.put("value", 8.98);
customsItem2Map.put("weight", 3.2);
customsItem2Map.put("origin_country", "us");
customsItem2Map.put("hs_tariff_number", "654321");
Map<String, Object> customsInfoMap = new HashMap<String, Object>();
customsInfoMap.put("customs_certify", true);
customsInfoMap.put("customs_signer", "Dr. Pepper");
customsInfoMap.put("contents_type", "gift");
customsInfoMap.put("eel_pfc", "NOEEI 30.37(a)");
customsInfoMap.put("non_delivery_option", "return");
customsInfoMap.put("restriction_type", "none");
CustomsItem customsItem1 = CustomsItem.create(customsItem1Map);
CustomsItem customsItem2 = CustomsItem.create(customsItem2Map);
List<CustomsItem> customsItemsList = new ArrayList<CustomsItem>();
customsItemsList.add(customsItem1);
customsItemsList.add(customsItem2);
customsInfoMap.put("customs_items", customsItemsList);
CustomsInfo customsInfo = CustomsInfo.create(customsInfoMap);
// this will be coming from your database or other input source
// hard coding it here for demonstration purposes only
List<Map<String, Object>> orders = new ArrayList<Map<String, Object>>();
Map<String, Object> sampleOrder = new HashMap<String, Object>();
sampleOrder.put("name", "Sawyer Bateman");
sampleOrder.put("street1", "1A Larkspur Cres");
sampleOrder.put("street2", "");
sampleOrder.put("city", "St. Albert");
sampleOrder.put("state", "AB");
sampleOrder.put("zip", "T8N2M4");
sampleOrder.put("phone", "780-483-2746");
sampleOrder.put("country", "CA");
sampleOrder.put("reference", "reference_number_123456");
orders.add(sampleOrder);
// loop over your orders and add a shipment for each
List<Map<String, Object>> shipments = new ArrayList<Map<String, Object>>();
Map<String, Object> shipment = new HashMap<String, Object>();
Map<String, Object> toAddressMap = new HashMap<String, Object>();
for(Map<String, Object> order : orders) {
toAddressMap.put("name", order.get("name"));
toAddressMap.put("street1", order.get("street1"));
toAddressMap.put("street2", order.get("street2"));
toAddressMap.put("city", order.get("city"));
toAddressMap.put("state", order.get("state"));
toAddressMap.put("zip", order.get("zip"));
toAddressMap.put("phone", order.get("phone"));
toAddressMap.put("country", order.get("country"));
shipment.put("to_address", toAddressMap);
shipment.put("from_address", fromAddress);
shipment.put("parcel", parcel);
shipment.put("customs_info", customsInfo);
shipment.put("reference", order.get("reference"));
shipments.add(shipment);
}
// create batch
Map<String, Object> batchMap = new HashMap<String, Object>();
batchMap.put("shipment", shipments);
Batch batch = Batch.create(batchMap);
// ** below this point should be a seperate script so that batch creation isn't duplicated
// ** store batch.id and use it in a new script with Batch.retrieve("{BATCH_ID}");
// loop through each shipment in the batch, purchasing the lowest rate for each
for (Shipment createdShipment : batch.getShipments()) {
// shipments in a new batch do not yet have rates, fetch them before purchasing
createdShipment = createdShipment.newRates();
List<String> buyCarriers = new ArrayList<String>();
buyCarriers.add("USPS");
// List<String> buyServices = new ArrayList<String>();
// buyServices.add("FirstClassPackageServiceInternational");
createdShipment.buy(createdShipment.lowestRate(buyCarriers));
}
// request a batch label of type pdf (other options are epl2 or zpl)
batch = batch.refresh();
if (batch.status.getPostagePurchased() == batch.getShipments().size()) {
Map<String, Object> labelMap = new HashMap<String, Object>();
labelMap.put("file_format", "pdf");
batch.label(labelMap);
} else {
// something went wrong, one of the shipments wasn't purchased successfully in the above loop
// probably wouldn't ever happen, shipment.buy above would throw an error
System.out.println("Uh oh");
}
// batch label creation is asyncronous; wait for it to be done before continuing
while(true) {
batch = batch.refresh();
if (batch.getLabelUrl() != null) {
break;
}
Thread.sleep(8000);
}
System.out.println(batch.prettyPrint());
} catch (EasyPostException e) {
e.printStackTrace();
}
} | 6 |
public synchronized void setSkin(String skinName) {
//LogUtil.logInfo("setSkin(" + skinName + ")");
if (skinName == null || skinName.length() == 0) {
// Blank values of "skinName" reset skin to default.
resetSkin();
return;
}
if (isInteger(modelName)) {
// Skins not supported for block models
return;
}
this.skinName = skinName;
String lowercaseUrl = skinName.toLowerCase();
boolean isFullUrl = (lowercaseUrl.startsWith("http://") || lowercaseUrl.startsWith("https://"))
&& lowercaseUrl.endsWith(".png");
boolean isHumanoid = Model.HUMANOID.equals(modelName);
String downloadUrl;
if (isFullUrl) {
// Full URL was given, download from there.
downloadUrl = skinName;
} else {
// Only the player name was given. Download from skin server.
downloadUrl = Minecraft.skinServer + skinName.replaceAll("[^a-zA-Z0-9:._]", "") + ".png";
}
// Non-humanoid skins are only downloaded if full URL was given.
// (See "Interaction with ExtPlayerList" in CPE ChangeModel spec)
if (isHumanoid || isFullUrl) {
new SkinDownloadThread(this, downloadUrl, skinName, !isHumanoid).start();
}
} | 8 |
private void paintPlaceable(Placeable obj, Graphics2D g2) {
if (obj == null) {
System.out.println("obj in paintPlaceable is null");
} else {
int yPos = obj.getPosition().getY();
int xPos = obj.getPosition().getX();
int ySide = obj.getDimension().height;
int xSide = obj.getDimension().width;
for (int y = 0; y < ySide; y++) {
for (int x = 0; x < xSide; x++) {
Color color = obj.getGUIColor();
g2.setColor(color);
g2.fill(new Rectangle(GlobalPositioning.getXPixel(xPos + x), GlobalPositioning.getYPixel(yPos + y),
Board.getSquareWidth(), Board.getSquareHeight()));
}
}
}
} | 3 |
private static void handleMoveType3(PGNMove move, String strippedMove, byte color, byte[][] board)
throws PGNParseException {
byte piece = WHITE_PAWN;
int fromhPos = getChessATOI(strippedMove.charAt(1));
int tohPos = getChessATOI(strippedMove.charAt(2));
int tovPos = strippedMove.charAt(3) - '1';
int fromvPos = -1;
if (strippedMove.charAt(0) == PAWN.charAt(0)) {
piece = (byte) (BLACK_PAWN * color);
fromvPos = getPawnvPos(fromhPos, tovPos, piece, board);
} else if (strippedMove.charAt(0) == KNIGHT.charAt(0)) {
piece = (byte) (BLACK_KNIGHT * color);
fromvPos = getSingleMovePiecevPos(tohPos, tovPos, fromhPos, piece, board, KNIGHT_SEARCH_PATH);
} else if (strippedMove.charAt(0) == BISHOP.charAt(0)) {
piece = (byte) (BLACK_BISHOP * color);
fromvPos = getMultiMovePiecevPos(tohPos, tovPos, fromhPos, piece, board, BISHOP_SEARCH_PATH);
} else if (strippedMove.charAt(0) == ROOK.charAt(0)) {
piece = (byte) (BLACK_ROOK * color);
fromvPos = getMultiMovePiecevPos(tohPos, tovPos, fromhPos, piece, board, ROOK_SEARCH_PATH);
} else if (strippedMove.charAt(0) == QUEEN.charAt(0)) {
piece = (byte) (BLACK_QUEEN * color);
fromvPos = getMultiMovePiecevPos(tohPos, tovPos, fromhPos, piece, board,
QUEEN_KING_SEARCH_PATH);
} else if (strippedMove.charAt(0) == KING.charAt(0)) {
piece = (byte) (BLACK_KING * color);
fromvPos = getSingleMovePiecevPos(tohPos, tovPos, fromhPos, piece, board,
QUEEN_KING_SEARCH_PATH);
}
if (fromvPos == -1 || fromhPos == -1) {
throw new PGNParseException(move.getFullMove());
}
move.setFromSquare(getChessCoords(fromhPos, fromvPos));
move.setToSquare(getChessCoords(tohPos, tovPos));
if (move.isCaptured()) {
move.setCapturedPiece(PIECES[board[tohPos][tovPos] * -color]);
}
} | 9 |
public Composite(final Delegate<?> ... delegates) {
super(
new InvocationHandler() {
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
for (Delegate<?> delegate : delegates) {
try {
Method handler = delegate.getClassTarget().getMethod(method.getName(), method.getParameterTypes());
return delegate.getHandler().invoke(proxy, handler, args);
}
catch(NoSuchMethodException ex) {
// too bad
}
}
throw new NoSuchMethodException(method.toString());
}
}
);
} | 4 |
public static int main(Iterator<String> argi) {
RepoConfig repoConfig = new RepoConfig();
while( argi.hasNext() ) {
String arg = argi.next();
if( repoConfig.parseCommandLineArg(arg, argi) ) {
} else {
System.err.println("Unrecognized argument: "+arg);
return 1;
}
}
repoConfig.fix();
System.out.println("Primary local repo: "+repoConfig.getPrimaryRepoDir());
for( File f : repoConfig.getRepoDirs() ) {
System.out.println("Local repo: "+f);
}
for( RepoSpec rs : repoConfig.remoteRepos ) {
System.out.println("Remote repo: "+rs.location+(rs.name == null ? "" : " ("+rs.name+")"));
}
return 0;
} | 5 |
private void renderIntersections(Graphics2D g2)
{
Iterator<Intersection> it = model.intersectionsIterator();
while (it.hasNext())
{
Intersection intersection = it.next();
// ONLY RENDER IT THIS WAY IF IT'S NOT THE START OR DESTINATION
// AND IT IS IN THE VIEWPORT
if ((!model.isStartingLocation(intersection))
&& (!model.isDestination(intersection))
&& viewport.isCircleBoundingBoxInsideViewport(intersection.x, intersection.y, INTERSECTION_RADIUS))
{
// FIRST FILL
if (intersection.isOpen())
{
g2.setColor(OPEN_INT_COLOR);
} else
{
g2.setColor(CLOSED_INT_COLOR);
}
recyclableCircle.x = intersection.x - viewport.x - INTERSECTION_RADIUS;
recyclableCircle.y = intersection.y - viewport.y - INTERSECTION_RADIUS;
g2.fill(recyclableCircle);
// AND NOW THE OUTLINE
if (model.isSelectedIntersection(intersection))
{
g2.setColor(HIGHLIGHTED_COLOR);
} else
{
g2.setColor(INT_OUTLINE_COLOR);
}
Stroke s = recyclableStrokes.get(INT_STROKE);
g2.setStroke(s);
g2.draw(recyclableCircle);
}
}
// AND NOW RENDER THE START AND DESTINATION LOCATIONS
Image startImage = model.getStartingLocationImage();
Intersection startInt = model.getStartingLocation();
renderIntersectionImage(g2, startImage, startInt);
Image destImage = model.getDesinationImage();
Intersection destInt = model.getDestination();
renderIntersectionImage(g2, destImage, destInt);
} | 6 |
public static void refreshDefaultTrayToolTip()
{
if( !SystemTray.isSupported() ) return;
AsyncFunction task = new AsyncFunction() {
@Override
public Object doInBackground() {
try {
IConfig servlet = (IConfig) ConfigManager.getConfigManager().getActiveContainer();
IConfig database = (IConfig) ConfigManager.getConfigManager().getActiveDatabase();
String servletName = "Not Selected", databaseName = "Not Selected";
String servletStatus = "N/A", databaseStatus = "N/A";
if( servlet != null )
{
servletName = servlet.getConfigName();
servletStatus = Settings.isServiceUp(servlet.getHost(), servlet.getPort()) ? "Online" : "Offline";
}
if( database != null )
{
databaseName = database.getConfigName();
databaseStatus = Settings.isServiceUp(database.getHost(), database.getPort()) ? "Online" : "Offline";
}
setTooltip(
Settings.SERVER_NAME + "\n" +
"Servlet: " + servletName + " [" + servletStatus + "]\n" +
"Database: " + databaseName + " [" + databaseStatus + "]");
} catch (Exception e) {
trace(STDERR, e);
}
return null;
}
};
task.call();
} | 6 |
public void geefLijntje(boolean goed) {
if (gekozenAntwoord.isGoed())
imagePanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, Color.GREEN, Color.GREEN));
else imagePanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, Color.RED, Color.RED));
} | 1 |
public double[][] rankedAttributes ()
throws Exception {
int i, j;
if (m_attributeList == null || m_attributeMerit == null) {
throw new Exception("Search must be performed before a ranked "
+ "attribute list can be obtained");
}
int[] ranked = Utils.sort(m_attributeMerit);
// reverse the order of the ranked indexes
double[][] bestToWorst = new double[ranked.length][2];
for (i = ranked.length - 1, j = 0; i >= 0; i--) {
bestToWorst[j++][0] = ranked[i];
//alan: means in the arrary ranked, varialbe is from ranked as from small to large
}
// convert the indexes to attribute indexes
for (i = 0; i < bestToWorst.length; i++) {
int temp = ((int)bestToWorst[i][0]);
bestToWorst[i][0] = m_attributeList[temp]; //for the index
bestToWorst[i][1] = m_attributeMerit[temp]; //for the value of the index
}
if (m_numToSelect > bestToWorst.length) {
throw new Exception("More attributes requested than exist in the data");
}
this.FCBFElimination(bestToWorst);
if (m_numToSelect <= 0) {
if (m_threshold == -Double.MAX_VALUE) {
m_calculatedNumToSelect = m_selectedFeatures.length;
} else {
determineNumToSelectFromThreshold(m_selectedFeatures);
}
}
/* if (m_numToSelect > 0) {
determineThreshFromNumToSelect(bestToWorst);
} */
return m_selectedFeatures;
} | 7 |
public double getPesoLlaveEntera(int capa, int neurona, int llave){
double peso = 0;
switch (llave) {
case 0:
peso = this.getPeso(capa, neurona, THRESHOLD);
break;
case 1:
peso = this.getPeso(capa, neurona, EMBARAZOS);
break;
case 2:
peso = this.getPeso(capa, neurona, CONCENTRACION_GLUCOSA);
break;
case 3:
peso = this.getPeso(capa, neurona, PRESION_ARTERIAL);
break;
case 4:
peso = this.getPeso(capa, neurona, GROSOR_TRICEPS);
break;
case 5:
peso = this.getPeso(capa, neurona, INSULINA);
break;
case 6:
peso = this.getPeso(capa, neurona, MASA_CORPORAL);
break;
case 7:
peso = this.getPeso(capa, neurona, FUNCION);
break;
case 8:
peso = this.getPeso(capa, neurona, EDAD);
break;
}
return peso;
} | 9 |
@Override
public void performEvent(ActionEvent e)
{
if ("Normal".equals(e.getActionCommand()))
{
Save.DIFFICULTY = 1;
}
if ("Hard".equals(e.getActionCommand()))
{
Save.DIFFICULTY = 2;
}
if ("Easy".equals(e.getActionCommand()))
{
Save.DIFFICULTY = 0;
}
if ("On".equals(e.getActionCommand()))
{
Save.SOUND_ON = true;
}
if ("Off".equals(e.getActionCommand()))
{
Save.SOUND_ON = false;
}
} | 5 |
private void addDice(String sides) {
List<String> letters = new ArrayList<String>(sides.length());
for ( int i = 0; i < sides.length(); i++){
letters.add(String.valueOf(sides.charAt(i)));
}
dice.add(new Dice<String>(letters));
} | 1 |
protected Command getCommand() {
CompoundCommand command = new CompoundCommand();
command.setDebugLabel("Drag Object Tracker");//$NON-NLS-1$
Iterator iter = getOperationSet().iterator();
Request request = getTargetRequest();
if (isCloneActive())
request.setType(REQ_CLONE);
else if (isMove())
request.setType(REQ_MOVE);
else
request.setType(REQ_ORPHAN);
if (!isCloneActive()) {
while (iter.hasNext()) {
EditPart editPart = (EditPart) iter.next();
command.add(editPart.getCommand(request));
}
}
if (!isMove() || isCloneActive()) {
if (!isCloneActive())
request.setType(REQ_ADD);
if (getTargetEditPart() == null)
command.add(UnexecutableCommand.INSTANCE);
else
command.add(getTargetEditPart().getCommand(getTargetRequest()));
}
return command.unwrap();
} | 8 |
public ISocketServerConnection getSocketServerConnection() {
return socketServerConnection;
} | 0 |
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource() == lstStock) {
if (lstStock.getSelectedValue() != null
&& lstStock.getSelectedValue() instanceof Stock) btnCreate
.setEnabled(true);
}
else if (e.getSource() == lstProduct) {
Object sel = lstProduct.getSelectedValue();
if (sel != null && sel instanceof ProductType) {
ProductType p = (ProductType) sel;
List<SubProcess> sps = p.getSubProcesses();
if (sps != null && sps.size() > 0 && sps.get(0) != null) {
lstStock.setListData(sps.get(0).getStocks().toArray());
}
else lstStock.setListData(new Object[0]);
}
else {
lstStock.setListData(new Object[0]);
}
}
} | 9 |
public CheckResultMessage checkDayofMonth() {
return checkReport1.checkDayofMonth();
} | 0 |
public int GetNextStopBusStop()
{
//set a random bus stop to get off at
SetStopBusStop((GetSelectedBusStop()+1)+rndStop.nextInt(busStop.length-GetSelectedBusStop()));
//SetStopBusStop(rndStop.nextInt(busStop.length+1)+GetSelectedBusStop());
//System.out.println("Stop: "+(GetStopBusStop()+1)) ;
//return the stop chosen
return GetStopBusStop();
} | 0 |
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
} | 0 |
public void calculateScaleRange() {
if( !automaticScale && userScaleRange != 0.0 ) {
scaleRange = userScaleRange;
} else {
RootedTree tree = treePane.getTree();
if (tree != null) {
final double treeHeight = tree.getHeight(tree.getRootNode());
if( treeHeight == 0.0 ) {
scaleRange = 0.0;
} else {
double low = treeHeight / 10.0;
double b = -(Math.ceil(Math.log10(low)) - 1);
for(int n = 0; n < 3; ++n) {
double factor = Math.pow(10, b);
double x = ((int)(low * factor) + 1)/factor;
if( n == 2 || x < treeHeight / 5.0 ) {
scaleRange = x;
break;
}
++b;
}
}
}
}
} | 7 |
private final void method2454(int i, int i_39_, int i_40_, int i_41_,
AnimatableToolkit class64, int i_42_,
Class101 class101, AbstractToolkit var_ha, int i_43_) {
do {
try {
if (i != 6253)
((Player) this).aString10544 = null;
anInt10563++;
int i_44_ = i_43_ * i_43_ + i_39_ * i_39_;
if (i_44_ >= 262144
&& (i_42_ ^ 0xffffffff) <= (i_44_ ^ 0xffffffff)) {
int i_45_
= ((int) (2607.5945876176133
* Math.atan2((double) i_39_, (double) i_43_))
& 0x3fff);
AnimatableToolkit class64_46_
= (Canvas_Sub1.method122
(((Mob) this).anInt10252,
((Mob) this).anInt10302,
((Mob) this).anInt10208, i_45_,
i_41_, (byte) -35, var_ha));
if (class64_46_ == null)
break;
var_ha.C(false);
class64_46_.method608(class101, null, i_40_, 0);
var_ha.C(true);
}
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("ke.V(" + i + ',' + i_39_
+ ',' + i_40_ + ',' + i_41_
+ ','
+ (class64 != null ? "{...}"
: "null")
+ ',' + i_42_ + ','
+ (class101 != null ? "{...}"
: "null")
+ ','
+ (var_ha != null ? "{...}"
: "null")
+ ',' + i_43_ + ')'));
}
break;
} while (false);
} | 9 |
public static void run()
{
System.out.println("\n\n--|Cards|----------------------------------------------------------------------");
System.out.println();
String value[] = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
String suit[] = { "diamonds", "clubs", "hearts", "spades" };
// load a hat with cards
Hat<String> full_deck = new Hat<String>();
Hat<String> playing_deck = new Hat<String>();
String one_card;
for( int v=0; v<13; v++ )
{
for( int s=0; s<4; s++)
{
// assemble a card string like "Queen of hearts" etc
one_card = value[v];
one_card += " of ";
one_card += suit[s];
full_deck.put(one_card); // put card in hat
}
}
playing_deck = full_deck;
// now a 5-card hand and then return them to the deck
for( int h=0; h<3; h++)
{
for( int c=0; c<5; c++ )
{
System.out.println(playing_deck.pull());
}
System.out.println("");
playing_deck = full_deck;
}
} | 4 |
@Override
public String toString() {
String wasQueuedTxt = "";
if (wasQueued() == true) {
int queueOverstay;
if (getParkingTime() == 0) {
queueOverstay = getDepartureTime() - getArrivalTime() - Constants.MAXIMUM_QUEUE_TIME;
wasQueuedTxt = "\nExit from Queue: " + getDepartureTime() +
"\nQueuing Time: " + (getDepartureTime() - getArrivalTime()) +
"\nExceeded maximum acceptable queuing time by: " + queueOverstay;
} else {
wasQueuedTxt = "\nExit from Queue: " + getParkingTime() +
"\nQueuing Time: " + (getParkingTime() - getArrivalTime());
}
} else {
wasQueuedTxt = "\nVehicle was not queued";
}
String wasSatisfiedTxt = "";
if (isSatisfied() == true) {
wasSatisfiedTxt = "satisfied";
} else {
wasSatisfiedTxt = "not satisfied";
}
String wasParkedTxt = "";
if (wasParked()) {
wasParkedTxt = "\nEntry to Car Park: " + this.parkingTime +
"\nExit from Car Park: " + (getDepartureTime()) +
"\nParking Time: " +
(getDepartureTime() - getParkingTime());
} else {
wasParkedTxt = "\nVehicle was not parked";
}
return "Vehicle vehID: " + this.vehID +
"\nArrival Time: " + this.arrivalTime +
wasQueuedTxt + wasParkedTxt +
"\nCustomer was " + wasSatisfiedTxt;
} | 4 |
@Override
public void executeMsg(Environmental affecting, CMMsg msg)
{
super.executeMsg(affecting,msg);
if((affecting instanceof MOB)&&(!CMLib.flags().isAliveAwakeMobileUnbound((MOB)affecting,true)))
return;
if(disabled)
return;
if(((!(affecting instanceof MOB))||(!msg.amISource((MOB)affecting)))
&&((text().length()==0)||(text().equalsIgnoreCase(msg.source().Name())))
&&((msg.sourceMinor()!=CMMsg.TYP_EMOTE)
||(msg.tool() instanceof Social)))
lastMsg=msg;
} | 9 |
@AfterClass
public static void tearDownClass() {
} | 0 |
public CheckResultMessage checkDayofMonth5() {
int r1 = get(2, 5);
int c1 = get(3, 5);
date();
if (checkVersion(file).equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
if (!(getValueString(r1 + maxDay, c1 - 1, 4).equals(maxDay
+ "日"))) {
return error("日期设置错误!<" + fileName + ">" + " Sheet:1-1"
+ ", 应设为本月最后日期:" + maxDay + "日");
}
in.close();
} catch (Exception e) {
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
if (!(getValueString(r1 + maxDay, c1 - 1, 4).equals(maxDay
+ "日"))) {
return error("日期设置错误!<" + fileName + ">" + " Sheet:1-1"
+ ", 应设为本月最后日期:" + maxDay + "日");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付支付机构汇总表格:<" + fileName + ">Sheet:1-1日期核对正确");
} | 5 |
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 {
javax.swing.UIManager.LookAndFeelInfo[] installedLookAndFeels=javax.swing.UIManager.getInstalledLookAndFeels();
for (int idx=0; idx<installedLookAndFeels.length; idx++)
if ("Nimbus".equals(installedLookAndFeels[idx].getName())) {
javax.swing.UIManager.setLookAndFeel(installedLookAndFeels[idx].getClassName());
break;
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Anagrams.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Anagrams.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Anagrams.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Anagrams.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Anagrams().setVisible(true);
}
});
} | 6 |
private RenderableObject generateShape(Scanner inFile) {
Point loc = null;
RenderableShape rs = new RenderableShape(loc);
String current = inFile.next();
while (inFile.hasNext()
&& !(isCloseTag(current) && parseTag(current) == LegalTag.Object)) {
if (isOpenTag(current)) {
switch (parseTag(current)) {
case Location:
loc = new Point(inFile.nextInt(), inFile.nextInt());
rs.setLocation(loc);
break;
case Line:
rs.add(generateLine(inFile));
break;
default:
break;
}
}
current = inFile.next();
}
return rs;
} | 6 |
public void setPlacePool(ParkingPlacePool placePool) throws ParkingException {
if (placePool == null) {
throw new ParkingException("Parking place pool is null");
}
this.placePool = placePool;
} | 1 |
@Override
public Query rewrite(IndexReader reader) throws IOException {
int numDisjunctions = disjuncts.size();
if (numDisjunctions == 1) {
Query singleton = disjuncts.get(0);
Query result = singleton.rewrite(reader);
if (getBoost() != 1.0f) {
if (result == singleton) result = (Query)result.clone();
result.setBoost(getBoost() * result.getBoost());
}
return result;
}
DisjunctionMaxQuery clone = null;
for (int i = 0 ; i < numDisjunctions; i++) {
Query clause = disjuncts.get(i);
Query rewrite = clause.rewrite(reader);
if (rewrite != clause) {
if (clone == null) clone = (DisjunctionMaxQuery)this.clone();
clone.disjuncts.set(i, rewrite);
}
}
if (clone != null) return clone;
else return this;
} | 7 |
private void refreshFootprint(int slot) {
footprints[slot] = (byte) (random.nextInt(1 << (bitsPerSlot) - 1) + 1);
} | 0 |
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
} | 2 |
public double[][] fast_idct(double[][] input)
{
double output[][] = new double[8][8];
double temp[][] = new double[8][8];
double temp1;
int i, j, k;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
temp[i][j] = 0.0;
for (k = 0; k < 8; k++)
{
temp[i][j] += input[i][k] * c[k][j];
}
}
}
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
temp1 = 0.0;
for (k = 0; k < 8; k++)
temp1 += cT[i][k] * temp[k][j];
temp1 += 128.0;
if (temp1 < 0)
output[i][j] = 0;
else if (temp1 > 255)
output[i][j] = 255;
else
output[i][j] = (int) Math.round(temp1);
}
}
return output;
} | 8 |
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
if (event.isCancelled())
return;
Player player = event.getPlayer();
if (this.parentarena.getArenaState() != ArenaState.STAT_READY)
return;
if (!this.parentarena.getplayers().contains(player))
return;
event.setCancelled(true);
} | 3 |
private LinkedList<SmallPacket> processData(Byte destination, Byte hops,
byte[] data, boolean ack, boolean routing, boolean keepalive) {
// data = eh.getPacket(data, destination);
LinkedList<SmallPacket> result = new LinkedList<SmallPacket>();
lock.lock();
SmallPacket dp;
boolean moar = false;
int maxChunkSize = 1024 - SmallPacket.HEADER_LENGTH;
byte[] chunk = new byte[maxChunkSize];
for (int i = 0; i <= Math.ceil(data.length / maxChunkSize); i++) {
if (data.length >= (i + 1) * maxChunkSize) {
moar = true;
System.arraycopy(data, i * maxChunkSize, chunk, 0, maxChunkSize);
} else {
moar = false;
chunk = new byte[data.length - i * maxChunkSize];
System.arraycopy(data, i * maxChunkSize, chunk, 0, data.length
- i * maxChunkSize);
}
try {
Byte sequencenr = 0;
if (!routing)
sequencenr = sequencer.getTo(destination);
if (!(sequencenr == null)) {
dp = new SmallPacket(IntegrationProject.DEVICE,
destination, hops, sequencenr, chunk, ack, routing,
keepalive, moar);
result.add(dp);
} else {
System.out
.println("Dropped packet because getTo return NULL GODDAMMIT!");
}
} catch (DatagramDataSizeException e) {
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("Fuck this");
e.printStackTrace();
}
}
lock.unlock();
return result;
} | 6 |
private VariableType simple_expression() {
TokenType[] op = new TokenType[]{
TokenType.SPLUS, TokenType.SMINUS, TokenType.SOR};
VariableType ltype, rtype = VariableType.VOID;
if(whenToken(new TokenType[]{TokenType.SPLUS, TokenType.SMINUS}) ){
int linum = getLineNumber();
ltype = term();
if(ltype != VariableType.INTEGER)
throw new RuntimeException("Line\t\t\t\t" + linum + " : type error at" + "\n"
+ "\t actual : " + ltype + "\n"
+ "\t expected : " + VariableType.INTEGER);
} else {
ltype = term();
}
while(testToken(op)) {
int linum = getLineNumber();
if(whenToken(new TokenType[]{TokenType.SPLUS, TokenType.SMINUS})) {
rtype = term();
if(ltype != VariableType.INTEGER || rtype != VariableType.INTEGER)
throw new RuntimeException("Line\t\t\t\t" + linum + " : type mismatch" + "\n"
+ "\t left : " + ltype + "\n"
+ "\t right : " + rtype + "\n"
+ "\t expected : " + VariableType.INTEGER);
} else if(whenToken(TokenType.SOR)) {
rtype = term();
if(ltype != VariableType.BOOLEAN || rtype != VariableType.BOOLEAN)
throw new RuntimeException("Line\t\t\t\t" + linum + " : type mismatch" + "\n"
+ "\t left : " + ltype + "\n"
+ "\t right : " + rtype + "\n"
+ "\t expected : " + VariableType.BOOLEAN);
} else {
new RuntimeException("Line\t\t\t\t" + "unknown error at" + linum);
}
ltype = rtype;
}
return ltype;
} | 9 |
public PanelGrille(int largeur, int hauteur) {
this.setBackground(Color.black);
cellules = new JCellule[largeur][hauteur];
this.setLayout(new GridLayout(largeur, hauteur));
for (int i = 0; i < largeur; i++) {
for (int j = 0; j < hauteur; j++) {
cellules[i][j] = new JCellule(i, j);
cellules[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JCellule cellule = (JCellule) e.getSource();
ControllerGrille.flipCell(((PanelGrille) cellule.getParent()).getGrid(), cellule.getCoordonneeX(), cellule.getCoordonneeY(), getPanelOptions().getLblGeneration(), getPanelOptions().getBtnProchaineGeneration());
}
});
cellules[i][j].setVisible(true);
this.add(cellules[i][j]);
}
}
this.setVisible(true);
} | 2 |
@Override
public int pulse() {
if (npc != null) {
if (npc.isInteracting() && players.getLocalPlayer().isInteracting()) {
if (widgets.canContinue()) {
widgets.clickContinue();
sleep(1700, 2000);
}
} else {
npc.interact("Talk-to");
sleep(3000, 5000);
}
} else if (npcs.getNearest(npc.getId()) == null) {
requestExit();
sleep(1000, 1500);
}
return random(50, 75);
} | 5 |
public EditorController getNewLevel(int columns, int rows) {
EditorController controller = new EditorController();
Board currentLevel = new Board(columns, rows);
controller.setModel(currentLevel);
LevelEditorView editorView = new LevelEditorView(columns, rows);
controller.setView(editorView);
// initialize fields with the empty state
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Field field = new Field(FieldState.EMPTY);
currentLevel.setField(j, i, field);
// we need the controller for each field for the drag and drop
// functionality
FieldController fieldController = new FieldController();
DraggableElementDestination elementDestination = new DraggableElementDestination(
fieldController);
fieldController.setView(elementDestination);
fieldController.setModel(field);
editorView.addElement(elementDestination);
}
}
return controller;
} | 2 |
@Override
public void removeExtension(String ext) {
extensions.remove(ext);
} | 0 |
private File getFile(String source){
if(source.indexOf(getOsFileSeparator()) == -1){
System.out.println("디렉토리 구분자가 잘못되었습니다."); //리소스 경로 잠못된것인지 체크
}
File file = new File(source);
if(file.isDirectory() && !file.exists()){
System.out.println("지정한 경로가 존재하지 않습니다."); //리소스 경로에 리소스가 있는지 체크
}
return file;
} | 3 |
public String longestPrefixOf(String s) {
if (s == null || s.length() == 0) return null;
int length = 0;
Node<Value> x = root;
int i = 0;
while (x != null && i < s.length()) {
char c = s.charAt(i);
if (c < x.c) x = x.left;
else if (c > x.c) x = x.right;
else {
i++;
if (x.val != null) length = i;
x = x.mid;
}
}
return s.substring(0, length);
} | 7 |
private boolean shoudCheckNewVersion() {
Logger.getLogger(MainInterface.class.getName()).entering(MainInterface.class.getName(), "shoudCheckNewVersion");
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Checking if the software should check for a new version");
String autoCheckUpdates = PropertiesManager.getInstance().getKey("autoCheckUpdates");
if (autoCheckUpdates != null && autoCheckUpdates.equals("false")) {
autoUpdatesCheckBoxMenuItem.setSelected(false);
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "shoudCheckNewVersion", false);
return false;
}
String lastUpdateCheckString = PropertiesManager.getInstance().getKey("lastUpdateCheck");
if (lastUpdateCheckString == null) {
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "No previous check date found. Should check");
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "shoudCheckNewVersion", true);
return true;
}
Date lastUpdateCheckDate;
try {
lastUpdateCheckDate = DateFormat.getDateInstance().parse(lastUpdateCheckString);
} catch (ParseException ex) {
Logger.getLogger(MainInterface.class.getName()).log(Level.WARNING, "Couldn't parse the previous update check date", ex);
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "shoudCheckNewVersion", true);
return true;
}
Calendar cal = new GregorianCalendar();
cal.setTime(lastUpdateCheckDate);
cal.add(Calendar.DATE, 7);
if (new Date().after(cal.getTime())) {
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Should check for a new version of the software");
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "shoudCheckNewVersion", true);
return true;
}
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "shoudCheckNewVersion", false);
return false;
} | 5 |
public Output draw() {
if (_drawOutput != null) {
return _drawOutput;
}
return drawRandom();
} | 1 |
@SuppressWarnings({ "unchecked", "rawtypes" })
public void dispatchTask(final String supportedService, final Task t) {
List<ProductLine<?>> lines = getProductLinesBySupportedService(supportedService);
if (lines == null) {
lines = new ArrayList<ProductLine<?>>();
for (ProductLineFactory factory : factoryList) {
ProductLine<?> productLine = factory.newProductLine(supportedService);
if (productLine != null) lines.add(productLine);
}
mProductLinesNameMap.put(supportedService, lines);
}
for (ProductLine line : lines) {
line.appendTask(t);
}
} | 7 |
public void flattenSelection()
{
if (selection.width == 0 || selection.height == 0)
return;
for (int x = selection.x; x < selection.width + selection.x; x++)
{
for (int y = selection.y; y < selection.height + selection.y; y++)
{
try
{
drawPoint(x, y, this.selectImg[x - selection.x][y
- selection.y]);
}
catch (ArrayIndexOutOfBoundsException e)
{}
}
}
} | 5 |
public void tick() {
for(int i = 0; i < buttons.length; i++) {
oldButtons[i] = buttons[i];
}
} | 1 |
public void removeRow(int position) {
// Si la matière est renseignée, on la supprime de la liste des matières de l'enseignant.
if(!table.getModel().getValueAt(position, 0).equals("")) {
selectedTeacher.removeFieldAt(position);
}
// Puis on supprime la ligne dans le tableau
int indice = 0, indice2 = 0, nbRow = this.getRowCount()-1, nbCol = this.getColumnCount();
Object temp[][] = new Object[nbRow][nbCol];
for(Object[] value : this.data){
if(indice != position){
temp[indice2++] = value;
}
System.out.println("Indice = " + indice);
indice++;
}
this.data = temp;
temp = null;
this.fireTableDataChanged();
} | 3 |
public void compFinalResult() {
do {
iStage++;
compAllocation();
if (compDistribution()) {
/* deadline can not be satisfied */
if (!bDeadline) {
System.out.println("THE DEADLINE CAN NOT BE SATISFIED!");
return;
} else {
System.out.println("\nNEW ROUND WITHOUT CHECKING:");
dEval = 1;
}
} else {
compExecTime();
}
// System.out.println("Evaluation Value =========="+dEval);
} while (dEval > 0);
// while (evaluateResults());
// System.out.println("==================Distribution=====================");
for (int i = 0; i < iClass; i++) {
// System.out.print("FinalDistribution[" + i + "] ");
for (int j = 0; j < iSite; j++) {
dmDist[i][j] = Math.round(dmDist[i][j]);
// System.out.print(dmDistribution[i][j] + ",");
}
// System.out.println();
}
// System.out.println("==================Allocation=====================");
for (int i = 0; i < iClass; i++) {
System.out.print("FinalAllocation[" + i + "] ");
for (int j = 0; j < iSite; j++) {
dmAlloc[i][j] = Math.round(dmAlloc[i][j]);
// System.out.print(dmAllocation[i][j] + ",");
}
// System.out.println();
}
// System.out.println("Stage = " + iStage);
} | 7 |
public static boolean hasNull(Object... objs) {
boolean result = false;
for (Object obj : objs) {
if (obj == null) {
result = true;
break;
}
}
return result;
} | 2 |
public SolarSystem(
int numberOfPlanets,
int height,
int width,
Force gravity,
boolean centrifugal_flag,
double averageEnergy,
boolean sun_flag,
double sun_size){
int i,j;
Color colour;
total_mass = 0;
centre_of_mass_x = 0;
centre_of_mass_y = 0;
originalEnergy = 0;
potentialEnergy = 0;
kineticEnergy = 0;
momentumX = 0;
momentumY = 0;
Force.SCALE=1;
this.numberOfPlanets = numberOfPlanets;
this.averageEnergy = averageEnergy;
this.centrifugal_flag = centrifugal_flag;
this.sun_flag = sun_flag;
this.sun_size = sun_size;
this.planets = new Planet[numberOfPlanets];
this.gravity=gravity;
colour=Color.RED;
this.centreOfMass = new Planet(0,0,5,0,colour);
for(i = 0; i < numberOfPlanets; i++) {
double x,y,radius,mass;
x = (Math.random()*width % (width/2)) + (width/4);
y = (Math.random()*width % (height/2)) + (height/4);
radius = (Math.random()*width % 15) + 1;
colour=new Color((float)Math.random(),(float)Math.random(),(float)Math.random());
// Set the first two up at nice spots and sizes, handy for debugging force behaviour
if (i == 0){
x = 3 * width / 8 ;
y = 3 * height / 8;
radius = 10;
colour=Color.YELLOW;
}
if (i == 1){
x = 5 * width / 8;
y = 5 * height / 8;
radius = 10;
colour=Color.GREEN;
}
mass = radius*radius*radius;
if (sun_flag && (i == numberOfPlanets -1) ){ // make it the last one so it renders on top
x=width/2;
y=height/2;
radius = 25;
mass = this.sun_size;
colour = Color.WHITE;
}
this.planets[i] = new Planet(x,y,radius,mass,colour);
this.total_mass += mass;
this.centreOfMass.posX = this.centre_of_mass_x+=(mass/total_mass)*(x-centre_of_mass_x);
this.centreOfMass.posY = this.centre_of_mass_y+=(mass/total_mass)*(y-centre_of_mass_y);
}
// do a dummy run to add up the potential eneGrgy at start
for(i = 0; i < this.numberOfPlanets; i++) {
for(j = i +1 ; j < this.numberOfPlanets; j++) {
this.potentialEnergy += this.planets[i].Attract(this.planets[j],gravity);
}
// zap the velocity and acceleration back to zero after the dummy run to get the potential
this.planets[i].velocityX=0;
this.planets[i].velocityY=0;
this.planets[i].deltaVelocityX=0;
this.planets[i].deltaVelocityY=0;
}
// now we know the total energy, we can scale
// else when you bump up the number of planets,
// the energy in the system goes exponetially up and the animation goes bonkers.
Force.SCALE = averageEnergy * numberOfPlanets/this.potentialEnergy;
this.potentialEnergy=averageEnergy * numberOfPlanets;
if (centrifugal_flag){ // get stuff to orbit the centre of mass, using the sun's mass as an attractor
double momentum_x = 0;
double momentum_y = 0;
double SunMass=planets[numberOfPlanets-1].mass;
for(i = 0; i < numberOfPlanets-1; i++) {
// distance to centre of mass
double distCoM = Math.sqrt(
(planets[i].posY - centre_of_mass_y) * (planets[i].posY - centre_of_mass_y) +
(planets[i].posX - centre_of_mass_x) * (planets[i].posX - centre_of_mass_x));
double v=gravity.centrifugal(distCoM,sun_size);
planets[i].velocityX += (planets[i].posY - centre_of_mass_y) * v / distCoM;
planets[i].velocityY +=-(planets[i].posX - centre_of_mass_x) * v / distCoM;
momentum_x += planets[i].mass * planets[i].velocityX;
momentum_y += planets[i].mass * planets[i].velocityY;
kineticEnergy += (planets[i].velocityX * planets[i].velocityX) +
(planets[i].velocityY * planets[i].velocityY) *
planets[i].mass/2 ;
}
// i = last one, which might be a sun, so shift it to balance the momentum
planets[i].velocityX -= momentum_x / planets[i].mass;
planets[i].velocityY -= momentum_y / planets[i].mass;
kineticEnergy += (planets[i].velocityX * planets[i].velocityX) +
(planets[i].velocityY * planets[i].velocityY) *
planets[i].mass/2 ;
}
this.originalEnergy=this.potentialEnergy+this.kineticEnergy;
} | 9 |
public void loadBookmark() throws Exception
{ ArrayList<Float> myList = new ArrayList<Float>();
FileReader fileReader = new FileReader(new File("BookMark.txt"));
BufferedReader reader = new BufferedReader(fileReader);
String s;
/* float lowVal,highVal,lowValInDataSet,highValInDataSet;
int numberTicks=5,numPixelsReserved=35;*/
s=reader.readLine();
myList=getValuesFromRow(s);
parent.percentIdentityAxis.resetAxisInfo(myList.get(0),myList.get(1),myList.get(2),myList.get(3),myList.get(4),myList.get(5),myList.get(6));
s=reader.readLine();
myList=getValuesFromRow(s);
parent.queryLengthAxis.resetAxisInfo(myList.get(0),myList.get(1),myList.get(2),myList.get(3),myList.get(4),myList.get(5),myList.get(6));
s=reader.readLine();
myList=getValuesFromRow(s);
parent.minusLog10Axis.resetAxisInfo(myList.get(0),myList.get(1),myList.get(2),myList.get(3),myList.get(4),myList.get(5),myList.get(6));
s=reader.readLine();
myList=getValuesFromRow(s);
parent.bitScoreAxis.resetAxisInfo(myList.get(0),myList.get(1),myList.get(2),myList.get(3),myList.get(4),myList.get(5),myList.get(6));
s=reader.readLine();
myList=getValuesFromRow(s);
float f=myList.get(0);
parent.setJitterVal((int)f);
parent.getXAxis().setDisplayed(parent.bitScoreAxis.floatIsDisplayedToBoolean(myList.get(1)));
parent.setShowGeneAnnotations(parent.bitScoreAxis.floatIsDisplayedToBoolean(myList.get(2)));
parent.setShowGeneLabels(parent.bitScoreAxis.floatIsDisplayedToBoolean(myList.get(3)));
f=myList.get(4);
parent.setNumPixelsReservedForGeneAnnotations((int)f);
s=reader.readLine();
myList=getValuesFromRow(s);
f=myList.get(0);
parent.setLowX((int)f);
f=myList.get(1);
parent.setHighX((int)f);
s=reader.readLine();
System.out.println(s.equals("**"));
listOfFiles.clear();
List<HitScores> listOfHS = new ArrayList<HitScores>();
while(s.equals("**"))
{System.out.println(s);
s=reader.readLine();
}
while(!s.equals("**"))
{
listOfHS.add(new HitScores(s));
s=reader.readLine();
}
QueryHitGroup query1 = new QueryHitGroup( Color.BLACK,listOfHS,75, "March 20 Wastewater" );
listOfHS = new ArrayList<HitScores>();
while(s.equals("**")) s=reader.readLine();
while(!s.equals("**"))
{
listOfHS.add(new HitScores(s));
s=reader.readLine();
}
QueryHitGroup query2 = new QueryHitGroup( Color.RED,listOfHS,250,"Environmental Sequences" );
listOfHS = new ArrayList<HitScores>();
while(s.equals("**")) s=reader.readLine();
while(!s.equals("**"))
{
listOfHS.add(new HitScores(s));
s=reader.readLine();
}
QueryHitGroup query3 = new QueryHitGroup( Color.BLUE,listOfHS,250, "NC_008752 Acidovorax avenae subsp. citrulli AAC00-1, complete genome");
listOfFiles.add(query1);
listOfFiles.add(query2);
listOfFiles.add(query3);
grandFa.setList(listOfFiles);
reader.close();
fileReader.close();
parent.repaint();
} | 6 |
public static Class<?> formulaClass(Class<?extends Deduction> rule) {
try {
return (Class<?>) rule.getMethod("formulaClass", null).invoke(null,null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final CommandFailure other = (CommandFailure) obj;
if (feedbackPropertyReference == null) {
if (other.feedbackPropertyReference != null)
return false;
}
else if (!feedbackPropertyReference.equals(other.feedbackPropertyReference))
return false;
if (timeDelay == null) {
if (other.timeDelay != null)
return false;
}
else if (!timeDelay.equals(other.timeDelay))
return false;
return true;
} | 9 |
public static String encrypt(final String text) {
String encryptedText = null;
TripleDesCipher cipher = new TripleDesCipher();
cipher.setKey("GWT_DES_KEY_16_BYTES".getBytes());
try {
encryptedText = cipher.encrypt(String.valueOf(text));
} catch (DataLengthException e1) {
e1.printStackTrace();
// Window.alert(e1.getMessage());
} catch (IllegalStateException e1) {
e1.printStackTrace();
// Window.alert(e1.getMessage());
} catch (InvalidCipherTextException e1) {
e1.printStackTrace();
// Window.alert(e1.getMessage());
}
return encryptedText;
} | 3 |
private void processLabors(int year, List<Man> mankind, List<Woman> womankind) {
List<Man> fathers = calculateFathers(mankind);
List<Human> children = new ArrayList<Human>();
for (Iterator<Woman> it = womankind.iterator(); it.hasNext(); ) {
Woman woman = it.next();
if (woman.isLaborAccepted()) {
Man father = findFather(fathers, woman);//подбор потенциального отца
if (father != null) {
Human child = processLabor(father, woman);
if (child == null) {//смерть во время родов
it.remove();
} else {
children.add(child);//сразу в mankind или womankind добавлять нельзя, т.к. получим ConcurrentModificationException при итерации по womankind
}
}
}
}
int mans = 0;
int womans = 0;
for (Human child: children) {
if (child.getSex() == Human.Sex.MALE) {
mankind.add((Man)child);
mans++;
} else if (child.getSex() == Human.Sex.FEMALE) {
womankind.add((Woman)child);
womans++;
}
}
if (year % debugFactor == 0) {LOGGER.debug("Year: " + year + ", newborns: " + (mans + womans) + "(" + mans + "/" + womans + ")");}
} | 8 |
public void sortArray() {
this.arrayAccess = 0;
this.comparisions = 0;
int arrLength = this.array.length;
/**
* This denotes the index of the minimum element. It is assumed that the
* first element during the iteration is the minimum and then the array
* is scanned till the end to find a value that is smaller than that and
* finally the current iteration's minimum is swapped into place which
* is just before the last iteration's minimum. We can see that why this
* is not "Online" and not "Stable".
*/
int iMin;
/**
* Iterate through the array once. No need to look for the last element
* since it will contain the largest number automatically.
*/
for (int i = 0; i < arrLength - 1; i++) {
/**
* Assume the current index to be the index holding the minimum
* value.
*/
iMin = i;
/**
* Scan through the array starting from one element next to the
* current index "i+1" till "arrLength-1". Check if the "j"th
* element is lower than "iMin". If so, update "iMin".
*/
for (int j = i + 1; j < arrLength; j++) {
if (isLesser(j, iMin)) {
iMin = j;
}
this.arrayAccess += 2;
this.comparisions++;
}
/**
* If the index was not changed at all during the process, or if the
* "i"th element itself was the local minimum, then there is no need
* to swap. Else swap them.
*/
if (iMin != i) {
this.swapArrayValues(i, iMin);
}
}
} | 4 |
protected Double coerceToDouble(Object value) {
if (value == null || "".equals(value)) {
return Double.valueOf(0);
}
if (value instanceof Double) {
return (Double)value;
}
if (value instanceof Number) {
return Double.valueOf(((Number)value).doubleValue());
}
if (value instanceof String) {
try {
return Double.valueOf((String)value);
} catch (NumberFormatException e) {
throw new ELException(LocalMessages.get("error.coerce.value", value, value.getClass(), Double.class));
}
}
if (value instanceof Character) {
return Double.valueOf((short)((Character)value).charValue());
}
throw new ELException(LocalMessages.get("error.coerce.type", value, value.getClass(), Double.class));
} | 7 |
public XmlRuleSpider(final String filePath){
this.cobweb = new MemoryBasedCobweb();
parseXml(filePath);
} | 0 |
public void changePlayerMarker(String username, int markerID){
try {
cs = con.prepareCall("{call changePlayerMarker(?,?)}");
cs.setString(1, username);
cs.setInt(2, markerID);
cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
public void procBtnRech() {
int compsSize = getCompsSize();
if (optEmploi.isSelected()) {
if (compsSize > 0) {
if (!jckbprox.isSelected()) {
activerRechercher(true);
setErrorMsg(" ");
} else {
final String text = txtSalesp.getText();
// System.out.println("textTitre:" + text + "|length" + length);
if (text.isEmpty()) {
//Texte vide => Désactiver le bouton
activerRechercher(false);
setErrorMsg("Vous n'avez pas saisi de Salaire espéré");
} else {
try {
int value = Integer.parseInt(text);
if (value > 0) {
activerRechercher(true);
setErrorMsg(" ");
} else {
//Texte nombre <=0 => Désactiver le bouton
activerRechercher(false);
setErrorMsg("Le salaire espéré doit être un chiffre supérieur à 0");
}
} catch (NumberFormatException numberFormatException) {
//Texte pas un nombre => Désactiver le bouton
activerRechercher(false);
setErrorMsg("Le salaire espéré n'est pas un nombre");
}
}
}
} else {
activerRechercher(false);
}
} else if (optStage.isSelected()) {
if (compsSize > 0) {
activerRechercher(true);
setErrorMsg(" ");
} else {
setErrorMsg("Vous n'avez pas choisi de compétence");
activerRechercher(false);
}
}
} | 8 |
public static void addClass(Course course, int type){ //adding class information - name, index, intake size for each course class created
String classType = type==1?"lecture":type==2?"tutorial":"laboratory";
System.out.println("How many classes for " + course.getName() + " - " + classType + " ?");
int classAmt;// = sc.nextInt();
while(true){//only int input accepted
if(sc.hasNextInt()){
classAmt = sc.nextInt();
break;
}else {
System.out.println("Please enter a valid choice!");
sc.next();
}
}
for(int i =0;i<classAmt;i++){ //repeat this step for # of classes they've entered
System.out.println("Add a Course Class : Input Class Name, Class Index, Class Intake Size.");
int inClassType;
while(true){//only int input accepted
if(sc.hasNextInt()){
inClassType = sc.nextInt();
break;
}else {
System.out.println("Please enter a valid choice!");
sc.next();
}
}
CourseClass tempCourseClass = new CourseClass(sc.next(), sc.next(), inClassType, type, course);
course.getCourseClassList().add(tempCourseClass);
}
System.out.println("New Course Class : " + classAmt + " " + classType + " has been added successfully!\n");
} | 7 |
@Override
public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException {
List paramList1 = new ArrayList<>();
List paramList2 = new ArrayList<>();
StringBuilder sb = new StringBuilder(UPDATE_QUERY);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_DIRSTAY_NO, DB_DIRSTAY_STAY_NO, criteria, paramList1, sb, COMMA);
Appender.append(DAO_DIRSTAY_STATUS, DB_DIRSTAY_STATUS, criteria, paramList1, sb, COMMA);
Appender.append(DAO_ID_DIRECTION, DB_DIRSTAY_ID_DIRECTION, criteria, paramList1, sb, COMMA);
Appender.append(DAO_ID_HOTEL, DB_DIRSTAY_ID_HOTEL, criteria, paramList1, sb, COMMA);
sb.append(WHERE);
Appender.append(DAO_ID_DIRSTAY, DB_DIRSTAY_ID_STAY, beans, paramList2, sb, AND);
Appender.append(DAO_DIRSTAY_NO, DB_DIRSTAY_STAY_NO, beans, paramList2, sb, AND);
Appender.append(DAO_DIRSTAY_STATUS, DB_DIRSTAY_STATUS, beans, paramList2, sb, AND);
Appender.append(DAO_ID_DIRECTION, DB_DIRSTAY_ID_DIRECTION, beans, paramList2, sb, AND);
Appender.append(DAO_ID_HOTEL, DB_DIRSTAY_ID_HOTEL, beans, paramList2, sb, AND);
return sb.toString();
}
}.mapQuery();
paramList1.addAll(paramList2);
try {
return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn);
} catch (DaoException ex) {
throw new DaoQueryException(ERR_DIR_STAY_UPDATE, ex);
}
} | 1 |
@Override
public String getColorRepresentation(char roomChar, int line)
{
switch (line)
{
case 0:
if (links.containsKey(Integer.valueOf(Directions.NORTH)))
return " ^ ";
return " ";
case 1:
{
if (links.containsKey(Integer.valueOf(Directions.EAST)))
{
if (links.containsKey(Integer.valueOf(Directions.WEST)))
return "<" + roomChar + ">";
return " " + roomChar + ">";
}
else
if (links.containsKey(Integer.valueOf(Directions.WEST)))
return "<" + roomChar + " ";
return " " + roomChar + " ";
}
case 2:
if (links.containsKey(Integer.valueOf(Directions.SOUTH)))
return " v ";
return " ";
default:
return " ";
}
} | 8 |
private void lisaaButtonActionPerformed(ActionEvent evt) {
if (!kurssiField.getText().isEmpty()) {
if (kurssiField.getText().length() > 50) {
JOptionPane.showMessageDialog(this, "Kurssin nimi voi olla enintään 50 merkkiä pitkä.", "Virhe", JOptionPane.ERROR_MESSAGE);
} else {
Kurssi uusiKurssi = new Kurssi(kurssiField.getText());
if (Database.lisaaKurssi(uusiKurssi)) {
kurssiField.setText("");
}
}
} else if (kurssiField.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Kurssin nimi ei voi olla tyhjä.", "Virhe", JOptionPane.ERROR_MESSAGE);
} else {
String message = "Tapahtui vakava tuntematon virhe!\n" + "Ottakaa välittömästi yhteys tirehtööriin!\n" + "Sähköposti: Henry.Heikkinen@majavapaja.fi";
JOptionPane.showMessageDialog(this, message, "Error #???", JOptionPane.ERROR_MESSAGE);
}
} | 4 |
@Test
public void testPermutate1() {
int[] testExpansionTabel = new int[]{
1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30,
31, 32, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16
};
byte[] block = new byte[]{1, 2, 3, 4};
byte[] expected = new byte[]{1, 2, 3, 4, 1, 2};
byte[] result = ByteHelper.permutate(block, testExpansionTabel);
for (int i = 0; i < block.length; i++) {
assertEquals(result[i], expected[i]);
}
} | 1 |
public synchronized void join(RMIClientInterface n) throws RemoteException {
threadList.add(n);
for (Iterator i = threadList.iterator(); i.hasNext();) {
RMIClientInterface client = (RMIClientInterface) i.next();
client.joinMessage(n.getName());
}
if (topic != null) {
System.out.println(topic);
n.topicMessage("", topic);
}
if (telePointerMode.equals("Single")) {
if (point != null) {
n.pointerMessage("", point);
if (height != 0)
n.pointerHeight("", height);
if (width != 0)
n.pointerWidth("", width);
}
} else if (telePointerMode.equals("Multiple")) {
if (!telePointerList.isEmpty()) {
n.pointerMultipleMessage("", telePointerList);
}
}
} | 8 |
public static RecipeBook matcherNOBT(RecipeBook k, Recipe lijst) {
RecipeBook a = new RecipeBook();
LNode boek = k.first();
while (boek != null) {
boolean res = true;
RNode pijl = boek.getElement().first();
while (pijl != null && res==true) {
res = lijst.bevatGeq(pijl.getElement());
pijl = pijl.getNext();
}
if (res==true) {
a.add(boek.getElement());
}
boek = boek.getNext();
}
return a;
} | 4 |
public int lookup(String key) {
int index = 0;
int base = 1; // base at index 0 should be 1
int keyLength = key.length();
for(int i = 0; i < keyLength; i++) {
int previous = index;
index = index + base + key.charAt(i);
if(index > baseBuffer.limit()) { // Too long
return -1;
}
base = baseBuffer.get(index);
if (base == 0 ) { // Didn't find match
return -1;
}
if(checkBuffer.get(index) != previous){ // check doesn't match
return -1;
}
if(base >= TAIL_OFFSET) { // If base is bigger than TAIL_OFFSET, start processing "tail"
return matchTail(base, index, key.substring(i + 1));
}
}
// If we reach at the end of input keyword, check if it is complete match by looking for following terminating character
int endIndex = index + base + TERMINATING_CHARACTER;
return checkBuffer.get(endIndex) == index ? index : 0;
} | 6 |
private static ObjectType parseArray(String sig, Cursor c) throws BadBytecode {
int dim = 1;
while (sig.charAt(++c.position) == '[')
dim++;
return new ArrayType(dim, parseType(sig, c));
} | 1 |
public BiNode addChild(BiNode child){
if(this.value_type.compareTo(child.value_type) < 0){
child.father = this.father;
return child.addChild(this);
}else{
if(children[0] == null){
children[0] = child;
child.father = this;
}else
if(children[1] == null){
children[1] = child;
child.father = this;
}else{
if(this.value_type.compareTo(child.value_type) == 0){
child.addChild(children[1]);
child.father = this;
children[1] = child;
}else{
children[1] = children[1].addChild(child);
}
//TODO реалізувати складання оптимальної суперпозиції
odd ^= 1;
}
return this;
}
} | 4 |
public static String get(String s) throws IOException {
URL url = new URL("http://oberien.net/download/Oberien/" + s);
InputStream is = url.openStream();
int i;
StringBuffer sb = new StringBuffer();
while ((i = is.read()) != -1) {
char c = (char) i;
sb.append(c);
}
is.close();
return sb.toString();
} | 1 |
public void setFovX(float fovX) {
Radar.fovX = fovX;
} | 0 |
public void updateAsScheduled(int numUpdates) {
if (destroyed()) {
I.say(this+" IS DESTROYED! SHOULD NOT BE ON SCHEDULE!") ;
this.setAsDestroyed() ;
}
structure.updateStructure(numUpdates) ;
if (! structure.needsSalvage()) {
if (base != null && numUpdates % 10 == 0) updatePaving(true) ;
personnel.updatePersonnel(numUpdates) ;
}
if (structure.intact()) {
stocks.updateStocks(numUpdates) ;
}
} | 5 |
public ContentObject getObject(ContentType type, String id) {
if (type instanceof RegionType)
return getRegion(id);
else if (type instanceof LowLevelTextType) { //Text lines, word, glyph
for (int i=0; i<regions.size(); i++) {
Region reg = regions.getAt(i);
if (reg instanceof LowLevelTextContainer) {
ContentObjectRelation rel = getLowLevelTextObject((LowLevelTextContainer)reg, (LowLevelTextType)type, id);
if (rel != null)
return rel.getObject2();
}
}
}
return null;
} | 5 |
@Override
public void mouseDragged(MouseEvent evt) {
int mouseX = evt.getX();
int mouseY = evt.getY();
int row = FindTileRow(mouseY);
int col = FindTileCol(mouseX);
Point p = new Point(row, col);
if (p != lastTilePressed) {
if (row != -1 && col != -1) {
lastTilePressed = p;
ChangeTile(row, col);
repaint();
}
}
} | 3 |
public static void populateEmployeeInfo(ManageEmployeePage emp,String username){
Employee employee=new Employee();
employee.setUsername(username);
employee=(Employee)DatabaseProcess.getRow(employee);
Gui.setCurrentEmployee(employee);
emp.getDobText().setText(employee.getDob().toString());
emp.getAddressText().setText((employee.getAddress()));
emp.getPhoneText().setText(employee.getPhone());
emp.getNameText().setText(employee.getName());
emp.getPositionText().setText(employee.getPosition());
Schedule s=new Schedule();
s.setUsername(username);
int year = 113;
int day = 22;
int month = 04;
Date work = new Date(year,month,day);
s.setWorkDay(work);
if(DatabaseProcess.getRow(s) != null){
s=(Schedule)DatabaseProcess.getRow(s);
String str = s.getHourRate().toString();
String str2 = "$"+str;
emp.getSalaryText().setText(str2);
Time t = s.getFrom();
Time t2 = s.getTo();
String str3 = t + " - " + t2;
emp.getSchedule().setText(str3);}
else{
emp.getSalaryText().setText("");
emp.getSchedule().setText("");
}
} | 1 |
public static int integerParseInt(String data) throws Exception{
int result =0; //返回值
int initType = 1; //用来标示正和负
int i=0; //遍历字符的首
if(null==data)
throw new Exception("字符串转化异常");
if('-'==data.charAt(0)){
initType=-1;
i++;
}else if(0<=data.charAt(0)||9>=data.charAt(0))
initType=1;
else
throw new Exception("字符串转化异常");
while(i<data.length()){
char getOneData = data.charAt(i);
if('0'>getOneData||'9'<getOneData)
throw new Exception("字符串转化异常");
if(initType==-1)
result+=(getOneData-48)*(Math.pow(10,data.length()-i-1));
else
result+=(getOneData-48)*(Math.pow(10,data.length()-i-1));
i++;
}
return result*initType;
} | 8 |
public void start() {
if (graphics == null) {
throw new SystemMissingException("The game's graphics system has not yet been initialized");
}
if (scenemanager == null) {
throw new SystemMissingException("The game's scene management system has not yet been initialized");
}
if (input == null) {
throw new SystemMissingException("The game's input monitoring system has not yet been initialized");
}
if (scenemanager.size() <= 0) {
throw new SystemMissingException("The game requires at least one scene to run");
}
timer.start();
graphics.getWindow().setVisible(true);
} | 4 |
Module addSubModule(Module module) {
if (null == module) {
return this;
}
if (null == this.subModules) {
this.subModules = new HashSet<>();
}
this.subModules.add(module);
return this;
} | 2 |
public boolean saveChunks(boolean par1, IProgressUpdate par2IProgressUpdate)
{
int i = 0;
for (Iterator iterator = field_73245_g.iterator(); iterator.hasNext();)
{
Chunk chunk = (Chunk)iterator.next();
if (par1)
{
func_73243_a(chunk);
}
if (chunk.needsSaving(par1))
{
func_73242_b(chunk);
chunk.isModified = false;
if (++i == 24 && !par1)
{
return false;
}
}
}
if (par1)
{
if (field_73247_e == null)
{
return true;
}
field_73247_e.saveExtraData();
}
return true;
} | 7 |
public int newLocal(final Type type) {
Object t;
switch (type.getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.BYTE:
case Type.SHORT:
case Type.INT:
t = Opcodes.INTEGER;
break;
case Type.FLOAT:
t = Opcodes.FLOAT;
break;
case Type.LONG:
t = Opcodes.LONG;
break;
case Type.DOUBLE:
t = Opcodes.DOUBLE;
break;
case Type.ARRAY:
t = type.getDescriptor();
break;
// case Type.OBJECT:
default:
t = type.getInternalName();
break;
}
int local = nextLocal;
nextLocal += type.getSize();
setLocalType(local, type);
setFrameLocal(local, t);
return local;
} | 9 |
public int[] get_circles_years()
{
if(circles.isEmpty())
return null;
int years[]=new int[circles.size()];
int next_year_index=0;
boolean is_exist=false;
for(int i=0; i<circles.size(); i++)
{
int new_year=circles.get(i).get_circle_year(); //get year
for(int j=0; j<next_year_index; j++) //check if year
{
if(new_year==years[j]) //if year already exist
{
is_exist=true;
break;
}
}
if(is_exist==false)
{
years[next_year_index]=new_year;
next_year_index++;
}
else
is_exist=false;
}
int new_years[]=new int[next_year_index];
for(int i=0; i< next_year_index; i++)
new_years[i]=years[i];
Arrays.sort(new_years);
return new_years;
} | 6 |
@Override
public void executeTask() {
try {
fs = new ServerSocket(ClientGUITask.port);
} catch (Exception e) {
System.out.println("problem with initial file sender setup");
}
try {
do {
while (!ClientGUITask.clientSend)
;
try {
if (ClientGUITask.port != fs.getLocalPort()) {
fs.close();
System.out.println((new StringBuilder())
.append("Opened port ")
.append(ClientGUITask.port)
.append(" for sending files").toString());
fs = new ServerSocket(ClientGUITask.port);
}
fs.setSoTimeout(0x186a0);
ClientSenderTask fileserver = new ClientSenderTask(
fs.accept());
TaskManager.DoTask(fileserver);
} catch (Exception e) {
System.out.println((new StringBuilder())
.append("Client sender handler : ").append(e)
.toString());
System.out
.println("(handler times out to allow port change)");
}
} while (true);
} catch (Exception e) {
System.out.println("But this should be impossible!");
}
ClientGUITask.clientSenderExists = false;
} | 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.