method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
6ffbeff5-3b43-4f55-ad3c-f58eab2a8d5a | 1 | @Test
public void enqueueTest() {
for (int i = 1; i < 8; i++) {
System.out.println("");
printTime(testArrayDequeEnqueue(100000 * (int) Math.pow(2, i)));
printTime(testQueueEnqueue(100000 * (int) Math.pow(2, i)));
}
} |
6f2bbc94-a944-4518-89a5-1e32b95635da | 8 | public boolean isAccessible(Case caseP){
return (this instanceof RobotRoues && (caseP.getNature() == NatureTerrain.TERRAIN_LIBRE || caseP.getNature() == NatureTerrain.HABITAT))
|| (this instanceof RobotChenilles && (caseP.getNature() != NatureTerrain.EAU) && (caseP.getNature() != NatureTerrain.ROCHE))
|| (this instanceof RobotPattes && (caseP.getNature() != NatureTerrain.EAU))
|| (this instanceof RobotVolant);
} |
cd83f6f3-a98f-47c4-9b90-87229b247847 | 2 | public static void display_all(List<?> list) {
for (Object t : list ){
System.out.println(t);
}
} |
cea960f0-ba00-450a-9999-6766e69bee32 | 4 | public void outputBarChart() {
System.out.println("Grade distribution: ");
int[] frequency = new int[11];
for(int grade : grades) {
++frequency[grade/10];
}
for(int count = 0; count < frequency.length; count++) {
if(count == 10)
System.out.printf("%5d: ", 100);
else
System.out.printf("%02d-%02d: ", count * 10, count * 10 + 9);
for(int stars = 0; stars < frequency[count]; stars++)
System.out.print("*");
System.out.println();
}
} |
d7dda272-7a13-491b-a2c3-c8219bda37ea | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PolicyImpl other = (PolicyImpl) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} |
b3ddc002-874c-4d5d-bae8-9a34048d9339 | 1 | public void parse() throws GOLException {
try {
checkFile();
buildBoard();
} catch (IOException ioE) {
throw new GOLException("Die Datei konnte nicht geöffnet werden.");
}
} |
31157385-7668-47a9-bb57-ee94a91538be | 6 | public static void open(boolean startnew)
{
if(closed == false)
{
try{
out.close();
closed = true;
}catch(IOException e){
System.out.println("ChangesFile.open IOException: " + e.toString());
}
}else{System.out.println("changesfile error");}
try{
File file = new File(path);
java.awt.Desktop.getDesktop().edit(file);
}catch(IOException e){
System.out.println("ChangesFile.open IOException: " + e.toString());
}
if(startnew)
{
path = "Changes.txt";
try{
out = new BufferedWriter(new FileWriter(path));
closed = false;
out.write("List of changes made:");
out.newLine();
out.newLine();
}catch(IOException e){
System.out.println("ChangesFile.initializer IOException: " + e.toString());
}catch(ExceptionInInitializerError e){
System.out.println("ChangesFile.initializer ExceptionInInitializerError: " + e.toString());
}
}
} |
297919c4-4e8f-4478-ad8d-e2e0b084c9d6 | 7 | public List<String> findGame(String gameName)
{
List<String> games = new ArrayList<String>();
String searchURL = "http://videogames.pricecharting.com/search?q=" + gameName.trim();
String line = "";
//Trys to connect to pricecharting and search.
try
{
URL url = new URL(searchURL);
BufferedReader buff = new BufferedReader(new InputStreamReader(url.openStream()));
boolean EOF = false;
//Reads the first 10 lines the 10th line
//will indicate if the game was found or multiple games were found
for(int i = 0; i<10; i++)
{
line = buff.readLine();
}
//If 10th line contains Search Results then multiple games were found
if(line.contains("| Search Results"))
{
while(!EOF)
{
line = buff.readLine().trim();
//end content indicates the end of the file.
if(line.contains("end content"))
{
EOF = true;
}
//This line is the start of each game
if(line.contains("<td class=\"title\">"))
{
String[] line2 = buff.readLine().trim().split(">");
line = line2[1].substring(0,line2[1].length()-3);
String gameURL = "http://videogames.pricecharting.com".concat(line2[0].substring(9,line2[0].length()-1));
System.out.println(gameURL);
games.add(line);
System.out.println(line);
buff.readLine().trim();
line2 = buff.readLine().trim().split(">");
line = line2[1].substring(0,line2[1].length()-4);
games.add(line);
games.add(gameURL);
System.out.println(line);
System.out.println();
}
}
}
//if Search Results was not on the 10th line then the game was found and the url can be returned.
else
{
line = line.trim();
line = line.substring(7,line.length()-8);
//Found a game
if(line.length() > 0)
{
System.out.println("Game Found!");
System.out.println(url.toString());
games.add(searchURL);
}
//Else no results were found
else
{
//no results do nothing list will be passed back empty
}
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//returns the list of games if length of this list is 1 then the game
//was an exact hit. If greater then 1 then multiple games were found.
//if list length is 0 then no results were found.
return games;
} |
25ceb60c-8202-450f-b80b-92947386bc70 | 0 | public static void main(String[] args) {
testVerifierLoginMdp();
testSelectAll();
} |
93c94e08-a8b9-4fbb-85b6-e73c4491d415 | 9 | public static boolean isKSparse(long num, int k) {
if (num <= 0 || num == 1) {
return false;
}
if ((num & (num - 1)) == 0) {
return true;
}
while (num > 0) {
if ((num & 1) > 0) {
int zcount = 0;
num >>= 1;
while ((num > 0) && ((num & 1) == 0)) {
zcount++;
num >>= 1;
}
if (zcount < k)
return false;
} else {
num >>= 1;
}
if (num == 1) {
return true;
}
}
return true;
} |
1cbcda50-6b8b-4286-9ef1-069af8d10447 | 9 | void processMongoDBComand(Command cmd) {
String sqlQuery = "";
/**
* Insert type of query.
*/
if(cmd.getType().equals(SELECT))
{
sqlQuery += (SELECT + EMPTY_SPACE);
}
/**
* Insert columns to filter.
*/
ArrayList<String> columns = cmd.getColumns();
if(columns.isEmpty() == false) {
int i = 1;
for (String value : columns) {
sqlQuery += value;
if(i < columns.size()) {
sqlQuery += COMMA;
} else {
sqlQuery += EMPTY_SPACE;
}
i++;
}
} else {
/**
* No columns to filter, so selects all columns.
*/
sqlQuery += (ALL + EMPTY_SPACE);
}
/**
* From which table and with Where clause.
*/
sqlQuery += (FROM + EMPTY_SPACE + cmd.getTableName() + EMPTY_SPACE + WHERE + EMPTY_SPACE);
/**
* Parses type of operator.
*/
HashMap<String, Condition> columnsConditions = cmd.getColumnsConditions();
Iterator it = columnsConditions.entrySet().iterator();
int i = 1;
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
Condition cond = (Condition) pairs.getValue();
/**
* Reads command value fmor Hash.
*/
String commandValue = cond.getValue();
/**
* Converts IN braces to curved parentheses.
*/
if(cond.getRestriction().contains(IN.toLowerCase())) {
commandValue = commandValue.replaceAll("\\[", "\\(").replaceAll("\\]", "\\)");
}
sqlQuery += pairs.getKey() + EMPTY_SPACE + getQualifier(cond.getRestriction()) + EMPTY_SPACE + commandValue + EMPTY_SPACE;
/**
* Assesses AND and OR clause for aggregation.
*/
if(i < columnsConditions.size()) {
if(cmd.isAndClause()){
sqlQuery += AND+EMPTY_SPACE;
}
if(cmd.isOrClause()){
sqlQuery += OR+EMPTY_SPACE;
}
} // No need for else
i++;
it.remove(); // avoids a ConcurrentModificationException
}
/**
* Write SQL query to file.
*/
writeSQLQuery(sqlQuery);
} |
e2a202a3-404d-47d4-bc04-6e212c2c64a0 | 3 | protected PlayerEntity(final Vector2d pos, final Vector2d dir) {
super(pos, dir);
switch ((int) (Math.random() * 3)) {
case COLOR_RED:
colorID = COLOR_RED;
img = ImageLoader.ship_red;
break;
case COLOR_GREEN:
colorID = COLOR_GREEN;
img = ImageLoader.ship_green;
break;
case COLOR_BLUE:
colorID = COLOR_BLUE;
img = ImageLoader.ship_blue;
break;
}
} |
7fa31b06-b243-4de4-88f2-cddef4c43df1 | 7 | private void closeRequest(OnDemandData onDemandData)
{
try
{
if(socket == null)
{
long l = System.currentTimeMillis();
if(l - openSocketTime < 4000L)
return;
openSocketTime = l;
socket = clientInstance.openSocket(43594 + client.portOff);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
outputStream.write(15);
for(int j = 0; j < 8; j++)
inputStream.read();
loopCycle = 0;
}
ioBuffer[0] = (byte)onDemandData.dataType;
ioBuffer[1] = (byte)(onDemandData.ID >> 8);
ioBuffer[2] = (byte)onDemandData.ID;
if(onDemandData.incomplete)
ioBuffer[3] = 2;
else
if(!clientInstance.loggedIn)
ioBuffer[3] = 1;
else
ioBuffer[3] = 0;
outputStream.write(ioBuffer, 0, 4);
writeLoopCycle = 0;
anInt1349 = -10000;
return;
}
catch(IOException ioexception) { }
try
{
socket.close();
}
catch(Exception _ex) { }
socket = null;
inputStream = null;
outputStream = null;
expectedSize = 0;
anInt1349++;
} |
1a187ace-a105-4bb9-96ef-700a17155f11 | 7 | public final Object put(Object key, Object value) {
int h;
for (h = firstIndex(key); table[h] != null; h = nextIndex(h)) {
if (key.equals(table[h])) {
h |= halfTableLength;
Object tem = table[h];
table[h] = value;
return tem;
}
}
if (used >= usedLimit) {
// rehash
halfTableLength = table.length;
usedLimit = (int)(halfTableLength * LOAD_FACTOR);
Object[] oldTable = table;
table = new Object[halfTableLength << 1];
for (int i = oldTable.length >> 1; i > 0;) {
--i;
if (oldTable[i] != null) {
int j;
for (j = firstIndex(oldTable[i]); table[j] != null; j = nextIndex(j))
;
table[j] = oldTable[i];
// copy the value
table[j | halfTableLength] = oldTable[i + (oldTable.length >> 1)];
}
}
for (h = firstIndex(key); table[h] != null; h = nextIndex(h))
;
}
used++;
table[h] = key;
table[h | halfTableLength] = value;
return null;
} |
15e0aa22-7e1b-44e5-8bf0-456e659eba8c | 5 | public boolean almostEquals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
Term other = (Term) obj;
if (parts == null) {
if (other.parts != null)
return false;
} else if (!parts.equals(other.parts))
return false;
return true;
} |
0bf786e7-be7c-43ba-95ea-a384333e618b | 7 | private int[][] generateTerrain(int s, double sea, double shore, double forest, double v, long sd){
int[][] terrain = new int[s][s];
HeightMapGenerator g = new HeightMapGenerator();
g.setSize(s, s);
g.setVariance(v);
g.setSeed(sd);
Random r = new Random();
r.setSeed(sd);
double[][] heightMap = g.generate();
map = new BufferedImage(s, s, BufferedImage.TYPE_INT_ARGB);
for(int x = 0; x < s; x++)
for(int y = 0; y < s; y++){
if(heightMap[x][y] <= sea){
terrain[x][y] = Static.TERRAIN_WATER;
map.setRGB(x, y, -16776961);
}
else if(heightMap[x][y] <= shore){
terrain[x][y] = Static.TERRAIN_SHORE;
map.setRGB(x, y, -128);
}
else if(heightMap[x][y] > shore){
terrain[x][y] = Static.TERRAIN_EARTH;
map.setRGB(x, y, -16744448);
}
if(heightMap[x][y] > forest){
if(r.nextDouble() > 0.95) Static.world.add(new Tree(x, y));
}
}
Static.ui.setMap(map);
return terrain;
} |
f60afeaa-fbe5-469b-b3f9-54a197e47ae4 | 6 | public boolean retainAll(Collection<?> c){
if(c == null)
return false;
if(c.isEmpty()){
clear();
return true;
}
boolean modStatus = false;
for(int i = 0; i < size; i++){
if(!c.contains(elements[i])){
remove(i);
i--;
modStatus = true;
}
}
return (modStatus) ? true : false;
} |
25959d6c-6041-4a51-b5cc-d9fc4c7063f7 | 2 | public void test_1() {
// Data calculated using R:
// x <- 1:100
// pchisq(x,1,lower.tail=F)
double chiSqPcomp[] = { 3.173105e-01, 1.572992e-01, 8.326452e-02, 4.550026e-02, 2.534732e-02, 1.430588e-02, 8.150972e-03, 4.677735e-03, 2.699796e-03, 1.565402e-03, 9.111189e-04, 5.320055e-04, 3.114910e-04, 1.828106e-04, 1.075112e-04, 6.334248e-05, 3.737982e-05, 2.209050e-05, 1.307185e-05, 7.744216e-06, 4.592834e-06, 2.726505e-06, 1.620014e-06, 9.633570e-07, 5.733031e-07, 3.414174e-07, 2.034555e-07, 1.213155e-07, 7.237830e-08, 4.320463e-08, 2.580284e-08, 1.541726e-08, 9.215887e-09, 5.511207e-09, 3.297053e-09, 1.973175e-09, 1.181292e-09, 7.074463e-10, 4.238055e-10, 2.539629e-10, 1.522292e-10, 9.127342e-11, 5.473986e-11, 3.283759e-11, 1.970344e-11, 1.182530e-11, 7.098670e-12, 4.262192e-12, 2.559625e-12, 1.537460e-12, 9.236597e-13, 5.550063e-13, 3.335484e-13, 2.004896e-13, 1.205298e-13, 7.247102e-14, 4.358119e-14, 2.621178e-14, 1.576720e-14, 9.485738e-15, 5.707481e-15, 3.434573e-15, 2.067066e-15, 1.244192e-15, 7.489807e-16, 4.509230e-16, 2.715071e-16, 1.634955e-16, 9.846344e-17,
5.930446e-17, 3.572249e-17, 2.151974e-17, 1.296498e-17, 7.811703e-18, 4.707141e-18, 2.836647e-18, 1.709580e-18, 1.030406e-18, 6.210993e-19, 3.744097e-19, 2.257177e-19, 1.360867e-19, 8.205339e-20, 4.947748e-20, 2.983651e-20, 1.799356e-20, 1.085212e-20, 6.545447e-21, 3.948125e-21, 2.381600e-21, 1.436721e-21, 8.667648e-22, 5.229434e-22, 3.155239e-22, 1.903853e-22, 1.148835e-22, 6.932733e-23, 4.183826e-23, 2.525018e-23, 1.523971e-23 };
// Let's see if our ChiSquare is OK
for (int i = 0; i < chiSqPcomp.length; i++) {
double x = i + 1;
double p = FisherExactTest.get().chiSquareCDFComplementary(x, 1);
double diff = Math.abs(p - chiSqPcomp[i]) / chiSqPcomp[i];
if (verbose) Gpr.debug("pvalue: " + p + "\tpvalue (from R): " + chiSqPcomp[i] + "\tdifference: " + diff);
Assert.assertTrue(diff < MAX_DIFF);
}
} |
ddbff60b-f2e1-4d99-b098-9afe3f00a3ca | 3 | private static File[] removeDotFiles( File[] versions )
{
Vector<File> files = new Vector<File>();
for ( int i=0;i<versions.length;i++ )
if ( !versions[i].getName().startsWith(".")
&& versions[i].isFile() )
files.add( versions[i] );
versions = new File[files.size()];
files.toArray( versions );
return versions;
} |
94c9f568-61b3-48d4-b2ef-bf255b8be7af | 0 | private FSALabelHandler() {
} |
88909add-bac0-4ca1-9265-402cd11f90d1 | 5 | public Object getField(Reference ref, Object obj)
throws InterpreterException {
if (isWhite(ref))
return super.getField(ref, obj);
FieldIdentifier fi = (FieldIdentifier) Main.getClassBundle()
.getIdentifier(ref);
if (fi != null && !fi.isNotConstant()) {
Object result = fi.getConstant();
if (currentFieldListener != null)
fi.addFieldListener(currentFieldListener);
if (result == null)
result = getDefaultValue(ref.getType());
return result;
}
throw new InterpreterException("Field " + ref + " not constant");
} |
bbc72e09-30ea-4628-aa6b-a01bf85243ff | 2 | public void update() {
super.update();
try {
if (motorRunning)
movement();
} catch (Throwable t) {
motorRunning = false;
getArena().motorFailure(SpriteMobile.this, t);
}
} |
d967177c-a84c-4506-9bc2-9f4f6a1c3d84 | 7 | public void scanColumn(int columnPoint) {
HashMap<Integer, SpanInfo> rowMap = new HashMap<Integer, SpanInfo>();
SpanInfo si = new SpanInfo();
si.name = originTable[0][columnPoint];
si.row = 0;
si.num = 0;
rowMap.put(0, si);
for (int i = 0; i < originTable.length; i++) {
if (si.name.equals(originTable[i][columnPoint])) {
si.num++;
if (i == originTable.length - 1) {
for (int j = si.row; j < si.row + si.num; j++) {
rowMap.put(j, si);
}
}
} else {
for (int j = si.row; j < si.row + si.num; j++) {
rowMap.put(j, si);
}
si = new SpanInfo();
si.name = originTable[i][columnPoint];
si.row = i;
si.num = 1;
if (i == originTable.length - 1) {
for (int j = si.row; j < si.row + si.num; j++) {
rowMap.put(j, si);
}
}
}
}
columnMap.put(columnPoint, rowMap);
} |
7f532250-0501-45f5-996c-3ba415320781 | 9 | public static void analyzeListSorts(){
TreeMap<Long, Class<?>> map = new TreeMap<Long, Class<?>>();
List<Class<?>> sorts = getSorts();
for(Class<?> clazz : sorts){
sampleListTest(clazz, false);
System.out.println("--------");
}
for(Class<?> clazz : sorts){
long time = sampleListTest(clazz, false);
System.out.println("--------");
map.put(time, clazz);
}
for(Map.Entry<Long, Class<?>> entry : map.entrySet()){
System.out.println(entry.getValue().getSimpleName() + " sort: "
+ entry.getKey() + " ns");
}
} |
1d60f3f5-f5d8-44f5-a2c4-0959aa5e37e9 | 5 | @Override
/**
* Decides how to act at a given state of the game
* @param raiseAllowed is it allowed to raise or not
*/
public PlayerAction makeBet(boolean raiseAllowed) throws Exception {
PlayerAction action = new PlayerAction();
action.oldStake = currentBet;
if (folded) {
action.action = PlayerAction.ACTION.FOLD;
return action;
}
action = strategy.chooseAction(state, this);
double payToCall = state.getBiggestRaise() - currentBet;
action.potOdd = payToCall / (payToCall + state.getPot());
if (action.action == PlayerAction.ACTION.CALL
|| (action.action == PlayerAction.ACTION.RAISE && !raiseAllowed)) {
action.action = PlayerAction.ACTION.CALL;
action.toPay = state.getBiggestRaise() - currentBet;
makeRaise(action.toPay);
} else if (action.action == PlayerAction.ACTION.RAISE) {
makeRaise(action.toPay);
} else { // Fold
folded = true;
action.action = PlayerAction.ACTION.FOLD;
}
return action;
} |
3ebdf616-b1a8-4139-b4f2-14448e9888d3 | 7 | public void makeManufacturer(String[] names, TechType[] types)
{
if(names.length%3!=0)
Log.errOut("Test: Not /3 names: "+CMParms.toListString(names));
else
{
for(int i=0;i<6;i++)
{
Manufacturer M=CMLib.tech().getManufacturer(names[i]);
if((M!=null)&&(M!=CMLib.tech().getDefaultManufacturer()))
{
Log.errOut("Dup Reset Manufacturer Name: "+names[i]);
continue;
}
M=(Manufacturer)CMClass.getCommon("DefaultManufacturer");
M.setName(names[i]);
if(i%3==0)
{
M.setMinTechLevelDiff((byte)0);
M.setMaxTechLevelDiff((byte)(M.getMinTechLevelDiff()+CMLib.dice().roll(1, 3, 2)));
}
else
if(i%3==1)
{
M.setMinTechLevelDiff((byte)3);
M.setMaxTechLevelDiff((byte)(M.getMinTechLevelDiff()+CMLib.dice().roll(1, 3, 2)));
}
else
if(i%3==2)
{
M.setMinTechLevelDiff((byte)(8-CMLib.dice().roll(1, 3, 0)));
M.setMaxTechLevelDiff((byte)10);
}
M.setEfficiencyPct(0.75+CMath.div(CMLib.dice().rollNormalDistribution(1, 50, 0),100.0));
M.setReliabilityPct(0.75+CMath.div(CMLib.dice().rollNormalDistribution(1, 50, 0),100.0));
M.setManufactureredTypesList(CMParms.toListString(types));
CMLib.tech().addManufacturer(M);
}
}
} |
9bbbcf25-936f-4b98-b307-4bd4ac9524c0 | 4 | private void initialPropertyChange(PropertyChangeEvent e) {
switch (e.getPropertyName()) {
case Labels.SEND_INITIAL_DVIEW:
if (e.getOldValue() instanceof DocumentView
&& e.getNewValue() instanceof Integer) {
DocumentView docView = (DocumentView) e.getOldValue();
docCon.addDocView((int) e.getNewValue(), docView);
docCon.getView(docCon.getCurrentID())
.addPropertyChangeListener(this);
}
break;
case Labels.UPDATE_INITIAL_TOOLBAR:
JTextComponent curTextSection = docCon
.getView(docCon.getCurrentID()).getTemplatePanel()
.getCurrentSection();
ITextSection curText = docCon.getDoc(docCon.getCurrentID())
.getSectionTexts()
.get(Translator.containerToSection(curTextSection));
mainView.getToolbarPanel().getTextFontCombo()
.setSelectedItem(curText.getFont());
mainView.getToolbarPanel().getTextSizeCombo()
.setSelectedItem(curText.getSize());
mainView.getToolbarPanel().getTextColorCombo()
.setSelectedItem(curText.getColor());
default:
// Do nothing, never invoked
break;
}
} |
be99e99b-bc53-4234-9ff0-ec7d869ba323 | 6 | public boolean checkCounter(char area){
switch (area){
case 'a': if(counter<6) return false; break;
case 'b': if(counter<16) return false; break;
case 'c': if(counter<2) return false; break;
}
return true;
} |
0310a331-00ea-477b-a0fc-0e16f95f6613 | 2 | @Override
public int compareTo(AstronomicalObject o) {
return (this.mass < o.mass) ? -1 : (this.mass > o.mass) ? 1 : 0;
} |
fb0882b0-85cb-47e4-8cff-277c7f689465 | 7 | @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public String viewUserById(@PathVariable int userId, @RequestParam(value = "origin", required = false)String origin, Model model) {
User user = (User)(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
GrantedAuthority targetAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
List<ROLE> userRoles;
String userType = "";
if(userId != userDao.getUserByName(user.getUsername()).getUser_id() && !user.getAuthorities().contains(targetAuthority)) {
return "403";
}
if(userDao.getUserById(userId) == null) {
model.asMap().clear();
return "redirect:overall";
}
if(origin != null) {
model.addAttribute("origin", origin);
}
userRoles = userDao.getUserRolesByUserID(userId);
if(userRoles != null) {
if(userRoles.contains(ROLE.ROLE_ADMIN)) {
userType = "Administrator";
} else if(userRoles.contains(ROLE.ROLE_USER)) {
userType = "User";
}
}
model.addAttribute("sysUser", userDao.getUserById(userId));
model.addAttribute("userType", userType);
return "user_view";
} |
b55c2949-a193-42a1-84a0-374c6b67e8a0 | 6 | public void addShapeList(ShapeList sl, Hashtable<String, ImageArea> areas)
throws Exception {
if (areas != null && areas.size() > 0) {
ImagemapShape imshape = null;
ImageArea area = null;
Shape shape = null;
for (String key : areas.keySet()) {
imshape = null;
area = areas.get(key);
shape = area.getShape();
System.out.println(key + " = " + areas.get(key));
System.out.println(shape);
if (shape.getType().compareToIgnoreCase("rect") == 0) {
Rectangle rect = shape.getRect();
imshape = new ImagemapShape(rect.x, rect.y, rect.x
+ rect.width, rect.y + rect.height);
} else if (shape.getType().compareToIgnoreCase("poly") == 0) {
Polygon poly = shape.getPoly();
imshape = new ImagemapShape(poly);
} else if (shape.getType().compareToIgnoreCase("circle") == 0) {
Circle circle = shape.getCircle();
imshape = new ImagemapShape(circle);
} else
throw new Exception("illegal shape " + shape.getType());
imshape.setId(area.getId());
imshape.set_comp(area.getComparitor());
imshape.set_name(area.getName());
imshape.setImageFile(area.getImageFile());
sl.add_shape(imshape);
}
}
} |
98f2e17d-3990-4ac9-8b6d-d0e503db06c1 | 8 | private boolean acceptLicense() {
StringBuffer licenseText = new StringBuffer();
InputStream is;
try {
JarFile extractJar = new JarFile("extract.jar");
is = extractJar.getInputStream(extractJar.getJarEntry("license/cpl-v10.html"));
} catch (IOException e) {
return true;
}
if (is == null) {
return true;
}
InputStreamReader isr = null;
BufferedReader br = null;
try {
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line = br.readLine();
while (line != null) {
licenseText.append(line);
line = br.readLine();
}
return acceptReject(licenseText.toString());
} catch (IOException e) {
System.err.println("Could not read line from license file: " + e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
} |
73baa67a-77bd-4d00-b1a3-48b7eea618f6 | 5 | public void defineField(String fieldname, String guiname, String type) {
try {
if (fields.contains(fieldname)) return;
if (guiname==null) guiname=fieldname;
fields.add(fieldname);
fieldtypes.put(fieldname,type);
fieldguinames.put(fieldname,guiname);
addGuiComponent(fieldname);
if (cls!=null) {
Field field = cls.getField(fieldname);
// if obj==null we get an undocumented exception in case the field
// is NOT static, so we assume that the field is appropriately
// static for now.
setField(fieldname, field.get(obj),true);
}
} catch (NoSuchFieldException e) {
System.out.println("Cls:"+cls);
throw new JGameError("Field "+fieldname+" not found.");
} catch (IllegalAccessException e) {
throw new JGameError("Field "+fieldname+" has access error.");
} } |
2f85d587-b281-44c8-8b7b-3a93f3711c5d | 6 | public boolean hasHighSeasMove() {
if (canMoveToHighSeas()) return true;
Tile tile = getTile();
if (tile != null && getMovesLeft() > 0) {
for (Tile t : tile.getSurroundingTiles(1)) {
if (t.isDirectlyHighSeasConnected()
&& getMoveType(t).isLegal()) return true;
}
}
return false;
} |
31fd73f3-f7e2-4682-864b-a68a97406868 | 5 | private void dyingUpdate(Vector3f orientation, float distance){
double time = ((double)Time.getTime())/((double)Time.SECOND);
double timeDecimals = time - (double)((int)time);
if(deathTime == 0)
deathTime = time;
final float time1 = 0.1f;
final float time2 = 0.3f;
final float time3 = 0.45f;
final float time4 = 0.6f;
if(time < deathTime + time1){
material.setTexture(animations.get(6));
transform.setScale(1,0.96428571428571428571428571428571f,1);
}else if(time < deathTime + time2){
material.setTexture(animations.get(7));
transform.setScale(1.7f,0.9f,1);
}else if(time < deathTime + time3){
material.setTexture(animations.get(8));
transform.setScale(1.7f,0.9f,1);
}else if(time < deathTime + time4){
material.setTexture(animations.get(9));
transform.setScale(1.7f,0.5f,1);
}else{
state = DEAD;
}
} |
5a447db9-585d-4378-8843-3d178601a310 | 6 | @Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == addVehicle) {
addVehicle();
} else if (source == removeVehicle) {
removeVehicle();
} else if (source instanceof Vehicle) {
Vehicle vehicle = (Vehicle) source;
if (e.getActionCommand().equals(Constants.OPERATION_CREATE)) {
addVehicle(vehicle);
} else if (e.getActionCommand().equals(Constants.OPERATION_UPDATE)) {
updateVehicle(vehicle);
} else if (e.getActionCommand().equals(Constants.OPERATION_DELETE)) {
removeVehicle(vehicle);
}
}
} |
1a9865a8-ad03-4e49-84be-2bfec5b3abe2 | 0 | public static void welcome() {
} |
f6a98a5d-41cc-4dfc-9b73-8724daa58300 | 8 | public static boolean cppTypeWithoutInteriorPointersP(StandardObject typespec) {
{ Surrogate basetype = StandardObject.typeSpecToBaseType(typespec);
Stella_Class renamed_Class = ((Stella_Class)(basetype.surrogateValue));
if (StandardObject.arrayTypeSpecifierP(typespec)) {
return (StandardObject.cppNonPointerTypeP(StandardObject.extractParameterType(typespec, Stella.SYM_STELLA_ANY_VALUE, new Object[1])));
}
if (Stella_Class.createNativeClassP(renamed_Class) &&
(!Surrogate.subtypeOfP(basetype, Stella.SGT_STELLA_NATIVE_EXCEPTION))) {
{ boolean alwaysP000 = true;
{ Slot slot = null;
Iterator iter000 = renamed_Class.classSlots();
loop000 : while (iter000.nextP()) {
slot = ((Slot)(iter000.value));
if (Stella_Object.storageSlotP(slot) &&
(StorageSlot.nativeSlotP(((StorageSlot)(slot))) &&
(!StorageSlot.slotHasUnknownTypeP(((StorageSlot)(slot)), renamed_Class)))) {
if (!StandardObject.cppNonPointerTypeP(slot.slotBaseType)) {
alwaysP000 = false;
break loop000;
}
}
}
}
{ boolean value000 = alwaysP000;
return (value000);
}
}
}
return (false);
}
} |
26925f90-0f48-4903-9578-c6a5ac15d53a | 5 | @Override
public void run() {
// First place an order:
for(Course course : Course.values()) {
Food food = course.randomSelection();
table.placeOrder(this, food);
++nPlates;
}
try {
barrier.await();
} catch(InterruptedException ie) {
print(this + " interrupted while ordering meal");
return;
} catch(BrokenBarrierException e) {
throw new RuntimeException(e);
}
// Now wait for each ordered plate:
for(int i = 0; i < nPlates; i++)
try {
// Blocks until course has been delivered:
print(this + "eating " + placeSetting.take());
} catch(InterruptedException e) {
print(this + "waiting for meal interrupted");
return;
}
print(this + "finished meal, leaving");
} |
121813f7-886f-44e1-a9c3-3a17751a4660 | 6 | private static String verifyUrl(String url, ArrayList<String> keyWordsInURL,ArrayList<String> exclusionKeyWords) {
if (!url.toLowerCase().startsWith("http")) {
return null;
}
try {
new URL(url);
}
catch (MalformedURLException e) {
Logger.getLogger(Crawler.class).debug("Exception :"+e.getMessage() + " Description :"+ e.toString());
return null;
}
for(int i=0; i<keyWordsInURL.size(); i++){
if(!url.toLowerCase().contains(keyWordsInURL.get(i).toLowerCase())){
return null;
}
}
for(int i=0; i<exclusionKeyWords.size(); i++){
if(url.toLowerCase().contains(exclusionKeyWords.get(i).toLowerCase())){
return null;
}
}
return url;
} |
256215f0-e2e3-4b69-92f3-a4aa7a6a6a7b | 7 | public double getLinfDistance(finger_print fp){
double score=0;
double max=0;
for(Integer key : this.feature_map.keySet()){
if(fp.feature_map.containsKey(key)){
score=Math.pow(this.feature_map.get(key)-fp.feature_map.get(key), 1);
if(score >max) max=score;
}
else {
score=Math.pow(this.feature_map.get(key), 1);
if(score >max) max=score;
}
}
for(Integer key : fp.feature_map.keySet()){
if(!this.feature_map.containsKey(key)){
score=Math.pow(fp.feature_map.get(key), 1);
if(score >max) max=score;
}
}
return max;
} |
f614a38f-172c-4733-bd24-dbbad3ab1690 | 0 | public void setjLabelPrenom(JLabel jLabelPrenom) {
this.jLabelPrenom = jLabelPrenom;
} |
10887a25-753a-4624-8825-bfd53397ec24 | 9 | public boolean checkIfOne(String num)
{
switch(num)
{
case "one": return true;
case "two": return true;
case "three": return true;
case "four": return true;
case "five": return true;
case "six": return true;
case "seven": return true;
case "eight": return true;
case "nine": return true;
default: return false;
}
} |
2038a51e-9d69-4e14-8153-ffac590dfb95 | 2 | @Override
public Move getMove(Board board) {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inputStreamReader);
try {
System.out.print("Starting coord: ");
String s1 = reader.readLine();
Coordinate startingCoord = new Coordinate(s1);
System.out.print("Ending coord: ");
String s2 = reader.readLine();
Coordinate endingCoord = new Coordinate(s2);
Move move = new Move(startingCoord, endingCoord);
return move;
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
return getMove(board);
}
return null;
} |
1689a2a3-406d-4dc7-9fcf-aa645b79d857 | 1 | public void updateDepsAll(){
updateDeps();
for (GameObject child: children){
child.updateDepsAll();
}
} |
23829f2b-93d7-4f06-b1ae-d682000628f7 | 5 | public String ping() {
if (domain == null || domain.isEmpty())
return "Input domain is not correct";
StringBuffer buf = new StringBuffer();
String s = "";
Process process = null;
try {
process = Runtime.getRuntime().exec("cmd /c " + "ping " + domain);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((s = br.readLine()) != null) {
buf.append(s + "\r\n");
}
process.waitFor();
logger.info(buf.toString());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (process != null)
process.destroy();
}
return buf.toString();
} |
a46caa1a-9c1e-4c8a-8151-144aa84569bd | 8 | final Class258_Sub2 method2256(byte i) {
anInt8692++;
if (i != -121)
method2256((byte) 33);
if (aClass258_Sub2_8688 == null) {
d var_d = ((AbstractToolkit) aHa_Sub2_8693).aD4579;
Class308.anIntArray3883[3] = anInt8690;
Class308.anIntArray3883[4] = anInt8686;
Class308.anIntArray3883[2] = anInt8691;
Class308.anIntArray3883[5] = anInt8697;
Class308.anIntArray3883[1] = anInt8695;
Class308.anIntArray3883[0] = anInt8689;
boolean bool = false;
int i_0_ = 0;
for (int i_1_ = 0; i_1_ < 6; i_1_++) {
if (!var_d.method4(i ^ 0x1f68, Class308.anIntArray3883[i_1_]))
return null;
TextureDefinition class12
= var_d.getTexture(Class308.anIntArray3883[i_1_], -6662);
int i_2_ = !((TextureDefinition) class12).aBoolean199 ? 128 : 64;
if (i_0_ < i_2_)
i_0_ = i_2_;
if ((((TextureDefinition) class12).aByte205 ^ 0xffffffff) < -1)
bool = true;
}
for (int i_3_ = 0; (i_3_ ^ 0xffffffff) > -7; i_3_++)
Class341.anIntArrayArray4233[i_3_]
= var_d.method5(false, Class308.anIntArray3883[i_3_], 1.0F,
i_0_, i_0_, i + 192);
aClass258_Sub2_8688
= new Class258_Sub2(aHa_Sub2_8693, 6407, i_0_, bool,
Class341.anIntArrayArray4233);
}
return aClass258_Sub2_8688;
} |
0efa1591-bd56-434f-b88f-2489b22e23a0 | 0 | public MinecraftApplet(String mine_bin_path, URL[] urls){
this.mine_bin_path = mine_bin_path;
this.urls = urls;
} |
793c5492-01ac-4558-ba40-2ec361102626 | 7 | private boolean isSingleProjectDirectory(File dir) {
List<File> files = dirFilelist(dir);
List<File> dirs = dirDirlist(dir);
for (File f : files) {
for (String ext : PROJECT_EXTENSIONS) {
if (f.getName().endsWith(ext))
return true;
}
}
for (File f : dirs) {
for (String ext : PROJECT_EXTENSIONS) {
if (ext.endsWith("/") && (f.getAbsolutePath().replaceAll("\\\\", "/") + "/").endsWith(ext))
return true;
}
}
return false;
} |
63379b88-b64a-4bfa-ab74-cf7d8a6efe1d | 6 | @Override
protected void process(Set<ICollidable> collidables)
{
//Remove finished objects
Iterator<ICollidable> it_remover = collidables.iterator();
while(it_remover.hasNext())
{
if(it_remover.next().isFinished())
{
it_remover.remove();
}
}
for(ICollidable collidable : collidables)
{
//The collisions for the collidable
Set<Direction> collisions = new HashSet<Direction>();
//Clear old data for collidables colliding with the collidable
collidingCollidables.get(collidable).clear();
for(ICollidable otherCollidable : collidables)
{
//Don't compare if it's the same collidable. It does not collide with itself.
if(collidable == otherCollidable)
{
continue;
}
Set<Direction> collisionsFound = getCollision(collidable, otherCollidable);
// Log.debug("Collision retrieved: " + collision);
if(!collisionsFound.isEmpty())
{
collisions.addAll(collisionsFound);
//Add this collidable to the set of collidables colliding with the target collidable
collidingCollidables.get(collidable).add(otherCollidable);
}
}
collidable.onCollision(collisions);
//overwrite old set of collisions with latest data
collidableCollisions.put(collidable, collisions);
}
} |
0c8fa2dd-0e52-4b2c-ac03-3b250358a4a0 | 1 | public void log(String message) {
if(debug) {
int i = indent.get();
System.out.println(indent(i) + message);
}
} |
e69fbcee-6281-4744-97c5-aeab6a3bd8dc | 5 | public void keoista(int i) {
int vasen = vasen(i);
int oikea = oikea(i);
int pienin;
if (oikea <= keonKoko) {
if (keko[vasen] < keko[oikea]) {
pienin = vasen;
} else {
pienin = oikea;
}
if (keko[i] > keko[pienin]) {
vaihda(i, pienin);
keoista(pienin);
}
} else if (vasen == keonKoko && keko[i] > keko[vasen]) {
vaihda(i, vasen);
}
} |
e93f3761-0647-4957-909e-e6ea32db4b32 | 7 | public void trainBtnPress()
{
//make or load a nerual network
//currently we are just creating a new one based on the given topology.
//-- Get the topology.
//Create a neural network with given topology.
//Get hidden topology
String [] sigHidden = sigNetNeurons.getText().split(",");
String [] scrawlHidden = scrawlNetNeurons.getText().split(",");
int tempInt;
ArrayList<Integer> sigList = new ArrayList<Integer>();
ArrayList<Integer> scrawlList = new ArrayList<Integer>();
int[] sigTop;
int [] scrawlTop;
//put sig into the list
for (String str : sigHidden)
{
tempInt = Integer.parseInt(str);
if (tempInt > 0)
{
sigList.add(tempInt);
}
}
//put scrawl into the list
for (String str : scrawlHidden)
{
tempInt = Integer.parseInt(str);
if (tempInt > 0)
{
scrawlList.add(tempInt);
}
}
tempInt = 0;
sigTop = new int[sigList.size()];
for (Integer theInt : sigList)
{
sigTop[tempInt++] = theInt.intValue();
}
tempInt = 0;
scrawlTop = new int[scrawlList.size()];
for (Integer theInt : scrawlList)
{
scrawlTop[tempInt++] = theInt.intValue();
}
//-- Got the topology.
//-- Create the neural network.
controller.createNetworkIfNotExist(sigTop,scrawlTop);
//-- Created the neural network
//-- Train the neural network.
if (trainingFile != null)
{
controller.trainNetwork(trainingFile, ((Integer)itrSpinner.getValue()).intValue() );
}
else
{
return;
}
//-- Trained the neural network.
//-- Compute the accuracy and print the results
controller.printAccuracy();
//-- Computed the accuracy and printed the results
} |
970c55fc-3ef8-4fe0-845e-2530b4f50546 | 8 | public void Dijkstra(int startNode) {
System.out.println("Dijkestra's shortest path to all nodes");
Node[] S = new Node[size]; //All vertices for which we have computed the shortest distance
Node[] p = new Node[size]; //array of predecessors of v in the path s to v
PriorityQueue<Node> V_S = new PriorityQueue(); //Vertices waiting to be processed
int S_tail = 0;
Node start = graph[startNode];
S[S_tail] = start; //Initialize S with start vertex
start.d = 0;
S_tail++;
/*Initialize V_S with the remaining vertices*/
int currentNode = startNode;
currentNode = (currentNode + 1) % size;
while (currentNode != startNode) {
Node v = graph[currentNode];
/*for all v in V_S (line 2 - 6)*/
int vIndex = (int) (v.getItem() - 65); //find index in matrix
p[vIndex] = S[0];
if (S[0].connections[vIndex] != null) { //if there is an edge (s,v)
v.d = S[0].connections[vIndex].weight;
}
V_S.add(v);
currentNode = (currentNode + 1) % size;
}
/*Dijkestra's main loop*/
Node u = S[0];
/*While V_S is not empty*/
while (!V_S.isEmpty()) {
u = V_S.remove(); //find smallest d and remove
S[S_tail] = u;
S_tail = (S_tail + 1) % size;
/*For all v adjacent to u in V_S*/
int uIndex = u.getIndex();
int vIndex = uIndex;
vIndex = (vIndex + 1) % size;
while (vIndex != uIndex) {
Edge u_v = u.connections[vIndex];
if (u_v != null && vIndex != startNode) {
Node v = u_v.target;
if ((u.d + u_v.weight) < v.d) {
v.d = (u.d + u_v.weight);
p[vIndex] = u;
}
}
vIndex = (vIndex + 1) % size;
}
}
for (int i = 0; i < size; i++) {
System.out.println(graph[i].getItem() + " " + graph[i].d);
}
} |
ed3efbb6-e2b6-43d3-8837-22ec894485da | 6 | public void tetrisCommandMessage( String msg, ConnectionToClient client) throws IOException
{
if (msg.equals(""))
return;
//initialize local variables
String message[] = msg.split(" ");
String instruction = "";
String operand = "";
boolean hasWhiteSpace = false;
//Find if multipart message
if ( message.length != 1) hasWhiteSpace = true;
//If there is a white space, we must load the instruction with its operand
if(hasWhiteSpace)
{
instruction = message[0];
operand = message[1];
}
else //If there is no white space, then there is no operand and only load the instruction
instruction = message[0];
// ****************************************************************************************//
// List of all client-side usable commands
switch (instruction.toLowerCase())
{
//*******************************************************************//
// Control methods
//The client won the match.
case ("gameWon"):
findOpponent(client).send("gameWon"+operand);
break;
//The client lost the match.
case ("gameLost"):
findOpponent(client).send("gameLost"+operand);
break;
//The match can start.
case ("ready"):
findOpponent(client).send("/ready");
break;
}
} |
a83cd976-71ee-469b-b86b-97ce91d4e39d | 8 | private static boolean encodeUnescaped(char c, boolean fullUri) {
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')
|| ('0' <= c && c <= '9'))
{
return true;
}
if ("-_.!~*'()".indexOf(c) >= 0)
return true;
if (fullUri) {
return URI_DECODE_RESERVED.indexOf(c) >= 0;
}
return false;
} |
7138c900-9ed5-462a-ae3b-dd99cfc8f2ac | 3 | private int getColumnDataWidth(int column)
{
if (! isColumnDataIncluded) return 0;
int preferredWidth = 0;
int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
break;
}
return preferredWidth;
} |
5dd7a47c-acb0-493a-af61-089650335424 | 4 | public int[] twoSum(int[] numbers, int target) {
int[] two =new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0 ; i < numbers.length; i++)
map.put(numbers[i],i);
for (int i = 0 ; i < numbers.length; i++){
if(map.get(target - numbers[i])!= null && map.get(target - numbers[i])!= i){
two[0] = i+1;
two[1] = map.get(target - numbers[i])+1;
return two;
}
}
return two;
} |
4cda9af5-0a08-48da-963c-b2ceddd56cbc | 0 | public TreeSelectionEvent(JoeTree tree, int type) {
setTree(tree);
setType(type);
} |
55265bf2-2ef6-4f9f-81e6-a39744666bfb | 8 | public static ArrayList<Association> refineStepOne(
ArrayList<Association> associations) {
ArrayList<Association> temp = new ArrayList<Association>();
double newAvg = 0;
for (int i = 0; i < associations.size(); i++) {
Association current = associations.get(i);
DataPoint p = Global.DBSIMULATOR.get(current.getPID());
DataPoint q = Global.DBSIMULATOR.get(current.getQID());
double d = current.getDistance();
Cluster c1 = null, c2 = null;
if (!clusterMap.containsKey(p.getClusterID()))
clusterMap.put(p.getClusterID(), new Cluster(p));
c1 = clusterMap.get(p.getClusterID());
if (c1.getDataPointSet().size() == 1)
c1.setAverageDistance(p.getAverage());
if (!clusterMap.containsKey(q.getClusterID()))
clusterMap.put(q.getClusterID(), new Cluster(q));
c2 = clusterMap.get(q.getClusterID());
if (c2.getDataPointSet().size() == 1)
c2.setAverageDistance(q.getAverage());
if (c1.getID().equals(c2.getID())
&& d <= Global.K * c1.getAverageDistance()&& d < Global.MAX_ASSOCIATION_DISTANCE) {
c1.setChanged(true);
newAvg = d + (c1.getAverageDistance() * c1.getSize());
c1.addAssociation(current);
c1.setAverageDistance(newAvg / c1.getSize());
} else
temp.add(current);
}
return temp;
} |
2c678185-ffe7-4dfc-993e-8b6ffa296bcd | 5 | @Override
public void actionPerformed(ActionEvent event) {
Component comp = getFocusOwner();
if (comp instanceof JTextComponent && comp.isEnabled()) {
JTextComponent textComp = (JTextComponent) comp;
ActionListener listener = textComp.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
if (listener != null) {
listener.actionPerformed(event);
}
} else {
Deletable deletable = getTarget(Deletable.class);
if (deletable != null && deletable.canDeleteSelection()) {
deletable.deleteSelection();
}
}
} |
16d9a748-bbfc-4d08-9b18-bd2891ef3aac | 3 | @Override
public void caseAFalseHexp(AFalseHexp node)
{
for(int i=0;i<indent;i++) System.out.print(" ");
indent++;
System.out.println("(FalseLiteral");
inAFalseHexp(node);
if(node.getFalse() != null)
{
node.getFalse().apply(this);
}
outAFalseHexp(node);
indent--;
for(int i=0;i<indent;i++) System.out.print(" ");
System.out.println(")");
} |
0eb57260-82ac-4793-8e47-721b36073916 | 7 | public static String reverseTranscribe(String inString) throws Exception
{
StringBuffer buff = new StringBuffer();
for ( int x= inString.length() - 1; x >=0; x-- )
{
char c = inString.charAt(x);
if ( c == 'A' )
buff.append( 'T' );
else if ( c == 'T' )
buff.append( 'A' );
else if ( c == 'C' )
buff.append( 'G' );
else if ( c == 'G' )
buff.append ( 'C' );
else if ( c == 'N')
buff.append( 'N') ;
else if ( c== '-' )
buff.append('-');
else throw new Exception("Unexpected character " + c );
}
return buff.toString();
} |
af203fb9-cf6c-4cde-9cf9-1a981c43b251 | 1 | public UnicodeFont getFont() {
if(unifont != null)
return unifont;
return defaultUnifont;
} |
2d821757-5c92-4911-ba18-5c8c19b7ac5d | 9 | double isSlightlyEqual(MembershipFunction mf, InnerOperatorset op) {
if(mf instanceof FuzzySingleton)
{ return op.slightly(isEqual( ((FuzzySingleton) mf).getValue())); }
if((mf instanceof OutputMembershipFunction) &&
((OutputMembershipFunction) mf).isDiscrete() ) {
double[][] val = ((OutputMembershipFunction) mf).getDiscreteValues();
double deg = 0;
for(int i=0; i<val.length; i++){
double mu = op.slightly(isEqual(val[i][0]));
double minmu = (mu<val[i][1] ? mu : val[i][1]);
if( deg<minmu ) deg = minmu;
}
return deg;
}
double mu1,mu2,minmu,degree=0;
for(double x=min; x<=max; x+=step){
mu1 = mf.compute(x);
mu2 = op.slightly(isEqual(x));
minmu = (mu1<mu2 ? mu1 : mu2);
if( degree<minmu ) degree = minmu;
}
return degree;
} |
2566add2-acb1-42db-ad12-4f4a50a37e18 | 3 | public void visitSRStmt(final SRStmt stmt) {
print("aswrange array: ");
if (stmt.array() != null) {
stmt.array().visit(this);
}
print(" start: ");
if (stmt.start() != null) {
stmt.start().visit(this);
}
print(" end: ");
if (stmt.end() != null) {
stmt.end().visit(this);
}
println("");
} |
f2a2b41a-eee7-4c01-af9a-c2f3d1da9edd | 2 | @Test
public void delMinReturnsValuesInCorrectOrderWhenInputIsGivenInAscendingOrder() {
int[] expected = new int[100];
for (int i = 0; i < 100; i++) {
h.insert(new Vertex(0, i));
expected[i] = i;
}
Arrays.sort(expected);
int[] actual = new int[100];
for (int i = 0; i < 100; i++) {
actual[i] = h.delMin().getDistance();
}
assertArrayEquals(expected, actual);
} |
2edbf240-066a-4fdb-b85e-2a3364c18c56 | 9 | private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
int column = convertColumna(posX);
if (iniciaPartida && !movimiento) {
int fila = posicionLibre(column);
if (fila != -1) {
posYLibre = (fila + 1) * (2 * radio) + radio;
movimiento = true;
choque = false;
velocidadCaida = 4;
posY = 75;
while (movimiento) {
try {
Thread.sleep(10);
this.paintComponent(this.getGraphics());
} catch (InterruptedException ex) {
Logger.getLogger(HiloNuevo.class.getName()).log(Level.SEVERE, null, ex);
}
}
//aca va las busquedas de ganador
logica.nuevoEstado(column, tuTurno);
if (logica.hayEmpate()) {
iniciaPartida = false;
JOptionPane.showMessageDialog(this, "Empataron csm!!!");
} else if(choque){
if(logica.hayGanador(0, column, k)){
iniciaPartida = false;
JOptionPane.showMessageDialog(this, "Ganaste!!! por fin. Te sientes realizado?");
}
} else if (logica.hayGanador(fila, column, k)){
iniciaPartida = false;
JOptionPane.showMessageDialog(this, "Ganaste!!! por fin. Ahora puedes morir en paz.");
} else{
tuTurno = !tuTurno; //cambia de turno
}
}
}
}//GEN-LAST:event_formMouseClicked |
e248c552-548b-4f25-8601-4f1fb8c68529 | 3 | public PlanAussendienst(JSONObject help, Object obj) throws FatalError {
super("Aussendienst");
if (isInt(obj)) {
dienst = new Aussendienst((Integer) obj);
} else {
try {
int difficult = help.getInt("Stufe");
int medicine = -1;
try {
medicine = help.getInt("Medizin");
} catch (JSONException e3) {
}
dienst = new Aussendienst(difficult, medicine);
} catch (JSONException e2) {
configError();
}
}
} |
ab0e7414-fdfa-4b9b-b258-2cfa0b345b2d | 1 | static String stripEnding(String clazz) {
if (!clazz.endsWith(DEFAULT_ENDING)) {
return clazz;
}
int viewIndex = clazz.lastIndexOf(DEFAULT_ENDING);
return clazz.substring(0, viewIndex);
} |
27030303-d04c-43d0-857a-624bdc455ab1 | 7 | @Override
public void onKeyPressed(char key, int keyCode, boolean coded)
{
// Tests the functions of the wavsound
if (!coded)
{
// On d plays the sound
if (key == 'd')
{
this.testtrack.play(null);
System.out.println("Plays a track");
}
// On e loops the sound
else if (key == 'e')
{
this.testtrack.loop(null);
System.out.println("Loops a track");
}
// On a stops the sounds
else if (key == 'a')
{
this.testtrack.stop();
System.out.println("Stops the track");
}
// On s pauses all sounds
else if (key == 's')
{
this.testtrack.pause();
System.out.println("Pauses the track");
}
// On w unpauses all sounds
else if (key == 'w')
{
this.testtrack.unpause();
System.out.println("Unpauses the track");
}
// On r releases the track from a loop
else if (key == 'r')
{
this.testtrack.release();
System.out.println("Releases the track");
}
}
} |
e784e831-81a1-4576-b4a4-c78602ad50f5 | 4 | public static long pop_intersect(long A[], long B[], int wordOffset, int numWords) {
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g'
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for( i = wordOffset; i <= n - 8; i += 8 ) {
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, (A[i] & B[i]), (A[i+1] & B[i+1]))
{
long b = (A[i] & B[i]), c = (A[i + 1] & B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+2] & B[i+2]), (A[i+3] & B[i+3]))
{
long b = (A[i + 2] & B[i + 2]), c = (A[i + 3] & B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, (A[i+4] & B[i+4]), (A[i+5] & B[i+5]))
{
long b = (A[i + 4] & B[i + 4]), c = (A[i + 5] & B[i + 5]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+6] & B[i+6]), (A[i+7] & B[i+7]))
{
long b = (A[i + 6] & B[i + 6]), c = (A[i + 7] & B[i + 7]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += pop(eights);
}
if( i <= n - 4 ) {
long twosA, twosB, foursA, eights;
{
long b = (A[i] & B[i]), c = (A[i + 1] & B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = (A[i + 2] & B[i + 2]), c = (A[i + 3] & B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += pop(eights);
i += 4;
}
if( i <= n - 2 ) {
long b = (A[i] & B[i]), c = (A[i + 1] & B[i + 1]);
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += pop(eights);
i += 2;
}
if( i < n ) {
tot += pop((A[i] & B[i]));
}
tot += (pop(fours) << 2) + (pop(twos) << 1) + pop(ones) + (tot8 << 3);
return tot;
} |
267948e5-f972-4bc1-8252-54f2e6d44ca3 | 0 | public void leaving(String name, Object o)
{
info(StringUtils.shortName(o.getClass()) + "-" + o.hashCode() + " leaving " + name + "()");
} |
dd53dd11-4350-4be5-81b6-3e19c0c21699 | 2 | private Solution findOptimum(ArrayList<Cockroach> cockroaches) {
Solution optimum = new Solution(cockroaches.get(0));
for (int i = 1; i < cockroaches.size(); ++i) {
Solution next = new Solution(cockroaches.get(1));
if (next.isBetterThan(optimum)) {
optimum = next;
}
}
return optimum;
} |
8cb18ad5-dad5-40f8-962b-276810b47425 | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/* We will loop, possibly for all of the remaining characters. */
for (;;) {
j = offset;
b = true;
/* Compare the circle buffer with the to string. */
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/* If we exit the loop with b intact, then victory is ours. */
if (b) {
return true;
}
/* Get the next character. If there isn't one, then defeat is ours. */
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
1bb2a8d2-833e-4f19-b419-e35d7a3c02ed | 6 | public static Double resolver(ColaLigada<String> posfija) throws Exception{
Double a=0.0;
Double b=0.0;
Double c=0.0;
PilaLigada<Double> pila= new PilaLigada<>();
while(!posfija.vacia()){
String simbolo=posfija.pop();
switch (simbolo) {
case "^":
b=pila.pop();
a=pila.pop();
pila.push(Math.pow(a, b));
break;
case "*":
b=pila.pop();
a=pila.pop();
pila.push(a*b);
break;
case "/":
b=pila.pop();
a=pila.pop();
pila.push(a/b);
break;
case "+":
b=pila.pop();
a=pila.pop();
pila.push(a+b);
break;
case "-":
b=pila.pop();
a=pila.pop();
pila.push(a-b);
break;
default:
pila.push(Double.parseDouble(simbolo));
break;
}
}
return pila.pop();
} |
46b0660e-288e-40c0-8f47-03087e80a5f9 | 9 | public Packer() {
super("Pack-U-Like");
saveChooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
return (f.getName().endsWith(".png"));
}
public String getDescription() {
return "PNG Images (*.png)";
}
});
chooser.setMultiSelectionEnabled(true);
chooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
return (f.getName().endsWith(".png") || f.getName().endsWith(".jpg") || f.getName().endsWith(".gif"));
}
public String getDescription() {
return "Images (*.jpg, *.png, *.gif)";
}
});
sizes.addElement(Integer.valueOf(64));
sizes.addElement(Integer.valueOf(128));
sizes.addElement(Integer.valueOf(256));
sizes.addElement(Integer.valueOf(512));
sizes.addElement(Integer.valueOf(1024));
sizes.addElement(Integer.valueOf(2048));
sizes2.addElement(Integer.valueOf(64));
sizes2.addElement(Integer.valueOf(128));
sizes2.addElement(Integer.valueOf(256));
sizes2.addElement(Integer.valueOf(512));
sizes2.addElement(Integer.valueOf(1024));
sizes2.addElement(Integer.valueOf(2048));
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
bar.add(file);
JMenuItem save = new JMenuItem("Save");
file.add(save);
file.addSeparator();
JMenuItem quit = new JMenuItem("Quit");
file.add(quit);
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save();
}
});
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
setJMenuBar(bar);
JPanel panel = new JPanel();
panel.setLayout(null);
sheetPanel = new SheetPanel(this);
JScrollPane pane = new JScrollPane(sheetPanel);
pane.setBounds(5, 5, 530, 530);
JScrollPane listScroll = new JScrollPane(list);
listScroll.setBounds(540, 5, 200, 350);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
Object[] values = list.getSelectedValues();
ArrayList sprites = new ArrayList();
for (int i = 0; i < values.length; i++) {
sprites.add(values[i]);
}
list.removeListSelectionListener(this);
select(sprites);
list.addListSelectionListener(this);
}
});
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setCellRenderer(new FileListRenderer());
panel.add(pane);
panel.add(listScroll);
JButton add = new JButton("Add");
add.setFont(add.getFont().deriveFont(Font.BOLD));
add.setMargin(new Insets(0, 0, 0, 0));
add.setBounds(745, 5, 40, 30);
panel.add(add);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int resp = chooser.showOpenDialog(Packer.this);
if (resp == JFileChooser.APPROVE_OPTION) {
File[] selected = chooser.getSelectedFiles();
for (int i = 0; i < selected.length; i++) {
try {
sprites.addElement(new Sprite(selected[i]));
} catch (IOException x) {
x.printStackTrace();
JOptionPane.showMessageDialog(Packer.this, "Unable to load: " + selected[i].getName());
}
}
}
regenerate();
}
});
JButton remove = new JButton("Del");
remove.setFont(add.getFont().deriveFont(Font.BOLD));
remove.setMargin(new Insets(0, 0, 0, 0));
remove.setBounds(745, 35, 40, 30);
panel.add(remove);
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] selected = list.getSelectedValues();
for (int i = 0; i < selected.length; i++) {
sprites.removeElement(selected[i]);
}
regenerate();
}
});
JLabel label;
label = new JLabel("Border");
label.setBounds(540, 375, 200, 25);
panel.add(label);
border.setBounds(540, 400, 200, 25);
panel.add(border);
border.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
regenerate();
}
});
label = new JLabel("Width");
label.setBounds(540, 425, 200, 25);
panel.add(label);
widths.setBounds(540, 450, 200, 25);
panel.add(widths);
widths.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
twidth = ((Integer) widths.getSelectedItem()).intValue();
sheetPanel.setTextureSize(twidth, theight);
regenerate();
}
});
label = new JLabel("Height");
label.setBounds(540, 475, 200, 25);
panel.add(label);
heights.setBounds(540, 500, 200, 25);
heights.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
theight = ((Integer) heights.getSelectedItem()).intValue();
sheetPanel.setTextureSize(twidth, theight);
regenerate();
}
});
panel.add(heights);
twidth = 512;
theight = 512;
sheetPanel.setTextureSize(twidth, theight);
widths.setSelectedItem(Integer.valueOf(twidth));
heights.setSelectedItem(Integer.valueOf(theight));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setContentPane(panel);
setSize(800, 600);
setResizable(false);
setVisible(true);
} |
c19c2434-8b29-41d3-bf6f-814329e6b131 | 8 | private void updateChartData() {
//
// Get the asset allocations
//
int[] types = SecurityRecord.getTypes();
double[] amounts = new double[types.length];
int rows = positionModel.getRowCount();
for (int row=0; row<rows; row++) {
SecurityRecord s = positionModel.getSecurityAt(row);
int type = s.getType();
for (int i=0; i<types.length; i++) {
if (type == types[i]) {
amounts[i] += s.getPrice()*positionModel.getSharesAt(row);
break;
}
}
}
//
// Fill in the chart data
//
if (chartData == null)
chartData = new ArrayList<PieChartElement>(types.length);
else
chartData.clear();
int colorIndex = 0;
for (int i=0; i<types.length; i++) {
if (amounts[i] != 0.0) {
chartData.add(new PieChartElement(colors[colorIndex++],
SecurityRecord.getTypeString(types[i]),
amounts[i]));
if (colorIndex == colors.length)
colorIndex = 0;
}
}
//
// Update the plot with the new data
//
if (chart != null)
chart.chartModified();
} |
c54f2f3a-dfef-49ab-bf66-416754512ba4 | 2 | public void method455(int time, int destY, int drawHeight, int destX) {
if (!aBoolean1579) {
double deltaX = destX - startX;
double deltaY = destY - startY;
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
aDouble1585 = startX + deltaX * angle / distance;
aDouble1586 = startY + deltaY * angle / distance;
aDouble1587 = anInt1582;
}
double d1 = speed + 1 - time;
aDouble1574 = (destX - aDouble1585) / d1;
aDouble1575 = (destY - aDouble1586) / d1;
aDouble1576 = Math.sqrt(aDouble1574 * aDouble1574 + aDouble1575 * aDouble1575);
if (!aBoolean1579) {
aDouble1577 = -aDouble1576 * Math.tan(slope * 0.02454369D);
}
aDouble1578 = 2D * (drawHeight - aDouble1587 - aDouble1577 * d1) / (d1 * d1);
} |
2513a5ab-6104-408f-b5a7-222dfc3f1e68 | 5 | public int getMIPSRating()
{
int rating = 0;
switch (allocationPolicy_)
{
// Assuming all PEs in all Machine have same rating.
case ResourceCharacteristics.TIME_SHARED:
case ResourceCharacteristics.OTHER_POLICY_SAME_RATING:
rating = getMIPSRatingOfOnePE() * machineList_.getNumPE();
break;
// Assuming all PEs in a given Machine have the same rating.
// But different machines in a Cluster can have different rating
case ResourceCharacteristics.SPACE_SHARED:
case ResourceCharacteristics.OTHER_POLICY_DIFFERENT_RATING:
for (int i = 0; i < machineList_.size(); i++) {
rating += ((Machine) machineList_.get(i)).getMIPSRating();
}
break;
default:
break;
}
return rating;
} |
a1254f40-6446-400b-a381-6857e861e7a2 | 9 | public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n, m, c,testCase = 0;
while (true) {
n = sc.nextInt();
m = sc.nextInt();
c = sc.nextInt();
testCase++;
if (n == 0 && m == 0 && c == 0) {
break;
}
int fuse[] = new int[n+5];
int amphere = 0,maxAmphere = 0;
boolean state[] = new boolean[n+5];
boolean blown = false;
for(int i=0;i<n;i++)
{
fuse[i] = sc.nextInt();
}
for(int i=0;i<m;i++)
{
int bulb = sc.nextInt();
bulb--;
if(state[bulb])
{
state[bulb] = false;
amphere -= fuse[bulb];
}
else
{
state[bulb] = true;
amphere += fuse[bulb];
maxAmphere = Math.max(amphere,maxAmphere);
if(amphere>c)
blown = true;
}
}
System.out.println("Sequence "+testCase);
if(!blown)
{
System.out.println("Fuse was not blown.");
System.out.println("Maximal power consumption was "+maxAmphere+" amperes.");
}
else
{
System.out.println("Fuse was blown.");
}
System.out.println();
}
} |
7119aa7d-2b4b-4c08-847c-4509e1a4b3de | 4 | public void useCharge() {
int[][] glory = {{1712, 1710, 3}, {1710, 1708, 2}, {1708, 1706, 1}, {1706, 1704, 1}};
for (int i = 0; i < glory.length; i++) {
if (c.itemUsing == glory[i][0]) {
if (c.isOperate) {
c.playerEquipment[c.playerAmulet] = glory[i][1];
} else {
c.getItems().deleteItem(glory[i][0], 1);
c.getItems().addItem(glory[i][1], 1);
}
if (glory[i][2] > 1) {
c.sendMessage("Your amulet has "+glory[i][2]+" charges left.");
} else {
c.sendMessage("Your amulet has "+glory[i][2]+" charge left.");
}
}
}
c.getItems().updateSlot(c.playerAmulet);
c.isOperate = false;
c.itemUsing = -1;
} |
5cdcaf1b-f48b-4d05-89a5-2167b020e61a | 2 | private static void createAndFillHuffmanTree(int[] header) throws IOException
{
huffmanTree = new GradProjectDataStruct();
for(int i = 0; i < header.length; i++)
if(header[i] != 0)
huffmanTree.insert(new Node(header[i], i));
huffmanTree.createHuffTree();
huffmanTree.fillHuffTable(huffmanTree.root);
} |
2d0c6e76-8319-471a-8745-8f4abd0054c3 | 2 | public void updateTeacher(Teacher teacher)
{
PreparedStatement ps;
try {
if(teacher.getId() > 0)
{
ps = con.prepareStatement("UPDATE teacher SET name=?, value=? WHERE id=?");
ps.setInt(3, teacher.getId());
}
else
{
ps = con.prepareStatement("INSERT INTO teacher (name, value) VALUES (?, ?)");
}
ps.setString(1, teacher.getName());
ps.setInt(2, teacher.getValue());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
235eb096-77e6-41eb-936a-e09a714425d8 | 4 | public ProfileProperties verifyProfileKey(String key) {
String sql = "select * from app.profiles"+
" where key='"+key+"'";
ProfileProperties retVal = null;
if( dbConn != null ) {
try {
Connection conn = dbConn.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if( rs.next() ) {
retVal = new ProfileProperties();
retVal.setKey(key);
retVal.setId(rs.getInt("id"));
retVal.setRid(rs.getInt("rid"));
retVal.setpPublic(rs.getBoolean("public"));
retVal.setpEnabled(rs.getBoolean("enabled"));
retVal.setReverse_cost(rs.getBoolean("reverse_cost"));
retVal.setPgr_dd(rs.getBoolean("pgr_dd"));
retVal.setPgr_sp(rs.getBoolean("pgr_sp"));
Statement s = conn.createStatement();
ResultSet r = s.executeQuery("select host from app.hosts "+
"where id="+retVal.getId());
List<String> hosts = new ArrayList<String>();
while(r.next())
hosts.add(r.getString("host"));
String[] h = (String[])hosts.toArray(new String[0]);
retVal.setHosts(h);
r.close();
s.close();
}
rs.close();
stmt.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
return retVal;
} |
863be76d-5828-4e55-bc03-7a0fe04c7985 | 8 | public static void main(String[] args) {
for(int i=0; i<100; i++) {
char c = (char)(Math.random() * 26 + 'a');
System.out.print(c + ": ");
switch(c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("vowel");
break;
case 'y':
case 'w':
System.out.println("Sometimes a vowel");
break;
default:
System.out.println("consonant");
}
}
} |
72c92fc8-a3f3-4bf6-9817-82fb4e0acede | 5 | protected int whoIsWinner() {
if ( !haveAllPlayerFinished() ) {
return -1;
}
// eXgp : TODO
if ( true ) {
System.out.println("game!");
}
int winner = -1;
int scoreOfWinner = Integer.MIN_VALUE;
for ( int i=0; i<players.length; ++i ) {
if ( scoreOfWinner < players[i].getScore() ) {
if ( winner >= 0 ) {
return -2;
} else {
winner = i;
scoreOfWinner = players[i].getScore();
}
}
}
return winner;
} |
214adc0d-cbd4-40b5-b950-b978f657d562 | 2 | public void setScoreboardTitle(String scoreboardTitle) {
if(scoreboardTitle == null)
throw new NullPointerException();
scoreboardTitle = replaceColorCodes(scoreboardTitle);
this.scoreboardTitle = scoreboardTitle;
if(scoreboard != null)
objective.setDisplayName(scoreboardTitle);
} |
c04fe7dd-857a-4fde-bc7b-0ecc052bf0a0 | 8 | private static Object readNumber(final JsonReader data) throws JsonParseException {
StringBuilder result = new StringBuilder();
while(true) {
int c = data.read();
if(Character.isWhitespace(c) || c == '}' || c == ',' || c == ']' || c == '\0') {
data.skip(-1);
break;
}
if(c == -1) break;
result.append((char) c);
}
String s = result.toString();
try {
return new BigDecimal(s);
}
catch(NumberFormatException e) {
throw new JsonParseException("Number", data, e);
}
} |
970d2455-4ebb-473a-b2b9-961af4d1a23f | 3 | public void changePosition(com.novativa.www.ws.streamsterapi.Position position) throws java.rmi.RemoteException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[8]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("ChangePosition");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("", "ChangePosition"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {position});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
extractAttachments(_call);
} catch (org.apache.axis.AxisFault axisFaultException) {
throw axisFaultException;
}
} |
e38f3f24-058b-4e5e-bb8c-59f1faa2870b | 4 | public int countOccurrences(int target){
IntBTNode cursor = root;
int count = 0;
int nextElement;
if(root == null){
return 0;
}
while(cursor != null){
if(target < cursor.getData())
{
nextElement = cursor.getLeft().getData();
System.out.println("next data = " +nextElement);
cursor = cursor.getLeft();
}else if(target > cursor.getData())
{
cursor = cursor.getRight();
}else
{//means target and cursor.data are equal
count++;
System.out.println("find!!" + counter + "\ncount = " + count);
//System.out.println("next value right" + cursor.getRight().getData());
//System.out.println("next value left" + cursor.getLeft().getData());
//cursor = cursor.getLeft();
cursor = cursor.getRight();
}
}
return count;
} |
53152de6-c89a-4ec2-9e86-6096610998f9 | 1 | public String fetchOption() {
if(!hasOptionArg()) {
throw new InputMismatchException("There is no option at the head of ArgSet.");
} else {
String s = pop();
return s.substring(2);
}
} |
1dbbc856-423f-474e-87b7-0031e3351e9d | 1 | private boolean differByTwoVerticalAndOneHorizontal(Field from, Field to) {
return Math.abs(from.distanceBetweenRank(to)) == 1 && Math.abs(from.distanceBetweenFile(to)) == 2;
} |
4351e278-ed84-4001-8dae-c546373bebc8 | 2 | @Override
public void contextInitialized(ServletContextEvent arg0) {
if ((myDaemonThread == null) || (myDaemonThread.isAlive())) {
myDaemonThread = new DaemonThread();
myDaemonThread.start();
}
} |
7023888f-1efd-46a5-8207-843e67a26a0b | 7 | private Cmds getCommand(String message) {
int begin = message.indexOf(' ') + 1;
int end = message.indexOf(' ', begin);
if(end == NOT_FOUND)
end = message.length();
String cmd = message.substring(begin, end);
if(cmd.equals("start"))
return Cmds.CMD_START_STOPWATCH;
else if(cmd.equals("stop"))
return Cmds.CMD_STOP_STOPWATCH;
else if(cmd.equals("get"))
return Cmds.CMD_GET_STOPWATCH;
else if(cmd.equals("timer")) {
begin = message.indexOf(' ', end);
if(begin == NOT_FOUND)
return Cmds.CMD_INVALID;
return Cmds.CMD_SET_TIMER;
}
else if(cmd.equals("rmtimer"))
return Cmds.CMD_REMOVE_TIMER;
return Cmds.CMD_INVALID;
} |
c7f52e20-d2cf-43e4-929b-f5dffe5fe7fd | 7 | public static final void writeFile(File targetFile, String encoding, String[] fileContent) throws IOException {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter writer = null;
try {
fos = new FileOutputStream(targetFile);
osw = new OutputStreamWriter(fos, encoding);
writer = new BufferedWriter(osw);
for(String line : fileContent) {
writer.write(line);
writer.write('\n');
}
} finally {
if(writer != null) try { writer.close(); } catch(IOException ex) {}
if(osw != null) try { osw.close(); } catch(IOException ex) {}
if(fos != null) try { fos.close(); } catch(IOException ex) {}
}
} |
1711fc14-080c-4abb-8a13-92d99c05e1ce | 8 | public static Highscore [] load(InputStream in)
throws IOException {
Vector highscores=new Vector(20,40);
InputStreamReader inr = new InputStreamReader(in);
String line;
while ( (line=jgame.impl.EngineLogic.readline(inr)) != null ) {
Vector fields = new Vector(5,10);
// XXX we use "`" to represent empty string because
// StringTokenizer skips empty tokens
Vector tokens = jgame.impl.EngineLogic.tokenizeString(line,'\t');
//StringTokenizer toker = new StringTokenizer(line,"\t");
for (Enumeration e=tokens.elements(); e.hasMoreElements(); ) {
String tok = (String)e.nextElement();
if (tok.equals("`")) tok="";
fields.addElement(tok);
}
Highscore hs=null;
if (fields.size()==1) {
// we assume we have a highscore with no fields and empty name
hs=new Highscore(Integer.parseInt((String)fields.elementAt(0)), "");
}
if (fields.size() >= 2) {
hs=new Highscore(Integer.parseInt((String)fields.elementAt(0)),
(String)fields.elementAt(1) );
}
if (fields.size() >= 3) {
hs.fields=new String[fields.size()-2];
for (int i=2; i<fields.size(); i++) {
hs.fields[i-2] = (String)fields.elementAt(i);
}
}
highscores.addElement(hs);
}
Highscore [] ret = new Highscore [highscores.size()];
for (int i=0; i<highscores.size(); i++) {
ret[i] = (Highscore)highscores.elementAt(i);
}
return ret;
//return (Highscore[])highscores.toArray(new Highscore[]{});
} |
d1ffe2f5-2f6c-4a1d-917f-9c6ed6d0f25a | 2 | public String getBodyString() {
try {
if (body != null) {
return new String(body, "utf8");
} else {
return "";
}
} catch (UnsupportedEncodingException ignored) {
}
return "";
} |
b694ef19-c65d-4871-9220-8356d39b8086 | 5 | public void iaComputeState(){
if(myIA.getAlert() && myIA.getTime()>0){
this.st = st.stalk;
}
else if(myIA.getHit()){
this.st = st.strike;
myIA.setHit(false);
myIA.actStnby();
}
else if(myIA.getStnby() && myIA.getTime()<2) {
this.st = st.standby;
myIA.addTime(Gdx.graphics.getDeltaTime());
}
else{
myIA.decAlert();
myIA.clearTimer();
myIA.decStnby();
this.st = walk;
}
} |
1998ec83-ad6c-42b6-ac76-7e830c7bbea2 | 9 | public void orderTicketToQueue(String ticketNo, String seatNum,
String token, String[] params, String date, String rangCode) {
HttpResponse response = null;
HttpPost httpPost = null;
try {
URIBuilder builder = new URIBuilder();
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("method",
"confirmSingleForQueue"));
parameters.add(new BasicNameValuePair(
"org.apache.struts.taglib.html.TOKEN", token));
parameters.add(new BasicNameValuePair("leftTicketStr", ticketNo));
parameters.add(new BasicNameValuePair("textfield", "中文或拼音首字母"));
// 一个人只有一个checkbox0
parameters.add(new BasicNameValuePair("orderRequest.train_date",
date));
parameters.add(new BasicNameValuePair("orderRequest.train_no",
params[3]));
parameters.add(new BasicNameValuePair(
"orderRequest.station_train_code", params[0]));
parameters.add(new BasicNameValuePair(
"orderRequest.from_station_telecode", params[4]));
parameters.add(new BasicNameValuePair(
"orderRequest.to_station_telecode", params[5]));
parameters.add(new BasicNameValuePair(
"orderRequest.seat_type_code", ""));
parameters.add(new BasicNameValuePair(
"orderRequest.ticket_type_order_num", ""));
parameters.add(new BasicNameValuePair(
"orderRequest.bed_level_order_num",
"000000000000000000000000000000"));
parameters.add(new BasicNameValuePair("orderRequest.start_time",
params[2]));
parameters.add(new BasicNameValuePair("orderRequest.end_time",
params[6]));
parameters.add(new BasicNameValuePair(
"orderRequest.from_station_name", params[7]));
parameters.add(new BasicNameValuePair(
"orderRequest.to_station_name", params[8]));
parameters.add(new BasicNameValuePair("orderRequest.cancel_flag",
"1"));
parameters.add(new BasicNameValuePair("orderRequest.id_mode", "Y"));
// 订票人信息 第一个人
String[] orders = StringUtils.split(configInfo.getOrderPerson(),
",");
int n = 1;
for (int i = 0; i < orders.length; i++) {
userInfo = userInfoMap.get(orders[i]);
if (userInfo == null) {
logger.warn("this name is not have!name:" + orders[i]);
continue;
}
parameters.add(new BasicNameValuePair("checkbox"
+ userInfo.getIndex(), "" + userInfo.getIndex()));
parameters
.add(new BasicNameValuePair("passengerTickets", seatNum
+ ",0,1," + userInfo.getPassenger_name()
+ ",1," + userInfo.getPassenger_id_no() + ",,Y"));
parameters.add(new BasicNameValuePair("oldPassengers", userInfo
.getPassenger_name()
+ ",1,"
+ userInfo.getPassenger_id_no() + ""));
parameters.add(new BasicNameValuePair("passenger_" + n
+ "_seat", seatNum));
parameters.add(new BasicNameValuePair("passenger_" + n
+ "_ticket", "1"));
parameters.add(new BasicNameValuePair("passenger_" + n
+ "_name", userInfo.getPassenger_name()));
parameters.add(new BasicNameValuePair("passenger_" + n
+ "_cardtype", "1"));
parameters.add(new BasicNameValuePair("passenger_" + n
+ "_cardno", userInfo.getPassenger_id_no()));
parameters.add(new BasicNameValuePair("passenger_" + n
+ "_mobileno", ""));
parameters.add(new BasicNameValuePair("checkbox9", "Y"));
}
parameters.add(new BasicNameValuePair("orderRequest.reserve_flag",
"A"));
parameters.add(new BasicNameValuePair("randCode", rangCode));
builder.setScheme("https").setHost("dynamic.12306.cn")
.setPath("/otsweb/order/confirmPassengerAction.do");
UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters,
"UTF-8");
URI uri = builder.build();
httpPost = new HttpPost(uri);
httpPost.setEntity(uef);
httpPost.addHeader("Accept",
"application/json, text/javascript, */*");
httpPost.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
httpPost.addHeader("Connection", "keep-alive");
httpPost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httpPost.addHeader("Origin", "https://dynamic.12306.cn");
httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
httpPost.addHeader("Host", "dynamic.12306.cn");
httpPost.addHeader("Referer",
"https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init");
httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
httpPost.addHeader(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17");
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
JSONObject jsonObject = JSONObject.parseObject(EntityUtils
.toString(entity));
HttpClientUtils.closeQuietly(response);
logger.info(jsonObject.toJSONString());
String errorMessage = jsonObject.getString("errMsg");
if ("Y".equals(errorMessage)
|| StringUtils.isEmpty(errorMessage)) {
logger.info("订票成功了,赶紧付款吧!");
} else if (StringUtils.contains(errorMessage, "验证码")) {
checkOrderInfo(ticketNo, seatNum, token, params, date);
} else if (StringUtils.contains(errorMessage, "排队人数现已超过余票数")) {
searchTicket(date);
} else if (StringUtils.contains(errorMessage, "非法的订票请求")) {
searchTicket(date);
} else {
logger.info(errorMessage);
searchTicket(date);
}
}
} catch (Exception e) {
logger.error("orderTicketToQueue error!", e);
httpPost.abort();
} finally {
HttpClientUtils.closeQuietly(response);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.