text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public int hashCode() {
return myRHS.hashCode() ^ myLHS.hashCode();
}
| 0 |
private String generateString(String symbol, int lenght){
char[] word = new char[lenght];
for(int i=0; i<lenght; i++){
word[i] = symbol.charAt(random.nextInt(symbol.length()));
}
return new String(word);
}
| 1 |
public void createShowTimes() {
int cineplexCode;
String cinemaCode;
int movieCode;
String showTimeDate;
String showTimesString;
System.out.println("Create ShowTimes");
System.out.println("================");
System.out.println("CINEPLEX CODE\tCINEPLEX NAME");
System.out.println("..................................");
for(Cineplex cineplex: cineplexBL.getCineplexes()) {
System.out.println(cineplex.getCineplexCode() + "\t\t" + cineplex.getCineplexName());
}
System.out.println();
System.out.print("Please enter CINEPLEX CODE: ");
cineplexCode = ConsoleReader.readIntInput();
Cineplex cineplex = cineplexBL.getCineplex(cineplexCode);
if(cineplex == null){
System.out.println("Cineplex not found!");
return;
}
System.out.println();
System.out.println(cineplex.getCineplexName());
System.out.println(".................");
System.out.println("CINEMA CODE\tCINEMA NAME");
for(Cinema cinema: cineplex.getCinemas()) {
System.out.println(cinema.getCinemaCode()+"\t\t"+cinema.getCinemaName());
}
System.out.println();
System.out.print("Please enter CINEMA CODE: ");
cinemaCode = ConsoleReader.readString();
Cinema cinema = cinemaBL.getCinema(cinemaCode);
if(cinema == null){
System.out.println("Cinema not found!");
return;
}
System.out.println();
System.out.println("Movies");
System.out.println("..................");
System.out.println("MOVIE CODE\tMOVIE TITLE");
for(Movie movie: movieBL.getNowShowingMovies()) {
System.out.println(movie.getMovieCode() + "\t\t" + movie.getTitle());
}
System.out.println();
System.out.print("Please enter MOVIE CODE: ");
movieCode = ConsoleReader.readIntInput();
Movie movie = movieBL.getMovie(movieCode);
if(movie == null){
System.out.println("Error movie does not exist!");
return;
}
System.out.println();
System.out.print("Please enter date of the ShowTime (DD/MM/YYYY): ");
showTimeDate = ConsoleReader.readDateString(); //FIX ME PLEASE!!!
System.out.println();
System.out.print("Please enter time (HH:mm HH:mm ... ): ");
showTimesString = ConsoleReader.readTimeInput();
ShowTime showTime;
for(String time: showTimesString.split(" ")) {
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy HH:mm");
try {
Date date = sdf.parse(showTimeDate + " " + time);
showTimeBL.createShowTime(cinema, movie, date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 8 |
public void clearBreakpoint(int lineNumber) {
sourceLines.get(lineNumber).clearBreakpoint();
}
| 0 |
public void buildARFF(String filename) {
try {
ARFFWriter writer = new ARFFWriter(filename, "index");
String docClasses = "{";
boolean first = true;
for (String className : classes) {
if (first) {
docClasses += className;
first = false;
}
else {
docClasses += ", " + className;
}
}
writer.addAttribute("@documentClass@", docClasses + "}");
writer.addAttribute("@documentName@", "STRING");
writer.addAttribute("@hasStemming@", "NUMERIC");
for (String term : index.keySet()) {
writer.addAttribute(term, "NUMERIC");
}
writer.beginData();
for (String entry : documentVectors.keySet()) {
String[] tmp = entry.split("/");
writer.startRow();
writer.addConstantValue(true, 0, tmp[0]);
writer.addStringValue(false, 1, tmp[1]);
writer.addNumericValue(false, 2, this.useStemming ? 1 : 0);
TreeMap<Integer, Double> list = documentVectors.get(entry);
for (Integer idx : list.keySet()) {
// The first tree entries are class, name and the stemming attributes, so we have
// to add 3 to the index
writer.addNumericValue(false, idx + 3, list.get(idx).intValue());
}
writer.endRow();
}
writer.close();
logger.info("Wrote document vectors to " + filename);
} catch (Exception e) {
e.printStackTrace();
}
}
| 7 |
public boolean canAccess(String key) {
if (permissions.containsKey(key) && permissions.get(key).equals(true)) { return true; }
return false;
}
| 2 |
private static String getSuppressedString(Exception e) {
String str = "";
Throwable[] suppressed = e.getSuppressed();
if (suppressed.length == 0)
return null;
else if (suppressed.length == 1) {
return suppressed[0].toString();
} else {
str = suppressed[0].toString();
for (int i = 1; i < suppressed.length - 2; i++) {
str += suppressed[i].toString() + ", ";
}
str += suppressed[suppressed.length - 1].toString();
return str;
}
}
| 3 |
@Test
public void test() {
//Output file
File outputFile = new File("e:\\temp\\debug\\XmlVariableFileTest.xml");
if (outputFile.exists())
assertTrue(outputFile.delete());
//Create variables
// V1
StringVariable v1 = new StringVariable("v1");
v1.setCaption("c1");
v1.setDescription("v1");
v1.setId(1);
v1.setReadOnly(true);
v1.setSortIndex(1);
v1.setTextType(1);
v1.setVersion(1);
v1.setVisible(false);
try {
v1.setValue(new StringValue("v"));
} catch (Exception e) {
e.printStackTrace();
fail();
}
ValidStringValues validValues = new ValidStringValues();
validValues.addValidValue("v");
validValues.addValidValue("w");
v1.setConstraint(validValues);
// V2
BooleanVariable v2 = new BooleanVariable("v2");
try {
v2.setValue(new BooleanValue(true));
} catch (Exception e1) {
e1.printStackTrace();
fail();
}
//Create map
VariableMap vars = new VariableMap();
vars.add(v1);
vars.add(v2);
//Write
XmlVariableFileWriter writer = new XmlVariableFileWriter();
writer.write(vars, outputFile);
//Read
XmlVariableFileReader reader = new XmlVariableFileReader();
try {
vars = reader.read(outputFile.toURI().toURL());
} catch (MalformedURLException e) {
fail();
e.printStackTrace();
}
assertNotNull(vars);
//Check variables
StringVariable r1 = (StringVariable)vars.getById(1);
assertTrue(v1.getName().equals(r1.getName()));
assertTrue(v1.getCaption().equals(r1.getCaption()));
assertTrue(v1.getDescription().equals(r1.getDescription()));
assertTrue(v1.getSortIndex() == r1.getSortIndex());
assertTrue(v1.getTextType() == r1.getTextType());
assertTrue(v1.getVersion() == r1.getVersion());
assertTrue(((StringValue)v1.getValue()).val.equals(((StringValue)r1.getValue()).val));
assertNotNull(r1.getConstraint());
validValues = (ValidStringValues)r1.getConstraint();
assertTrue(validValues.getValidValues().size() == 2);
assertTrue(validValues.getValidValues().iterator().next().equals("v") || validValues.getValidValues().iterator().next().equals("w") );
BooleanVariable r2 = (BooleanVariable)vars.get("v2");
assertTrue(((BooleanValue)v2.getValue()).val == ((BooleanValue)r2.getValue()).val);
}
| 5 |
@Override
public boolean checkGrammarTree(GrammarTree grammarTree,
SyntaxAnalyser syntaxAnalyser) throws GrammarCheckException {
GrammarTree tree = grammarTree.getSubNode(0);
if (tree == null || tree.getSiblingAmount() < 5) {
this.throwExceptionAndAddErrorMsg("step", syntaxAnalyser, null);
}
syntaxAnalyser.setOperionName("step");
// determine the target cube name
checkToken(tree, TokenType.IDENTIFIER, null, true, syntaxAnalyser);
syntaxAnalyser.setTargetCube(tree.getValue().getToken());
// determine the first mutative dimension
tree = tree.next();
checkToken(tree, TokenType.IDENTIFIER, null, true, syntaxAnalyser);
syntaxAnalyser.addDimensionLevelInfo(tree.getValue().getToken(), null);
// determine the second mutative dimension
tree = tree.next();
checkToken(tree, TokenType.IDENTIFIER, null, true, syntaxAnalyser);
syntaxAnalyser.addDimensionLevelInfo(tree.getValue().getToken(), null);
// determine the dimension condition operator
int amount = tree.getNextAmount();
if (amount % 2 != 0) {
this.throwExceptionAndAddErrorMsg("step", syntaxAnalyser, null);
}
for (int i = 0; i < amount; i += 2) {
tree = tree.next();
checkToken(tree, TokenType.IDENTIFIER, null, true, syntaxAnalyser);
String operatianalDimmensionName = tree.getValue().getToken();
tree = tree.next();
checkToken(tree, TokenType.CONSTANT, null, true, syntaxAnalyser);
syntaxAnalyser.addDimensionLevelInfo(operatianalDimmensionName,
tree.getValue().getToken());
}
return true;
}
| 4 |
public static XMLReader getXMLReader(Source inputSource, SourceLocator locator)
throws TransformerException
{
try
{
XMLReader reader = (inputSource instanceof SAXSource)
? ((SAXSource) inputSource).getXMLReader() : null;
if (null == reader)
{
try {
javax.xml.parsers.SAXParserFactory factory=
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware( true );
javax.xml.parsers.SAXParser jaxpParser=
factory.newSAXParser();
reader=jaxpParser.getXMLReader();
} catch( javax.xml.parsers.ParserConfigurationException ex ) {
throw new org.xml.sax.SAXException( ex );
} catch( javax.xml.parsers.FactoryConfigurationError ex1 ) {
throw new org.xml.sax.SAXException( ex1.toString() );
} catch( NoSuchMethodError ex2 ) {
}
catch (AbstractMethodError ame){}
if(null == reader)
reader = XMLReaderFactory.createXMLReader();
}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
}
catch (org.xml.sax.SAXException se)
{
// What can we do?
// TODO: User diagnostics.
}
return reader;
}
catch (org.xml.sax.SAXException se)
{
throw new TransformerException(se.getMessage(), locator, se);
}
}
| 9 |
public void drawText(Graphics g){
g.setFont(font);
// draw lives
g.setColor(Color.WHITE);
g.drawImage(CharacterManager.boyStandFront, WindowManager.width - 100, WindowManager.height - 90, this);
g.drawString("x", WindowManager.width - 65, WindowManager.height - 50);
g.drawString(Integer.toString(CharacterManager.lives), WindowManager.width - 40, WindowManager.height - 50);
// draw pause message
/*if (!inGame && paused){
g.setColor(Color.WHITE);
g.drawString("Paused", centerText(g, "Paused"), WindowManager.height / 2);
}*/
// draw death messages
if (CharacterManager.dead){
g.setColor(Color.RED);
if (CharacterManager.lives > 0){
g.drawString("FATALITY", centerText(g, "FATALITY"), WindowManager.height / 2);
}
else {
g.drawString("GAME OVER", centerText(g, "GAME OVER"), WindowManager.height / 2);
}
}
// KOOOOOOOONAAAAAAAMIIIIIIIIIIIII!!!!!!!!!!
if (state == KONAMI){
g.setColor(new Color(0x660000));
g.drawString("Cheat Menu", centerText(g, "Cheat Menu"), 75);
drawCheckBox(g, moonJumpBox, moonJump, "Moon Jump");
drawCheckBox(g, flyBox, fly, "Fly");
drawCheckBox(g, infLivesBox, infLives, "Infinite Lives");
drawCheckBox(g, superCoinsBox, superCoins, "Super Coins");
drawCheckBox(g, invBox, inv, "Invincibility");
}
}
| 3 |
@Override
public int hashCode() {
int hash = 0;
hash += (inhusa != null ? inhusa.hashCode() : 0);
return hash;
}
| 1 |
private static void read() {
String temp = null;
try {
File file = new File(SavePath.getSettingsPath());
if(file.exists()) {
FileReader fileReader = new FileReader(file.getAbsoluteFile());
BufferedReader bufferedReader = new BufferedReader(fileReader);
temp=bufferedReader.readLine();
bufferedReader.close();
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
setDefaultSettings();
}
if (temp!=null){
convertFromString(temp);
} else {
setDefaultSettings();
}
}
| 3 |
public void dumpExpression(TabbedPrintWriter writer)
throws java.io.IOException {
if (!postfix)
writer.print(getOperatorString());
writer.startOp(writer.NO_PAREN, 2);
subExpressions[0].dumpExpression(writer);
writer.endOp();
if (postfix)
writer.print(getOperatorString());
}
| 2 |
@SuppressWarnings("unchecked")
private static void loader(){
for(String name : typeNames){
try {
types.add((Class<? extends Pet>) Class.forName(name));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| 3 |
public void visitDefExpr(final DefExpr expr) {
if (expr instanceof MemExpr) {
visitMemExpr((MemExpr) expr);
}
}
| 1 |
public PRectangle createCartesianIntersection(PRectangle src2) {
PRectangle rec = new PRectangle(src2.x, src2.y, src2.width, src2.height);
float xLeft = (x > rec.x) ? x : rec.x;
float xRight = ((x + width) > (rec.x + rec.width)) ?
(rec.x + rec.width) : (x + width);
float yBottom = ((y - height) < (rec.y - rec.height) ?
(rec.y - rec.height) : (y - height));
float yTop = (y > rec.y) ? rec.y : y;
rec.x = xLeft;
rec.y = yTop;
rec.width = xRight - xLeft;
rec.height = yTop - yBottom;
// If rectangles don't intersect, return zeroed intersection.
if (rec.width < 0 || rec.height < 0) {
rec.x = rec.y = rec.width = rec.height = 0;
}
return rec;
}
| 6 |
public String getDifficultyString() {
switch (difficulty){
case 0:
return "Human";
case 1:
return "Random";
case 2:
return "Moderate";
case 3:
return "Hard";
case 4:
return "Extreme";
default:
return "Unknown difficulty";
}
}
| 5 |
public void beginTurn()
{
for (Unit unit : units) {
unit.beginTurn();
}
}
| 1 |
public static Reminder findByApptAndUser(long apptId, long userId) throws SQLException {
PreparedStatement statement = connect.prepareStatement(
"select * from Reminder where appointmentId = ? and userId = ?");
statement.setLong(1, apptId);
statement.setLong(2, userId);
statement.executeQuery();
ResultSet resultSet = statement.getResultSet();
if(!resultSet.next()) return null;
Reminder rtn = new Reminder();
rtn.id = resultSet.getLong("id");
rtn.reminderAhead = resultSet.getLong("reminderAhead");
return rtn;
}
| 1 |
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while( slow != null &&fast!= null && fast.next!= null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
return true;
}
return false;
}
| 4 |
@Override
public void doAlgorithm() {
GraphModel g = graphData.getGraph();
boolean cont = true;
int fillin = 0;
while(cont) {
Vertex v1 = requestVertex(g, "select a vertex");
Vector<Vertex> InV = new Vector<>();
Vector<Vertex> OutV = new Vector<>();
for(Vertex v : g) {
if(g.isEdge(v,v1)) InV.add(v);
if(g.isEdge(v1,v)) OutV.add(v);
}
step("All in-edges of the selected vertex would be connected" +
"to all out-edges.");
for(Vertex iv : InV) {
for(Vertex ov : OutV) {
if(!g.isEdge(iv,ov)) {
g.addEdge(new Edge(iv,ov));
fillin++;
}
}
}
step("The selected vertex would be removed.");
g.removeVertex(v1);
step("The vertex is removed and the number of fillins is" + fillin + ".");
if(g.numOfVertices()==0) cont = false;
}
}
| 8 |
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create (Gson gson, TypeToken<T> type) {
if (!type.getRawType().isEnum())
return null;
final Map<String, T> map = Maps.newHashMap();
for (T c : (T[]) type.getRawType().getEnumConstants()) {
map.put(c.toString().toLowerCase(Locale.US), c);
}
return new TypeAdapter<T>() {
@Override
public T read (JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String name = reader.nextString();
if (name == null)
return null;
return map.get(name.toLowerCase(Locale.US));
}
@Override
public void write (JsonWriter writer, T value) throws IOException {
if (value == null) {
writer.nullValue();
} else {
writer.value(value.toString().toLowerCase(Locale.US));
}
}
};
}
| 5 |
public LearningEvaluation evalModel (InstanceStream trainStream, InstanceStream testStream, AbstractClassifier model) {
ClassificationPerformanceEvaluator evaluator = new BasicClassificationPerformanceEvaluator();
evaluator.reset();
long instancesProcessed = 0;
System.out.println("Evaluating model...");
trainModel(trainStream, model);
while (testStream.hasMoreInstances()
&& ((MaxInstances < 0) || (instancesProcessed < MaxInstances))) {
Instance testInst = (Instance) testStream.nextInstance().copy();
int trueClass = (int) testInst.classValue();
testInst.setClassMissing();
double[] prediction = model.getVotesForInstance(testInst);
evaluator.addClassificationAttempt(trueClass, prediction, testInst
.weight());
instancesProcessed++;
if (instancesProcessed % INSTANCES_BETWEEN_MONITOR_UPDATES == 0) {
long estimatedRemainingInstances = testStream
.estimatedRemainingInstances();
if (MaxInstances > 0) {
long maxRemaining = MaxInstances - instancesProcessed;
if ((estimatedRemainingInstances < 0)
|| (maxRemaining < estimatedRemainingInstances)) {
estimatedRemainingInstances = maxRemaining;
}
}
}
}
return new LearningEvaluation(evaluator.getPerformanceMeasurements());
}
| 7 |
public IndexResolution resolveIndex(final int index, final boolean fallLeftOnBoundaries) {
checkIndex(index, "Index");
if (fallLeftOnBoundaries && index==0) {
/* If falling to left at index 0, then we miss the first component completely. This is
* not useful in practice!
*/
return null;
}
/* Search for the slice containing this index. We'll search from the index of the last
* successful call to here (0 on first call) since most calls to this method are made on
* indices quite close together.
*/
IndexResolution result = null;
Slice mapping;
int sliceIndex = lastResolvedSliceIndex;
int numSlices = scoreBoard.size();
while (sliceIndex>=0 && sliceIndex<numSlices) {
mapping = scoreBoard.get(sliceIndex);
if (mapping.startIndex>index) {
/* We're too far to the right, so let's go back one place. */
sliceIndex--;
}
else if (index<mapping.endIndex || (fallLeftOnBoundaries && index==mapping.endIndex)) {
/* Success! */
result = new IndexResolution(sliceIndex, mapping, index + mapping.componentIndexOffset);
break;
}
else {
/* Move to the right */
sliceIndex++;
}
}
lastResolvedSliceIndex = result!=null ? sliceIndex : lastResolvedSliceIndex;
return result;
}
| 9 |
private static boolean readFully(InputStream in, byte[] buf) throws IOException {
int len = buf.length;
int pos = 0;
while (pos < len) {
int read = in.read(buf, pos, len - pos);
if (read == -1) {
return true;
}
pos += read;
}
return false;
}
| 2 |
private void doAction(final Pair<String> action) {
switch(action.one) {
case "add_user":
final String[] temp = action.two.split(" ");
if( temp.length == 2 ) {
if( addUser(temp[0], temp[1]) ) {
writeToScreen("ADDUSER: Added user '" + temp[0] + "' with password '" + temp[1] + "'.");
}
else {
writeToScreen("ADDUSER: Error, that user already exists!");
}
}
else writeToScreen("ADDUSER: Error, missing parameter.");
break;
case "delete_user":
if( deleteUser(action.two, users.get(action.two).getPassword()) ) {
writeToScreen("DELUSER: Deleted user '" + action.two + "'.");
}
else {
writeToScreen("DELUSER: Error, no such user!");
}
break;
case "modify_user_perms":
final String[] temp1 = action.two.split(" ");
if( temp1.length == 2 ) {
final User user = users.get(temp1[0]);
if( user != null ) {
final Integer oldPerm = user.getPerm();
final Integer newPerm = Utils.toInt(temp1[0], oldPerm);
if( newPerm != oldPerm ) {
user.setPerm( newPerm );
writeToScreen("MODPERM: Permissions changed to " + user.getPerm() + " for user '" + user.getName() + "'.");
}
else {
writeToScreen("MODPERM: Error, new permissions same as old permissions, no changes made.");
}
}
else {
writeToScreen("MODPERM: Error, no such user!");
}
}
else writeToScreen("MODPERM: Error, missing parameter.");
break;
}
}
| 9 |
public boolean setWindow(GameWindow window) {
boolean test = false;
if (test || m_test) {
System.out.println("Game :: setWindow() BEGIN");
}
m_gameWindow = window;
if (test || m_test) {
System.out.println("Game :: setWindow() END");
}
return true;
}
| 4 |
public static void main(String[] args)
{
System.out.println(getPinyin("你你好吗"));
}
| 0 |
public static String getDisplayString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return nullSafeToString(obj);
}
| 1 |
private boolean setFrameworkFieldsAndValidate(Framework f) {
if (f == null) {
f = new Framework();
}
String name = txtName.getText();
String currentVersion = txtCurrentVersion.getText();
String homePage = txtHomePage.getText();
String creator = txtCreator.getText();
String lastReleaseDate = txtReleaseDate.getText();
String description = txtDescription.getText();
String platform = txtPlatform.getText();
if (name.isEmpty() || name.length() < 3) {
validationError("Name lenght should be greater than 3");
} else if (currentVersion.isEmpty()) {
validationError("You need to inform the framework current version");
} else if (creator.isEmpty()) {
validationError("Creator is obligatory");
} else if (platform.isEmpty()) {
validationError("Platform is obligatory");
}
// passed all validations...
else {
try {
f.setDescription(description);
f.setHomePage(homePage);
f.setName(name);
f.setCreator(creator);
f.setPlatform(platform);
// can't fail the following fields, if so, it won't validate...
f.setCurrentVersion(Double.valueOf(txtCurrentVersion.getText()));
// date isn't obligatory.. but user needs to set a valid date.
if (!lastReleaseDate.isEmpty()) {
Date releaseDate = dataFormatter.parse(lastReleaseDate);
f.setLastReleaseDate(releaseDate);
}
return true;
} catch (ParseException e) {
validationError("Check Last Release Date. Use format "
+ dataFormatter.toPattern());
} catch (NumberFormatException e) {
validationError("Invalid version");
}
}
return false;
}
| 9 |
public int getTextHeight(boolean shadowed) {
int height = 10;
if (name.equalsIgnoreCase("p11_full")) {
height = 11;
}
if (name.equalsIgnoreCase("p12_full")) {
height = 14;
}
if (name.equalsIgnoreCase("b12_full")) {
height = 14;
}
if (name.equalsIgnoreCase("q8_full")) {
height = 16;
}
return height;
}
| 4 |
public void test_16_indels() {
String vcfFile = "tests/1kg.indels.vcf";
VcfFileIterator vcf = new VcfFileIterator(vcfFile);
for (VcfEntry ve : vcf) {
StringBuilder seqChangeResult = new StringBuilder();
for (Variant sc : ve.variants()) {
if (seqChangeResult.length() > 0) seqChangeResult.append(",");
seqChangeResult.append(sc.getReference() + "/" + sc.getChange());
}
String seqChangeExpected = ve.getInfo("SEQCHANGE");
Assert.assertEquals(seqChangeExpected, seqChangeResult.toString());
}
}
| 3 |
public int[] Sort(int data[], int n){
// pre: 0 <= n <= data.length
// post: values in data[0..n-1] in ascending order
int numSorted = 0; // number of values in order
int index; // general index
while (numSorted < n){ // bubble a large element to higher array index
for (index = 1; index < n-numSorted; index++){
if (data[index-1] > data[index])
swap(data,index-1,index);
} // at least one more value in place
numSorted++;
}
return data;
}
| 3 |
@Override
@EventHandler
public void handleTeamPlayerDeath(PlayerDeathEvent e) {
if (inTeam( CTFPlugin.getTeamPlayer(e.getEntity()) )) {
System.out.println("Played died");
//set the respawn point
e.getEntity().setBedSpawnLocation(spawnLocations.get(rand.nextInt(spawnLocations.size())));
for (Iterator<ItemStack> i = e.getDrops().iterator(); i.hasNext();) {
ItemStack item = i.next();
if (item != null){
if (item.getType().equals(Material.WOOL)) {
//DROP ANY FUCKING WOOL
System.out.println("PLAYER WAS HOLDING WOOL");
}
else{
i.remove();
}
}
}
//Remove inventory
e.getEntity().getInventory().clear();
}
}
| 4 |
@Override
protected String createResourceString(ArrayList<StringResource> resource, String locale) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("\n\n");
sb.append(getAutoGeneratedText());
sb.append("\n");
sb.append("<resources>");
sb.append("\n\t");
Set<String> keysAdded = new HashSet<String>();
for (int i = 0; i < resource.size(); i++) {
StringResource res = resource.get(i);
if (res != null) {
String key = sanitiseKeyString(res.getKey());
if (!key.equals("") && !keysAdded.contains(key)) {
sb.append("\n\t");
String originalString = res.getLocaleString(locale);
String replacedString = regexReplaceInString(originalString);
boolean stringUpdated = !originalString.equals(replacedString);
String formattdProperty = "";
// If a regex took place, make sure the property
// "formatted=false" is added so it can handle unordered
// string replacements.
if (stringUpdated) {
formattdProperty = " formatted=\"false\"";
}
String escapedData = escapeData(replacedString);
String value = String.format(getStringItemTemplate(), res.getDescription(), key, formattdProperty,
escapedData);
sb.append(value);
keysAdded.add(key);
}
}
}
sb.append("\n");
sb.append("</resources>");
return sb.toString();
}
| 5 |
private void initialize()
{
File f = new File("etc/map.html");
brw.setUrl(f.toURI().toString());
//
brw.addProgressListener(new ProgressListener() {
@Override
public void completed(ProgressEvent arg0) {
for(Runnable r : enqueuedMarkers)
execute(r);
enqueuedMarkers.clear();
synchronized(jsOk_lock)
{
jsOk = true;
}
}
@Override
public void changed(ProgressEvent arg0) {
// TODO Auto-generated method stub
}
});
//
mgr.addDeviceListener(new DeviceListener() {
@Override
public void onNewDevice(final Device d) {
Runnable r = new Runnable() {
@Override
public void run() {
brw.evaluate("updateMarker("+
d.getLocation().getLat()+","+
d.getLocation().getLon()+
",\""+d.getDName()+"\");");
}
};
synchronized (jsOk_lock) {
if(jsOk)
execute(r);
else
enqueuedMarkers.add(r);
}
}
@Override
public void onDeviceOut(final Device d) {
Runnable r = new Runnable() {
@Override
public void run() {
String js="removeMarker(\""+
d.getDName()+"\");";
brw.evaluate(js);
}
};
synchronized(jsOk_lock)
{
if(jsOk)
execute(r);
else
enqueuedMarkers.add(r);
}
}
});
}
| 3 |
@Override
public boolean importData( TransferSupport support )
{
if( !canImport(support) )
return false;
JTabbedPaneTransferable d = null;
try
{
d = (JTabbedPaneTransferable)support.getTransferable().getTransferData( draggableTabbedPaneFlavor );
}
catch( UnsupportedFlavorException ex )
{
throw new RuntimeException( ex );
}
catch( IOException ex )
{
throw new RuntimeException( ex );
}
final JTabbedPaneTransferable data = d;
if( data != null )
{
SwingObjFatTabbedPane pane = SwingObjFatTabbedPane.this;
int mouseX = pane.getMousePosition().x;
int mouseY = pane.getMousePosition().y;
int index = pane.indexAtLocation( mouseX, mouseY );
if( index == -1 )
{
index = pane.getTabCount();
}
else
{
// Hack to find the width of the tab (technically, this is off by one pixel, but oh well)....
int tabX1;
int tabX2;
for( tabX1 = mouseX; pane.indexAtLocation(tabX1,mouseY) == index; tabX1-- );
for( tabX2 = mouseX; pane.indexAtLocation(tabX2,mouseY) == index; tabX2++ );
int tabCenter = tabX1 + (tabX2-tabX1) / 2;
// End hack.
if( mouseX > tabCenter )
index++;
}
pane.insertTab( data.title, data.icon, data.component, data.tip, index );
pane.setSelectedComponent( data.component );
data.didImport = true;
return true;
}
return false;
}
| 8 |
@Override
public void setWorkingDay(String workingDay) {
super.setWorkingDay(workingDay);
}
| 0 |
protected void dataAttributeChanged(final BPKeyWords keyWord, final Object value) {
if (value != null) {
if (keyWord == BPKeyWords.UNIQUE_NAME) {
setValue(value);
textChanged();
} else if (keyWord == BPKeyWords.NAME || keyWord == BPKeyWords.DESCRIPTION || keyWord == BPKeyWords.DATA) {
updateAttribute(keyWord, value);
}
}
}
| 5 |
public ArrayList<String> CMBProjetos(String CodDepartamento) throws SQLException {
ArrayList<String> Projeto = new ArrayList<>();
Connection conexao = null;
PreparedStatement comando = null;
ResultSet resultado = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_SELECT_PROJETOS_POR_DEPARTAMENTO);
comando.setString(1, CodDepartamento);
resultado = comando.executeQuery();
Projeto.removeAll(Projeto);
while (resultado.next()) {
Projeto.add(resultado.getString("NOME"));
}
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
return Projeto;
}
| 7 |
public byte[] crypt(byte[] data) {
int remaining = data.length;
int llength = 0x5B0;
int start = 0;
while (remaining > 0) {
byte[] myIv = BitTools.multiplyBytes(this.iv, 4, 4);
if (remaining < llength) {
llength = remaining;
}
for (int x = start; x < (start + llength); x++) {
if ((x - start) % myIv.length == 0) {
try {
byte[] newIv = cipher.doFinal(myIv);
for (int j = 0; j < myIv.length; j++) {
myIv[j] = newIv[j];
}
// System.out
// .println("Iv is now " + HexTool.toString(this.iv));
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
data[x] ^= myIv[(x - start) % myIv.length];
}
start += llength;
remaining -= llength;
llength = 0x5B4;
}
updateIv();
return data;
}
| 7 |
public int GetNpcKiller(int NPCID) {
int Killer = 0;
int Count = 0;
for (int i = 1; i < server.playerHandler.maxPlayers; i++) {
if (Killer == 0) {
Killer = i;
Count = 1;
} else {
if (npcs[NPCID].Killing[i] > npcs[NPCID].Killing[Killer]) {
Killer = i;
Count = 1;
} else if (npcs[NPCID].Killing[i] == npcs[NPCID].Killing[Killer]) {
Count++;
}
}
}
if (Count > 1 && npcs[NPCID].Killing[npcs[NPCID].StartKilling] == npcs[NPCID].Killing[Killer]) {
Killer = npcs[NPCID].StartKilling;
}
return Killer;
}
| 6 |
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.mute"))){
sender.sendMessage(ChatColor.DARK_RED + "You do not have permission! I am going to haunt you from " +
"beyond the grave!");
return true;
}
if(args.length == 1){
Player player = Bukkit.getPlayer(args[0]);
if(player == null || !player.isOnline()){
sender.sendMessage("OH NOES! Hes not online!");
return true;
}
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.mute.exempt"))){
sender.sendMessage(ChatColor.RED + "You can't mute this player!");
return true;
}
if(pluginMain.mutedPlayers.contains(player.getName())){
pluginMain.mutedPlayers.remove(player.getName());
sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + player.getName() + ChatColor.GREEN + " has been unmuted!");
}else{
pluginMain.mutedPlayers.add(player.getName());
sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + player.getName() + ChatColor.GREEN + " has been muted!");
}
}else{
sender.sendMessage(ChatColor.DARK_RED + "Invalid Arguments! /mute [player]");
}
return true;
}
| 6 |
@Override
public void mouseClick(int X, int Y) {
Rectangle TopRect = new Rectangle(this.getSize().getWidth() -10, 0, 10, 10);
Rectangle BottomRect = new Rectangle(this.getSize().getWidth() -10, this.getSize().getHeight() - 10, 10, 10);
if(TopRect.contains(X,Y) && this.ScrollYValue > 0)
{
this.ScrollYValue -=5;
}
else if(BottomRect.contains(X,Y))
{
this.ScrollYValue += 5;
}
// Selecttion
Rectangle SelectedRect;
for(int i = 0; i < this.Items.size(); i++)
{
SelectedRect = new Rectangle(0, (i * 64) - this.ScrollYValue, this.getSize().getWidth() - 10, 64);
if(SelectedRect.contains(X,Y))
{
this.SelectedItemIndex = i;
this.SelectedItem = this.Items.get(i);
if(this.ItemListener != null)
{
this.ItemListener.selectedItemChange(this, this.SelectedItem);
}
break;
}
}
if(this.getMouseListener() != null)
{
this.getMouseListener().MouseClick(this);
}
}
| 7 |
public LLParsePane(GrammarEnvironment environment, Grammar grammar,
LLParseTable table) {
super(environment, grammar);
this.table = new LLParseTable(table) {
public boolean isCellEditable(int r, int c) {
return false;
}
};
initView();
}
| 0 |
public static void main(String[] args) {
if (args.length == 0) {
solveRandomPuzzle();
} else {
if (args[0].equals("a")) {
new IdaVSAstarComparison().run(esim1);
}
if (args[0].equals("b")) {
new AverageRunTime(new ManDist_LinearConflict()).run();
}
if (args[0].equals("c")) {
new HeuristicComparison().run(esim1);
}
if (args[0].equals("d")) {
new HeapComparison().run();
}
}
// new BruteForceTest().run(esim0);
}
| 5 |
public static void main(String[] args) throws IOException, ParseException {
int classNumber = 5; //Define the number of classes in this Naive Bayes.
int Ngram = 1; //The default value is unigram.
// The way of calculating the feature value, which can also be "TFIDF",
// "BM25"
String featureValue = "BM25";
int norm = 0;//The way of normalization.(only 1 and 2)
int lengthThreshold = 5; //Document length threshold
int minimunNumberofSentence = 2; // each document should have at least 2 sentences
/*****parameters for the two-topic topic model*****/
String topicmodel = "languageModel"; // 2topic, pLSA, HTMM, LRHTMM, Tensor, LDA_Gibbs, LDA_Variational, HTSM, LRHTSM, ParentChild_Gibbs
String category = "tablet";
int number_of_topics = 20;
boolean loadNewEggInTrain = true; // false means in training there is no reviews from NewEgg
boolean setRandomFold = false; // false means no shuffling and true means shuffling
int loadAspectSentiPrior = 0; // 0 means nothing loaded as prior; 1 = load both senti and aspect; 2 means load only aspect
double alpha = 1.0 + 1e-2, beta = 1.0 + 1e-3, eta = topicmodel.equals("LDA_Gibbs")?200:5.0;//these two parameters must be larger than 1!!!
double converge = 1e-9, lambda = 0.9; // negative converge means do not need to check likelihood convergency
int varIter = 10;
double varConverge = 1e-5;
int topK = 20, number_of_iteration = 50, crossV = 1;
int gibbs_iteration = 2000, gibbs_lag = 50;
gibbs_iteration = 4;
gibbs_lag = 2;
double burnIn = 0.4;
boolean display = true, sentence = false;
// most popular items under each category from Amazon
// needed for docSummary
String tabletProductList[] = {"B008GFRDL0"};
String cameraProductList[] = {"B005IHAIMA"};
String phoneProductList[] = {"B00COYOAYW"};
String tvProductList[] = {"B0074FGLUM"};
/*****The parameters used in loading files.*****/
String amazonFolder = "./data/amazon/tablet/topicmodel";
String newEggFolder = "./data/NewEgg";
String articleType = "Tech";
// articleType = "GadgetsArticles";
String articleFolder = String.format("./data/ParentChildTopicModel/%sArticles", articleType);
String commentFolder = String.format("./data/ParentChildTopicModel/%sComments", articleType);
String suffix = ".json";
String tokenModel = "./data/Model/en-token.bin"; //Token model.
String stnModel = null;
String posModel = null;
if (topicmodel.equals("HTMM") || topicmodel.equals("LRHTMM") || topicmodel.equals("HTSM") || topicmodel.equals("LRHTSM"))
{
stnModel = "./data/Model/en-sent.bin"; //Sentence model.
posModel = "./data/Model/en-pos-maxent.bin"; // POS model.
sentence = true;
}
String fvFile = String.format("./data/Features/fv_%dgram_topicmodel_%s.txt", Ngram, articleType);
//String fvFile = String.format("./data/Features/fv_%dgram_topicmodel.txt", Ngram);
String fvStatFile = String.format("./data/Features/fv_%dgram_stat_topicmodel.txt", Ngram);
String aspectList = "./data/Model/aspect_"+ category + ".txt";
String aspectSentiList = "./data/Model/aspect_sentiment_"+ category + ".txt";
String pathToPosWords = "./data/Model/SentiWordsPos.txt";
String pathToNegWords = "./data/Model/SentiWordsNeg.txt";
String pathToNegationWords = "./data/Model/negation_words.txt";
String pathToSentiWordNet = "./data/Model/SentiWordNet_3.0.0_20130122.txt";
File rootFolder = new File("./data/results");
if(!rootFolder.exists()){
System.out.println("creating root directory"+rootFolder);
rootFolder.mkdir();
}
Calendar today = Calendar.getInstance();
String filePrefix = String.format("./data/results/%s-%s-%s%s-%s", today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH),
today.get(Calendar.HOUR_OF_DAY), today.get(Calendar.MINUTE), topicmodel);
File resultFolder = new File(filePrefix);
if (!resultFolder.exists()) {
System.out.println("creating directory" + resultFolder);
resultFolder.mkdir();
}
String infoFilePath = filePrefix + "/Information.txt";
////store top k words distribution over topic
String topWordPath = filePrefix + "/topWords.txt";
/*****Parameters in feature selection.*****/
String stopwords = "./data/Model/stopwords.dat";
String featureSelection = "DF"; //Feature selection method.
double startProb = 0.5; // Used in feature selection, the starting point of the features.
double endProb = 0.999; // Used in feature selection, the ending point of the features.
int DFthreshold = 30; // Filter the features with DFs smaller than this threshold.
// System.out.println("Performing feature selection, wait...");
// jsonAnalyzer analyzer = new jsonAnalyzer(tokenModel, classNumber, null, Ngram, lengthThreshold);
// analyzer.LoadStopwords(stopwords);
// analyzer.LoadDirectory(folder, suffix); //Load all the documents as the data set.
// analyzer.featureSelection(fvFile, featureSelection, startProb, endProb, DFthreshold); //Select the features.
System.out.println("Creating feature vectors, wait...");
// jsonAnalyzer analyzer = new jsonAnalyzer(tokenModel, classNumber, fvFile, Ngram, lengthThreshold, stnModel, posModel);
// newEggAnalyzer analyzer = new newEggAnalyzer(tokenModel, classNumber, fvFile, Ngram, lengthThreshold, stnModel, posModel, category, 2);
/***** parent child topic model *****/
ParentChildAnalyzer analyzer = new ParentChildAnalyzer(tokenModel, classNumber, fvFile, Ngram, lengthThreshold);
analyzer.LoadParentDirectory(articleFolder, suffix);
analyzer.LoadChildDirectory(commentFolder, suffix);
// analyzer.LoadNewEggDirectory(newEggFolder, suffix); //Load all the documents as the data set.
// analyzer.LoadDirectory(amazonFolder, suffix);
// analyzer.setFeatureValues(featureValue, norm);
_Corpus c = analyzer.returnCorpus(fvStatFile); // Get the collection of all the documents.
double mu = 800;
languageModelBaseLine lm = new languageModelBaseLine(c, mu);
lm.generateReferenceModel();
lm.printTopChild4Stn(filePrefix);
// bm25Corr.rankChild4Stn(c, TopChild4StnFile);
// bm25Corr.rankStn4Child(c, TopStn4ChildFile);
// bm25Corr.rankChild4Parent(c, TopChild4ParentFile);
// bm25Corr.discoverSpecificComments(c, similarityFile);
// String DFFile = filePrefix+"/df.txt";
// bm25Corr.outputDF(c, DFFile);
}
| 7 |
public void travel()
{
while(this.isLiving == true)
{
if(settlementList.size() > 1)
{
Settlement from;
Settlement to;
for(int i=0; i<settlementList.size() -1; i++)
{
from = settlementList.get(i);
to = settlementList.get(i+1);
if(to.getPopulation() >0)
{
this.move(from, to);
this.makeDeal(to);
this.calculateSpeed();
}
else
{
settlementList.remove(to);
continue;
}
}
from = settlementList.get(settlementList.size()-1);
to = settlementList.get(0);
isSafe = false;
this.move(from, to);
isSafe = true;
this.makeDeal(to);
this.calculateSpeed();
}
}
}
| 4 |
public OutputStream getOutputStream() throws IOException {
if (output==null) {
throw new IOException("headers already sent");
}
final Charset ascii = StandardCharsets.US_ASCII;
final byte[] separ = ": ".getBytes(ascii);
final byte[] comma = ", ".getBytes(ascii);
final byte[] endl = "\n".getBytes(ascii);
final OutputStream out = this.output;
this.output = null;
final boolean gzip = this.autoGzip && this.headers.getValue("Content-Encoding")==null;
if (gzip) {
this.headers.setValue("Content-Encoding", "gzip");
}
out.write("HTTP/1.1 ".getBytes(ascii));
out.write((this.status + " " + this.statusMessage).getBytes(ascii));
out.write(endl);
for (Map.Entry<String, String[]> header : this.headers.values()) {
out.write(header.getKey().getBytes(ascii));
out.write(separ);
boolean first = true;
for (String value : header.getValue()) {
if (first) {
first = false;
} else {
out.write(comma);
}
out.write(value.getBytes(ascii));
}
out.write(endl);
}
out.write(endl);
out.flush();
if (gzip) {
return new GZIPOutputStream(out);
}
return out;
}
| 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);
}
| 7 |
@SuppressWarnings("unchecked")
public void listen() {
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket socketS = (SSLServerSocket) ssf.createServerSocket(port);
bb.net.util.Socket.enableAnonConnection(socketS);
if(MH != null) {
//MH.println("Awaiting connections on " + socketS.getLocalSocketAddress());
while(continueLoop) {
SSLSocket s = (SSLSocket) socketS.accept();
if(!continueLoop) {
s.close();
break;
}
BasicIOHandler c = new BasicIOHandler(s.getInputStream(), s.getOutputStream(), MH, false);
clientSocketList.add(s);
MH.getConnections().add(c);
Thread t = new Thread(c);
t.start();
updateUserCount();
}
MH.setServerStatus(ServerStatus.SHUTDOWN);
MH.sendPackage(new DisconnectPacket(), MH.ALL());
for(IIOHandler ica : MH.getConnections()) {
try {
ica.stop();
} catch(Throwable e) {
e.printStackTrace();
}
}
MH.getConnections().clear();
}
} catch(KeyManagementException | NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
}
| 6 |
private double[] calculateCognitiveVelocity(int particle){
double[] cognitiveVelocity = new double[position[particle].length];
for(int k = 0; k < cognitiveVelocity.length; k++){
cognitiveVelocity[k] = cognitiveConstant * (personalBest[particle][k] - position[particle][k]);
}
return cognitiveVelocity;
}
| 1 |
protected int insertWithReturn(String sql) {
try {
// createConnection();
createPreparedStatement(sql);
int affectedRows = pstmt.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating failed, no rows affected.");
}
try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getInt(1);
} else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
} catch (SQLException e) {
errorLog(sql, e);
} finally {
try {
closePreparedStatement();
// closeConnection();
} catch (SQLException e) {
errorLog(sql, e);
}
}
return 0;
}
| 4 |
public int mergeAdjacentFace (HalfEdge hedgeAdj,
Face[] discarded)
{
Face oppFace = hedgeAdj.oppositeFace();
int numDiscarded = 0;
discarded[numDiscarded++] = oppFace;
oppFace.mark = DELETED;
HalfEdge hedgeOpp = hedgeAdj.getOpposite();
HalfEdge hedgeAdjPrev = hedgeAdj.prev;
HalfEdge hedgeAdjNext = hedgeAdj.next;
HalfEdge hedgeOppPrev = hedgeOpp.prev;
HalfEdge hedgeOppNext = hedgeOpp.next;
while (hedgeAdjPrev.oppositeFace() == oppFace)
{ hedgeAdjPrev = hedgeAdjPrev.prev;
hedgeOppNext = hedgeOppNext.next;
}
while (hedgeAdjNext.oppositeFace() == oppFace)
{ hedgeOppPrev = hedgeOppPrev.prev;
hedgeAdjNext = hedgeAdjNext.next;
}
HalfEdge hedge;
for (hedge=hedgeOppNext; hedge!=hedgeOppPrev.next; hedge=hedge.next)
{ hedge.face = this;
}
if (hedgeAdj == he0)
{ he0 = hedgeAdjNext;
}
// handle the half edges at the head
Face discardedFace;
discardedFace = connectHalfEdges (hedgeOppPrev, hedgeAdjNext);
if (discardedFace != null)
{ discarded[numDiscarded++] = discardedFace;
}
// handle the half edges at the tail
discardedFace = connectHalfEdges (hedgeAdjPrev, hedgeOppNext);
if (discardedFace != null)
{ discarded[numDiscarded++] = discardedFace;
}
computeNormalAndCentroid ();
checkConsistency();
return numDiscarded;
}
| 6 |
private void findRecord(String[] data) {
String option = null;
String prefix = null;
GregorianCalendar fromGc = null;
GregorianCalendar toGc = null;
long id = 0;
try {
option = data[1].toLowerCase();
MyArrayList<Employee> findResult = new MyArrayList<>();
switch (option) {
case "id":
findResult.clear();
id = Long.parseLong(data[2]);
Employee em = container.find(id);
System.out.println(em);
break;
case "lastname":
findResult.clear();
prefix = data[2];
container.find(findResult, prefix);
if(findResult.isEmpty())
System.out.println("No Finding Result!");
else
System.out.println(findResult);
break;
case "birthday":
findResult.clear();
fromGc = parseDate(data[2]);
toGc = parseDate(data[3]);
container.find(findResult, fromGc, toGc);
if(findResult.isEmpty())
System.out.println("No Finding Result!");
else
System.out.println(findResult);
break;
default:
System.out.println("Invalid command! Try to input command once more!");
break;
}
} catch(NumberFormatException e0){
System.out.println("Illegal argument!");
} catch (IllegalArgumentException e1) {
System.out.println(e1.getMessage());
} catch (Exception e) {
System.out.println("Invalid command! Try to input command once more!");
}
}
| 8 |
private void addDoorSprite( int centerX, int centerY, int level, ShipLayout.DoorCoordinate doorCoord, SavedGameParser.DoorState doorState ) {
int offsetX = 0, offsetY = 0, w = 35, h = 35;
int levelCount = 3;
// Dom't scale the image, but pass negative size to define the fallback dummy image.
BufferedImage bigImage = getScaledImage( "img/effects/door_sheet.png", -1*((offsetX+4*w)+w), -1*((offsetY+(levelCount-1)*h)+h) );
BufferedImage[] closedImages = new BufferedImage[levelCount];
BufferedImage[] openImages = new BufferedImage[levelCount];
for (int i=0; i < levelCount; i++) {
int chop = 10; // Chop 10 pixels off the sides for skinny doors.
closedImages[i] = bigImage.getSubimage(offsetX+chop, offsetY+i*h, w-chop*2, h);
openImages[i] = bigImage.getSubimage(offsetX+4*w+chop, offsetY+i*h, w-chop*2, h);
}
DoorSprite doorSprite = new DoorSprite( closedImages, openImages, level, doorCoord, doorState );
if ( doorCoord.v == 1 )
doorSprite.setSize( closedImages[level].getWidth(), closedImages[level].getHeight() );
else
doorSprite.setSize( closedImages[level].getHeight(), closedImages[level].getWidth() );
placeSprite( centerX, centerY, doorSprite );
doorSprites.add( doorSprite );
shipPanel.add( doorSprite, DOOR_LAYER );
}
| 2 |
public static byte[] ElgamalDecrypt(String key, String base, BigInteger x, BigInteger p) throws Exception {
BigInteger c = new BigInteger(key, 16);
BigInteger a = new BigInteger(base, 16);
//decrypt m = (c - a^x)(mod p)
BigInteger m = c.subtract(a.modPow(x, p)).mod(p);
return Utilities.toBytes(m);
}
| 0 |
public static void enemyturn() {
int enemyHitChance; //enemies Hit Chance
int enemyAttack; //enemies Attack
Random rnd = new Random();
EnemyRat RatTurn = new EnemyRat();
if (enemyHealth > 0 && Statistics.Health > 0) {
enemyHitChance = rnd.nextInt(20) + 3;
if (enemyHitChance > 12) {
enemyAttack = rnd.nextInt(3) + 1;
Statistics.Health -= enemyAttack;
System.out.printf("\n Rat(%d HP): You are hit for -%d damage!\n", enemyHealth, enemyAttack);
EnemyRat.playerturn(); }
else if (enemyHitChance <= 12) {
System.out.printf("\n Rat(%d HP): The Rat misses you!\n", enemyHealth);
EnemyRat.playerturn(); }
}
else if (enemyHealth <= 0) {
System.out.printf("\n > You have killed the Rat!\n");
Room2.combatDone = true;
Room2.afterCombat();
}
}
| 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Fragestellung other = (Fragestellung) obj;
if (frageStellung == null) {
if (other.frageStellung != null)
return false;
} else if (!frageStellung.equals(other.frageStellung))
return false;
return true;
}
| 6 |
public int dimensions() {
for (int i = 0; i < desc.length(); i++) {
if (desc.charAt(i) != Type.ARRAY_CHAR) {
return i;
}
}
throw new IllegalArgumentException(desc
+ " does not have an element type.");
}
| 2 |
@Override
public ArrayList<BoardPosition> getPossibleMoves(Board board, BoardPosition startingPosition) {
//replace with enpassant - b/c pawn cannot capture when going forward
ArrayList<BoardPosition> possibleMoves = new ArrayList<BoardPosition>();
PawnStraightMove forward = new PawnStraightMove();
PawnCapture rightCapture = new PawnCapture();
PawnCapture leftCapture = new PawnCapture();
int moveLength = 1;
if ((startingPosition.getRow() == 1 && getColor() == Board.BLACK_COLOR )
|| (startingPosition.getRow() == 6 && getColor() == Board.WHITE_COLOR)) {
moveLength = 2;
}
if (getColor() == Board.BLACK_COLOR) {
BoardPosition forwardDestination = new BoardPosition(startingPosition.getColumn(),
startingPosition.getRow() + moveLength);
BoardPosition rightDestination = new BoardPosition(startingPosition.getColumn() + 1,
startingPosition.getRow() + 1);
BoardPosition leftDestination = new BoardPosition(startingPosition.getColumn() - 1,
startingPosition.getRow() + 1);
forward.setDestination(startingPosition,forwardDestination , getColor());
rightCapture.setDestination(startingPosition, rightDestination, getColor());
leftCapture.setDestination(startingPosition, leftDestination, getColor());
} else {
BoardPosition destination = new BoardPosition(startingPosition.getColumn(),
startingPosition.getRow() - moveLength);
BoardPosition rightDestination = new BoardPosition(startingPosition.getColumn() + 1,
startingPosition.getRow() - 1);
BoardPosition leftDestination = new BoardPosition(startingPosition.getColumn() - 1,
startingPosition.getRow() - 1);
forward.setDestination(startingPosition, destination, getColor());
rightCapture.setDestination(startingPosition, rightDestination, getColor());
leftCapture.setDestination(startingPosition, leftDestination, getColor());
}
try {
possibleMoves.addAll(forward.getPossibleDestinations(board));
} catch (ArrayIndexOutOfBoundsException e) { }
try {
possibleMoves.addAll(rightCapture.getPossibleDestinations(board));
} catch (ArrayIndexOutOfBoundsException e) {
//do nothing
}
try {
possibleMoves.addAll(leftCapture.getPossibleDestinations(board));
} catch (ArrayIndexOutOfBoundsException e) {
//do nothing
}
return possibleMoves;
}
| 8 |
public static void toggleCommentAndClearText(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
toggleCommentAndClearForSingleNode(currentNode, undoable);
if (!undoable.isEmpty()) {
undoable.setName("Toggle Comment and Clear Decendants for Node");
tree.getDocument().getUndoQueue().add(undoable);
}
// Redraw
layout.draw(currentNode, OutlineLayoutManager.TEXT);
}
| 1 |
public void initLoadNetFile() {
isRun = true;
urlPath = "";
savePath = "";
fileName = "";
speedKB = 0;
}
| 0 |
public static void printType(Node node)
{
System.out.print(node.getNodeName() + " type=");
int type = node.getNodeType();
switch (type)
{
case Node.COMMENT_NODE:
System.out.println("COMMENT_NODE");
break;
case Node.DOCUMENT_FRAGMENT_NODE:
System.out.println("DOCUMENT_FRAGMENT_NODE");
break;
case Node.DOCUMENT_TYPE_NODE:
System.out.println("DOCUMENT_TYPE_NODE");
break;
case Node.ELEMENT_NODE:
System.out.println("ELEMENT_NODE");
break;
case Node.ENTITY_NODE:
System.out.println("ENTITY_NODE");
break;
case Node.ENTITY_REFERENCE_NODE:
System.out.println("ENTITY_REFERENCE_NODE");
break;
case Node.NOTATION_NODE:
System.out.println("NOTATION_NODE");
break;
case Node.PROCESSING_INSTRUCTION_NODE:
System.out.println("PROCESSING_INSTRUCTION_NODE");
break;
case Node.TEXT_NODE:
System.out.println("ENTITY_NODE");
break;
default:
break;
}
}
| 9 |
private static boolean isPrime(int n) {
if (n < 10) {
return n == 2 || n == 3 || n == 5 || n == 7;
}
int end = (int) Math.ceil(Math.sqrt(n));
for (int i = 2; i <= end; i++)
if (n % i == 0)
return false;
return true;
}
| 6 |
int readPartition(ByteSequencesReader reader) throws IOException {
long start = System.currentTimeMillis();
if (valueLength != -1) {
int limit = ramBufferSize.bytes / valueLength;
for(int i=0;i<limit;i++) {
BytesRef item = null;
try {
item = reader.next();
} catch (Throwable t) {
verifyChecksum(t, reader);
}
if (item == null) {
break;
}
buffer.append(item);
}
} else {
while (true) {
BytesRef item = null;
try {
item = reader.next();
} catch (Throwable t) {
verifyChecksum(t, reader);
}
if (item == null) {
break;
}
buffer.append(item);
// Account for the created objects.
// (buffer slots do not account to buffer size.)
if (bufferBytesUsed.get() > ramBufferSize.bytes) {
break;
}
}
}
sortInfo.readTime += System.currentTimeMillis() - start;
return buffer.size();
}
| 8 |
@Override
public VirtualMachineStatus status(VirtualMachine virtualMachine)
throws Exception {
boolean vmExists = checkWhetherMachineExists(virtualMachine);
if (!vmExists) {
return VirtualMachineStatus.NOT_CREATED;
}
ProcessBuilder statusProcess = getVMProcessBuilder(virtualMachine,
"status");
ExecutionResult statusInfo = HypervisorUtils.runProcess(statusProcess);
if (statusInfo.getReturnValue() != ExecutionResult.OK) {
if (statusInfo.getReturnValue() != VSERVER_STOPPED_EXIT_VALUE) {
throw new Exception(statusInfo.getStdErr().toString());
}
}
String status = statusInfo.getStdOut().get(0);
if (status.contains("running")) {
return VirtualMachineStatus.RUNNING;
} else if (status.contains("stopped")) {
return VirtualMachineStatus.POWERED_OFF;
}
return VirtualMachineStatus.NOT_REGISTERED;
}
| 5 |
private static int[] createMask(Text[] tt) {
int[] mask = new int[9];
try {
for (int i = 0; i < tt.length; i++) {
mask[i] = Integer.parseInt(tt[i].getText());
}
} catch (Exception e) {
e.printStackTrace();
}
return mask;
}
| 2 |
public static void main(String[] args) {
// cr�ation et ouverture du fichier en lecture
Fichier fichierR = new Fichier();
fichierR.ouvrir(args[0], 'R');
String ligneInput = null;
Map<String, Vertex<String>> vertices = new HashMap<String, Vertex<String>>();
Graph<String, Integer> graph = new AdjacencyMapGraph<String, Integer>(false);
// Cr�ation du graph en lisant ligne par ligne le fichier
while((ligneInput = fichierR.lire()) != null){
String[] champs = ligneInput.split("\t");
if(champs.length != 3)
continue;
Vertex<String> u;
if((u = vertices.get(champs[0])) == null){
u = graph.insertVertex(champs[0]);
vertices.put(champs[0], u);
}
Vertex<String> v;
if((v = vertices.get(champs[1])) == null){
v = graph.insertVertex(champs[1]);
vertices.put(champs[1], v);
}
graph.insertEdge(u, v, Integer.parseInt(champs[2]));
}
// Exemple d'utilisation de l'algorithme de dijkstra pour calculer la distance entre une ville de d�part et toutes les autres
// Algorithme de Dijkstra
net.datastructures.PositionalList<Edge<Integer>> modifiedGraph = GraphAlgorithms.MST(graph);
Fichier fichierW = new Fichier();
fichierW.ouvrir(args[1], 'W');
SparseMultigraph<Integer, String> g = new SparseMultigraph<Integer, String>();
System.out.println("Ville 1 - Ville 2 - Poids");
for (Edge<Integer> edge : modifiedGraph) {
int vertex1 = Integer.valueOf((String)edge.getVertex()[0].getElement());
int vertex2 = Integer.valueOf((String)edge.getVertex()[1].getElement());
g.addVertex(vertex1);
g.addVertex(vertex2);
g.addEdge(vertex1+":"+vertex2+":"+edge.getElement(), vertex1, vertex2);
if(Integer.parseInt((String) edge.getVertex()[0].getElement()) < 10){
fichierW.ecrire(edge.getVertex()[0].getElement()+" "+edge.getVertex()[1].getElement()+" "+edge.getElement());
System.out.println(" "+edge.getVertex()[0].getElement()+" "+edge.getVertex()[1].getElement()+" "+edge.getElement());
}
else{
System.out.println(" "+edge.getVertex()[0].getElement()+" "+edge.getVertex()[1].getElement()+" "+edge.getElement());
fichierW.ecrire(edge.getVertex()[0].getElement()+" "+edge.getVertex()[1].getElement()+" "+edge.getElement());
}
}
fichierW.fermer();
Layout<Integer, String> layout = new ISOMLayout(g);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int)screenSize.getWidth();
int height = (int)screenSize.getHeight();
layout.setSize(new Dimension(width-100,height-100));
BasicVisualizationServer<Integer,String> vv = new BasicVisualizationServer<Integer,String>(layout);
vv.setPreferredSize(new Dimension(width,height)); //Sets the viewing area size
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new Transformer<String, String>() {
@Override
public String transform(String c) {
return c.split(":")[2];
}
});
JFrame frame = new JFrame("Simple Graph View");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}
| 6 |
private void indirectSort(T[] a, int[] perm, int[] aux,
int lo, int hi)
{ // Sort perm[lo..hi].
if (hi <= lo)
return;
int mid = lo + (hi - lo) / 2;
indirectSort(a, perm, aux, lo, mid); // Sort left half.
indirectSort(a, perm, aux, mid + 1, hi); // Sort right half.
mergeIndirect(a, perm, aux, lo, mid, hi); // Merge results (code on page
// 271).
}
| 1 |
@Override
public void Undo()
{
Rectangle obr = getObjectRectangle();
for (LevelItem obj : objs)
{
Rectangle r = obj.getRect();
r.x -= XDelta;
r.y -= YDelta;
r.width -= XSDelta;
r.height -= YSDelta;
obj.setRect(r);
if (obj instanceof NSMBObject && (this.XSDelta != 0 || this.YSDelta != 0))
((NSMBObject) obj).UpdateObjCache();
}
Rectangle.union(obr, getObjectRectangle(), obr);
EdControl.level.repaintTilemap(obr.x, obr.y, obr.width, obr.height);
}
| 4 |
public void setPoints(Vecteur<Integer>[] value) {
etat = value;
}
| 0 |
public void restart()
{
for(Tile t : gameBoard)
{
t.updateState(TileState.BLANK);
}
player = 1;
gameWon = false;
}
| 1 |
public static void main(String[] artgs) {
long startTime = System.nanoTime();
//the first and last digits must be 2, 3, 5, 7
// System.out.print("Primes under 10: ");
// for (int i = 2; i < 10; i++) {
// if (p7primefinder.isPrime(i)) {
// System.out.print(i + ", ");
// }
// }
// System.out.println();
// System.out.print("Primes under 100: ");
// for (int i = 10; i < 100; i++) {
// if (p7primefinder.isPrime(i)) {
// System.out.print(i + ", ");
// }
// }
// System.out.println();
// System.out.print("Primes under 1000: ");
// for (int i = 100; i < 1000; i++) {
// if (p7primefinder.isPrime(i)) {
// System.out.print(i + ", ");
// }
// }
// System.out.println();
int sum = 0, count = 0;
final int MAX = 1000000;
for (int i = 10; i <= MAX; i++) {
boolean failed = false;
int temp = i;
while (temp > 0) {
if (p7primefinder.isPrime(temp)) {
temp /= 10;
} else {
failed = true;
break;
}
}
if (!failed) {
temp = Integer.valueOf(String.valueOf(i).substring(1));
while (true) {
if (p7primefinder.isPrime(temp)) {
if (temp > 9) {
temp = Integer.valueOf(String.valueOf(temp).substring(1));
} else {
break;
}
} else {
failed = true;
break;
}
}
}
if (!failed) {
System.out.println(i);
sum += i;
count++;
}
}
long endTime = System.nanoTime();
System.out.println("Time Elapsed: 0." + (endTime - startTime) +"s");
System.out.println(count + " values with a sum of: " + sum);
}
| 8 |
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(ChooseParameterDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChooseParameterDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChooseParameterDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChooseParameterDialog.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 ChooseParameterDialog().setVisible(true);
}
});
}
| 6 |
private void button8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button8MouseClicked
if(numberofpins < 4)
{
if(numberofpins == 0)
{
Login_form.setString1("7");
}
if(numberofpins == 1)
{
Login_form.setString2("7");
}
if(numberofpins == 2)
{
Login_form.setString3("7");
}
if(numberofpins == 3)
{
Login_form.setString4("7");
}
numberofpins +=1;
jLabel2.setText(Integer.toString(numberofpins));
}
else
{
System.out.print(Timetable_main_RWRAF.checkDelete());
JOptionPane.showMessageDialog(null,"You've already entered your 4 digit pin!", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE);
}// TODO add your handling code here:
}//GEN-LAST:event_button8MouseClicked
| 5 |
public ArrayList<Trade> newRound(int round, ArrayList<EconomicIndicator> indicators, ArrayList<Stock> stocks) {
HashMap<String, Stock> stockMap = mapPrices(stocks);
ArrayList<Trade> allTrades = new ArrayList<Trade>();
for (Player player : players){
ArrayList<Trade> trades = player.placeTrade(round,
copyIndicaotrs(indicators), copyStocks(stocks), portfolios.get(player).copy());
if (trades == null){
continue;
}
for (Trade trade : trades){
if(trade.getAction() == Trade.SELL){
portfolios.get(player).sellStock(stockMap.get(trade.getStock().getName()), trade.getQuantity());
allTrades.add(trade);
}
}
for (Trade trade : trades){
if(trade.getAction() == Trade.BUY){
portfolios.get(player).buyStock(stockMap.get(trade.getStock().getName()), trade.getQuantity());
allTrades.add(trade);
}
}
}
return allTrades;
}
| 6 |
@Override
public void deserialize(Buffer buf) {
reportedId = buf.readUInt();
if (reportedId < 0 || reportedId > 4294967295L)
throw new RuntimeException("Forbidden value on reportedId = " + reportedId + ", it doesn't respect the following condition : reportedId < 0 || reportedId > 4294967295L");
reason = buf.readByte();
if (reason < 0)
throw new RuntimeException("Forbidden value on reason = " + reason + ", it doesn't respect the following condition : reason < 0");
}
| 3 |
/* */ @EventHandler
/* */ public void onPlayerInteractEntity(PlayerInteractEntityEvent event)
/* */ {
/* 225 */ if (Main.getAPI().isSpectating(event.getPlayer()))
/* */ {
/* 227 */ if (Main.getAPI().isReadyForNextScroll(event.getPlayer()))
/* */ {
/* 229 */ if (Main.getAPI().getSpectateMode(event.getPlayer()) == SpectateMode.SCROLL)
/* */ {
/* 231 */ if (Bukkit.getServer().getOnlinePlayers().length > 2)
/* */ {
/* 233 */ Main.getAPI().scrollRight(event.getPlayer(), Main.getAPI().getSpectateablePlayers());
/* 234 */ Main.getAPI().disableScroll(event.getPlayer(), 5L);
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */
/* 242 */ event.setCancelled(true);
/* 243 */ return;
/* */ }
/* */ }
| 4 |
public boolean start() {
if (socketExchanger == null) {
log.error("A socket-exchanger is required.");
}
if (serverSocket == null && !openSocketServer()) {
return false;
}
int initWorkers = socketExchanger.minWorkers;
if (initWorkers < 1) initWorkers = 1;
boolean initError = false;
try {
for (int i = 0; i < initWorkers; i++)
socketExchanger.execute(socketExchanger.getWorker(null), true);
} catch (Exception e) {
initError = true;
log.error("Failed to instantiate a socket worker.", e);
} finally {
if (initError) closeServerSocket();
}
if (initError) return false;
socketExchanger.execute(this, false);
return true;
}
| 8 |
public static void removeStateChange(int objectType, int objectX, int objectY, int objectHeight)
{
for (int index = 0; index < stateChanges.size(); index++)
{
StateObject so = stateChanges.get(index);
if(so == null)
continue;
if((so.getX() == objectX && so.getY() == objectY && so.getHeight() == objectHeight) && so.getType() == objectType || so.getStatedObject() == objectType)
{
stateChanges.remove(index);
break;
}
}
}
| 7 |
@Override
public void keyReleased(KeyEvent e) {
// if we're waiting for an "any key" typed then we don't
// want to do anything with just a "released"
if (waitingForKeyPress) {
return;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
firePressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_X) {
bombPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_B) {
epicPressed = false;
}
}
| 6 |
public void logMessage(int level, String message) {
if (this.level <= level) {
writeMessage(message);
}
if (nextLogger != null) {
nextLogger.logMessage(level, message);
}
}
| 2 |
@Points(value = 5)
@Test
public void dutchTwoHundredFrameBallAndScoreTest()
{
int[] pinsKnockedDownArray = new int[] { 1, 9, 10, 2, 8, 10, 3, 7, 10, 4, 6, 10, 5, 5, 10, 6, 4 };
for (int frameNumber = 1; frameNumber <= 9; frameNumber++)
{
assertEquals(frameNumber, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(1, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
boolean frameHasStrikeInIt = (frameNumber % 2 == 0);
if (frameHasStrikeInIt)
{
int roll = pinsKnockedDownArray[3 * (frameNumber / 2) - 1];
assert roll == 10 : "roll = " + roll + " <> 10!";
singlePlayerBowlingScoreboard_STUDENT.recordRoll(roll);
assertEquals(frameNumber + 1, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(1, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
}
else
// frameHasSpareInIt
{
int firstRoll = pinsKnockedDownArray[3 * ((frameNumber - 1) / 2)];
singlePlayerBowlingScoreboard_STUDENT.recordRoll(firstRoll);
assertEquals(frameNumber, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(2, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
int secondRoll = pinsKnockedDownArray[3 * ((frameNumber - 1) / 2) + 1];
assert firstRoll + secondRoll == 10 : "(firstRoll + secondRoll) + " + (firstRoll + secondRoll) + " <> 10!";
singlePlayerBowlingScoreboard_STUDENT.recordRoll(secondRoll);
assertEquals(frameNumber + 1, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(1, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
}
boolean lastFrameHasSpareInIt = frameHasStrikeInIt;
if (lastFrameHasSpareInIt && frameNumber > 2)
{
assertEquals(20 * (frameNumber - 1), singlePlayerBowlingScoreboard_STUDENT.getScore(frameNumber - 1));
assertEquals(20 * (frameNumber - 2), singlePlayerBowlingScoreboard_STUDENT.getScore(frameNumber - 2));
}
}
// Tenth frame:
{
assertEquals(10, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(1, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
int firstRoll = pinsKnockedDownArray[3 * (10 / 2) - 1];
assert firstRoll == 10 : "firstRoll = " + firstRoll + " <> 10!";
singlePlayerBowlingScoreboard_STUDENT.recordRoll(firstRoll);
assertEquals(180, singlePlayerBowlingScoreboard_STUDENT.getScore(9));
assertEquals(10, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(2, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
int secondRoll = pinsKnockedDownArray[3 * (10 / 2)];
singlePlayerBowlingScoreboard_STUDENT.recordRoll(secondRoll);
assertEquals(10, singlePlayerBowlingScoreboard_STUDENT.getCurrentFrame());
assertEquals(3, singlePlayerBowlingScoreboard_STUDENT.getCurrentBall());
int thirdRoll = pinsKnockedDownArray[3 * (10 / 2) + 1];
assert (secondRoll + thirdRoll) == 10 : "(secondRoll + thirdRoll) = " + (secondRoll + thirdRoll) + " <> 10!";
singlePlayerBowlingScoreboard_STUDENT.recordRoll(thirdRoll);
assertEquals(true, singlePlayerBowlingScoreboard_STUDENT.isGameOver());
}
assertEquals(200, singlePlayerBowlingScoreboard_STUDENT.getScore(10));
System.out.println("Dutch 200: \n" + singlePlayerBowlingScoreboard_STUDENT);
}
| 4 |
public CubeColor[][] getColorMapByFace(Face face) {
CubeColor[][] colorMap = new CubeColor[getCubeComplexity()][];
for (int i=0; i<getCubeComplexity(); i++) {
colorMap[i] = new CubeColor[getCubeComplexity()];
for (int j=0; j<getCubeComplexity(); j++) {
CubeColor color;
if (face == TOP) {
CubeBlock block = blockMap[getCubeComplexity() - 1 - i][0][j];
color = block.getColorList().get(0);
} else if (face == BOTTOM) {
CubeBlock block = blockMap[getCubeComplexity() - 1 - i]
[getCubeComplexity() - 1][getCubeComplexity() - 1 - j];
color = block.getColorList().get(0);
} else if (face == FRONT) {
CubeBlock block = blockMap[0][i][j];
color = getFrontRightBackFaceColor(i, j, block);
} else if (face == RIGHT) {
CubeBlock block = blockMap[j][i][getCubeComplexity() - 1];
color = getFrontRightBackFaceColor(i, j, block);
} else if (face == LEFT) {
CubeBlock block = blockMap[getCubeComplexity() - 1 - j]
[i][0];
color = getBackFaceColor(i, j, block);
} else if (face == BACK) {
CubeBlock block = blockMap[getCubeComplexity() - 1]
[i][getCubeComplexity() - 1 - j];
color = getFrontRightBackFaceColor(i, j, block);
} else {
throw new CubeException("Unknown face: "+face);
}
colorMap[i][j] = color;
}
}
return colorMap;
}
| 8 |
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(ContadorLineas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ContadorLineas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ContadorLineas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ContadorLineas.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 ContadorLineas().setVisible(true);
}
});
}
| 6 |
private void plotOverlay( Graphics2D g )
{
// If overlay drawing fails, just ignore it
try
{
File overlayImg = graphDef.getOverlay();
if ( overlayImg != null )
{
BufferedImage img = ImageIO.read(overlayImg);
int w = img.getWidth();
int h = img.getHeight();
int rgbWhite = Color.WHITE.getRGB();
int pcolor, red, green, blue;
// For better performance we might want to load all color
// ints of the overlay in one go
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
pcolor = img.getRGB(i, j);
if ( pcolor != rgbWhite )
{
red = (pcolor >> 16) & 0xff;
green = (pcolor >> 8) & 0xff;
blue = pcolor & 0xff;
g.setColor( new Color(red, green, blue) );
g.drawLine( i, j, i, j );
}
}
}
}
} catch (IOException e) {}
}
| 5 |
public void showAutoComplete(InterfaceController controller, ConstructEditor editor, IAutoCompleteListener listener, EInterfaceAction binding)
{
if(mAutoCompleteDialog != null &&
mAutoCompleteEditor != editor) {
hideAutoComplete(true);
}
// Figure out top left position of dialog
Component editorComponent = editor.get_component();
Point locationOnScreen = editorComponent.getLocationOnScreen();
Dimension sizeOnScreen = editorComponent.getSize();
Point location = new Point(locationOnScreen.x, locationOnScreen.y + sizeOnScreen.height + 5);
// Instantiate a new dialog for this editor
if(mAutoCompleteEditor == null || mAutoCompleteEditor != editor) {
mAutoCompleteEditor = editor;
mAutoCompleteDialog = new AutoCompleteDialog(controller, editor, listener, binding);
}
// Update the location of the component
// TODO: Constrain to desktop
mAutoCompleteDialog.setLocation(location);
mAutoCompleteDialog.setVisible(true);
mAutoCompleteDialog.getEntryField().requestFocus();
}
| 4 |
private JLabel getJLabel1() {
if (jLabel1 == null) {
jLabel1 = new JLabel();
jLabel1.setText("SQL:");
}
return jLabel1;
}
| 1 |
private String getExceptParams(ArrayList<String> alExcept) {
String resultado = "";
for (Map.Entry<String, String> entry : this.parameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (!value.equalsIgnoreCase("")) {
String strParam;
Iterator<String> iterator = alExcept.iterator();
Boolean encontrado = false;
while (iterator.hasNext()) {
strParam = iterator.next();
if (key.equals(strParam)) {
encontrado = true;
}
}
if (!encontrado) {
resultado += key + "=" + value + "&";
}
}
}
return resultado;
}
| 5 |
private double calcWeightsLL(int a, int b) {
double sum=0;
int ri=trainSet.getRi(a);
int rii=trainSet.getRi(b);
for (int j = 0; j < trainSet.getRi(b); j++) {
for (int k = 0; k < trainSet.getRi(a); k++) {
for (int c = 0; c < trainSet.getS(); c++) {
int Nijkc = 0;
int NJikc = 0;
int NKijc = 0;
Count countForC = getCountForClassifier(c);
Nijkc = countForC.getNijkc(a, b, j, k);
int[] classifiers = trainSet.getClassifiers();
int Nc = getNc(c);
int[] XI = trainSet.getXi(a);
for (int i = 0; i < XI.length; i++) {
if (XI[i]==k && classifiers[i]==c)
NJikc++;
}
// for (int i = 0; i < rii; i++) {
// NJikc+=countForC.getNijkc(a, b, i, k);
// }
// for (int i = 0; i < ri; i++) {
// NKijc+=countForC.getNijkc(a, b, j, i);
// }
NKijc = countForC.getNKijc(a, b, j);
double multiplier = (double)Nijkc / trainSet.getN();
double numerador=Nijkc*Nc;
double denominator = NJikc*NKijc;
double multiplied = (double)(numerador)/(denominator);
double logarithm = Math.log(multiplied)/Math.log(2);
if (!(multiplier==0 || numerador==0 || denominator==0))
sum+=multiplier*logarithm;
}
}
}
return sum;
}
| 9 |
@Test
public void testDisconnectDueToMin() throws Exception {
final Properties config = new Properties();
final int min_uptime = 20;
final int max_uptime = 2000;
config.setProperty("min_uptime", "" + min_uptime);
config.setProperty("max_uptime", "" + max_uptime);
final long started = System.currentTimeMillis();
final MockConnectionProcessor proc = new MockConnectionProcessor();
final Filter f = new DisconnectFilter(proc, config);
while (proc.disconnect_count == 0) {
Assert.assertEquals(10, f.filter(10));
Thread.sleep(min_uptime);
}
final long age = System.currentTimeMillis() - started;
Assert.assertTrue("older than min_uptime ... age=" + age + " max_uptime=" + max_uptime + " min_uptime=" + min_uptime, age > min_uptime);
Assert.assertTrue("younger than max_uptime ... age=" + age + " max_uptime=" + max_uptime + " min_uptime=" + min_uptime, age < max_uptime);
}
| 1 |
public static int getLogLevel() {
for (Map.Entry<Integer, Integer> entry : logLevelEquivalents.entrySet()) {
if (entry.getValue().equals(org.apache.log4j.Logger.getRootLogger().getLevel().toInt())) {
return entry.getKey();
}
}
return 0;
}
| 2 |
private void mouseAction(int idx) {
/* Spurious entry into cell (Random mouse movement) */
if (m_dragFlag == false || State.gameOverFlag) {
return;
}
boolean adjacent = checkAdjacentCell(idx);
if (m_Button[idx].isSelected() == false) {
if (adjacent || m_wordStack.isEmpty()) {
m_wordStack.push(idx);
markCells();
keyAction(false);
}
} else if (m_wordStack.front() == idx) /* re-entering most recently marked button */ {
unmarkCells(m_wordStack.pop());
/* Deduct last char */
wordJTextField.setText(wordJTextField.getText().substring(0, wordJTextField.getText().length() - 1));
keyAction(false);
} else { /* re-entering second most recently marked button */
Stack tempStack = new Stack(m_wordStack);
if (tempStack.numberOfElements() <= 1) {
return;
}
int mostRecent = (Integer) tempStack.pop();
int secondRecent = (Integer) tempStack.pop();
if (idx == secondRecent) {
unmarkCells(m_wordStack.pop());
/* Deduct last char */
wordJTextField.setText(wordJTextField.getText().substring(0, wordJTextField.getText().length() - 1));
keyAction(false);
}
}
}
| 8 |
public Object getChild(Object parent, int index) {
if (parent instanceof Page) {
Page p = (Page) parent;
if (index >= p.subPages.size()) {
int j = index - p.subPages.size();
return p.names.get(j);
} else {
return p.subPages.get(index);
}
} else {
return null;
}
}
| 2 |
public void visitMultiANewArrayInsn(final String desc, final int dims) {
mv.visitMultiANewArrayInsn(desc, dims);
if (constructor) {
for (int i = 0; i < dims; i++) {
popValue();
}
pushValue(OTHER);
}
}
| 2 |
protected void write(final byte[] message) throws SyslogRuntimeException {
if (this.socket == null) {
createDatagramSocket(false);
}
final InetAddress hostAddress = getHostAddress();
final DatagramPacket packet = new DatagramPacket(
message,
message.length,
hostAddress,
this.syslogConfig.getPort()
);
int attempts = 0;
while(attempts != -1 && attempts < (this.netSyslogConfig.getWriteRetries() + 1)) {
try {
this.socket.send(packet);
attempts = -1;
} catch (final IOException ioe) {
if (attempts == (this.netSyslogConfig.getWriteRetries() + 1)) {
throw new SyslogRuntimeException(ioe);
}
}
}
}
| 5 |
public void removeProduction(Production production) {
myProductions.remove(production);
GrammarChecker gc = new GrammarChecker();
/**
* Remove any variables that existed only in the production being
* removed.
*/
String[] variablesInProduction = production.getVariables();
for (int k = 0; k < variablesInProduction.length; k++) {
if (!GrammarChecker.isVariableInProductions(this,
variablesInProduction[k])) {
removeVariable(variablesInProduction[k]);
}
}
/**
* Remove any terminals that existed only in the production being
* removed.
*/
String[] terminalsInProduction = production.getTerminals();
for (int i = 0; i < terminalsInProduction.length; i++) {
if (!GrammarChecker.isTerminalInProductions(this,
terminalsInProduction[i])) {
removeTerminal(terminalsInProduction[i]);
}
}
}
| 4 |
private void cleaningText() {
int latinCount = 0, nonLatinCount = 0;
for(int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c <= 'z' && c >= 'A') {
++latinCount;
} else if (c >= '\u0300' && UnicodeBlock.of(c) != UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) {
++nonLatinCount;
}
}
if (latinCount * 2 < nonLatinCount) {
StringBuffer textWithoutLatin = new StringBuffer();
for(int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c > 'z' || c < 'A') textWithoutLatin.append(c);
}
text = textWithoutLatin;
}
}
| 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.