method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
5223775b-412f-4815-bf98-875deede91b1 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_UNWORNONLY);
if(target==null)
return false;
if(mob.isMine(target))
{
mob.tell(L("You'd better put it down first."));
return false;
}
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(L("@x1 is already HUGE!",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>, incanting.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final Ability A=target.fetchEffect("Spell_Shrink");
if((A!=null)&&(A.canBeUninvoked()))
A.unInvoke();
else
{
mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> grow(s) to an enormous size!"));
beneficialAffect(mob,target,asLevel,100);
}
}
}
else
beneficialVisualFizzle(mob,target,L("<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>, incanting but nothing happens."));
// return whether it worked
return success;
} |
77cc8781-b941-40dd-98e6-f6b693c2c967 | 7 | public void Moverse() {
if (movimiento == false) {
// ESCALADA
getRobot1().inicializarMapa(getAnchoEntorno(), getAltoEntorno());
while (robot1.getPuntoActual().equals(robot1.getPuntoDestino()) == false
&& robot1.getPararMovimiento() == false) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
robot1.setPuntoAnterior(robot1.getPuntoActual());
DibujoEntorno[(int) robot1.getPuntoAnterior().getX()][(int) robot1
.getPuntoAnterior().getY()] = 0;
actualizarSensores();
robot1.seleccionMovimiento();
DibujoEntorno[(int) robot1.getPuntoActual().getX()][(int) robot1
.getPuntoActual().getY()] = 2;
}
} else {
// AESTRELLA
getRobot1().inicializarMapaDistancias(DibujoEntorno, getAnchoEntorno(), getAltoEntorno());
while (robot1.getPuntoActual().equals(robot1.getPuntoDestino()) == false
&& robot1.getPararMovimiento() == false) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
robot1.setPuntoAnterior(robot1.getPuntoActual());
DibujoEntorno[(int) robot1.getPuntoAnterior().getX()][(int) robot1
.getPuntoAnterior().getY()] = 0;
//METODOS DEL ALGORITMO AESTRELLA
getRobot1().aEstrella();
DibujoEntorno[(int) robot1.getPuntoActual().getX()][(int) robot1
.getPuntoActual().getY()] = 2;
}
}
// System.out.println("Robot parado");
} |
447a3d32-25ae-40ee-8cab-0d47bc9be247 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> hold(s) <T-NAMESELF> and cast(s) a spell.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
int level=CMLib.utensils().disenchantItem(target);
if(target.amDestroyed())
mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> fades away!"));
else
if(level>-999)
{
mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> fades and becomes dull!"));
if((target.basePhyStats().disposition()&PhyStats.IS_BONUS)==PhyStats.IS_BONUS)
target.basePhyStats().setDisposition(target.basePhyStats().disposition()-PhyStats.IS_BONUS);
if(level<=0)
level=1;
target.basePhyStats().setLevel(level);
target.recoverPhyStats();
}
else
mob.tell(L("@x1 doesn't seem to be enchanted.",target.name(mob)));
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> hold(s) <T-NAMESELF> and whisper(s), but fail(s) to cast a spell."));
// return whether it worked
return success;
} |
06a9060c-dce0-4cb5-8456-e653dbbf14cd | 3 | private Sign findSign(Inventory inventory) {
if (inventories.containsValue(inventory)) {
for (Map.Entry<Block, Inventory> entry : inventories.entrySet()) {
if (entry.getValue().equals(inventory)) {
Block block = entry.getKey();
return (Sign) block.getState();
}
}
}
return null;
} |
f6646ad0-5f38-4e23-b829-c6ab01ff3e54 | 1 | public void visit_fsub(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} |
83c892d7-774d-49db-8b6f-7bc34f9790fb | 6 | public final static URL getMbReleasesOfArtist(String artistID)
throws MusicbrainzUrlException {
if(artistID == null || artistID.equals(""))
throw new MusicbrainzUrlException("The artistID is null or empty");
URL url= null;
URI uri= null;
try {
//lookup of musicbrainz
uri= new URI("http","www.musicbrainz.org",
"/ws/2/release-group",
"artist="+artistID+"&type=album|ep",
null);
if(uri != null)
url= uri.toURL();
} catch (URISyntaxException e) {
throw new MusicbrainzUrlException("URISyntaxException "+e.getMessage(), e);
} catch (MalformedURLException e) {
throw new MusicbrainzUrlException("MalformedURLException "+e.getMessage(), e);
} catch (Exception e) {
throw new MusicbrainzUrlException("Exception "+e.getMessage(), e);
}
return url;
} |
85e6a1ee-97b3-47d8-84b0-753f9e2c7ced | 8 | public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectIntMap ) ) {
return false;
}
TObjectIntMap that = ( TObjectIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectIntIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
int value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
} |
5923a332-f5f7-4ca0-8a2f-7104da9f96b7 | 7 | private static boolean inDB(String nameText) throws Exception {
String[] spl1 = nameText.split(",\\s", 2);
for(String s : spl1) {
if(s.matches("^[0-9]+$")) {
System.out.println("Nur Nummer!? -> " + nameText);
return false;
}
}
String name = spl1[0].replaceAll("[.,;:!?]", "");
String compName = "";
if(spl1.length > 1) {
compName = spl1[1].replaceAll("[,;:!?]", "");
compName += " ";
}
compName += name;
int aid = createArtist(compName);
String[] names = name.split("\\s");
createName(names[0], aid);
if(names.length > 1) {
for(int i = 1; i < names.length; i++) {
String n = names[i].replaceAll("[.,;:!?]", "");
createMoreName(n, aid, i-1);
}
}
if(spl1.length > 1) {
String[] mNames = spl1[1].split("\\s");
for(int i = 0; i < mNames.length; i++) {
String n = mNames[i].replaceAll("[.,;:!?]", "");
createMoreName(n, aid, i + (names.length - 1));
}
}
return true;
} |
27d31f7a-9a87-4c54-a180-ae11557adeec | 5 | private long removeRefContactNym(long lIndex) {
//
// loop through the elements in the actual container, in order to find the one
// at lIndex. Once it is found, then loop through the reference list and remove
// the corresponding reference for that element.
//
ContactNym refActualElement = GetContactNym(lIndex);
if (refActualElement == null)
return lIndex; // oh well.
// Loop through the reference list and remove the corresponding reference
// for the specified element.
//
for(int intIndex = 0; intIndex < elementList.size(); intIndex++)
{
Object theObject = elementList.get(intIndex);
if ((theObject == null) || !(theObject instanceof ContactNym))
continue;
ContactNym tempRef = (ContactNym)(theObject);
if ((ContactNym.getCPtr(tempRef) == ContactNym.getCPtr(refActualElement)))
{
elementList.remove(tempRef);
break;
}
}
return lIndex;
} |
be6073d0-f0a6-4186-9815-f76255b197f6 | 2 | static int rank (int[] N, int key) {
if (N.length == 0 || N.equals(null)) {
throw new IllegalArgumentException("Cannot process empty or null array");
}
int iterative = rank_iterative(N, key);
int recursive = rank_recursive(N, key, N.length - 1, 0);
assert iterative == recursive;
return iterative;
} |
ebd3deeb-32bf-4c9b-95f1-8487a412d871 | 7 | @Override
public void onBrowserEvent(Event event) {
// If we're not yet dragging, only trigger mouse events if the event occurs
// in the caption wrapper
switch (event.getTypeInt()) {
case Event.ONMOUSEDOWN:
case Event.ONMOUSEUP:
case Event.ONMOUSEMOVE:
case Event.ONMOUSEOVER:
case Event.ONMOUSEOUT:
if (!m_dragging && !isCaptionEvent(event)) {
return;
}
break;
default:
}
super.onBrowserEvent(event);
} |
4a840e9c-70e1-41df-bc1f-8136bafc3d7f | 7 | public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} |
d5fd348e-848c-4430-9ef5-46cb5773cb71 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Uf)) {
return false;
}
Uf other = (Uf) object;
if ((this.coduf == null && other.coduf != null) || (this.coduf != null && !this.coduf.equals(other.coduf))) {
return false;
}
return true;
} |
4b433c6f-10a4-40e2-80d0-1a0d51d0c1d5 | 1 | public Type getSuperType() {
return (this == tObject) ? tObject : tRange(tObject, this);
} |
72789e81-8b3e-49cb-a784-d398cd0a9308 | 5 | private static void appendJSONPair(StringBuilder json, String key, String value)
throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
} |
df67011a-3172-46b5-812e-20e962971852 | 4 | public void loadPM(long playerName, int world) {
//synchronized(c) {
if(c.getOutStream() != null && c != null) {
if(world != 0) {
world += 9;
} else if(!Config.WORLD_LIST_FIX) {
world += 1;
}
c.getOutStream().createFrame(50);
c.getOutStream().writeQWord(playerName);
c.getOutStream().writeByte(world);
c.flushOutStream();
} |
91b2b35b-40c5-4627-aabc-a1ce5a66f3ef | 8 | public void moveEntityWithHeading(float par1, float par2)
{
if (this.isInWater())
{
this.moveFlying(par1, par2, 0.02F);
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.800000011920929D;
this.motionY *= 0.800000011920929D;
this.motionZ *= 0.800000011920929D;
}
else if (this.handleLavaMovement())
{
this.moveFlying(par1, par2, 0.02F);
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.5D;
this.motionY *= 0.5D;
this.motionZ *= 0.5D;
}
else
{
float var3 = 0.91F;
if (this.onGround)
{
var3 = 0.54600006F;
int var4 = this.worldObj.getBlockId(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.boundingBox.minY) - 1, MathHelper.floor_double(this.posZ));
if (var4 > 0)
{
var3 = Block.blocksList[var4].slipperiness * 0.91F;
}
}
float var8 = 0.16277136F / (var3 * var3 * var3);
this.moveFlying(par1, par2, this.onGround ? 0.1F * var8 : 0.02F);
var3 = 0.91F;
if (this.onGround)
{
var3 = 0.54600006F;
int var5 = this.worldObj.getBlockId(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.boundingBox.minY) - 1, MathHelper.floor_double(this.posZ));
if (var5 > 0)
{
var3 = Block.blocksList[var5].slipperiness * 0.91F;
}
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= (double)var3;
this.motionY *= (double)var3;
this.motionZ *= (double)var3;
}
this.field_705_Q = this.field_704_R;
double var10 = this.posX - this.prevPosX;
double var9 = this.posZ - this.prevPosZ;
float var7 = MathHelper.sqrt_double(var10 * var10 + var9 * var9) * 4.0F;
if (var7 > 1.0F)
{
var7 = 1.0F;
}
this.field_704_R += (var7 - this.field_704_R) * 0.4F;
this.field_703_S += this.field_704_R;
} |
fea16fbf-76fd-4c0b-9de1-991319b9f3ad | 5 | public static void sendFileReq
(
Socket sckIn
, String strId
, EzimFileOut efoIn
)
throws Exception
{
if
(
efoIn != null
&& strId != null && strId.length() > 0
)
{
EzimDtxSemantics.initByteArrays();
long lSize = 0;
FileInputStream fisTmp = null;
try
{
OutputStream osTmp = sckIn.getOutputStream();
lSize = efoIn.getFile().length();
fisTmp = new FileInputStream(efoIn.getFile());
efoIn.setSize(lSize);
// create necessary header fields
Hashtable<String, String> htTmp
= new Hashtable<String, String>();
htTmp.put
(
EzimDtxSemantics.HDR_CTYPE
, EzimDtxFileSemantics.CTYPE_FILEREQ
);
htTmp.put
(
EzimDtxSemantics.HDR_CLEN
, "0"
);
htTmp.put
(
EzimDtxFileSemantics.HDR_FILEREQID
, strId
);
htTmp.put
(
EzimDtxFileSemantics.HDR_FILENAME
, efoIn.getFile().getName()
);
htTmp.put
(
EzimDtxFileSemantics.HDR_FILESIZE
, Long.toString(lSize)
);
// output header in bytes
EzimDtxSemantics.sendHeaderBytes(sckIn, htTmp);
// make sure everything is sent
osTmp.flush();
}
finally
{
try
{
if (fisTmp != null) fisTmp.close();
}
catch(Exception e)
{
EzimLogger.getInstance().severe(e.getMessage(), e);
}
}
}
} |
17047df3-620e-44ab-b8aa-169f5493b88d | 4 | public String encriptar(String textoParaEncriptar, String metodoEncriptacion) {
String encriptadoString = "";
try {
if (!textoParaEncriptar.equalsIgnoreCase("")) {//Pasamos el password obtenido del caja de password
MessageDigest md = MessageDigest.getInstance(metodoEncriptacion);
md.reset();
md.update(textoParaEncriptar.getBytes());//Pasamos el psw a bytes
byte bytes[] = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xff & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);//Generamos el sb que se encuentra en HEX
}
encriptadoString = sb.toString();
}
} catch (Exception e) {
System.out.println("----------Desde Seguridad.java-------------");
System.out.println("La sentencia fracasó por:\n\n" + e.toString());
System.out.println("----------Desde Seguridad.java-------------");
e.printStackTrace();
}
return encriptadoString;
} |
d3d3ddcd-7c1e-4edc-af8b-8d721b012f71 | 7 | @Override
public MethodResult ExecuteNonQuery(String rawSql) {
MethodResult res = new MethodResult();
Connection conn = null;
try {
if ((conn = this.getConnection()) != null) {
Statement statement = conn.createStatement();
if (DEBUG) {
qlog.log(rawSql);
}
statement.executeUpdate(rawSql);
if (rawSql.toLowerCase().contains("insert")) {
res.addValue("id", this.getLastInsertRowId(statement));
}
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
res.setException(SQL_EXCEPTION);
} catch (NullPointerException e) {
e.printStackTrace();
res.setException(ARGUMENT_EXCEPTION);
} catch (Exception e) {
e.printStackTrace();
res.setException(INTERNAL_EXCEPTION);
} finally {
MethodResult closeRes = closeConnection(conn);
if (!closeRes.isSuccessful()) {
res.setException(closeRes.getException());
}
}
return res;
} |
7854aa54-a6ad-4162-b1d1-1f3a70040b0e | 0 | @Override
public String toString(){
return "" + this.armorItem.toString();
} |
5fb2cd84-57b9-41b0-aab3-91aed7778cb7 | 5 | public void characters(char ch[], int start, int length)
throws SAXException {
if(inHits) {
try {
hits = Integer.parseInt(new String(ch, start, length));
} catch (NumberFormatException e) {
System.err.println("Breakout: Could not parse level_width");
System.exit(1);
}
}
if(inScore) {
try {
score = Integer.parseInt(new String(ch, start, length));
} catch (NumberFormatException e) {
System.err.println("Breakout: Could not parse level_width");
System.exit(1);
}
}
if(inColor) {
color = new String(ch, start, length);
}
} |
076c5343-d030-4213-9cd0-ad5e9cf1f0cc | 9 | public boolean isAutarkic(IGroup g) {
if (g.getGroupType() == GroupType.PACKAGE) {
return false;
}
if (g.getGroupType() == GroupType.INNER_ACTIVITY) {
return true;
}
if (g.getGroupType() == GroupType.CONCURRENT_ACTIVITY) {
return true;
}
if (g.getGroupType() == GroupType.CONCURRENT_STATE) {
return true;
}
if (getChildrenGroups(g).size() > 0) {
return false;
}
for (Link link : getLinks()) {
if (EntityUtils.isPureInnerLink3(g, link) == false) {
return false;
}
}
for (ILeaf leaf : g.getLeafsDirect()) {
if (leaf.getEntityPosition() != EntityPosition.NORMAL) {
return false;
}
}
return true;
} |
c3557edc-4a23-44c9-bd32-fb8ff590d68f | 7 | public ShopItem getItemByName(String... names) {
if (names != null && names.length > 0)
for (ShopItem nextItem : items) {
String name = nextItem.getName();
if (!isStringValid(name)){
continue;
}
else
for (String nextName : names)
if (isStringValid(nextName) && name.equalsIgnoreCase(nextName))
return nextItem;
}
return null;
} |
84ec2a76-919d-4a79-b5de-6d680a012334 | 1 | public static synchronized Singleton_2 getInstance() {
// 这个方法比上面有所改进
if (instance == null) {
// 实例化
instance = new Singleton_2();
}
return instance;
} |
1a44db68-011b-43a7-b40e-7f0f4592590e | 3 | @Override
public ArrayList<Map<String, String>> getUnexpiredAuctions() {
ArrayList<Map<String,String>> auctions = new ArrayList<Map<String,String>>();
TypedQuery<Auction> unexpiredAuctionsQuery = emgr.createNamedQuery(
"Auction.findAllUnexpiredAuctions", Auction.class);
unexpiredAuctionsQuery.setParameter("auctionExpired", 0);
List<Auction> obtainedAuctions = (List<Auction>) unexpiredAuctionsQuery.getResultList();
for (int i = 0; i < obtainedAuctions.size(); i++) {
Map<String, String> tempMap = new HashMap<String,String>();
System.out.println("\n -------------auct ID " + obtainedAuctions.get(i).getAuctionId() + "-------------");
// Obtain the current date and time
Calendar currentDateCalendar = Calendar.getInstance();
System.out.println("CURRENT DATE " + currentDateCalendar.getTime().toString());
// Obtain the end time and date
Time endTime = obtainedAuctions.get(i).getEndTime();
System.out.println("END TIME = " + endTime.toString());
Calendar endDateCal = new GregorianCalendar();
endDateCal.setTime(obtainedAuctions.get(i).getEndDate());
System.out.println("PRE- END DATE " + endDateCal.getTime().toString());
// Assign the time to the end date calendar
String[] splitEndTime = endTime.toString().split(":");
endDateCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(splitEndTime[0]));
endDateCal.set(Calendar.MINUTE, Integer.parseInt(splitEndTime[1]));
endDateCal.set(Calendar.SECOND, Integer.parseInt(splitEndTime[2]));
System.out.println("END DATE " + endDateCal.getTime().toString());
if (currentDateCalendar.after(endDateCal)) {
System.out.println("EXPIRED!!!!!!!!!!!!!!!!!");
// Set the auction as expired.
Auction auction = emgr.find(Auction.class, obtainedAuctions.get(i).getAuctionId());
short expired = 1;
auction.setAuctionExpired(expired);
emgr.persist(auction);
} else {
System.out.println("Not yet expired.");
int daysBetween = Days.daysBetween(new DateTime(currentDateCalendar.getTime()), new DateTime(endDateCal.getTime())).getDays();
// Obtain the time difference and compensate for 1 hour (since the calendar starts at 01:00 and not 00:00)
Date dateDiff = new Date(endDateCal.getTime().getTime() - currentDateCalendar.getTime().getTime() - 3600000);
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss");
System.out.println("Duration: " + timeFormat.format(dateDiff));
tempMap.put("auctionName", obtainedAuctions.get(i).getAuctionName());
tempMap.put("auctionDescription", obtainedAuctions.get(i).getAuctionDescription());
tempMap.put("auctionId", Integer.toString(obtainedAuctions.get(i).getAuctionId()));
tempMap.put("auctionDaysLeft", Integer.toString(daysBetween));
tempMap.put("auctionTimeLeft", timeFormat.format(dateDiff));
TypedQuery<Bid> bidQuery = emgr.createNamedQuery("Bid.findBidByAuction", Bid.class);
bidQuery.setParameter("auctionId", obtainedAuctions.get(i).getAuctionId());
try {
Bid obtainedBid = bidQuery.getSingleResult();
int bidConsequence = obtainedBid.getBidConsequence();
double currentHighestBid = obtainedBid.getCurrentHighest();
tempMap.put("auctionBidConsequence", Integer.toString(bidConsequence));
tempMap.put("auctionHighestBid", Double.toString(currentHighestBid));
auctions.add(tempMap);
} catch(NoResultException e) {
System.out.println("Catched NoResultException - " + e.getMessage());
tempMap.put("auctionBidConsequence", "0");
tempMap.put("auctionHighestBid", obtainedAuctions.get(i).getStartPrice());
auctions.add(tempMap);
continue;
}
} // End of else (not expired)
} // End loop for obtainedAuctions
return auctions;
} // End of getUnexpiredAuctions |
f179a202-2f11-4f2f-9d1e-a31bd8116392 | 6 | public boolean checkMainDiagonal() {
//upper left to lower right (main diagonal)
for (int col = 0; col < numColumns - 3; col++) {
for (int row = 0; row < numRows - 3; row++) {
int curr = gameGrid[col][row].getState();
if (curr > 0
&& curr == gameGrid[col + 1][row + 1].getState() //increment the column
&& curr == gameGrid[col + 2][row + 2].getState() //and the row by equal
&& curr == gameGrid[col + 3][row + 3].getState()) //amounts and get the state
{
winX = col;
winY = row;
game.setGameIsOver(true);
return true;
}
}
}
return false;
} |
f86e33c7-ae84-4975-8fe1-0b8c93111470 | 3 | public UserScreen() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(new Rectangle(0, 0, 1365, 799));
getContentPane().setFont(new Font("Times New Roman", Font.PLAIN, 12));
getContentPane().setForeground(new Color(255, 255, 204));
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setForeground(new Color(255, 255, 153));
panel.setBounds(10, 11, 321, 213);
getContentPane().add(panel);
panel.setLayout(null);
JLabel lblPassword = new JLabel("Password");
lblPassword.setFont(new Font("Segoe Print", Font.BOLD, 12));
lblPassword.setBounds(10, 36, 101, 16);
panel.add(lblPassword);
JLabel lblUserName = new JLabel("User name");
lblUserName.setFont(new Font("Segoe Print", Font.BOLD, 12));
lblUserName.setBounds(10, 11, 85, 14);
panel.add(lblUserName);
passwordField = new JPasswordField();
passwordField.setBounds(105, 35, 101, 20);
panel.add(passwordField);
userName = new JTextField();
userName.setBounds(105, 5, 101, 20);
panel.add(userName);
userName.setColumns(10);
JButton butonLogin = new JButton(" Login");
butonLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
UserService us=new UserService();
User user=us.login(userName.getText(), passwordField.getText());
if(user!=null){
if(user.getType()==0){
//0 is admin
AdminScreen adm=new AdminScreen();
adm.setVisible(true);
closeWindow();
}else if(user.getType()==1){
EmployeeScreen emp=new EmployeeScreen();
emp.setVisible(true);
closeWindow();
}
}else {
JOptionPane.showMessageDialog(null, "The user doesn`t exist!");
}
}
});
butonLogin.setBounds(10, 80, 89, 23);
panel.add(butonLogin);
setFont(new Font("Cooper Black", Font.PLAIN, 12));
setTitle("Hello User!");
} |
c2a978f5-d15b-4974-bc3b-325554c7a224 | 5 | public LinkCache(String directory) throws IOException {
if (directory == null) {
throw new IllegalArgumentException("directory is null.");
}
File file = new File(directory);
if (!(file.exists() && file.isDirectory() && file.canWrite() && file.canRead())) {
throw new IOException("Directory must exist and have read and write access.");
}
mDirectory = file;
} |
9887fa89-b0aa-4afa-80b7-1f2eb1c5c31a | 8 | public void removegroup (int i0, int j0)
// completely remove a group (at end of game, before count)
// note all removals
{
if (Pos.haschildren()) return;
if (P.color(i0, j0) == 0) return;
Action a;
P.markgroup(i0, j0);
int i, j;
int c = P.color(i0, j0);
Node n = Pos.node();
if (n.contains("B") || n.contains("W")) n = newnode();
for (i = 0; i < S; i++)
for (j = 0; j < S; j++)
{
if (P.marked(i, j))
{
a = new Action("AE", Field.string(i, j));
n
.addchange(new Change(i, j, P.color(i, j), P.number(i,
j)));
n.expandaction(a);
if (P.color(i, j) > 0)
{
n.Pb++;
Pb++;
}
else
{
n.Pw++;
Pw++;
}
P.color(i, j, 0);
update(i, j);
}
}
copy();
} |
9cb3f005-6838-4f92-8813-7c98109cd481 | 2 | private static String convertToString(String[] data, char identifier) {
StringBuilder sb = new StringBuilder();
sb.append(identifier + "" + DATA_DIVIDER);
for(int i = 0; i < data.length; i++) {
sb.append(data[i]);
//No divider on last data value
if(i < data.length - 1) {
sb.append(DATA_DIVIDER);
}
}
return sb.toString();
} |
4579a188-b2a8-4963-921f-3f6fc0968635 | 5 | private void computeAnswer() {
long ans = getSumOfKthPowers(N);
int coeff;//coeff of current subset contribution in inclusion exclusion sum
for (int mask = 1; mask < (1 << primeCount); mask++) {
long x = 1l;
coeff = 1;
for (int i = 0; i < primeCount; i++) {
if (((1 << i) & mask) > 0) {
x = x * primes[i];
coeff *= -1;
}
}
ans = ans + coeff * mul(pow(x, K), getSumOfKthPowers(N / x));
if (ans < 0) ans += mod;
if (ans >= mod) ans -= mod;
}
System.out.println(ans);
} |
c5fc6bc5-b754-4a56-bfb5-15c33a6509ae | 6 | private void initiate(){
System.out.println("Initializig SIB");
OntModel model = ModelFactory.createOntologyModel();
InputStream in = this.getClass().getResourceAsStream(this.ontologyFile);
if (in == null) {
throw new IllegalArgumentException(
"File: " + this.ontologyFile + " not found"
);
}
// read the RDF/XML file
System.out.println("Reading " + this.ontologyFile);
model.read(in, null);
System.out.println("Connecting to " + Config.SIB_NAME + " @ " + Config.SIB_HOST + ":" + Config.SIB_PORT);
this.kp = new KPICore(Config.SIB_HOST, Config.SIB_PORT, Config.SIB_NAME);
this.kp.join();
if(removeOWL){
if(confirm()){
System.out.println("Removing RPSLS triples from SIB");
this.kp.update_sparql("DELETE { ?a ?b ?c } WHERE { ?a ?b ?c FILTER regex ( str( ?a ) , \"^http://rpsls.games.unibo.it/Ontology.owl\" ) }");
System.out.println("RPSLS triples removed correctly");
}
}
if(loadOWL){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
model.write(baos);
System.out.println("Writing " + this.ontologyFile + "to SIB");
this.kp.insert_rdf_xml(baos.toString());
System.out.println("RPSLS ontology wrote correctly");
}
if(clearSIB){
if(confirm()){
System.out.println("Removing all triples from SIB");
this.kp.remove(null, null, null, "uri", "uri");
System.out.println("SIB clear");
}
}
System.exit(0);
} |
e3d9593b-3c2c-410c-8716-6b3a6555bdd7 | 1 | public void config(String name, String remote_addr, int listen_on, String log_dir, Properties[] filter_configs)
{
try
{
final Route route = new Route(name, listen_on, remote_addr, new File(working_directory, log_dir), filter_configs);
synchronized (routes)
{
routes.add(route);
}
new Thread(route, name).start();
info(name + " route started.");
}
catch (IOException e)
{
error("route creation failed for " + name + e.getMessage());
System.exit(1);
}
} |
852dbb4f-c79b-4783-9677-2cc66033d9b0 | 0 | public void go() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Being child = being.split();
Supervisor.getSupervisor().registerBeing(child);
} |
8b31b61c-d3b9-496c-8a61-fc0e04411042 | 5 | public boolean checkUser(String login, String password) {
result = "?";
ArrayList<User> users;
try {
users = DataBase.getInstance().getUsers();
for (Iterator it = users.iterator(); it.hasNext();) {
User user = (User) it.next();
if (user.getLogin().equals(login) && user.getPassword().equals(password)) {
result = "OK";
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, e);
}
if (this.result.equals("OK")) {
return true;
} else {
return false;
}
} |
443e9849-15f7-4858-a3fa-eac1465b5a5b | 7 | public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} |
b329b606-8520-45a4-9758-f1fd9cd9a9b6 | 4 | public void dump() {
for (int i = 0; i < framePointers.size(); i++) {
System.out.print("[");
int endFrame = runStack.size();
if (i < framePointers.size() - 1) {
endFrame = framePointers.get(i + 1);
}
for (int j = framePointers.get(i); j < endFrame; j++) {
System.out.print(runStack.get(j));
if (j < endFrame - 1) {
System.out.print(",");
}
}
System.out.print("] ");
}
System.out.print("\n");
} |
5de4d3ed-9968-460d-80e3-30f5a04d8d89 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VentanaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VentanaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VentanaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VentanaInicio.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 VentanaInicio().setVisible(true);
}
});
} |
4b9db98b-a1b6-4195-ba91-8c2dda9f8cfe | 0 | @Override
public void restoreTemporaryToCurrent() {tmp = cur;} |
e24cb83c-06e8-48d8-94b4-b3d928bf3bd9 | 7 | public static void addBook(Messagable ui, String isbn, String category, String author, String title, float dailyLateFee, float maxLateFee, int numberOfCopies){
boolean itemAdded = true;
if(Book.bookExists(isbn)){
itemAdded = false;
ui.sendMessage("ERROR: Item already exists");
}
if(numberOfCopies < 1){
itemAdded = false;
ui.sendMessage("ERROR: Must have at least 1 copy.");
}
if(isbn.isEmpty()){
itemAdded = false;
ui.sendMessage("ERROR: Enter an isbn");
}
if(dailyLateFee < 0){
itemAdded = false;
ui.sendMessage("ERROR: Enter a Daily Late Fee");
}
if(maxLateFee < dailyLateFee){
itemAdded = false;
ui.sendMessage("ERROR: Max Late Fee must be less than Daily Late Fee");
}
if(maxLateFee < 0){
itemAdded = false;
ui.sendMessage("ERROR: Enter a Max Late Fee");
}
if(itemAdded){
Book.addBook(isbn, category, title, author, dailyLateFee, maxLateFee, numberOfCopies);
ui.sendMessage("SUCCESS: Book added to database");
}
} |
f31238d2-d829-414e-93b2-f97bb7757bac | 4 | private void setUpNextAndPreviousButtons()
{
// create the image icons for the buttons
Icon prevIcon = new ImageIcon(DigitalPicture.class.getResource("leftArrow.gif"),
"previous index");
Icon nextIcon = new ImageIcon(DigitalPicture.class.getResource("rightArrow.gif"),
"next index");
// create the arrow buttons
colPrevButton = new JButton(prevIcon);
colNextButton = new JButton(nextIcon);
rowPrevButton = new JButton(prevIcon);
rowNextButton = new JButton(nextIcon);
// set the tool tip text
colNextButton.setToolTipText("Click to go to the next column value");
colPrevButton.setToolTipText("Click to go to the previous column value");
rowNextButton.setToolTipText("Click to go to the next row value");
rowPrevButton.setToolTipText("Click to go to the previous row value");
// set the sizes of the buttons
int prevWidth = prevIcon.getIconWidth() + 2;
int nextWidth = nextIcon.getIconWidth() + 2;
int prevHeight = prevIcon.getIconHeight() + 2;
int nextHeight = nextIcon.getIconHeight() + 2;
Dimension prevDimension = new Dimension(prevWidth,prevHeight);
Dimension nextDimension = new Dimension(nextWidth, nextHeight);
colPrevButton.setPreferredSize(prevDimension);
rowPrevButton.setPreferredSize(prevDimension);
colNextButton.setPreferredSize(nextDimension);
rowNextButton.setPreferredSize(nextDimension);
// handle previous column button press
colPrevButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
colIndex--;
if (colIndex < 0)
colIndex = 0;
displayPixelInformation(colIndex,rowIndex);
}
});
// handle previous row button press
rowPrevButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
rowIndex--;
if (rowIndex < 0)
rowIndex = 0;
displayPixelInformation(colIndex,rowIndex);
}
});
// handle next column button press
colNextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
colIndex++;
if (colIndex >= picture.getWidth())
colIndex = picture.getWidth() - 1;
displayPixelInformation(colIndex,rowIndex);
}
});
// handle next row button press
rowNextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
rowIndex++;
if (rowIndex >= picture.getHeight())
rowIndex = picture.getHeight() - 1;
displayPixelInformation(colIndex,rowIndex);
}
});
} |
487e9b28-5500-48f0-b63c-500b955b1749 | 5 | public static String userOS() {
String os = System.getProperty("os.name").toUpperCase();
if (os.indexOf("WIN") >= 0) {
return "Windows";
} else if (os.indexOf("MAC") >= 0) {
return "MacOSX";
} else if (os.indexOf("SUNOS") >= 0) {
return "Solaris";
} else if (os.indexOf("NIX") >= 0 || os.indexOf("NUX") >= 0) {
return "Linux";
}
else {
return "Unsupported";
}
} |
ff87e5a3-bb35-4870-9df7-3b45fb7a43a3 | 6 | private void updateCreature(Creature creature,
long elapsedTime)
{
//creature.updateRotation(elapsedTime);
// change x
float dx = creature.getVelocityX();
float oldX = creature.getX();
float newX = oldX + dx * elapsedTime;
Point tile =
getTileCollision(creature, newX, creature.getY());
if (tile == null) {
creature.setX(newX);
}
else {
// line up with the tile boundary
if (dx > 0) {
creature.setX(
TileMapRenderer.tilesToPixels(tile.x) -
creature.getWidth());
}
else if (dx < 0) {
creature.setX(
TileMapRenderer.tilesToPixels(tile.x + 1));
}
creature.collideHorizontal();
}
// change y
float dy = creature.getVelocityY();
float oldY = creature.getY();
float newY = oldY + dy * elapsedTime;
tile = getTileCollision(creature, creature.getX(), newY);
if (tile == null) {
creature.setY(newY);
}
else {
// line up with the tile boundary
if (dy > 0) {
creature.setY(
TileMapRenderer.tilesToPixels(tile.y) -
creature.getHeight());
}
else if (dy < 0) {
creature.setY(
TileMapRenderer.tilesToPixels(tile.y + 1));
}
creature.collideVertical();
}
} |
06aeb3c1-f9a3-4f86-99b1-70e6a6ca38f5 | 9 | private void updateStateWaitingName(List<Keyword> keywords, List<String> terms) {
//We came here since we didn't get a jump, if we got a jump we're in RECIPE_FOUND
if (keywords == null || keywords.isEmpty()) {
if (terms != null && !terms.isEmpty()) {
//Will save first term no matter what user said.
recipeName = terms.get(0);
getCurrentDialogState().setCurrentState(RecipeAssistance.RA_RECIPE_NOT_FOUND);
return;
}
}
//If there was a keyword something's wrong, and if there's no terms somethings wrong as well, unless a keyword to this state was passed
else {
if (keywords != null && !keywords.isEmpty()) {
for (Keyword kw : keywords) {
for (DialogState d : kw.getReference()) {
if (d.getCurrentState().equals(RecipeAssistance.RA_WAITING_FOR_RECIPE_NAME)) {
getCurrentDialogState().setCurrentState(RecipeAssistance.RA_WAITING_FOR_RECIPE_NAME);
return;
}
}
}
}
DialogManager.giveDialogManager().setInErrorState(true);
}
} |
48767ec3-2044-442b-be3f-93dc5986e853 | 3 | public static void main(final String[] args) {
PrintStream origErr = System.err;
PrintStream origOut = System.out;
System.setErr(origOut);
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});
bombersCount = args.length - 1;
PORT_NO = Integer.parseInt(args[args.length - 1]);
IBomber[] bombers = new IBomber[bombersCount];
try {
File mapFile = initMap();
Match m = createMatch(bombers, mapFile);
m.parseMap();
createBombers(bombers, m, args);
m.run();
createAndSendInitialMessageToAllBots(m, bombers);
// LET'S PLAY
// System.out.println("Shall the game begin");
do {
String status = m.getStatus();
System.out.print(status);
sendToAllBots(bombers, status);
Thread.sleep(1000);
} while (!m.passRound());
System.out.println(m.getStatus());
sendToAllBots(bombers, "THE END\n");
} catch (InterruptedException ex) {
System.out.println("DBG: interrupted" + ex);
} catch (IOException ex) {
System.out.println("DBG: exception" + ex);
} finally {
System.out.println("Starting to kill bombers");
killBombers(bombers);
System.out.println("DONE");
}
} |
790617fe-9c19-448b-884c-eb6c041da7c7 | 1 | @Test
public void throwException() {
C c = new C();
c.in = "1";
try {
c.execute();
fail("Exception expected");
} catch (ComponentException E) {
assertEquals(c.op2, E.getSource());
assertEquals("crash", E.getCause().getMessage());
}
} |
1cfd2cdb-bcb1-4f64-8e2a-bbdf888b8fc8 | 8 | private void grow() {
HugeLongArray oldAddresses = addresses;
// instead of just doubling the size - this gives more prime number sizes which tend to distribute hash codes better
int newCapacity = oldAddresses.size() <= 1 ? 2 : oldAddresses.size() * 2 - 1;
initialize(newCapacity);
for (int oldAddressIndex = 0; oldAddressIndex < oldAddresses.size(); oldAddressIndex++) {
long address = oldAddresses.get(oldAddressIndex);
if (address != NO_ADDRESS) {
boolean cheap = false;
int entriesCount = getEntriesCount(address);
if (entriesCount == 1) {
// maybe possible to do a cheap copy of key/value pair
int key = getKeyInsideIndex(address, 0);
int index = hashIndex(key);
if (addresses.get(index) == NO_ADDRESS) {
// possible to do a cheap copy, since only 1 key/value pair and hashIndex in new growing map is still empty - just point to the old address
addresses.set(index, address);
countHashCodes++;
cheap = true;
}
}
if (!cheap) {
// extract all key/value pairs at 'address' and put then into the growing new map
byte[] data = memoryManager.read(address);
memoryManager.free(address);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
int count = byteBuffer.getInt();
for (int i = 0; i < count; i++) {
int storedKey = byteBuffer.getInt();
int storedArrayLength = byteBuffer.getInt();
long[] storedArray = new long[storedArrayLength];
for (int j = 0; j < storedArrayLength; j++) {
storedArray[j] = byteBuffer.getLong();
}
put(storedKey, storedArray);
size--; // correct the size that was modified by put()
}
}
}
}
} |
1385751f-c1e4-4a8a-b323-267da508ac34 | 1 | public void upgrade() {
if(tier < 19) {
fuelCapacity += 20;
fuelLevel += 20;
tier++;
} else {
tier = 20;
fuelCapacity = 500;
fuelLevel = 480;
}
} |
be15652e-b292-4698-9384-92d868230f96 | 3 | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
if (cmd.getName().equalsIgnoreCase("kits"))
{
if ((sender instanceof Player))
{
Player player = (Player) sender;
if(player.hasPermission("EasyPvpKits.Kits"))
{
kits.clear();
ItemStack pvp = new ItemStack(Material.DIAMOND_SWORD);
ItemMeta pvpmeta = pvp.getItemMeta();
pvpmeta.setDisplayName(ChatColor.GOLD + "Pvp");
ArrayList<String> pvplore = new ArrayList<String>();
pvplore.add(ChatColor.RED + "Choose the Pvp kit.");
pvpmeta.setLore(pvplore);
pvp.setItemMeta(pvpmeta);
kits.setItem(10, pvp);
ItemStack archer = new ItemStack(Material.BOW);
ItemMeta archermeta = archer.getItemMeta();
archermeta.setDisplayName(ChatColor.GOLD + "Archer");
ArrayList<String> archerlore = new ArrayList<String>();
archerlore.add(ChatColor.RED + "Choose the Archer kit.");
archermeta.setLore(archerlore);
archer.setItemMeta(archermeta);
kits.setItem(11, archer);
ItemStack heavy = new ItemStack(Material.DIAMOND_CHESTPLATE);
ItemMeta heavymeta = heavy.getItemMeta();
heavymeta.setDisplayName(ChatColor.GOLD + "Heavy");
ArrayList<String> heavylore = new ArrayList<String>();
heavylore.add(ChatColor.RED + "Choose the Heavy kit.");
heavymeta.setLore(heavylore);
heavy.setItemMeta(heavymeta);
kits.setItem(12, heavy);
ItemStack assassin = new ItemStack(Material.NETHER_STAR);
ItemMeta assassinmeta = assassin.getItemMeta();
assassinmeta.setDisplayName(ChatColor.GOLD + "Assassin");
ArrayList<String> assassinlore = new ArrayList<String>();
assassinlore.add(ChatColor.RED + "Choose the Assassin kit.");
assassinmeta.setLore(assassinlore);
assassin.setItemMeta(assassinmeta);
kits.setItem(13, assassin);
ItemStack pyro = new ItemStack(Material.FLINT_AND_STEEL);
ItemMeta pyrometa = pyro.getItemMeta();
pyrometa.setDisplayName(ChatColor.GOLD + "Pyro");
ArrayList<String> pyrolore = new ArrayList<String>();
pyrolore.add(ChatColor.RED + "Choose the Pyro kit.");
pyrometa.setLore(pyrolore);
pyro.setItemMeta(pyrometa);
kits.setItem(14, pyro);
ItemStack filler = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7);
ItemMeta fillermeta = filler.getItemMeta();
fillermeta.setDisplayName(" ");
ArrayList<String> fillerlore = new ArrayList<String>();
fillerlore.add(" ");
fillermeta.setLore(fillerlore);
filler.setItemMeta(fillermeta);
kits.setItem(0, filler);
kits.setItem(1, filler);
kits.setItem(2, filler);
kits.setItem(3, filler);
kits.setItem(4, filler);
kits.setItem(5, filler);
kits.setItem(6, filler);
kits.setItem(7, filler);
kits.setItem(8, filler);
kits.setItem(9, filler);
kits.setItem(17, filler);
kits.setItem(18, filler);
kits.setItem(19, filler);
kits.setItem(20, filler);
kits.setItem(21, filler);
kits.setItem(22, filler);
kits.setItem(23, filler);
kits.setItem(24, filler);
kits.setItem(25, filler);
kits.setItem(26, filler);
player.openInventory(kits);
return true;
}
}
}
return false;
} |
19ac1ecc-768d-4be2-b9fb-3ae8eae963ab | 9 | void display()
{
String s;
switch( cardRanks[0] )
{
case 1:
s = "high card";
break;
case 2:
s = "pair of " + Card.rankAsString(cardRanks[1]) + "\'s";
break;
case 3:
s = "two pair " + Card.rankAsString(cardRanks[1]) + " " +
Card.rankAsString(cardRanks[2]);
break;
case 4:
s = "three of a kind " + Card.rankAsString(cardRanks[1]) + "\'s";
break;
case 5:
s = Card.rankAsString(cardRanks[1]) + " high straight";
break;
case 6:
s = "flush";
break;
case 7:
s = "full house " + Card.rankAsString(cardRanks[1]) +
" over " + Card.rankAsString(cardRanks[2]);
break;
case 8:
s = "four of a kind " + Card.rankAsString(cardRanks[1]);
break;
case 9:
s = "straight flush " + Card.rankAsString(cardRanks[1]) + " high";
break;
default:
s = "error in Hand.display: cardRanks[0] contains invalid value";
}
s = " " + s;
// moves the output over a little in the console
//so its easier to see when viewing the output
System.out.println(s);
} |
68c471e2-da51-48fc-a8ba-8e4db1d36a53 | 4 | public void updateSubTypes() {
int offset = 0;
if (!isStatic()) {
subExpressions[offset++].setType(Type.tSubType(getClassType()));
}
Type[] paramTypes = methodType.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
Type pType = (hints != null && hints[i + 1] != null) ? hints[i + 1]
: paramTypes[i];
subExpressions[offset++].setType(Type.tSubType(pType));
}
} |
547a86e6-a178-44db-908b-bbf3b637c695 | 3 | public void arrivalCheck(int currentPhase){
for(int i = 0 ; i < this.TrainList.size() ; i++){
Train tmpTrain = this.TrainList.get(i);
if(tmpTrain.endTime == currentPhase){
Train tmpTrain2 = this.TrainList.remove(i);
i--;
ArrayList<Customer> tmpClist = tmpTrain2.customerList.dequeueAll();
EndCustomerList ecl = EndCustomerList.getInstance();
for(int k = 0 ; k < tmpClist.size() ; k++){
Customer end = tmpClist.remove(k);
end.setCustomerTimeStatus(Define.endTime, currentPhase);
end.setCustomerTimeStatus(Define.totalTravelTime, currentPhase - end.getStartTime());
ecl.enqueueCustomer(end);
}
}
}
} |
523ebdd9-ac1e-4afc-9ce9-7ba43510c76d | 9 | public final void run(EventTaskRunner runner) {
try {
if(Log.ON){Log.d("taskrunner","["+mid+"]"+"action:"+toString());}
action(runner);
if (isKeep()) {
if(Log.ON){Log.d("taskrunner","["+mid+"]"+"action: next keep");}
runner.start(this);
} else if(runner != null&&mNextAction != null&&isNext()) {
if(Log.ON){Log.d("taskrunner","["+mid+"]"+"action: next "+mNextAction.toString());}
runner.start(mNextAction);
}
} catch(Throwable t) {
t.printStackTrace();
if(mErrorAction != null) {
runner.start(mErrorAction);
}
}
} |
8fec0dd6-cd97-4d28-8c24-c1b858705b77 | 7 | public static void testSwap(String f, int[][] grid, int[][] grid0,
int myType, int i, int j, int k, int l) {
if ((i == k) && (j == l)) {
if (grid[i][j] != myType) {
System.out.printf("Failed on %s @ (%d, %d) should not have moved\n", f, i, j);
} else {
if (mostlyTheSame(f, grid, grid0, i, j, k, l))
System.out.printf("Success on %s @ (%d, %d) did not move\n", f, i, j);
else {
int x = Utility.unmatchedX;
int y = Utility.unmatchedY;
System.out.printf("Failed on %s @ (%d, %d) => (%d, %d): Unexpected change @ (%d, %d). \n\tExpected %c Got %c\n",
f, i, j, k, l,
x, y,
Utility.shortNames[grid0[x][y]],
Utility.shortNames[grid[x][y]]);
}
}
return;
}
if (grid[k][l] != myType) {
System.out.printf("Failed on %s: Expected %c @ (%d, %d)\tGot %c\n", f,
Utility.shortNames[myType], k, l,
Utility.shortNames[grid[k][l]]);
} else if (grid[i][j] != Schelling.OPEN) {
System.out.printf("Failed on %s: Expected OPEN @ (%d, %d)\tGot %c\n", f, i, j,
Utility.shortNames[myType]);
} else {
if (mostlyTheSame(f, grid, grid0, i, j, k, l))
System.out.printf("Success on %s @ (%d, %d) => (%d, %d)\n", f, i, j, k, l);
else {
int x = Utility.unmatchedX;
int y = Utility.unmatchedY;
System.out.printf("Failed on %s @ (%d, %d) => (%d, %d): Unexpected change @ (%d, %d). \n\tExpected %c Got %c\n",
f, i, j, k, l,
x, y,
Utility.shortNames[grid0[x][y]],
Utility.shortNames[grid[x][y]]);
}
}
} |
54d8a808-c0f4-4406-a5e8-79b84d9cfdb5 | 8 | public void hashify(Node n) {
if(n==null){return;}
if (n.parent == n && n != null) {
hashInsert(n, n.label.charAt(0), n);
for (Node child : n.children) {
hashify(child);
}
} else if (n.parent != n && n != null) {
if (n.label != null) {
hashInsert(n.parent, n.label.charAt(0), n);
for (Node child : n.children) {
hashInsert(n, child.label.charAt(0), child);
hashify(child);
}
}
}
} |
d6f4a989-9588-4e78-91f0-e27da520e578 | 0 | @Override
public int create(Secteur unSecteur) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} |
94ce8872-07b0-4218-8611-1f5d1d381a6d | 2 | @Override
public Ingredient addIngredient(String s) {
Ingredient c = getIngredient(s);
if (c != null) {
return c;
} else {
try (Connection connection = DriverManager.getConnection(connectionString);) {
int idNewCategory = getNextIdAndIncrement();
PreparedStatement statement = connection.prepareStatement("insert into ingredient values (?, ?)");
statement.setInt(1, idNewCategory);
statement.setString(2, s.toUpperCase(Locale.ENGLISH));
statement.executeUpdate();
statement = connection.prepareStatement("insert into parent values (?, 0)");
statement.setInt(1, idNewCategory);
statement.execute();
connection.close();
return getIngredient(s);
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
} |
8e2f5d83-5862-4f70-a1f9-346ccf1b45ca | 0 | @Override
public String toString() {
return "Medicament{" + "depotlegal=" + depotlegal + ", nomcommercial=" + nomcommercial + ", code=" + code + ", composition=" + composition + ", effets=" + effets + ", contrindic=" + contrindic + ", prix=" + prix + '}';
} |
e2bf63d7-8be0-4564-acd3-fe1c86f72643 | 8 | @Override
public void collidedWith(Participant p1, Participant p2) {
if (p1 instanceof Asteroid && p2 instanceof Ship) {
asteroidCollision((Asteroid)p1);
shipCollision((Ship)p2);
}
else if (p1 instanceof Ship && p2 instanceof Asteroid) {
asteroidCollision((Asteroid)p2);
shipCollision((Ship)p1);
}
else if (p1 instanceof Bullet && p2 instanceof Asteroid) {
asteroidCollision((Asteroid)p2);
bulletCollision((Bullet)p1);
}
else if (p1 instanceof Asteroid && p2 instanceof Bullet) {
bulletCollision((Bullet)p2);
asteroidCollision((Asteroid)p1);
}
// else if (p1 instanceof Star && p2 instanceof Asteroid) {
// starCollision((Star)p1);
// }
// else if (p1 instanceof Asteroid && p2 instanceof Star) {
// starCollision((Star)p2);
// }
} |
9e0214b2-b49b-43cc-8d45-b802b90ee1c4 | 1 | WorldTile(BufferedImage image, boolean passable, int minimapColor, int cost) {
this.passable = passable;
if (image == null) {
logger.error(new NullPointerException(), "Attempted to add a null tile image to the map!");
}
this.image = image;
tileWidth = image.getWidth();
tileHeight = image.getHeight();
this.minimapColor = new Color(minimapColor);
} |
88f9efde-c4f0-4687-ba2a-49b4fbcd2e50 | 0 | public Communicate() {
// TODO Auto-generated constructor stub
} |
e5a4b828-33c9-4fde-a535-b7778eb3ae08 | 2 | public void run() {
while (true) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(7);
Socket socket = null;
System.out.println("Waiting for connection....");
socket = serverSocket.accept();
System.out.println("Connection successful");
System.out.println("Waiting for input");
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
socket.getInputStream();
socket.getInetAddress().getHostAddress();
String inputLine = in.readLine();
handleClient(inputLine);
in.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
}
}
} |
93414cbc-152e-463c-9293-d05d747f2d6b | 7 | public static boolean allKeyArgumentsBoundP(Proposition goal) {
if ((goal.kind == Logic.KWD_FUNCTION) ||
Proposition.singleValuedPredicateP(goal)) {
if (((Vector)(KeyValueList.dynamicSlotValue(goal.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null))) != null) {
{ boolean alwaysP000 = true;
{ int i = Stella.NULL_INTEGER;
int iter000 = 0;
int upperBound000 = goal.arguments.length() - 2;
loop000 : for (;iter000 <= upperBound000; iter000 = iter000 + 1) {
i = iter000;
if (!Logic.quantifiedArgumentBoundP((goal.arguments.theArray)[i], null)) {
alwaysP000 = false;
break loop000;
}
}
}
{ boolean value000 = alwaysP000;
return (value000);
}
}
}
else {
{ boolean alwaysP001 = true;
{ int i = Stella.NULL_INTEGER;
int iter001 = 0;
int upperBound001 = goal.arguments.length() - 2;
loop001 : for (;iter001 <= upperBound001; iter001 = iter001 + 1) {
i = iter001;
if (!Logic.argumentBoundP((goal.arguments.theArray)[i])) {
alwaysP001 = false;
break loop001;
}
}
}
{ boolean value001 = alwaysP001;
return (value001);
}
}
}
}
else {
return (false);
}
} |
eb9fd3b6-44b4-4984-8f1f-db738d527fb2 | 9 | @Test
public void testUpdateEditorsPick() {
Integer testISBN = 800;
Set<StockBook> books = new HashSet<StockBook>();
books.add(new ImmutableStockBook(testISBN, "Book Name", "Book Author",
(float) 100, 1, 0, 0, 0, false));
try {
storeManager.addBooks(books);
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
Set<BookEditorPick> editorPicksVals = new HashSet<BookEditorPick>();
BookEditorPick editorPick = new BookEditorPick(testISBN, true);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (Exception e) {
e.printStackTrace();
fail();
}
List<Book> lstEditorPicks = new ArrayList<Book>();
try {
lstEditorPicks = client.getEditorPicks(1);
} catch (Exception e) {
e.printStackTrace();
fail();
}
Boolean testISBNisInEditorPicks = false;
for (Book book : lstEditorPicks) {
if (book.getISBN() == testISBN)
testISBNisInEditorPicks = true;
}
assertTrue("Chk if list contains testISBN!", testISBNisInEditorPicks);
editorPicksVals.clear();
editorPick = new BookEditorPick(testISBN, false);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
Boolean exceptionThrown = false;
lstEditorPicks = new ArrayList<Book>();
try {
lstEditorPicks = client.getEditorPicks(1);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
editorPicksVals.clear();
editorPick = new BookEditorPick(-1, false);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
editorPicksVals.clear();
editorPick = new BookEditorPick(1000000000, false);
editorPicksVals.add(editorPick);
try {
storeManager.updateEditorPicks(editorPicksVals);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
} |
e006c08e-b46d-4a82-807b-86cac2bbedcc | 1 | private Object get(final int local) {
maxLocals = Math.max(maxLocals, local);
return local < locals.size() ? locals.get(local) : Opcodes.TOP;
} |
1abd5a86-671d-47f4-a437-f39ef30567d7 | 3 | @Override
public void tick() {
if (target.isAlive()) {
if (target.getPos().distance(pos) < 10 && isAlive) {
this.hit();
// pos = target.getPos();
} else {
Vector2d diff = target.getPos().difference(pos);
diff.setLength(speed);
pos = pos.sum(diff);
}
} else {
isAlive = false;
}
} |
6acd253a-21a4-4a31-b73a-14cc71e085a5 | 3 | static private float[] subArray(final float[] array, final int offs, int len)
{
if (offs+len > array.length)
{
len = array.length-offs;
}
if (len < 0)
len = 0;
float[] subarray = new float[len];
for (int i=0; i<len; i++)
{
subarray[i] = array[offs+i];
}
return subarray;
} |
47601456-9bc5-479d-912b-301e9d4c359a | 9 | void setVisibilityFlags(BitSet bs) {
/*
* set all fixed objects visible; others based on model being displayed
*
*/
for (int i = dipoleCount; --i >= 0;) {
Dipole dipole = dipoles[i];
dipole.visibilityFlags = ((dipole.modelIndex < 0 || bs
.get(dipole.modelIndex))
&& dipole.mad != 0
&& dipole.visible
&& dipole.origin != null
&& dipole.vector != null
&& dipole.vector.length() != 0
&& dipole.dipoleValue != 0 ? myVisibilityFlag : 0);
}
//dumpDipoles("setVis");
} |
04d926d7-16ee-4655-9ee6-29a9d8f28820 | 1 | private JFileChooser createFileChooser() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TextFileFilter());
if (defaultDirectory != null) {
fileChooser.setCurrentDirectory(defaultDirectory);
}
return fileChooser;
} |
bafa4dc8-e21b-4b19-9665-c490f7323bd2 | 1 | private String suffer(int i) {
String message = this.letter+" loses "+i
+" hitpoints.";
hitpoints = hitpoints - i;
if (hitpoints <= 0) {
this.board.removePawn(this);
message += this.letter+" is dead.";
}
return message;
} |
d5071957-503e-45a5-9023-329110c416ff | 4 | protected void generateForce () {
double currentLength = getCurrentLength();
boolean isContract = currentLength <= myRestLength;
double distance = Math.abs(currentLength - myRestLength);
double amplitude = distance * myStifness;
if (amplitude == 0)
return;
double centerX = (myObject1.getX() + myObject2.getX()) / 2;
double centerY = (myObject1.getY() + myObject2.getY()) / 2;
double fx = isContract ? myObject1.getX() - centerX : centerX - myObject1.getX();
double fy = isContract ? myObject1.getY() - centerY : centerY - myObject1.getY();
if (currentLength == 0) {
fx = lastFx;
fy = lastFy;
}
else {
fx = fx / (currentLength / 2) * amplitude;
fy = fy / (currentLength / 2) * amplitude;
lastFx = fx;
lastFy = fy;
}
myObject1.setForce(fx, fy);
myObject2.setForce(-fx, -fy);
} |
ea527333-9de7-42ac-a501-75d1ad2b7b2e | 1 | @SuppressWarnings("unchecked")
public Vector arbitrary(Random random, long size)
{
int length = (int) Arbitrary.random(random, 0,
Math.min(Integer.MAX_VALUE, size));
Vector list = new Vector(length);
for (int i = 0; i < length; ++i) {
list.add(i, subGenerator.arbitrary(random, size));
}
return list;
} |
5065b6da-e33f-48fa-96e9-0e67cf16102e | 4 | protected boolean isConnected(Node from, Node to) {
// Antennas are hardwired - we exclude links between pairs of antennas.
// MobileNodes are not connected among themselves
if(from instanceof Antenna && to instanceof MobileNode ||
to instanceof Antenna && from instanceof MobileNode) {
double dist = from.getPosition().squareDistanceTo(to.getPosition());
return dist < rMaxSquare;
}
return false;
} |
e26205b5-4e20-4f35-9818-b1fe64d157f1 | 8 | public static int getXfromString(String location) {
if ((location.charAt(0) == 'a')) {
return 0;
}
if ((location.charAt(0) == 'b')) {
return 1;
}
if ((location.charAt(0) == 'c')) {
return 2;
}
if ((location.charAt(0) == 'd')) {
return 3;
}
if ((location.charAt(0) == 'e')) {
return 4;
}
if ((location.charAt(0) == 'f')) {
return 5;
}
if ((location.charAt(0) == 'g')) {
return 6;
}
if ((location.charAt(0) == 'h')) {
return 7;
}
return -1;
} |
be239de2-095e-4933-b637-7eb720f3e733 | 9 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession(true);
String id = request.getParameter("driverId");
String pwd = request.getParameter("driverPwd");
PrintWriter pw = response.getWriter();
AdminQuery aq = new AdminQuery();
String pg = "";
System.out.println("ID=|"+id+"|Pwd=|"+pwd);
if (id == null || pwd == null)
{
pg += "<div class='register_box'><div id='panel'>";
pg += "<form id='driverLogin' action='DriverLogin' method='post' accept-charset='UTF-8'>" +
"<fieldset >" +
"<legend>Delivery Driver Login</legend>" +
"<input type='hidden' name='submitted' id='submitted' value='1'/>" +
"<div id='row'><label for='driverId' >Login ID: </label>" +
"<input type='text' name='driverId' id='driverID' maxlength=\"25\" /></div>" +
"<div id='row'><label for='driverPwd' >Password: </label>" +
"<input type='password' name='driverPwd' id='driverPwd' maxlength=\"25\" /></div>" +
"<center><div id='row'><input type='submit' name='driverSubmit' value='Log on' /></div></center>" +
"</fieldset>" +
"</form></div></div>";
}
else if (id != null && pwd != null && id.length() > 0 && pwd.length() > 0)
{
//both fields were entered, so lookup driver id in database.
// Integer driverID = Integer.parseInt(id.trim());
id = id.trim();
pwd = pwd.trim();
String driverQuery = "select password from deliverypersons where deliv_id = "+id;
ResultSet driverRes = aq.executeQuery(driverQuery);
try {
if (driverRes.next())
{
//a password was retrieved from the DB
String dbPwd = driverRes.getString(1).trim();
if (dbPwd.equals(pwd))
{
//Login information is correct--
session.setAttribute("driverName", id);
session.setAttribute("Pwd", pwd);
pg += getDelivery(id);
// //Complete Delivery Button--Process payment
// pg += "</div><form id='completeOrder' action='Driver' method='post' accept-charset='UTF-8'>" +
// "<center><div id='row'><input type='submit' name='complete' value='Process Payment' /></center>"+
// "</form>";
pg += "</div><form id='logout' action='Driver' method='post' accept-charset='UTF-8'>" +
"<center><div id='row'><input type='submit' name='driverLogout' value='Log out' /></center>"+
"</form>";
}
else
{
pg += "<div class='register_box'><div id='err'>Invalid Login Information</div><div id='panel'>";
pg += "<form id='driverLogin' action='DriverLogin' method='post' accept-charset='UTF-8'>" +
"<fieldset >" +
"<legend>Delivery Driver Login</legend>" +
"<input type='hidden' name='submitted' id='submitted' value='1'/>" +
"<div id='row'><label for='driverId' >Login ID: </label>" +
"<input type='text' name='driverId' id='driverID' maxlength=\"25\" /></div>" +
"<div id='row'><label for='driverPwd' >Password: </label>" +
"<input type='password' name='driverPwd' id='driverPwd' maxlength=\"25\" /></div>" +
"<center><div id='row'><input type='submit' name='driverSubmit' value='Log on' /></div></center>" +
"</fieldset>" +
"</form></div></div>";
}
}
else
{
//invalid login information
pg += "<div class='register_box'><div id='err'>Invalid Login Information</div><div id='panel'>";
pg += "<form id='driverLogin' action='DriverLogin' method='post' accept-charset='UTF-8'>" +
"<fieldset >" +
"<legend>Delivery Driver Login</legend>" +
"<input type='hidden' name='submitted' id='submitted' value='1'/>" +
"<div id='row'><label for='driverId' >Login ID: </label>" +
"<input type='text' name='driverId' id='driverID' maxlength=\"25\" /></div>" +
"<div id='row'><label for='driverPwd' >Password: </label>" +
"<input type='password' name='driverPwd' id='driverPwd' maxlength=\"25\" /></div>" +
"<center><div id='row'><input type='submit' name='driverSubmit' value='Log on' /></div></center>" +
"</fieldset>" +
"</form></div></div>";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//at least one of the fields is empty
pg += "<div class='register_box'><div id='err'>Invalid Login Information</div><div id='panel'>";
pg += "<form id='driverLogin' action='DriverLogin' method='post' accept-charset='UTF-8'>" +
"<fieldset >" +
"<legend>Delivery Driver Login</legend>" +
"<input type='hidden' name='submitted' id='submitted' value='1'/>" +
"<div id='row'><label for='driverId' >Login ID: </label>" +
"<input type='text' name='driverId' id='driverID' maxlength=\"25\" /></div>" +
"<div id='row'><label for='driverPwd' >Password: </label>" +
"<input type='password' name='driverPwd' id='driverPwd' maxlength=\"25\" /></div>" +
"<center><div id='row'><input type='submit' name='driverSubmit' value='Log on' /></div></center>" +
"</fieldset>" +
"</form></div></div>";
}
writePage(pg, pw);
} |
03ded8fe-5b8f-44dd-9ce9-ce2a12bc2632 | 2 | public static Inventory deserialize(byte[] bytes) {
NbtTagCompound root = NbtFactory.toCompound(NbtSerializer.toTag(bytes));
if (root.getInt(VERSION_KEY) != NBT_VERSION)
throw new IllegalArgumentException("Incompatible NBT-version!");
NbtTagList<NbtTagCompound> items = root.getList(ITEMS_KEY);
Inventory inventory = Bukkit.getServer().createInventory(null, items.size());
for (int i = 0; i < items.size(); i++) {
NbtTagCompound compound = items.getValue(i);
inventory.setItem(i, NbtFactory.loadItemStack(compound));
}
return inventory;
} |
88bcc6c2-44cb-40c5-9c19-f50026ab0a86 | 5 | @Override
protected boolean perform(final CommandSender sender, final Command command, final String label, final List<String> args, final Region region) {
final String owner = RegionExecutor.parse(args, 0, "<Owner>", sender);
if (owner == null) return false;
if (!region.owners.contains(owner)) {
Main.courier.send(sender, "demote-missing", owner, RegionExecutor.formatName(region), RegionExecutor.formatWorld(region));
return true;
}
region.owners.remove(owner);
// Do not allow an owner to remove their own ownership accidentally if they can't add themselves back forcibly
if (!sender.hasPermission("simpleregions.override.commands") && sender instanceof Player && !region.owners.inherits(sender)) {
region.owners.add(owner);
Main.courier.send(sender, "demote-prevent");
return true;
}
this.catalog.repository.saveRegion(region, false);
Main.courier.send(sender, "demote", Bukkit.getOfflinePlayer(owner).getName(), RegionExecutor.formatName(region), RegionExecutor.formatWorld(region));
return true;
} |
1c67a2b2-ef4c-4b9c-82da-30a0b308e5f0 | 9 | private void generateSqlProperties() {
StringBuilder sbr = new StringBuilder();
sbr.append("JNDI.CONNECTION java:comp/env/jdbc/" + this.jndi + "\n\n");
sbr.append("CLASS.BROKER.IMPL br.com.topsys.database.jdbc.TSDataBaseBrokerImpl\n\n");
switch (this.database) {
case DBModel.DB_ORACLE:
sbr.append("CLASS.SEQUENCE.IMPL br.com.topsys.database.jdbc.sequence.TSSequenceOracleImpl\n\n");
sbr.append("CODIGO.UNIQUE 1\n\n");
sbr.append("CODIGO.FOREIGNKEY 2292\n\n");
sbr.append("CODIGO.RAISE.EXCEPTION 04088\n\n\n");
break;
case DBModel.DB_POSTGRES:
sbr.append("CLASS.SEQUENCE.IMPL br.com.topsys.database.jdbc.sequence.TSSequencePostgresImpl\n\n");
sbr.append("CODIGO.UNIQUE 23505\n\n");
sbr.append("CODIGO.FOREIGNKEY 23503\n\n");
sbr.append("CODIGO.RAISE.EXCEPTION 09000\n\n\n");
break;
case DBModel.DB_SQLSERVER:
sbr.append("CLASS.SEQUENCE.IMPL br.com.topsys.database.jdbc.sequence.TSSequenceSQLServerImpl\n\n");
sbr.append("CODIGO.UNIQUE 2627\n\n");
sbr.append("CODIGO.FOREIGNKEY 547\n\n");
sbr.append("CODIGO.RAISE.EXCEPTION 55555\n\n\n");
break;
}
for (String table : this.tableNames) {
String tableName = table.toUpperCase();
String DAOName = this.camelCase(tableName);
String myClass = DAOName.substring(0, 1).toUpperCase() + DAOName.substring(1, DAOName.length());
myClass = this.toSingular(myClass);
sbr.append("#" + myClass + "DAO\n");
String dao = myClass.toLowerCase() + "dao.";
this.columns = new ArrayList<String>();
for (DBModel dbModel : this.tables) {
if (table.equalsIgnoreCase(dbModel.getTable())) {
this.columns.add(dbModel.getColumn().toUpperCase());
}
}
String variables = "";
StringBuilder variablesToChange = new StringBuilder();
StringBuilder parameters = new StringBuilder();
for (String coluna : this.columns) {
variables += ", " + coluna;
if (!coluna.equals("ID")) {
variablesToChange.append("," + coluna + " = ?");
}
parameters.append(", ?");
}
String parametrosStr = parameters.toString();
variables = variables.replaceFirst(", ", "");
parametrosStr = parametrosStr.replaceFirst(", ", "");
sbr.append(dao + "get=SELECT " + variables + " FROM " + tableName + " WHERE ID = ?\n");
sbr.append(dao + "findall=SELECT " + variables + " FROM " + tableName + "\n");
String varInsert = " (ID, " + variables.replace(", ID", "");
varInsert = varInsert.replaceAll("ID, ID,", "ID,");
if(this.database == DBModel.DB_SQLSERVER) {
varInsert = varInsert.replaceAll(" ID, ", "");
varInsert = varInsert.replaceAll("[(]ID, ", "(");
sbr.append(dao + "insert=INSERT INTO " + tableName + varInsert + ") VALUES (" + parameters.toString().replaceFirst(", ", "").replaceFirst("\\?,", "") + ")\n");
} else {
sbr.append(dao + "insert=INSERT INTO " + tableName + varInsert + ") VALUES (" + parameters.toString().replaceFirst(", ", "") + ")\n");
}
sbr.append(dao + "update=UPDATE " + tableName + " SET " + variablesToChange.toString().replaceFirst(",", "") + " WHERE ID = ?\n");
sbr.append(dao + "delete=DELETE FROM " + tableName + " WHERE ID = ?\n\n");
}
TSFile.criarArquivo(this.directory + SRC + File.separator + CONFIG + File.separator + "sql.properties", sbr.toString(), TSConstant.CHARSET_UTF);
super.addInfoMessage("File sql.properties created!");
} |
b7789374-184c-4b75-8d34-c653a6ca043c | 1 | public void makeSelection() {
if(!list.getSelectedValue().startsWith("-1")) {
selection = list.getSelectedValue().substring(0, list.getSelectedValue().indexOf(";"));
dispose();
}
} |
1d692d0e-f326-43e0-849f-c8a65c1de127 | 0 | public static void main(String[] args) {
new WashStart().run();
} |
b0363de0-fc30-464a-a63a-e122d3345333 | 7 | public static void main(String[] args) {
//Define loop for number of eggs in the basket
for (int eggs = 0; eggs > -1; eggs++) {
//Check if the number of eggs in the basket has the correct remainder when removing eggs
if (eggs % 2 == 1 && eggs % 3 == 2 && eggs % 4 == 3 && eggs % 5 == 4 && eggs % 6 == 5 && eggs % 7 == 0) {
//if so, output result and break.
System.out.print("The basket contains " + eggs + " eggs.");
break;
}
}
BlockLetters.TONY_PAPPAS.outputBlockName();
} |
ec652e71-7da3-447f-a018-76c9a86d5c79 | 7 | @SuppressWarnings("unchecked")
private void parseQuery(String query, Map parameters)
throws UnsupportedEncodingException {
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0) {
key = URLDecoder.decode(param[0],
System.getProperty("file.encoding"));
}
if (param.length > 1) {
value = URLDecoder.decode(param[1],
System.getProperty("file.encoding"));
}
if (parameters.containsKey(key)) {
Object obj = parameters.get(key);
if(obj instanceof List) {
List<String> values = (List<String>)obj;
values.add(value);
} else if(obj instanceof String) {
List<String> values = new ArrayList<String>();
values.add((String)obj);
values.add(value);
parameters.put(key, values);
}
} else {
parameters.put(key, value);
}
}
}
} |
5df985b7-7210-42eb-965e-f8c527f71b9b | 9 | public byte[] data() {
if (buffer == null) {
buffer = new byte[FastConfig.HeaderLength];
}
int count = 0;
byte[] temp = MiscUtils.toByteArray(high);
for (int i = 0; i < temp.length; i++) {
buffer[count] = temp[i];
count++;
}
temp = MiscUtils.toByteArray(low);
for (int i = 0; i < temp.length; i++) {
buffer[count] = temp[i];
count++;
}
temp = MiscUtils.toByteArray(getSize());
for (int i = 0; i < temp.length; i++) {
buffer[count] = temp[i];
count++;
}
temp = MiscUtils.toByteArray(window);
for (int i = 0; i < temp.length; i++) {
buffer[count] = temp[i];
count++;
}
byte[] intTemp = MiscUtils.toByteArray(type);
intTemp = MiscUtils.toByteArray(type);
for (int i = 0; i < intTemp.length; i++) {
buffer[count] = intTemp[i];
count++;
}
intTemp = MiscUtils.toByteArray(id);
for (int i = 0; i < intTemp.length; i++) {
buffer[count] = intTemp[i];
count++;
}
intTemp = MiscUtils.toByteArray(length);
for (int i = 0; i < intTemp.length; i++) {
buffer[count] = intTemp[i];
count++;
}
intTemp = MiscUtils.toByteArray(score);
for (int i = 0; i < intTemp.length; i++) {
buffer[count] = intTemp[i];
count++;
}
return buffer;
} |
4e678d88-2224-40a7-b1f2-7b471e6c1657 | 2 | private static BasicBlock getBBlock(Mark m) {
BasicBlock b = m.block;
if (b != null && m.size > 0) {
b.exit = m.jump;
b.length = m.size;
b.stop = m.alwaysJmp;
}
return b;
} |
cb45186b-9869-497e-9347-5490898e008c | 8 | @Override
public void e(float sideMot, float forMot) {
if (this.passenger == null || !(this.passenger instanceof EntityHuman)) {
super.e(sideMot, forMot);
this.W = 0.5F; // Make sure the entity can walk over half slabs,
// instead of jumping
return;
}
EntityHuman human = (EntityHuman) this.passenger;
if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) {
// Same as before
super.e(sideMot, forMot);
this.W = 0.5F;
return;
}
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
// Set the entity's pitch, yaw, head rotation etc.
this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166
this.aO = this.aM = this.yaw;
this.W = 1.0F; // The custom entity will now automatically climb up 1
// high blocks
sideMot = ((EntityLiving) this.passenger).bd * 0.5F;
forMot = ((EntityLiving) this.passenger).be;
if (forMot <= 0.0F) {
forMot *= 0.25F; // Make backwards slower
}
sideMot *= 0.75F; // Also make sideways slower
float speed = 0.35F; // 0.2 is the default entity speed. I made it
// slightly faster so that riding is better than
// walking
this.i(speed); // Apply the speed
super.e(sideMot, forMot); // Apply the motion to the entity
try {
Field jump = null;
jump = EntityLiving.class.getDeclaredField("bc");
jump.setAccessible(true);
if (jump != null && this.onGround) { // Wouldn't want it jumping
// while
// on the ground would we?
if (jump.getBoolean(this.passenger)) {
double jumpHeight = 0.5D;
this.motY = jumpHeight; // Used all the time in NMS for
// entity jumping
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
e3a6627c-5f91-4fac-9b99-92b8657870eb | 5 | private void removeJSR(FlowBlock tryFlow, FlowBlock subRoutine) {
for (Jump jumps = tryFlow.removeJumps(subRoutine); jumps != null; jumps = jumps.next) {
StructuredBlock prev = jumps.prev;
prev.removeJump();
if (prev instanceof EmptyBlock && prev.outer instanceof JsrBlock
&& ((JsrBlock) prev.outer).isGood()) {
StructuredBlock next = prev.outer.getNextBlock();
prev.outer.removeBlock();
if (next instanceof ReturnBlock)
removeReturnLocal((ReturnBlock) next);
} else {
/*
* We have a jump to the subroutine, that is badly placed. We
* complain here.
*/
DescriptionBlock msg = new DescriptionBlock(
"ERROR: invalid jump to finally block!");
prev.appendBlock(msg);
}
}
} |
aefff3e2-b888-4c77-bc0b-250d5c55621d | 8 | public void mergeArray(int low, int middle, int high) {
/**
* Copying the whole set of values first.
*/
for (int i = low; i <= high; i++) {
this.auxArray[i] = this.array[i];
this.arrayAccess += 2;
}
/**
* Copying the indices for the left and the right sub-arrays which are
* nothing but an indexed access of the auxiliary array. "primeIndex" is
* the index for the main array which will take the merged values.
*/
int leftIndex = low;
int rightIndex = middle + 1;
int primeIndex = low;
/**
* Now as long as there are values in the left or right arrays, just
* keep the loop running.
*/
while (true) {
/**
* Break as soon as one of them crosses over.
*/
if (leftIndex > middle) {
break;
}
if (rightIndex > high) {
break;
}
/**
* If the leftValue is <= rightValue, then put it in the primary
* array.
*/
if (isLesser(leftIndex, rightIndex)
|| isEqual(leftIndex, rightIndex))
this.array[primeIndex++] = this.auxArray[leftIndex++];
else
this.array[primeIndex++] = this.auxArray[rightIndex++];
this.comparisions++;
this.arrayAccess += 4;
}
while (leftIndex <= middle) {
this.array[primeIndex++] = this.auxArray[leftIndex++];
this.arrayAccess += 2;
}
while (rightIndex <= high) {
this.array[primeIndex++] = this.auxArray[rightIndex++];
this.arrayAccess += 2;
}
} |
87e5dff7-ed32-44a1-8ecc-3c862a8444b4 | 4 | private synchronized boolean handleReservationJob(Gridlet gridlet) {
int reqPE = gridlet.getNumPE();
SSGridlet sgl = new SSGridlet(gridlet);
long runTime = super.forecastExecutionTime(ratingPE, sgl.getLength());
ServerReservation sRes = reservTable.get(gridlet.getReservationID());
//-------------------- FOR DEBUGGING PURPOSES ONLY ---------------------
visualizer.notifyListeners(this.get_id(), ActionType.ITEM_ARRIVED, true, sgl);
//----------------------------------------------------------------------
if(sRes == null) {
String userName = GridSim.getEntityName( gridlet.getUserID() );
logger.info("Gridlet #" + gridlet.getGridletID() + " from " +
userName + " cannot be accepted because the reservation #" +
gridlet.getReservationID() + " has not been found.");
return false;
}
// job requires more PEs than what the reservation currently has
else if( sRes.getNumRemainingPE() < reqPE ) {
String userName = GridSim.getEntityName( gridlet.getUserID() );
logger.info("Gridlet #" + gridlet.getGridletID() + " from " +
userName + " cannot be accepted because the reservation #" +
sRes.getID() + " has only " + sRes.getNumRemainingPE() + " PEs.");
return false;
}
// job is expected to run for longer than the time previously reserved
else if (runTime > sRes.getRemainingTime()) {
String userName = GridSim.getEntityName( gridlet.getUserID() );
logger.info("Gridlet #" + gridlet.getGridletID() + " from " +
userName + " cannot be accepted because the reservation #" +
sRes.getID() + " has a remaining time of " +
sRes.getRemainingTime() + " seconds," +
" whereas the gridlet is expected to run for " +
runTime + " seconds.");
return false;
}
double startTime = Math.max(sRes.getStartTime(), GridSim.clock());
PERangeList selected = sRes.selectPERangeList(reqPE);
sgl.setPERangeList(selected);
sgl.setStartTime(startTime);
sgl.setActualFinishTime(startTime + runTime);
sgl.setStatus(Gridlet.QUEUED);
waitingJobs.add(sgl);
// if reservation has not been committed, then commit the reservation
if (sRes.getReservationStatus() == ReservationStatus.NOT_COMMITTED) {
sRes.setStatus(ReservationStatus.COMMITTED);
super.sendInternalEvent(sRes.getStartTime() - GridSim.clock(),
ConservativeBackfill.UPT_SCHEDULE);
}
super.sendInternalEvent(startTime - GridSim.clock(),
ConservativeBackfill.UPT_SCHEDULE);
//------------------ FOR DEBUGGING PURPOSES ONLY ----------------
visualizer.notifyListeners(this.get_id(), ActionType.ITEM_SCHEDULED, true, sgl);
//---------------------------------------------------------------
return true;
} |
61bd3715-5f64-4f98-808d-2b1c00bfd47b | 3 | public HashSet<String> generateCSVFromXML(String fileName, String csvFileName){
HashSet<String> stopwords = new HashSet<String>();
HashSet<String> productNameToWords = new HashSet<String>();
WordCleaner wc = new WordCleaner();
String stopwordFile = "xbox/stopwords.txt";
stopwords = getStopwords(stopwords, stopwordFile);
try{
FileWriter fWriter = new FileWriter(csvFileName);
PrintWriter pWriter = new PrintWriter(fWriter, false);
pWriter.print("sku");
pWriter.print(",");
pWriter.print("productId");
pWriter.print(",");
pWriter.print("name");
pWriter.print(",");
pWriter.print("format");
pWriter.print(",");
pWriter.print("shortDescription");
pWriter.print(",");
pWriter.print("manufacturer");
pWriter.print(",");
pWriter.print("genre");
pWriter.print(",");
pWriter.print("active");
pWriter.print(",");
pWriter.print("customerReviewAverage");
pWriter.print("\n");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fileName);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("product");
for(int i = 0; i < nList.getLength(); i++){
Node nNode = nList.item(i);
if(nNode.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) nNode;
pWriter.print(element.getElementsByTagName("sku").item(0).getTextContent().toString());
pWriter.print(",");
pWriter.print(element.getElementsByTagName("productId").item(0).getTextContent().toString());
pWriter.print(",");
String productName = replaceSpecialCharacters(element.getElementsByTagName("name").item(0).getTextContent().toString());
productName = processStringValues(productName, stopwords);
pWriter.print(productName.trim());
//pWriter.print(replaceSpecialCharacters(element.getElementsByTagName("name").item(0).getTextContent().toString()));
pWriter.print(",");
productNameToWords = wc.loadProductNameWords(productName, productNameToWords);
//System.out.println(productNameToWords.toString());
String formatvalue = processStringValues(element.getElementsByTagName("format").item(0).getTextContent().toString(), stopwords);
formatvalue = replaceSpecialCharacters(formatvalue);
pWriter.print(formatvalue);
//pWriter.print(element.getElementsByTagName("format").item(0).getTextContent().toString());
pWriter.print(",");
String shortDesc = replaceSpecialCharacters(element.getElementsByTagName("shortDescription").item(0).getTextContent().toString());
shortDesc = processStringValues(shortDesc, stopwords);
pWriter.print(shortDesc);
//pWriter.print(replaceSpecialCharacters(element.getElementsByTagName("shortDescription").item(0).getTextContent().toString()));
pWriter.print(",");
pWriter.print(checkNodeExistence(element, element.getElementsByTagName("manufacturer").getLength(), "manufacturer"));
pWriter.print(",");
pWriter.print(checkDetailsNode(element, element.getElementsByTagName("details").getLength(), "genre"));
pWriter.print(",");
pWriter.print(checkNodeExistence(element, element.getElementsByTagName("active").getLength(), "active"));
pWriter.print(",");
pWriter.print(checkNodeExistence(element, element.getElementsByTagName("customerReviewAverage").getLength(), "customerReviewAverage"));
pWriter.print("\n");
}
}
pWriter.flush();
pWriter.close();
fWriter.close();
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
return productNameToWords;
} |
09ee9508-7687-4577-9955-81b38bcd7c4f | 2 | public static TestSettings findStoryboardById(ArrayList<TestSettings> storyboards, int id) {
for(TestSettings storyboard:storyboards) {
if(storyboard.getId()==id) {
return storyboard;
}
}
return new TestSettings();
} |
f50c6f61-1e88-42c0-99b1-67f6568fa708 | 8 | public Player(int _playerId) {
playerId = _playerId;
playerRights = 0;
for (int i=0; i<playerItems.length; i++) {
playerItems[i] = 0;
}
for (int i=0; i<playerItemsN.length; i++) {
playerItemsN[i] = 0;
}
for (int i=0; i<playerLevel.length; i++) {
if (i == 3) {
playerLevel[i] = 10;
} else {
playerLevel[i] = 1;
}
}
for (int i=0; i<playerXP.length; i++) {
if (i == 3) {
playerXP[i] = 1300;
} else {
playerXP[i] = 0;
}
}
for (int i=0; i < Config.BANK_SIZE; i++) {
bankItems[i] = 0;
}
for (int i=0; i < Config.BANK_SIZE; i++) {
bankItemsN[i] = 0;
}
playerAppearance[0] = 0; // gender
playerAppearance[1] = 0; // head
playerAppearance[2] = 18;// Torso
playerAppearance[3] = 26; // arms
playerAppearance[4] = 33; // hands
playerAppearance[5] = 36; // legs
playerAppearance[6] = 42; // feet
playerAppearance[7] = 10; // beard
playerAppearance[8] = 0; // hair colour
playerAppearance[9] = 0; // torso colour
playerAppearance[10] = 0; // legs colour
playerAppearance[11] = 0; // feet colour
playerAppearance[12] = 0; // skin colour
apset = 0;
actionID = 0;
playerEquipment[playerHat]=-1;
playerEquipment[playerCape]=-1;
playerEquipment[playerAmulet]=-1;
playerEquipment[playerChest]=-1;
playerEquipment[playerShield]=-1;
playerEquipment[playerLegs]=-1;
playerEquipment[playerHands]=-1;
playerEquipment[playerFeet]=-1;
playerEquipment[playerRing]=-1;
playerEquipment[playerArrows]=-1;
playerEquipment[playerWeapon]=-1;
heightLevel = 0;
teleportToX = Config.START_LOCATION_X;
teleportToY = Config.START_LOCATION_Y;
absX = absY = -1;
mapRegionX = mapRegionY = -1;
currentX = currentY = 0;
//playerName = Misc.capitalize(playerName);
resetWalkingQueue();
} |
97b6b4f0-a8c8-4c05-b983-025898d275c7 | 6 | private void usernameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameKeyPressed
if(evt.getKeyCode() == KeyEvent.VK_ENTER){
try {
String name=username.getText();
String pass=password.getText();
String checkname = null;
String checkpass;
MyCon = new SQLConnection();
c = MyCon.getConnection("journal");
stmt = c.createStatement();
SQL = "SELECT * FROM journal.profile;";
rs = stmt.executeQuery(SQL);
while(rs.next()){
checkname = rs.getString("username");
checkpass = rs.getString("password");
if(checkname.toUpperCase().equals(name.toUpperCase()) && checkpass.equals(pass)){
found = 1;
break;
}
}
if(found == 1){
MyCon.useUsername(checkname);
new ShowProfile().show();
System.out.println("Login Ok");
this.dispose();
}
else{
System.out.println("Login Fail");
loginError.setVisible(true);
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_usernameKeyPressed |
1c525f0a-188f-4eaf-a8cb-3f3e8db7427f | 6 | public static double getSpeedMod(WeaponMaterial type) { //Higher numbers means slower
switch (type) {
case COPPER:
return 1.1;
case BRONZE:
return 1.1;
case SILVER:
return 1.2;
case IRON:
return 1;
case STEEL:
return 1;
case ADAMANTINE:
return 0.25;
}
return 1;
} |
7527f1a9-161b-4c96-94ab-c2ab31ddc2b5 | 5 | private static <E> void merge(E[] array, E[] temp,int begin, int end, Comparator<E> comparator){
int i = begin;
int tracker = begin;
int middex = (begin+end)/2;
int rightstart = middex+1;
// Goes through and compares the two segments of the array that we are focusing on.
while(i <= middex && rightstart <= end){
if(comparator.compare(array[i], array[rightstart])<=0){
temp[tracker++] = array[i++];
}else{
temp[tracker++] = array[rightstart++];
}
}
while(i <= middex){ //Means right completed first so shifts all into temp
temp[tracker++] = array[i++];
}
//Doesn't put right side elements into the temp array because they are already in order.
//Number of elements in temp array that need to be put into array.
int elements = tracker -begin;
for(int j =0; j < elements; j++){
array[begin+j] = temp[begin+j];
}
} |
cb64e953-7178-46ec-8dbc-367227cf3fba | 8 | private void writeExamples() throws Exception {
int i;
Vector<String> v = m_parent.getTagTextVector(m_doc, Constants.TAG_EXAMPLE, true);
Vector<String> vc = m_parent.getTagTextVector(m_doc, Constants.TAG_EXAMPLE_CODE, true);
Vector<String> vd = m_parent.getTagTextVector(m_doc, Constants.TAG_EXAMPLE_DESCRIPTION, true);
if (vc.size() != vd.size()) {
//throw new Exception("Size of ant.example.code(" + vc.size() + ") and ant.example.description(" + vd.size() + ") do not match for Task" + m_doc.qualifiedName() + ".\n Either all or none of the tags must be localized.");
logger.log(Level.WARNING, "Size of ant.example.code({0}) and ant.example.description({1}) do not match for Task{2}.\n Either all or none of the tags must be localized. Fallback in progress.", new Object[]{vc.size(), vd.size(), m_doc.qualifiedName()});
/*
vc = m_parent.getTagTextVector(m_doc, Constants.TAG_EXAMPLE_CODE, false);
vd = m_parent.getTagTextVector(m_doc, Constants.TAG_EXAMPLE_DESCRIPTION, false);
if (vc.size()!=vd.size()) {
logger.warning("examples doesn't match description");
}*/
}
if (v.size() == 0 && vc.size() == 0) {
//NO EXAMPLES
return;
}
write(m_stream, "task-examples-header.template");
for (i = 0; i < v.size(); i++) {
writeSingleExample(v.elementAt(i));
}
for (i = 0; i < Math.max(vc.size(),vd.size()); i++) {
if (i<vc.size() && i<vd.size())
writeSingleDetailedExample(vc.elementAt(i), vd.elementAt(i));
else if (i<vc.size())
writeSingleDetailedExample(vc.elementAt(i), " <b>missing example description</b> ");
else
writeSingleDetailedExample(" <b>missing example</b> ",vd.elementAt(i));
}
write(m_stream, "task-examples-footer.template");
} |
05ae5348-32f0-47f7-ba94-cb8f11076691 | 2 | private void init(Class<?> clazz, String conventionalName) {
final URL resource = clazz.getResource(conventionalName);
loader.setLocation(resource);
try {
loader.load();
} catch (IOException e) {
throw new IllegalStateException("Cannot load FXML login screen", e);
}
} |
8b380f37-ac5e-4683-aa12-65795e98e256 | 6 | public Vector<String> readScriptFile(File f) {
Vector<String> actions = null;
BufferedReader reader = null;
try {
if (f.canRead()) {
actions = new Vector<String>();
reader = new BufferedReader(new FileReader(f));
String line = reader.readLine();
while (line != null) {
actions.add(line);
line = reader.readLine();
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// do nothing
}
}
}
return actions;
} |
042ad3c5-1417-4943-876f-a1ff7f52ebea | 4 | public static void gotoNextLevel(GameStateManager gsm){
//save world we are currently in
World cw = (World)gsm.getGameState(gsm.getCurrentState());
Save.writeWorld(cw, index);
Save.writePlayerData(cw.getPlayer());
//get gametime to transfer to the new world and continue counting
int time = cw.GameTime;
//set a new world
gsm.setState(GameStateManager.GAME);
//increase index to indicate the new world's index
index++;
World nw = (World)gsm.getGameState(gsm.getCurrentState());
//if its a new map
if(index == maps){
String s = newMap();
nw.reloadMap(s);
maps++;
generateRandomTree(nw);
generateRandomOre(nw, Blocks.IRON, 3);
generateRandomOre(nw, Blocks.ROCK, 10);
populateEntities(nw, Entity.PIG, 10);
//set gametime to continue counting
nw.GameTime = time;
}else{
nw.readFromSave(Save.getWorldData(index));
//set gametime to continue counting
nw.GameTime = time;
}
Save.writeRandomParts();
for(int i = 0; i < nw.tileMap.getXRows(); i++)
for(int j = 0; j < nw.tileMap.getYRows(); j++){
if(nw.tileMap.getBlockID(i, j) == 7)
nw.getPlayer().setPosition(i*32 + 32+16, j*32);
}
} |
d7e69203-a923-40e0-ae03-e04fd27b0c18 | 3 | public String render(){
StringBuilder res = new StringBuilder();
if(statusCode != 0)
res.append("HTTP/1.0 ").append(statusCode).append(" \n");
if(header == null)
res.append(body.render());
else if(body == null)
res.append(header.render());
else{
res.append(header.render());
res.append("\n");
res.append(body.render());
}
return res.toString();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.