method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
8adf979f-6d27-4d05-8e52-b4748b1102ac
| 2 |
private DefaultMutableTreeNode createNodes(FAT32Directory rootElement) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rootElement);
DefaultMutableTreeNode childNode;
int i = 0;
FAT32Directory[] childs = new FAT32Directory[rootElement.getChildDirectories().size()];
for(FAT32Directory child: rootElement.getChildDirectories()) {
childs[i] = child;
if (!childs[i].getChildDirectories().isEmpty())
childNode = createNodes(childs[i]);
else
childNode = new DefaultMutableTreeNode(childs[i]);
node.add(childNode);
i++;
}
return node;
}
|
1be10f04-500d-4294-9951-45ffd971092a
| 7 |
public boolean isYCollision(int y) {
Point midpoint = getMidPoint(x, y, BOAT_WIDTH, BOAT_HEIGHT, rotation);
int centreX = (int) midpoint.getX();
int centreY = (int) midpoint.getY();
if (centreX > 150 && centreX < 1050 && centreY > 0 && centreY < map.grass.getHeight()) {
Color c = new Color(map.grass.getRGB(centreX-150, centreY));
if (c.getGreen() == 128) {
return true;
}
}
if(midpoint.getY() < 0.0) return true;
if(midpoint.getY() > gameHeight) return true;
return false;
}
|
c7c3764e-7570-43a7-8303-61e633c94e0b
| 9 |
public Object getResponseResult(HttpResponse response, String produces, Type returnType) throws Exception {
if (response == null || produces == null || returnType == null) {
throw new IllegalArgumentException("Response, produces and returnType cannot be null");
}
if (isResponseSuccessful(response.getStatus())) {
Object result = null;
if (produces.equals(JSON_CONTENT_TYPE)) {
String stringResponse = response.getStringContent();
logger.debug(String.format("Parsing json: '%s'", stringResponse));
result = getFromJSon(returnType, stringResponse);
} else if (produces.equals(OCTET_STREAM_CONTENT_TYPE)) {
result = response.getInputStream();
} else {
result = response.getStringContent();
}
return result;
} else {
int responseStatus = response.getStatus();
Exception exception = getFromJSon(Exception.class, response.getStringContent());
if (isClientException(responseStatus)) {
if (logger.isDebugEnabled()) {
logger.warn(String.format("CLIENT EXCEPTION - Response code: %s", responseStatus), exception);
}
} else if (isServerException(responseStatus)) {
logger.warn(String.format("SERVER EXCEPTION - Response code: %s", responseStatus), exception);
}
throw exception;
}
}
|
930b69c4-8cf9-49fd-b715-c23517dcac11
| 9 |
public static TVFFile read(DataInputStream stream) throws IOException
{
TVFFile tvf = new TVFFile();
tvf.magic = new byte[themagic.length];
for (int i = 0; i < tvf.magic.length; i++)
{
tvf.magic[i] = stream.readByte();
}
tvf.turremVersion = new byte[3];
for (int i = 0; i < tvf.turremVersion.length; i++)
{
tvf.turremVersion[i] = stream.readByte();
}
tvf.fileVersion = stream.readShort();
if (tvf.fileVersion != theFileVersion)
{
return null;
}
tvf.width = stream.readByte();
tvf.height = stream.readByte();
tvf.length = stream.readByte();
tvf.prelit = stream.readByte();
tvf.colorNum = stream.readShort();
tvf.colors = new TVFColor[tvf.colorNum];
for (int i = 0; i < tvf.colorNum; i++)
{
TVFColor c = new TVFColor();
c.id = stream.readByte();
c.r = stream.readByte();
c.g = stream.readByte();
c.b = stream.readByte();
tvf.colors[i] = c;
}
tvf.dynamicColorNum = stream.readShort();
if (tvf.dynamicColorNum > 0)
{
tvf.dynamicColors = new TVFDynamicColor[tvf.dynamicColorNum];
for (int i = 0; i < tvf.dynamicColorNum; i++)
{
TVFDynamicColor c = new TVFDynamicColor();
c.id = stream.readByte();
c.name = stream.readUTF();
tvf.dynamicColors[i] = c;
}
}
tvf.faceNum = stream.readInt();
tvf.faces = new TVFFace[tvf.faceNum];
for (int i = 0; i < tvf.faceNum; i++)
{
TVFFace f = new TVFFace();
f.x = stream.readByte();
f.y = stream.readByte();
f.z = stream.readByte();
f.dir = stream.readByte();
f.color = stream.readByte();
if (tvf.prelit == 1)
{
short lit = stream.readShort();
f.light[0] = (byte) ((lit >> 12) & 0x0F);
f.light[1] = (byte) ((lit >> 8) & 0x0F);
f.light[2] = (byte) ((lit >> 4) & 0x0F);
f.light[3] = (byte) ((lit >> 0) & 0x0F);
}
else if (tvf.prelit == 2)
{
byte lit = stream.readByte();
f.light[0] = lit;
f.light[1] = lit;
f.light[2] = lit;
f.light[3] = lit;
}
tvf.faces[i] = f;
}
return tvf;
}
|
73aef4a7-f62c-46d9-9753-34a8367d4399
| 2 |
public BaseExtractor createExtractor(int countOfClusters) {
if (countOfClusters < COUNT_OF_CLUSTERS_FAT12) {
System.out.println("FAT12Extractor do not implemented yet!");
throw new RuntimeException("FAT12Extractor do not implemented yet!");
} else if (countOfClusters < COUNT_OF_CLUSTERS_FAT16) {
System.out.println("FAT16Extractor do not implemented yet!");
throw new RuntimeException("FAT16Extractor do not implemented yet!");
} else {
extractor = new FAT32Extractor();
}
return extractor;
}
|
3c3fdd02-9171-4ff0-8522-aceeed144a75
| 2 |
public boolean isMultiPlayerJoinOpen() {
HUD hud = null;
for (int i = (huds.size() - 1); i >= 0; i--) {
hud = huds.get(i);
if (hud.getName().equals("ScreenMultiPlayerJoin")) {
return hud.getShouldRender();
}
}
return false;
}
|
b0981b46-9bb7-40e9-b55e-72aabdcd60d4
| 6 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Book other = (Book) obj;
if (!Objects.equals(this.isbn, other.isbn)) {
return false;
}
if (!Objects.equals(this.title, other.title)) {
return false;
}
if (!Objects.equals(this.author, other.author)) {
return false;
}
if (!Objects.equals(this.type, other.type)) {
return false;
}
return true;
}
|
4cf8b5ba-07db-4456-ad3f-d74a71800a26
| 9 |
@EventHandler(priority = EventPriority.HIGHEST)
public void onCraft(CraftItemEvent event) {
try {
if (!BackpackUtil.isBackpack(event.getRecipe().getResult()))
return;
final HumanEntity entity = event.getWhoClicked();
final ItemStack result = event.getRecipe().getResult();
BackpackData data = BackpackData.read(result);
if (data.getType() == null || data.getType().equals(""))
throw new RuntimeException("Corrupted backpack data!");
BackpackConfiguration configuration = BackpackUtil.getBackpackConfigurationFrom(result);
Debugger.getInstance().log(15, configuration.toString());
// Check permissions
if (configuration.hasPermission()) {
if (!entity.hasPermission(configuration.getPermission())) {
// TODO: send message
event.setCancelled(true);
return;
}
}
// Check multi world
if (configuration.hasMultiWorldSupport()) {
if (!configuration.getEnabledWorlds().contains(entity.getWorld().getName())) {
if (!entity.hasPermission(configuration.getMultiworldBypassPermission())) {
// TODO: send message
event.setCancelled(true);
return;
}
}
}
} catch (Exception e) {
// Will be thrown when the backpack data is corrupted!
// TODO: notify user
}
}
|
2d0fec82-e6da-4670-9173-641e3b9ca71e
| 6 |
public void drawBlocks(Graphics g){
for( int i = 0; i<Constant.MAP_Array_SIZE; i++){
for( int j = 0; j <80; j++){
switch(this.array[i][j]){
case 1:
g.drawImage(grass, j * 10 + 50, i * 10 + 50, 10, 10, this);
break ;
case 2:
g.drawImage(this.wall, j * 10 + 50, i * 10 + 50, 10, 10, this);
break ;
case 3:
g.drawImage(this.wallUndefeted, j * 10 + 50, i * 10 + 50, 10, 10, this);
break ;
case 4:
g.drawImage(this.water, j * 10 + 50, i * 10 + 50, 10, 10, this);
break ;
default:
break;
}
}
}
}
|
680f3a9e-74f0-419f-833e-b5686d2dabea
| 7 |
public Projeto selectTodosProjetos() throws SQLException {
Connection conexao = null;
PreparedStatement comando = null;
ResultSet resultado = null;
Projeto projet = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_SELECT_TODOS_PROJETOS);
resultado = comando.executeQuery();
if (resultado.next()) {
projet = new Projeto();
projet.setNome(resultado.getString("NOME"));
projet.setDescricao(resultado.getString("DESCRICAO"));
projet.setDataInicio(resultado.getDate("DATA_INCIO"));
projet.setDataTermino(resultado.getDate("DATA_TERMINO"));
projet.setIdProjeto(resultado.getInt("ID_PROJETO"));
DepartamentoDAO depDAO = new DepartamentoDAO();
projet.setDepartamento(depDAO.selectDepartamentoPorCodigo(resultado.getString("COD_DEPARTAMENTO")));
}
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 projet;
}
|
cb689e1e-01e3-4dcd-9c19-bbff35e1411a
| 4 |
public synchronized void removeClassPath(ClassPath cp) {
ClassPathList list = pathList;
if (list != null)
if (list.path == cp)
pathList = list.next;
else {
while (list.next != null)
if (list.next.path == cp)
list.next = list.next.next;
else
list = list.next;
}
cp.close();
}
|
60b05675-763a-42e6-996b-defcffeb2aa7
| 2 |
@Override
public Hashtable<Short, Integer> getDistribution() {
Hashtable<Short, Integer> dist = new Hashtable<Short, Integer>();
for (Short i : filter) {
Integer freq = dist.get(i);
if (freq==null) {
dist.put(i, 1);
}
else dist.put(i, ++freq);
}
return dist;
}
|
5725df0b-f1df-486a-9ac2-859b34208f3f
| 1 |
public void setLowThreshold(float threshold) {
if (threshold < 0)
throw new IllegalArgumentException();
lowThreshold = threshold;
}
|
7ff86f57-63fc-4a69-b362-dfb8d59f82dd
| 4 |
private void searchLastNameFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchLastNameFieldKeyTyped
int strLength = searchLastNameField.getText().length(); // Vi checker længden på vores String så vi kan begrænse dens max længde i vores IF-statement nedenfor.
char c = evt.getKeyChar();
if (strLength == 30 || !(Character.isAlphabetic(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_searchLastNameFieldKeyTyped
|
bf6ee15b-b5d4-405e-b3a6-99ce30128af4
| 7 |
private static void getFromHDFS(String hdfsFilePath, String localFilePath) {
try {
Registry nameNodeRegistry = LocateRegistry.getRegistry(Hdfs.Core.NAME_NODE_IP, Hdfs.Core.NAME_NODE_REGISTRY_PORT);
NameNodeRemoteInterface nameNodeStub = (NameNodeRemoteInterface) nameNodeRegistry.lookup("NameNode");
HDFSFile file = nameNodeStub.open(hdfsFilePath);
if (file == null) {
System.out.println("Error! HDFS file does not exists");
System.exit(-1);
}
HDFSInputStream in = file.getInputStream();
int c = 0;
int buff_len = Hdfs.Core.READ_BUFF_SIZE;
byte[] buff = new byte[buff_len];
File newFile = new File(localFilePath);
FileOutputStream out = null;
try {
out = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
try {
newFile.createNewFile();
out = new FileOutputStream(newFile);
} catch (IOException e1) {
System.out.println("Error! Failed to put file to HDFS.");
System.exit(-1);
}
}
int counter = 0;
while ((c = in.read(buff)) != 0) {
out.write(buff, 0, c);
counter += c;
}
out.close();
System.out.println("TOTALLY READ: " + counter);
} catch (RemoteException e) {
System.out.println("Error! Failed to put file to HDFS.");
System.exit(-1);
} catch (NotBoundException e) {
System.out.println("Error! Failed to put file to HDFS.");
System.exit(-1);
} catch (IOException e) {
System.out.println("Error! Failed to put file to HDFS.");
System.exit(-1);
}
}
|
65b300ed-954d-4597-acea-336f60815e28
| 4 |
public boolean Auth(String username, String password, final boolean isOk) {
driver.get("http://localhost:8090/auth");
final String elementToFind = (isOk) ? "userId" : "error";
WebElement element = driver.findElement(By.name("username"));
element.sendKeys(username);
element = driver.findElement(By.name("password"));
element.sendKeys(password);
element.submit();
boolean result;
try {
result = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
@Override
@NotNull
public Boolean apply(@NotNull WebDriver d) {
boolean res;
WebElement id = d.findElement(By.id(elementToFind));
if (isOk) res = id.getText().contains("Your id");
else res = id.getText().contains(ExceptionMessages.NO_SUCH_USER_FOUND);
return res;
}
});
} catch (Exception e) {
System.out.println(e.getMessage());
result = false;
}
if (isOk) driver.findElement(By.id("quit")).click(); /* Log out ! */
return result;
}
|
baa3bc98-7c8b-4292-80fc-9080a746e2f4
| 2 |
public static List<Fonction> selectFonction() throws SQLException {
String query ="";
List<Fonction> fonctions = new ArrayList<Fonction>();
ResultSet resultat;
try {
query = "SELECT * from FONCTION ";
PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query);
resultat = pStatement.executeQuery(query);
while (resultat.next()) {
Fonction fct = new Fonction(resultat.getInt("ID_FONCTION"), resultat.getString("FONCLIBELLE"));
fonctions.add(fct);
}
} catch (SQLException ex) {
Logger.getLogger(RequetesFonction.class.getName()).log(Level.SEVERE, null, ex);
}
return fonctions;
}
|
d59d0a93-b904-479e-97c4-b3c5592ba375
| 3 |
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>();
boolean[] visited = new boolean[n+1];
for(int i=0;i<=n;i++){
visited[i]=false;
g.add(new ArrayList<Integer>());
}
for(int i=0;i<m;i++){
int a = in.nextInt();
int b = in.nextInt();
g.get(a).add(b);
}
int[] dist = new int[n+1];
bfs(4, g, visited, dist);
for(int i=1;i<=n;i++){
System.out.printf("Node %d has shortest dist %d\n", i, dist[i]);
}
}
|
d0e34785-1e83-4053-bee9-2df3b8b10a35
| 9 |
public String raise(int minRaise, int maxRaise){
double avrgOppAPW = getAvrgOppAPW(match.holeCards.size());
if (avrgOppAPW != 0.0) {
double avrgOppWin = getAvrgOppWin(match.holeCards.size());
if (avrgOppAPW <= 0.35) {
if (avrgOppWin >= (match.stackSize / 4)) {
weight *= 1.5;
}
}
if (avrgOppAPW >= 0.75) {
weight *= 0.5;
}
}
if (match.abs_prob_win > 0.85 && avrgOppAPW < 0.5) {
weight *= 1.5;
}
double raiseAmt = weight * match.abs_prob_win * match.pot;
weight = 1.0;
if(minRaise <= raiseAmt ){
if(maxRaise < raiseAmt){
return "RAISE:"+maxRaise;
}else{
return "RAISE:"+((int) raiseAmt);
}
}else if(match.amtToCall <= raiseAmt){
return "CALL";
}else{
return "FOLD";
}
}
|
c8c88d61-b19e-4a02-a08c-5115c59a1266
| 1 |
public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
|
a6b8e6e6-f82a-4e79-86aa-db8a43db41d3
| 0 |
public Inches(float i) {
this.quantity = i;
}
|
29aba9e4-d7ba-43f9-a5b1-505825ac2a54
| 2 |
public void sendMessage(String receiver, String message) {
try {
mServerInt.sendMessage(mUserName, receiver, message, ServerInterface.CLIENT);
} catch (RemoteException e) {
if(connect()) {
sendMessage(receiver, message);
return;
}
System.out.println("Error while sending message");
}
}
|
f2e0a14e-0c93-49b1-ac30-d42b2438029e
| 7 |
public void readData(String trainingFileName) {
try {
FileReader fr = new FileReader(trainingFileName);
BufferedReader br = new BufferedReader(fr);
// 存放数据的临时变量
String lineData = null;
String[] splitData = null;
int line = 0;
// 按行读取
while (br.ready()) {
// 得到原始的字符串
lineData = br.readLine();
splitData = lineData.split(",");
// 转化为数据
// System.out.println("length:"+splitData.length);
if (splitData.length > 1) {
for (int i = 0; i < splitData.length; i++) {
if (splitData[i].startsWith("Iris-setosa")) {
data[line][i] = (float) 1.0;
} else if (splitData[i].startsWith("Iris-versicolor")) {
data[line][i] = (float) 2.0;
} else if (splitData[i].startsWith("Iris-virginica")) {
data[line][i] = (float) 3.0;
} else { // 将数据截取之后放进数组
data[line][i] = Float.parseFloat(splitData[i]);
}
}
line++;
}
}
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
|
1a9713ae-3e1b-4318-83ec-170809fb4aee
| 3 |
private static BitSet readVersionSet( int versionSetSize,
byte[] data, int p )
{
BitSet versions = new BitSet( versionSetSize*8 );
p += versionSetSize-1;
for ( int j=0;j<versionSetSize;j++,p-- )
{
byte mask = (byte)1;
for ( int k=0;k<8;k++ )
{
if ( (mask & data[p]) != 0 )
versions.set( k+(j*8) );
mask <<= 1;
}
}
return versions;
}
|
7e9699ae-7e35-475e-ad1e-9e1a62f5511d
| 3 |
static void setClock(int clock, boolean oTime) {
if (oTime) {
if ("black".equals(Engine.color)) {
whiteClock = clock;
} else {
blackClock = clock;
}
} else if ("black".equals(Engine.color)) {
blackClock = clock;
} else {
whiteClock = clock;
}
}
|
1c08216a-bffd-48c6-9b51-58690e27d899
| 4 |
@Override
public void getAll() throws SQLException {
Connection dbConnection = null;
java.sql.Statement statement = null;
String selectCourses = "SELECT id_person, name, surname, date_of_birth, pin, phone_number, position_id FROM person";
try {
dbConnection = PSQL.getConnection();
statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectCourses);
while (rs.next()) {
int id = rs.getInt("id_person");
String name = rs.getString("name");
String surname = rs.getString("surname");
Date date = rs.getDate("date_of_birth");
String pin = rs.getString("pin");
int phoneNr = rs.getInt("phone_number");
int positionId = rs.getInt("position_id");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
|
12ab7307-8e57-4f71-a4ac-82d82f48728a
| 2 |
@Override
public String print() {
String print = "";
for (int i = 0; i < expressionList.size(); i++) {
print += expressionList.get(i).print();
if (i != expressionList.size() - 1) {
print += " " + arithmeticParameter.getSymbol() + " ";
}
}
return print;
}
|
2291c79f-9dd9-4c8c-b4fe-12b834688b97
| 7 |
private Map<Position, Tile> createTileMapFromStrings(String[] tileStringArray){
Map<Position, Tile> tileMap = new HashMap<Position, Tile>();
for(int i = 0; i < 16; i++){
String line = tileStringArray[i];
for(int j = 0; j < 16; j++){
char c = line.charAt(j);
String type = "error";
if(c == '.'){ type = GameConstants.OCEANS; }
if(c == 'M'){ type = GameConstants.MOUNTAINS; }
if(c == 'o'){ type = GameConstants.PLAINS; }
if(c == 'f'){ type = GameConstants.FOREST; }
if(c == 'h'){ type = GameConstants.HILLS; }
Position p = new Position(i,j);
tileMap.put( p, new TileImpl( p, type ) );
}
}
return tileMap;
}
|
b74a7c24-2397-4200-be65-1fcf64bd8baa
| 5 |
private boolean setPrecisionArgPosition() {
boolean ret=false;
int xPos;
for (xPos=pos; xPos<fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos>pos && xPos<fmt.length()) {
if (fmt.charAt(xPos)=='$') {
positionalPrecision = true;
argumentPositionForPrecision=
Integer.parseInt(fmt.substring(pos,xPos));
pos=xPos+1;
ret=true;
}
}
return ret;
}
|
aac666c7-38ed-4eb7-829d-9e891cf4f7a2
| 3 |
public ArrayList<Cidade> consultar(String id){
ArrayList<Cidade> cidades = new ArrayList<>();
try {
if(id.equals("")){
sql = "SELECT * FROM tb_cidade";
}else{
sql = "SELECT * FROM tb_cidade WHERE id='"+id+"'";
}
ConsultarSQL(sql, true);
while (rs.next()) {
Cidade cidade = new Cidade();
cidade.setCod(rs.getString("id"));
cidade.setNome(rs.getString("cidade"));
cidades.add(cidade);
}
} catch (SQLException ex) {
Logger.getLogger(DaoCidade.class.getName()).log(Level.SEVERE, null, ex);
}
return cidades;
}
|
9232abea-5bed-4500-ab95-a5ab20522c09
| 8 |
public void listDirectory() throws IOException {
String directory = "";
for(int i = 0; i < 3; i++){ // 3 is to iterate through all the directories
if(oft.readDiskToBuffer(0, i) == -1)
break;
byte[] memory = oft.getBuffer(0);
for(int j = 0; j < memory.length; j = j + DIRECTORY_ENTRY_SIZE_IN_BYTES){
String name = "";
for(int k = 0; k < 4; k++){ //4 = max length of word
//writer.write(k);
if(memory[j + k] != -1 && memory[j + k] != 0)
name = name + (char) memory[j + k];
}
if(name != "")
directory = directory + " " + name;
}
}
if(directory.length() > 0)
writer.write(directory.substring(1));
else
writer.write("");
writer.newLine();
}
|
d2b000fd-3bba-445c-b591-34b7738f65b8
| 7 |
private static void drawBio (Display d)
{
int max = 50;
int max_iter = 50;
Complex t = new Complex(0,0);
int X = WIDTH/2;
int Y = HEIGHT/2;
for (int y = -Y; y < Y; ++y)
{
for (int x = -X; x < X; ++x)
{
Complex z = new Complex (x*0.01,y*0.01);
Complex c = new Complex(1.00003,1.01828);
int n = 0;
while ( (Math.pow(z.getRe(),2) < max) && (Math.pow(z.getIm(),2) < max) && (n < max_iter) )
{
t.setRe(z.getRe());
t.setIm(z.getIm());
z.setRe(Math.pow(t.getRe(),4)+Math.pow(t.getIm(),4) - 6*Math.pow(t.getRe(),2)*Math.pow(t.getIm(),2) + c.getRe());
z.setIm(4*Math.pow(t.getRe(),3)*t.getIm()-4*Math.pow(t.getIm(),3)*t.getRe() + c.getIm());
n++;
}
if (Math.abs(z.getRe())>10 || Math.abs(z.getIm())>1000 )
{
int col = n % max;
graph.setForeground(set_palette(d,col));
graph.drawPoint(X+x,Y+y);
}
}
}
}
|
19ec32c9-0ee1-402e-a9db-dd2f7df3890c
| 3 |
@Override
public void actionPerformed(ActionEvent event) {
Component comp = getFocusOwner();
if (comp instanceof JTextComponent) {
((JTextComponent) comp).selectAll();
} else {
SelectAllCapable selectable = getTarget(SelectAllCapable.class);
if (selectable != null && selectable.canSelectAll()) {
selectable.selectAll();
}
}
}
|
36be0635-23a7-4713-b68c-d2422ef096ae
| 4 |
public static void setObject(Item i, String readerName) {
ObjectInfo oi = new ObjectInfo();
oi.setType(i.getSym());
i = Scanner.get();
oi.setName(String.valueOf(i.getVal()));
if(oi.getType() == Constants.STRING) {
if(Scanner.get().getSym() == Constants.BECOMES) {
Item val = Scanner.get();
if(val.getSym() == Constants.STRCONST) {
oi.setValue(val.getVal());
}
GenerateForSpim.initParam(oi);
}
}
else if(i != null){
GenerateForSpim.initParam(oi);
ObjParser.allocateObject(i, readerName);
}
}
|
60d4589a-ae38-451f-8512-5cd46600bfac
| 0 |
public void keyTyped(KeyEvent e) {
}
|
1cf4d093-8a1e-42aa-8ef8-674bcaed4ccd
| 9 |
private void cleanUpOldAndTemporaryfiles(String newDir, String tempDir){
System.err.println("deleting unneeded temporary files");
System.gc();
for(int entry=0;entry<writeInvFile.length;entry++){
File pl_f=new File(newDir+"/pl_e"+entry+".dat");
File ospl_f=new File(tempDir+"/pl_e"+entry+"_sorted.dat");
//delete the unordered posting list
if(pl_f.exists()){
boolean deleted=false;
for(int i=0;i<10000&&!deleted;i++)
deleted=pl_f.delete();
if(!deleted)
System.err.println("Warining failed to delete unordered posting list");
}
//delete the old renamed ordered posting list
if(ospl_f.exists()){
boolean deleted=false;
for(int i=0;i<10000&&!deleted;i++){
deleted=ospl_f.delete();
}
if(!deleted)
System.err.println("Warining failed to delete old ordered posting list");
}
}
}
|
5b5a2bc6-117d-400f-8d52-69b5d9f65a8a
| 8 |
public ArrayList<String> topClassesExtractor(SimpleGraph openGraph, SimpleGraph closeGraph) throws IconvisOntoDataRetrieveException {
log.debug("[OntologyParser::topClassesExtractor] BEGIN");
ArrayList<String> topClasses = new ArrayList<String>();
try {
ArrayList<String> downClasses = new ArrayList<String>();
ArrayList<String> allClasses = classExtractor(closeGraph);
ArrayList<HashMap<String, Value>> solutions = openGraph.runSPARQL("SELECT ?class1 ?class2 WHERE { "
+ "?class1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?class2 ." + "}");
for (HashMap<String, Value> elemento : solutions) {
Value v1 = elemento.get("class1");
Value v2 = elemento.get("class2");
if (v1.toString().contains(IconvisBean.ontologyURI) && (v2.toString().contains(IconvisBean.ontologyURI) || v2.toString().contains("#Thing"))) {
downClasses.add(v1.toString().replaceAll(IconvisBean.ontologyURI + "#", ""));
}
}
StringBuilder builder = new StringBuilder();
for (String s : downClasses) {
builder.append(" ").append(s).append(" ");
}
String downClassesString = builder.toString();
for (String s : allClasses) {
if (!downClassesString.contains(" " + s + " ")) {
topClasses.add(s);
}
}
} catch (Exception e) {
log.error("[OntologyParser::topClassesExtractor] Exception:", e);
throw new IconvisOntoDataRetrieveException("Exception generated during the extraction of top classes from the ontology.");
}
log.debug("[OntologyParser::topClassesExtractor] END");
return topClasses;
}
|
e1b18343-f077-41d7-9fee-e65747a0e953
| 3 |
public static void main (String args[]) throws InterruptedException{
System.out.println("Starting");
ExecutorService exec = Executors.newCachedThreadPool();
Future<?> fu = exec.submit(new Callable<Void>(){
@Override
public Void call() throws Exception {
Random r = new Random();
for(int i=0;i<1E6;i++){
if (Thread.currentThread().isInterrupted()){
System.out.println("interrupted");
break;
}
Math.sin(r.nextDouble());
}
return null;
}
});
exec.shutdown();
Thread.sleep(500);
exec.shutdownNow();
//fu.cancel(false);
exec.awaitTermination(1, TimeUnit.DAYS);
System.out.println("finished");
}
|
a39e5e62-e870-4729-aa1a-b3f79de2a51b
| 2 |
@Override
public double getAmount() {
double result = 0.0;
if(positive.isDown()) {
result += 1.0;
}
if(negative.isDown()) {
result -= 1.0;
}
return result;
}
|
e7ded7d5-a257-44ea-b1fe-7daae847a50b
| 2 |
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int cases=scanner.nextInt();
while (cases-->0){
int n=scanner.nextInt();
List<Point> pointList=new ArrayList<>();
while (n-->0){
pointList.add(new Point(scanner.nextDouble(),scanner.nextDouble()));
}
System.out.println(entrance(pointList));
}
}
|
1c5c5030-2e78-4a44-940d-9b3a033d6b32
| 4 |
public int plusDMLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 14;
else if( ((int)optInTimePeriod < 1) || ((int)optInTimePeriod > 100000) )
return -1;
if( optInTimePeriod > 1 )
return optInTimePeriod + (this.unstablePeriod[FuncUnstId.PlusDM.ordinal()]) - 1;
else
return 1;
}
|
39595cde-6b6b-45a3-b821-2b038ce6029c
| 3 |
private void updateWaypoints(String wps){
LinkedList<Position> points = new LinkedList<Position>();
wps.replace("set waypoints ", ""); //remove beginning of the message
String[] tokens = wps.split(" ");
System.out.println("Received " + tokens.length + " wayponts!");
for(String token : tokens){
String[] waypoint = token.split(";");
if(waypoint !=null && waypoint.length == 2){
points.add(new Position(Double.parseDouble(waypoint[0]), Double.parseDouble(waypoint[1])));
}
}
Boat.getInstance().setWaypoints(new Waypoints(points));
}
|
9d7bf920-781f-4927-a915-a998bf35074e
| 3 |
public void testMinYear() {
final ISOChronology chrono = ISOChronology.getInstanceUTC();
final int minYear = chrono.year().getMinimumValue();
DateTime start = new DateTime(minYear, 1, 1, 0, 0, 0, 0, chrono);
DateTime end = new DateTime(minYear, 12, 31, 23, 59, 59, 999, chrono);
assertTrue(start.getMillis() < 0);
assertTrue(end.getMillis() > start.getMillis());
assertEquals(minYear, start.getYear());
assertEquals(minYear, end.getYear());
long delta = end.getMillis() - start.getMillis();
long expectedDelta =
(start.year().isLeap() ? 366L : 365L) * DateTimeConstants.MILLIS_PER_DAY - 1;
assertEquals(expectedDelta, delta);
assertEquals(start, new DateTime(minYear + "-01-01T00:00:00.000Z", chrono));
assertEquals(end, new DateTime(minYear + "-12-31T23:59:59.999Z", chrono));
try {
start.minusYears(1);
fail();
} catch (IllegalFieldValueException e) {
}
try {
end.minusYears(1);
fail();
} catch (IllegalFieldValueException e) {
}
assertEquals(minYear - 1, chrono.year().get(Long.MIN_VALUE));
}
|
843b6dd7-0a29-4e44-b858-ef5fb064ffc1
| 9 |
*/
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
double scaleFactorMultiplier;
double x = e.getX(), y = e.getY();
int wheelDirection = e.getWheelRotation();
if(wheelDebouncerOn == true)
{
if(wheelDirection < 0)
{
if(zoomLevel < 40)
zoomLevel++;
else return;
scaleFactorMultiplier = Math.pow(1.1, zoomLevel);
scaleFactor = 12.5 * scaleFactorMultiplier;
xOffset += (x - x*1.1)*scaleFactorMultiplier;
yOffset += (y - y*1.1)*scaleFactorMultiplier;
}
else if(wheelDirection > 0 )
{
if(zoomLevel > -15)
zoomLevel--;
else return;
scaleFactorMultiplier = Math.pow(1.1, zoomLevel);
scaleFactor = 12.5 * scaleFactorMultiplier;
xOffset -= (x/1.1-x)*scaleFactorMultiplier;
yOffset -= (y/1.1-y)*scaleFactorMultiplier;
}
// keep window from going too far out of bounds
if(xOffset > scaleFactor*(scaleMeters[2]-scaleMeters[0]))//this.getWidth())
xOffset = (int) (scaleFactor*(scaleMeters[2]-scaleMeters[0]) - 2.0*scaleFactor);
if(yOffset > scaleFactor*(scaleMeters[3]-scaleMeters[1]) - 2.0 * scaleFactor)//this.getHeight())
yOffset = (int) (scaleFactor*(scaleMeters[3]-scaleMeters[1]));//this.getHeight();
if(xOffset < -1.0*scaleFactor*(scaleMeters[2]-scaleMeters[0]))//this.getWidth())
xOffset = (int) (-1.0*scaleFactor*(scaleMeters[2]-scaleMeters[0]) + 2.0 * scaleFactor);
if(yOffset < -1.0*scaleFactor*(scaleMeters[3]-scaleMeters[1]))//this.getHeight())
yOffset = (int) (-1.0*scaleFactor*(scaleMeters[3]-scaleMeters[1])+2.0*scaleFactor);//this.getHeight();
repaint();
}
wheelDebouncerOn = !wheelDebouncerOn;
}
|
eab8b399-49c5-4bf7-ab2d-aa4c95b6f15c
| 2 |
public static String urlDecode(String string)
{
if (string == null)
{
return null;
}
try
{
return URLDecoder.decode(string, "UTF-8");
}
catch (Exception e)
{
return string;
}
}
|
9eafbeca-e183-4ed4-8385-731e15e520ca
| 3 |
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
}
|
62428d26-6c07-4caa-be8d-41ae3172eba2
| 7 |
public Pair<Item, Item> getStartAndEndItem(NonTerminal nt) {
if (nt == grammar.startSymbol) {
return new Pair<Item, Item>(startItem, endItem);
}
Item start = new StartItem(0, nt);
Item end = new EndItem(1);
start.shift = new Transition(start, nt, end);
for (Item i : items) {
if (i.atBegin() && i.production != null && !i.production.usedForReject) {
Production p = i.production;
if (p != null && p.lhs == nt) {
start.derives.add(new Transition(start, p.derivation, i));
}
}
}
return new Pair<Item, Item>(start, end);
}
|
d059d004-2123-48f9-b73d-043cf03bf209
| 6 |
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("/exit")) {
gameLogic.exit();
System.exit(0);
}
else if (ae.getActionCommand().equals("/cheat")) {
gameLogic._sideBar.addCard(BoardObject.type.DEV);
gameLogic._sideBar.addCard(BoardObject.type.WHEAT);
gameLogic._sideBar.addCard(BoardObject.type.SHEEP);
gameLogic._sideBar.addCard(BoardObject.type.ORE);
gameLogic._sideBar.addCard(BoardObject.type.WOOD);
gameLogic._sideBar.addCard(BoardObject.type.BRICK);
gameLogic._sideBar.repaint();
((JTextField)ae.getSource()).setText("");
return;
}
if (ae.getActionCommand().length() > 8 && ae.getActionCommand().substring(0,6).equals("/tell ")) {
int i;
for (i=6;i<ae.getActionCommand().length()-1;i++) {
if (ae.getActionCommand().charAt(i) == ' ')
break;
}
addLine(gameLogic._playerNum+"(private to "+ae.getActionCommand().substring(6,i)+") "+gameLogic._name+": "+ae.getActionCommand().substring(i+1));
gameLogic.sendLinePrivate("(private to "+ae.getActionCommand().substring(6,i)+") "+gameLogic._name+": "+ae.getActionCommand().substring(i+1),
ae.getActionCommand().substring(6,i));
}
else {
addLine(gameLogic._playerNum + gameLogic._name+": "+ae.getActionCommand());
gameLogic.sendLine(gameLogic._name+": "+ae.getActionCommand());
}
((JTextField)ae.getSource()).setText("");
}
|
9afac2b8-74eb-40ca-a5ad-6a8ee0c37c25
| 6 |
private boolean _jspx_meth_html_html_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// html:html
org.apache.struts.taglib.html.HtmlTag _jspx_th_html_html_0 = (org.apache.struts.taglib.html.HtmlTag) _jspx_tagPool_html_html_lang.get(org.apache.struts.taglib.html.HtmlTag.class);
_jspx_th_html_html_0.setPageContext(_jspx_page_context);
_jspx_th_html_html_0.setParent(null);
_jspx_th_html_html_0.setLang(true);
int _jspx_eval_html_html_0 = _jspx_th_html_html_0.doStartTag();
if (_jspx_eval_html_html_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" <head>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" <title>Roll Call - Login</title>\r\n");
out.write(" <link rel=\"stylesheet\" href=\"rollcall.css\" /> \r\n");
out.write(" </head>\r\n");
out.write(" <body id=\"login\">\r\n");
out.write(" <h1>Roll Call</h1>\r\n");
out.write(" <h2>CS 347</h2>\r\n");
out.write(" <div id=\"login-box\">\r\n");
out.write(" <!-- <form action=\"LoginServlet\" method=\"post\"> -->\r\n");
out.write(" <!-- <form action=\"doLogin\"> -->\r\n");
out.write(" <!-- Email <input property=\"username\" type=\"text\" name=\"email\"/><br> -->\r\n");
out.write(" <!-- Password <input property=\"password\" type=\"password\" name=\"password\"/> -->\r\n");
out.write(" <!-- <input type=\"submit\" name=\"submit\"/> -->\r\n");
out.write(" \r\n");
out.write(" <!--</form> --> \r\n");
out.write(" <!-- </form> -->\r\n");
out.write(" ");
if (_jspx_meth_html_form_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_html_html_0, _jspx_page_context))
return true;
out.write("\r\n");
out.write("\r\n");
out.write(" <form method=\"link\" action=\"profregister.jsp\">\r\n");
out.write(" <input type=\"submit\" value=\"Don't have an account? Sign up now\" class=\"submit\"/>\r\n");
out.write(" </form> \r\n");
out.write(" </div><!-- end login box -->\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" </body>\r\n");
out.write(" <div class=\"error-box btm\">");
if (_jspx_meth_html_errors_2((javax.servlet.jsp.tagext.JspTag) _jspx_th_html_html_0, _jspx_page_context))
return true;
out.write("</div>\r\n");
int evalDoAfterBody = _jspx_th_html_html_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_html_html_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_html_html_lang.reuse(_jspx_th_html_html_0);
return true;
}
_jspx_tagPool_html_html_lang.reuse(_jspx_th_html_html_0);
return false;
}
|
f17e3d1e-71a5-476c-9182-6a634eacec95
| 6 |
private void checkConnect(String[] tokens) {
final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
if(tokens.length > 2)
{
Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(tokens[1]);
int port = 0;
try
{
port = Integer.parseInt(tokens[2]);
}
catch(NumberFormatException ex){
Application.logger.error("An IO Error occured: " + ex.getMessage());
}
if (matcher.matches() && port >= 1 && port <= 65535) {
String message = Application.clientLogic.connect(tokens[1], port);
if (message != null) {
System.out.println("EchoClient> "+ message);
}
else
{
System.out.println("EchoClient> Server is not reachable. Check Your internet connection/Retry later");
}
} else {
System.out.println("EchoClient> Unknown ip address or port.");
}
}
else
{
System.out.println("EchoClient> IP address or port is missing");
}
}
|
9e91d123-2d2d-4bd6-b776-1fc542cecd49
| 9 |
public void method212(boolean flag, int xSize, int ySize, int x, int y, int rotation) {
int k1 = 256;
if (flag) {
k1 += 0x20000;
}
x -= offsetX;
y -= offsetY;
if (rotation == 1 || rotation == 3) {
int srcX = xSize;
xSize = ySize;
ySize = srcX;
}
for (int i2 = x; i2 < x + xSize; i2++) {
if (i2 >= 0 && i2 < baseX) {
for (int j2 = y; j2 < y + ySize; j2++) {
if (j2 >= 0 && j2 < baseY) {
setFlagMask(i2, j2, k1);
}
}
}
}
}
|
c93e6b39-6923-42e3-a97c-c2fac191cd3c
| 7 |
public static void doChanges(LauncherAPI api, Class<?> clazz)
{
try
{
final Class<?> c = api.getLauncher().getClassLoader()
.loadClass("net.minecraft.client.Minecraft");
for (final Field field : c.getDeclaredFields())
{
if (field.getType() == File.class)
{
field.setAccessible(true);
try
{
field.get(c);
field.set(null, api.getMinecraftDirectory());
}
catch (final IllegalArgumentException e)
{
}
catch (final IllegalAccessException e)
{
}
}
}
}
catch (final ClassNotFoundException e)
{
}
}
|
29357560-8f32-4f5b-81e8-683d3c730db0
| 4 |
KMPSearchState remove( KMPSearchState item ) throws MVDException
{
KMPSearchState previous,list,temp;
previous = temp = list = this;
while ( temp != null && temp != item )
{
previous = temp;
temp = temp.following;
}
if ( previous == temp ) // it matched immediately
{
list = temp.following; // could be null!
temp.following = null;
}
else if ( temp == null ) // it didn't find it!
throw new MVDException("List item not found");
else // temp in the middle of the list
{
previous.following = temp.following;
temp.following = null;
}
return list;
}
|
4dc80d4f-ff7f-47df-9425-65a2957ea868
| 0 |
public void onStart(IContext context) throws JFException {
engine = context.getEngine();
console = context.getConsole();
indicators = context.getIndicators();
console.getOut().println("---Auto Trader ON---");
}
|
bb60910a-2bcf-41be-8759-6732320e832f
| 8 |
@Override
public void receive(IPInterfaceAdapter src, Datagram datagram) throws Exception {
// hello message received from one of our neibourg (maybe not)
if (datagram.getPayload() instanceof HelloMessage) {
HelloMessage hello = (HelloMessage) datagram.getPayload();
// Check if the router is not already in our neighbor list.
if (!neighborList.containsKey(hello.routerId)) {
// if the sender has to router id in his neighbor list add him has a neighbor
// we had it permanently to our neighbor list.
if (hello.neighborList.contains(getRouterID())) {
neighborList.put(hello.routerId, new LinkState(hello.routerId, src.getMetric(), src));
} else {
Map<IPAddress, LinkState> OSPFTemp = neighborList;
OSPFTemp.put(hello.routerId, new LinkState(hello.routerId, src.getMetric(), src));
HelloMessage helloAnswer = new HelloMessage(getRouterID(), OSPFTemp.keySet());
src.send(new Datagram(src.getAddress(), datagram.src, IP_PROTO_LS, 1, helloAnswer), null);
}
} else {
// if the HelloMessage contains a distance which is smaller than the one stored
// lets replace it.
if (neighborList.get(hello.routerId).metric > src.getMetric()) {
neighborList.put(hello.routerId, new LinkState(hello.routerId, src.getMetric(), src));
}
}
LinkStateMessage currentNeighbors = new LinkStateMessage(getRouterID());
for (LinkState ls : neighborList.values()) {
currentNeighbors.addLS(ls);
}
LSDB.put(getRouterID(), currentNeighbors);
}
// LinkState message received from one of our neibourg
if (datagram.getPayload() instanceof LinkStateMessage) {
LinkStateMessage msg = (LinkStateMessage) datagram.getPayload();
// Check if it is not present or if sequence number is bigger than the one actually stored.
if (LSDB.get(msg.routerId) == null || msg.getSequence() > LSDB.get(msg.routerId).getSequence()) {
LSDB.put(msg.routerId, msg);
this.SendToAllButSender(src, msg);
}
Compute(LSDB);
}
}
|
3290b9e5-a31d-4b70-8023-5534452fc374
| 2 |
public List<Download> getDownloadsListFiltered() {
ArrayList<Download> list = new ArrayList<Download>();
for (Download download : downloads.values()) {
if (stateFilter.contains(download.getStatus())) {
list.add(download);
}
}
return list;
}
|
dafb5bbb-fb46-432b-b6bb-8656a8f53dc7
| 4 |
private List<Section> parseFile(final File file)
throws FileNotFoundException, IOException {
listOfSections = new LinkedList<Section>();
final BufferedReader input = new BufferedReader(new FileReader(file));
final StringBuilder docsText = new StringBuilder();
final StringBuilder codeText = new StringBuilder();
String line;
while (null != (line = input.readLine())) {
if (line.contains("*") || line.contains("////")) { //$NON-NLS-1$ //$NON-NLS-2$
if (codeText.length() > 0) {
save(docsText, codeText);
docsText.setLength(0);
codeText.setLength(0);
}
docsText.append(line).append("\n"); //$NON-NLS-1$
} else {
codeText.append(line).append("\n"); //$NON-NLS-1$
}
}
save(docsText, codeText);
return listOfSections;
}
|
00554951-ad15-4773-bcc1-37a18f471998
| 6 |
public static int getInt(String prompt, int low, int high) {
final int ALLOWABLE_INPUT_FAILURES = 3; // Avoid leaving a user stuck in here infinitely. If they fail to enter an int after 3 tries, bail out anyway.
String response;
int inputFailureCount = 0;
while (true) { // use an infinite loop. Exit will occur on return if they enter a valid <i>int</i> or after exhausting the attempt limit.
// try-block used to manage an interaction where there may be a failure: in particular, a user might enter something other than a parseable <i>int</i> value
try {
response = JOptionPane.showInputDialog(prompt); // no possible failure here, since we can pick up any pattern of characters
// Possible failure on following line, since non-<i>int</i> characters will generate an exception in the <i>Integer.parseInt()</i> method
// If a failure occurs in the <i>Integer.parseInt()</i> method call, then program execution will <i>throw</i> an exception that will immediately
// abandon the <i>try</i>-block and jump to the closest matching <i>catch</i>-block.
int convertedResponse = Integer.parseInt(response);
// we can only arrive here if the <i>Integer.parseInt()</i> method returned normally, that is, it did not <i>throw</i> an exception.
if (convertedResponse < low || convertedResponse > high) {
if (++inputFailureCount > ALLOWABLE_INPUT_FAILURES) {
showErrorGUI("Too many unsuccessful attempts. Setting to 0");
return 0; // exits on failure to complete input operation
}
showErrorGUI("Number must be between " + low + " and " + high + " (inclusive).");
} else
return convertedResponse; // exits on successful completion of input operation
} catch (NumberFormatException | NullPointerException exception) { // only arrive here if there was a failure in the <i>Integer.parseInt()</i> method or <Esc> at dialog
if (++inputFailureCount < ALLOWABLE_INPUT_FAILURES) {
showErrorGUI("You must enter an integer.");
} else {
showErrorGUI("Too many unsuccessful attempts. Setting to 0");
return 0; // exits on failure to complete input operation
}
}
}
} // end public static int getInt()
|
cc3ff8e3-0c1f-410e-ab2a-ef87893d2ba4
| 2 |
public void setType(EComponentType type) throws ComponentException {
if (type == null) {
throw new ComponentException("Type is null");
}
if (this.type != null) {
throw new ComponentException("Type has already been set");
}
this.type = type;
}
|
4b7385fd-2ed3-413b-b74f-cb147324df4a
| 2 |
public void testGet() {
YearMonth test = new YearMonth();
assertEquals(1970, test.get(DateTimeFieldType.year()));
assertEquals(6, test.get(DateTimeFieldType.monthOfYear()));
try {
test.get(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.get(DateTimeFieldType.dayOfMonth());
fail();
} catch (IllegalArgumentException ex) {}
}
|
ee9bf2e3-5fce-4d2a-9799-c23fad1280c9
| 3 |
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
JEditorPane pane = (JEditorPane) e.getSource();
if (e instanceof HTMLFrameHyperlinkEvent) {
HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
HTMLDocument doc = (HTMLDocument) pane.getDocument();
doc.processHTMLFrameHyperlinkEvent(evt);
} else {
try {
goNew(e.getURL().toString());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
|
a9dd4d8d-4f03-4b73-9186-12b056d4b21a
| 0 |
public int getFirmwareVer() {
return lastFirmwareVer;
}
|
e4672568-5743-47d3-86c5-bec49745c2ce
| 9 |
public static String underscoreFromCamel(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
char[] a = str.toCharArray();
for (char element : a) {
char c = element;
if (c >= 'A' && c <= 'Z') {
sb.append('_');
c += ('a' - 'A');
} else if (c == '_') {
sb.append('_');
} else if (c >= '0' && c <= '9' && sb.length() > 0 && sb.charAt(sb.length() - 1) == '_') {
sb.setLength(sb.length() - 1);
}
sb.append(c);
}
return sb.toString();
}
|
26d4fbbb-e4eb-4a04-abb2-4d444c24c26d
| 0 |
public String getMessage() {
String message = this.content + " - by: " + this.user.getName() + "\n";
return message;
}
|
ff63ff10-39ca-4332-9456-b36e86375e01
| 2 |
private void isLessThanInteger(Integer param, Object value) {
if (value instanceof Integer) {
if (!(param < (Integer) value)) {
throw new IllegalStateException("Integer is not greater than supplied value.");
}
} else {
throw new IllegalArgumentException();
}
}
|
344b8567-5157-4a92-bcc0-e5e6e8170ea8
| 3 |
public static Stack<String> getNames(CommandDescriptor descriptor)
{
Stack<String> commands = new Stack<>();
commands.push(descriptor.getName());
Dispatcher dispatcher = descriptor.getDispatcher();
while (dispatcher != null && dispatcher.getDescriptor() != null)
{
descriptor = dispatcher.getDescriptor();
if (descriptor.getName().isEmpty())
{
break;
}
commands.add(descriptor.getName());
dispatcher = descriptor.getDispatcher();
}
return commands;
}
|
97e2d3bd-15ec-466c-b144-192c240b7cbc
| 7 |
public static boolean kifVariableDeclarationP(Stella_Object tree) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(tree);
if (testValue000 == Logic.SGT_STELLA_CONS) {
{ Cons tree000 = ((Cons)(tree));
switch (tree000.length()) {
case 1:
return (Logic.questionMarkSymbolP(tree000.value));
case 2:
return (Logic.questionMarkSymbolP(tree000.value) &&
(Stella_Object.symbolP(tree000.rest.value) &&
(!Logic.questionMarkSymbolP(tree000.rest.value))));
default:
return (false);
}
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol tree000 = ((Symbol)(tree));
if (Logic.questionMarkSymbolP(tree000)) {
return (true);
}
}
}
else {
return (false);
}
}
return (false);
}
|
7dfdff18-6c01-46ae-afd6-2c17d1fc061e
| 4 |
private boolean mouseOver() {
if (window.mouse.width>x &&
window.mouse.height>y &&
window.mouse.width<x+w &&
window.mouse.height<y+h )
return true;
return false;
}
|
8577b322-8735-433b-861e-5730fcd22cc6
| 1 |
public String receiveMessage() {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
connectionSocket.receive(packet);
} catch (Exception e) {
e.printStackTrace();
}
return new String(packet.getData()).trim();
}
|
179adbe2-4156-43fe-9dab-77da878a7d43
| 8 |
public void processUpdateOrder(String orderId, String orderSz, String orderPr, String QteTime)
{
System.out.println("Received Update call back with follg. values");
System.out.print("OrderId: " + orderId);
System.out.print(" orderSz: " + orderSz);
System.out.print(" orderPr: " + orderPr);
System.out.println(" QteTime: " + QteTime);
int index = findIndex(askTableModel, orderId, 3);
if (index >= 0)
{
if (QteTime != null)
askTableModel.setValueAt(formatTime(QteTime), index, 2);
if (orderSz != null)
askTableModel.setValueAt(new Integer(orderSz), index, 1);
if (orderPr != null)
askTableModel.setValueAt(new Float(orderPr), index, 0);
changeColor(TableModelEvent.UPDATE, index, tblAsk);
}
else
{
index = findIndex(bidTableModel, orderId, 0);
if (index >= 0)
{
if (QteTime != null)
bidTableModel.setValueAt(formatTime(QteTime), index, 1);
if (orderSz != null)
bidTableModel.setValueAt(new Integer(orderSz), index, 2);
if (orderPr != null)
bidTableModel.setValueAt(new Float(orderPr), index, 3);
changeColor(TableModelEvent.UPDATE, index, tblBid);
}
}
return;
}
|
91b269cf-494a-42e4-b985-9a39148ab342
| 1 |
public ResultSet getList(String whereString) {
StringBuffer sql = new StringBuffer("");
sql.append("SELECT Question_ID,QType_ID,noofwords,instructions");
sql.append(" FROM `Essay`");
if (whereString.trim() != "") {
sql.append(" where " + whereString);
}
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
ResultSet rs = sQLHelper.runQuery(sql.toString());
//sQLHelper.sqlClose();
return rs;
}
|
c0d469e3-0083-4b49-8ff8-1f80d7321472
| 9 |
private void fillbuf(byte[] buf, int off, int len) {
double[] val = new double[nch];
double[] sm = new double[nch];
while(len > 0) {
for(int i = 0; i < nch; i++)
val[i] = 0;
for(Iterator<CS> i = clips.iterator(); i.hasNext();) {
CS cs = i.next();
if(!cs.get(sm)) {
i.remove();
continue;
}
for(int ch = 0; ch < nch; ch++)
val[ch] += sm[ch];
}
for(int i = 0; i < nch; i++) {
int iv = (int)(val[i] * 32767.0);
if(iv < 0) {
if(iv < -32768)
iv = -32768;
iv += 65536;
} else {
if(iv > 32767)
iv = 32767;
}
buf[off++] = (byte)(iv & 0xff);
buf[off++] = (byte)((iv & 0xff00) >> 8);
len -= 2;
}
}
}
|
efc00b74-fb78-4dc3-b42b-0cda5ae0335b
| 5 |
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] coins = br.readLine().split(" ");
int num_coin = coins.length;
int[][] result = new int[n + 1][num_coin];
for (int i = 0; i <= n; i++) {
for (int j = 0; j < coins.length; j++) {
if (i == 0) {
result[i][j] = 1;
} else {
int v1 = 0;
int v2 = 0;
try {
v1 = result[i - Integer.parseInt(coins[j])][j];
} catch (Exception e) {
}
try {
v2 = result[i][j - 1];
} catch (Exception e) {
}
result[i][j] = v1 + v2;
}
}
}
System.out.println(result[n][num_coin - 1]);
}
|
f30ed03b-8478-4c23-8155-7aa60cdaf579
| 4 |
@Override
public void setByte(long i, byte value)
{
if (value < 0 || value > 1) {
throw new IllegalArgumentException("The value has to be 0 or 1.");
}
if (ptr != 0) {
Utilities.UNSAFE.putByte(ptr + i, value);
} else {
if (isConstant()) {
throw new IllegalAccessError("Constant arrays cannot be modified.");
}
data[(int) i] = value;
}
}
|
e3927571-ae95-433b-bfc1-a11c46534151
| 4 |
public boolean actionChats(Actor actor, Actor other) {
// Base on comparison of recent activities and associated traits, skills
// or actors involved.
float success = talkResult(SUASION, SUASION, TRUTH_SENSE, other) ;
other.mind.incRelation(actor, success / 10) ;
switch (Rand.index(3)) {
case (0) : anecdote(actor, other) ; break ;
case (1) : gossip (actor, other) ; break ;
case (2) : advise (actor, other) ; break ;
}
final float novelty = actor.mind.relationNovelty(other) ;
if (novelty <= 0) {
stage = STAGE_BYE ;
}
return true ;
}
|
f4b5dce5-f1b3-4bc8-bbd6-42ed4360148b
| 9 |
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the number of games to run: ");
int numGames = scan.nextInt();
RPSScoreKeeper keeperRock = new RPSScoreKeeper();
RPSScoreKeeper keeperPaper = new RPSScoreKeeper();
RPSScoreKeeper keeperScissors = new RPSScoreKeeper();
RPSThrow rockThrow = new RPSThrow(RPSThrow.ROCK);
RPSThrow paperThrow = new RPSThrow(RPSThrow.PAPER);
RPSThrow scissorsThrow = new RPSThrow(RPSThrow.SCISSORS);
RPSThrow opponentThrow;
for(int i = 0; i < numGames; i++) {
opponentThrow = new RPSThrow();
boolean check = rockThrow.beats(opponentThrow);
if (check == true)
keeperRock.addWin();
else if (opponentThrow.beats(rockThrow))
keeperRock.addLoss();
else
keeperRock.addTie();
}
System.out.println("When we are rock: " + keeperRock);
for(int i = 0; i < numGames; i++) {
opponentThrow = new RPSThrow();
boolean check = paperThrow.beats(opponentThrow);
if (check == true)
keeperPaper.addWin();
else if (opponentThrow.beats(paperThrow))
keeperPaper.addLoss();
else
keeperPaper.addTie();
}
System.out.println("When we are paper: " + keeperPaper);
for(int i = 0; i < numGames; i++) {
opponentThrow = new RPSThrow();
boolean check = scissorsThrow.beats(opponentThrow);
if (check == true)
keeperScissors.addWin();
else if (opponentThrow.beats(scissorsThrow))
keeperScissors.addLoss();
else
keeperScissors.addTie();
}
System.out.println("When we are scissors: " + keeperScissors);
}
|
fd633c45-d66c-4532-9f92-5512162cb7b3
| 9 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof InstanceAce))
return false;
InstanceAce other = (InstanceAce) obj;
if (objectHashCode == null) {
if (other.objectHashCode != null)
return false;
} else if (!objectHashCode.equals(other.objectHashCode))
return false;
if (user_id == null) {
if (other.user_id != null)
return false;
} else if (!user_id.equals(other.user_id))
return false;
return true;
}
|
4c4a91dc-8de3-419d-a794-dc37bd1d3c56
| 0 |
public int getData( )
{
return data;
}
|
5396f2ff-6d68-47b5-a5e7-f17cea059e32
| 8 |
private void parseAreYouSure(String input) {
Scanner scanner = new Scanner(input);
if (scanner.hasNext()) {
String next = scanner.next();
if( (next.equals("yes") || next.equals("y")) && !scanner.hasNext()) {
state = State.Normal;
if (caller == AreYouSureCaller.Newgame) doNewGame();
else if (caller == AreYouSureCaller.Savegame) doSaveGame();
else if (caller == AreYouSureCaller.Loadgame) doLoadGame();
else if (caller == AreYouSureCaller.Exit) doExit();
}
else {
state = State.Normal;
print("Action not confirmed.");
}
}
caller = AreYouSureCaller.NoAction;
scanner.close();
}
|
9102cba8-30a3-4c54-af09-2a60bbc4843b
| 9 |
private ByteMatcher createRandomByteMatcher() {
int matcherType = random.nextInt(9);
boolean inverted = random.nextBoolean();
switch (matcherType) {
case 0:
return AnyByteMatcher.ANY_BYTE_MATCHER;
case 1:
return OneByteMatcher.valueOf((byte) random.nextInt(256));
case 2:
return new InvertedByteMatcher((byte) random.nextInt(256));
case 3:
return new ByteRangeMatcher(random.nextInt(256), random.nextInt(256), inverted);
case 4:
return new SetBinarySearchMatcher(createRandomByteSet(), inverted);
case 5:
return new SetBitsetMatcher(createRandomByteSet(), inverted);
case 6:
return new TwoByteMatcher((byte) random.nextInt(256), (byte) random.nextInt(256));
case 7:
return new AllBitmaskMatcher((byte) random.nextInt(256), inverted);
case 8:
return new AnyBitmaskMatcher((byte) random.nextInt(256), inverted);
default:
throw new RuntimeException("Case statement doesn't support value " + matcherType);
}
}
|
aeb00bd2-cf04-4c2b-8f33-28d85e39e010
| 7 |
private HeaderContext getParsedHeaders(String headerPart) {
final int len = headerPart.length();
HeaderContext headers = new HeaderContext();
int start = 0;
for (;;) {
int end = parseEndOfLine(headerPart, start);
if (start == end) {
break;
}
StringBuilder header = new StringBuilder(headerPart.substring(start, end));
start = end + 2;
//若行首有特殊字符('' or '\t')将"\r\n"替换为" "并清除特殊字符
while (start < len) {
int nonWs = start;
//记录连续的空白或者制表符的末尾索引,预计出现在一行的开头
while (nonWs < len) {
char c = headerPart.charAt(nonWs);
if (c != ' ' && c != '\t') {
break;
}
++nonWs;
}
if (nonWs == start) {
break;
}
// 跳过空白或制表符解析一行
end = parseEndOfLine(headerPart, nonWs);
//裁剪空白符或制表符末尾至end的部分,拼接至header,用空格隔开
header.append(" ").append(headerPart.substring(nonWs, end));
//start跳过空格
start = end + 2;
}
parseHeaderLine(headers, header.toString());
}
return headers;
}
|
d0f6be35-d17b-4dae-9bd6-6a0049d4e458
| 1 |
private void startCollectionEditing() {
// Work on shiet
// Drawing Text field for collection name
cp5.getController("enter collection name").setPosition(posX + 36,
posY + 100);
cp5.getController("enter collection name").setVisible(true);
// Add buttons for set key, loadFile, delete and save collection
ImageButton addFile = new ImageButton(parent, "Add File", 75, 550, 100,
25, 1) {
@Override
public void onMousePress(int x, int y) {
// Adding filePath to audioPathsArray
int result = jfile.showOpenDialog(new JFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfile.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
selectedCollection.set((Integer) 1, (String)selectedFile.getAbsolutePath());
}
}
};
ImageButton deleteFile = new ImageButton(parent, "Delete File", 195,
550, 100, 25, 1) {
@Override
public void onMousePress(int x, int y) {
// Add logic to delete specified file (media)
// get remove key from collection and thus removes that
// filePaths
selectedCollection.delete((Integer) selectedKey);
indexSelected = -1;
}
};
ImageButton setKey = new ImageButton(parent, "Set Key", 315, 550, 100,
25, 1) {
@Override
public void onMousePress(int x, int y) {
isSettingKey = true;
}
};
ImageButton saveCollection = new ImageButton(parent, "Save Collection",
435, 550, 100, 25, 1) {
@Override
public void onMousePress(int x, int y) {
parent.removeCollection(selectedCollection);
parent.addCollection(selectedCollection);
}
};
screenManager.addButton(addFile);
screenManager.addButton(deleteFile);
screenManager.addButton(setKey);
screenManager.addButton(saveCollection);
}
|
8503c762-8102-42f4-95f7-0247e92f3744
| 4 |
public void mouseMoved(MouseEvent me) {
int toolMode = documentViewModel.getViewToolMode();
if (toolMode == DocumentViewModel.DISPLAY_TOOL_SELECTION &&
!(annotation.getFlagLocked() || annotation.getFlagReadOnly())) {
ResizableBorder border = (ResizableBorder) getBorder();
setCursor(Cursor.getPredefinedCursor(border.getCursor(me)));
}else if (toolMode == DocumentViewModel.DISPLAY_TOOL_LINK_ANNOTATION) {
// keep it the same
} else{
// set cursor back to the hand cursor.
setCursor(documentViewController.getViewCursor(
DocumentViewController.CURSOR_HAND_ANNOTATION));
}
}
|
8205cdfb-36a2-4a6a-b16f-4bc92c80d9e6
| 3 |
private String parseTextElement(String name) throws ParserException, XMLStreamException {
StringBuilder text = new StringBuilder();
startElement(name);
while (is(CHARACTERS) || is(COMMENT)) {
if (is(CHARACTERS)) {
text.append(look().toString());
}
next();
}
endElement(name);
return replaceEscapeSequences(trimLines(text.toString()));
}
|
c5520b69-a8a4-47f5-b13c-e49f13fda0e7
| 3 |
public static ArrayList<Class<?>> getDetectedMouseClasses()
{
if (detected == null)
{
detected = new ArrayList<Class<?>>();
}
return detected;
}
|
38790d91-8217-4eb2-b877-0d01cbc6ba88
| 7 |
private void showTrack() {
int counter = 0;
while(counter < tracksize) {
if (posFido == counter) {
System.out.print('F');
} else {
System.out.print('o');
}
counter++;
}
System.out.println();
counter = 0;
while(counter < tracksize) {
if (posSpot == counter) {
System.out.print('S');
} else {
System.out.print('o');
}
counter++;
}
System.out.println();
counter = 0;
while (counter < tracksize) {
if (posRover == counter) {
System.out.print('R');
} else {
System.out.print('o');
}
counter++;
}
System.out.println();
for (int i = 0; i < tracksize; i++) {
System.out.print('-');
}
System.out.println(); //
}
|
80c48ef0-7a02-4bbd-b7f7-257366125a22
| 3 |
@Test
public void testGetLocationsByDeployment() throws IOException {
List<Location> remoteLocations = dexmaRestFacade.getLocationsByDeployment(265L);
assertEquals(3,remoteLocations.size());
Iterator<Location> itRemote = remoteLocations.iterator();
while (itRemote.hasNext()) {
Location loc = itRemote.next();
/*iteration over the local list. This operation is slow (O(N2)) but for test purposes
* is more than enough
*/
Iterator<Location> itLocal = locations.iterator();
boolean notFound = true;
while (itLocal.hasNext() && notFound) {
notFound = !loc.equals(itLocal.next());
}
assertEquals(notFound,false);
}
}
|
891ad13e-bea8-42e7-b710-267c8c4a0ce9
| 3 |
public ArrayList<Molecule> selectRandMols(int n){
ArrayList<Molecule> randMols = new ArrayList<Molecule>();
int max = bucket.size();
int prevRand = 0;
//System.out.printf("Max: %d\n", max);
int rand;
for(int i=0; i<n; i++){
rand = (int) (Math.random()*(double)max);
while(rand==0 || rand==prevRand){rand = (int) (Math.random()*(double)max);}
randMols.add(bucket.get(rand));
//System.out.printf("%d\t%d\n", rand, randMols.get(i).getID());
prevRand = rand;
}
return randMols;
}
|
a2294450-b687-414a-94f8-0b8d3dbbe378
| 6 |
@Override
public void startBackgroundMusic() {
System.out.println("*** startBackgroundMusic ***");
musicVolume = Options.getAsFloat(Options.MUSIC, "1.0f");
if (!isMuted() && hasOggPlaybackSupport()) {
if (isPlaying(BACKGROUND_TRACK))
stopBackgroundMusic();
nextSong++;
if (nextSong>4) nextSong = 1;
//nextSong = TurnSynchronizer.synchedRandom.nextInt(4)+1;
String backgroundTrack = "/resources/sound/Background " + nextSong + ".ogg";
System.out.println("next song: " + backgroundTrack);
try {
File backgroundFile = new File(MojamComponent.getMojamDir(), backgroundTrack);
URL backgroundURL = backgroundFile.toURI().toURL();
if (backgroundFile.exists()){
getSoundSystem().backgroundMusic(BACKGROUND_TRACK, backgroundURL, backgroundTrack, true);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
getSoundSystem().setVolume(BACKGROUND_TRACK, musicVolume);
}
|
e6aeaa2d-31b7-412f-aa72-375ecead1931
| 6 |
public static void redistributeWorker(long time, Peer peer, String workerId, OurSim ourSim) {
Allocation workerAllocation = peer.getAllocation(workerId);
if (workerAllocation == null) {
return;
}
PeerRequest request = workerAllocation.getRequest();
if (request != null) {
request.removeAllocatedWorker(workerId);
}
workerAllocation.setRequest(null);
workerAllocation.setConsumer(null);
workerAllocation.setLastAssign(time);
if (workerAllocation.isWorkerLocal()) {
peer.setWorkerState(workerId, WorkerState.IDLE);
redistributeLocalWorker(time, peer, workerId, ourSim);
} else {
redistributeRemoteWorker(time, peer, workerId, ourSim);
}
if (request != null && !request.isPaused() && request.getNeededWorkers() > 0) {
request.setCancelled(false);
Event requestWorkersEvent = ourSim
.createEvent(
PeerEvents.REQUEST_WORKERS,
time
+ ourSim.getLongProperty(Configuration.PROP_REQUEST_REPETITION_INTERVAL),
peer.getId(), request.getSpec(), true);
ourSim.addEvent(requestWorkersEvent);
}
}
|
b4c18271-f7fd-4647-b0be-ca454b2a3721
| 2 |
private int getBombCount() {
ArrayList<Spot> neighbors = grid.getNeighbors(loc);
int count = 0;
for(Spot s : neighbors)
if (s.isBomb())
count++;
return count;
}
|
77391093-69a7-48fd-834f-88ae1e45aab8
| 5 |
public boolean move(Direction dir) throws GameException
{
int length = getMaximumFreeDistance(dir, (int)speed);
switch(dir)
{
case TOP:
setLocation(getX(), getY()-length);
break;
case BOTTOM:
setLocation(getX(), getY()+length);
break;
case LEFT:
setLocation(getX()-length, getY());
break;
case RIGHT:
setLocation(getX()+length, getY());
break;
default:
break;
}
return length != 0 || dir == Direction.NO_MOVE;
}
|
5bc8e817-1c04-487c-9a61-e5f10f935966
| 5 |
@Override
public String toString() {
switch(this) {
case uneEtoile:
return "★";
case deuxEtoiles:
return "★★";
case troisEtoiles:
return "★★★";
case quatreEtoiles:
return "★★★★";
case cinqEtoiles:
return "★★★★★";
}
return null;
}
|
cd5d24b1-5bfa-4527-b6b6-fbf82012352a
| 0 |
public FileExtensionFilter(String extension) {
this.extension = extension;
}
|
d813da34-8633-4475-a6a5-833d80133a5d
| 8 |
private static void execDir( File f )
{
if( f.isDirectory() )
{
String[] children = f.list();
for( int i = 0; i < children.length; i++ )
{
execDir( new File( f, children[i] ) );
}
}
else if( f.getName().indexOf( "RunSamples" ) == -1 )
{
String fn = f.getName();
String packagename = f.getPath();
packagename = StringTool.replaceChars( "\\", packagename, "." ); // win
packagename = StringTool.replaceChars( "/", packagename, "." ); // unix
packagename = packagename.substring( packagename.indexOf( "docs." ) );
if( fn.indexOf( ".class" ) > -1 )
{
try
{
packagename = packagename.substring( 0, packagename.indexOf( ".class" ) );
Class cx = Class.forName( packagename );
Method[] m = cx.getMethods();
for( int t = 0; t < m.length; t++ )
{
if( m[t].getName().equals( "main" ) )
{
String[] args = new String[1];
try
{
log.info( "Running " + packagename );
m[t].invoke( cx, args );
}
catch( Throwable tx )
{
log.error( "Problem Running " + packagename + " main method.", tx );
}
}
}
}
catch( Exception e )
{
log.error( "Cannot run " + packagename + " main method.", e );
}
}
}
}
|
0ebd8dde-2687-45c3-a3db-1168942d3fd5
| 5 |
@RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(@ModelAttribute Student student, BindingResult result, @RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
switch(action.toLowerCase()){
case "add":
studentService.add(student);
studentResult = student;
break;
case "edit":
studentService.edit(student);
break;
case "delete":
studentService.delete(student.getStudentId());
studentResult = new Student();
break;
case "search":
Student searchedStudent = studentService.getStudent(student.getStudentId());
studentResult = searchedStudent != null ? searchedStudent : new Student();
break;
}
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
|
a8acd493-dc38-4919-a79a-0cb1caa12b56
| 2 |
@Override
public ResultSet query(String query)
throws MalformedURLException, InstantiationException, IllegalAccessException {
//Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
//connection = getConnection();
this.connection = this.getConnection();
statement = this.connection.createStatement();
switch (this.getStatement(query)) {
case SELECT:
result = statement.executeQuery(query);
return result;
default:
statement.executeUpdate(query);
return result;
}
} catch (SQLException ex) {
this.writeError("Error in SQL query: " + ex.getMessage(), false);
ex.printStackTrace();
}
return null;
}
|
4036e143-8e85-4d24-9482-639e67ed3dee
| 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);
}
|
5268e8a7-cdab-46e9-9a26-1ee95b75cb5f
| 3 |
private void recieveMessage(){
try {
BufferedReader in = null;
//PrintWriter out = null;
//out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String line = in.readLine();
logger.logMessage(line);
processMessage(line.toString());
} catch (IOException e) {
logger.logMessage(Level.WARNING,"Failed to open incoming socket.",e);
return;
}
catch (Exception e){
logger.logMessage(Level.WARNING,"Unknown Exception while receiving the message. ",e);
return;
}
try {
serverSocket.close();
} catch (IOException e) {
logger.logMessage(Level.WARNING, "Error while closing the socket." , e);
return;
}
}
|
2ef853d2-ab9e-46f2-9cd7-c9711bf9c098
| 0 |
public void setValue(String value) {
this.value = value;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.