method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
a2eb3333-a367-4b0e-ade2-b3ee6184a354 | 8 | public Response serve(Request request) throws InterruptedException {
authener.authen(request);
if (request.uri.equals("/")) {
Response welcome = serveFile(request.uri, request.header,
getHomeDir(), true);
welcome.markNoCache();
return welcome;
} else if (request.getCookie("d") != null
&& request.uri.endsWith(request.getCookie("d"))) {
Servlet servlet = getServlet("/homecam.Capturer.action");
return servlet.serve(request);
} else if (request.uri.endsWith(servletUriSuffix)) {
Servlet servlet = getServlet(request.uri);
return servlet.serve(request);
} else {
try {
String ext = request.uri.substring(
request.uri.lastIndexOf('.') + 1).toLowerCase();
if (ext.equals(request.uri) || theMimeTypes.containsKey(ext)
|| !authener.requireAuthen(request.uri, request.method)) {
return serveFile(request.uri, request.header, getHomeDir(),
true);
}
} catch (Exception e) {
log.error(request.uri, e);
}
}
return new Response(Server.HTTP_FORBIDDEN, Server.MIME_PLAINTEXT,
"Sorry cannot serve " + request.uri);
} |
45ee1413-8612-43c1-a2be-59f915c49eb2 | 6 | public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CadastroExercicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastroExercicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastroExercicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastroExercicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CadastroExercicio().setVisible(true);
}
});
} |
cbdc4894-2d7e-4f61-8291-27d217b9b6f4 | 1 | public void decoder(int[] octets_data){
if (taille ==5) {
vitesseXhigh = octets_data[0];
vitesseYhigh = octets_data[1];
vitesseXlow = octets_data[2];
vitesseYlow = octets_data[4];
arret_obst = (octets_data[5] & 0x10) >>> 4;
etat_capt_av_ar = (octets_data[5] & 0x6) >>> 2;
sens_deplacement = (octets_data[5] & 0x3);
}
} |
b3e64682-2150-4f8f-95a3-84e119c1f3f1 | 8 | final int[][] getVertexGroups(boolean bool, int i) {
anInt1845++;
int[] is = new int[256];
int maximumGroup = 0;
int amountVertices = (!bool ? ((Model) this).anInt1821
: ((Model) this).vertices);
for (int vertex = 0; vertex < amountVertices; vertex++) {
int group = ((Model) this).vgroups[vertex];
if ((group ^ 0xffffffff) <= -1) {
is[group]++;
if (maximumGroup < group)
maximumGroup = group;
}
}
int[][] vertexGroups = new int[1 + maximumGroup][];
for (int group = 0; (maximumGroup ^ 0xffffffff) <= (group ^ 0xffffffff); group++) {
vertexGroups[group] = new int[is[group]];
is[group] = 0;
}
for (int vertex = 0; amountVertices > vertex; vertex++) {
int group = ((Model) this).vgroups[vertex];
if ((group ^ 0xffffffff) <= -1)
vertexGroups[group][is[group]++] = vertex;
}
if (i > -14)
recolorTriangles((short) 9, (byte) 80, (short) -118);
return vertexGroups;
} |
37216efb-3a12-47f5-bfa3-11ef78eba760 | 3 | private int bsR(final int n) throws IOException {
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
if (bsLiveShadow < n) {
final InputStream inShadow = this.in;
do {
int thech = inShadow.read();
if (thech < 0) {
throw new IOException("unexpected end of stream");
}
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
} while (bsLiveShadow < n);
this.bsBuff = bsBuffShadow;
}
this.bsLive = bsLiveShadow - n;
return (bsBuffShadow >> (bsLiveShadow - n)) & ((1 << n) - 1);
} |
4f9144b8-059d-4832-b544-4bf4ce629b35 | 1 | public boolean ApagarTodosQuandoExcluiPessoa(int idPessoa){
try{
PreparedStatement comando = banco.getConexao()
.prepareStatement("UPDATE telefones SET ativo = 0 WHERE id_pessoa= ?");
comando.setInt(1, idPessoa);
comando.executeUpdate();
comando.getConnection().commit();
return true;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}
} |
84d48001-9aae-4978-a507-f29b17759ae7 | 3 | public boolean exit() {
int reponse = analyseSave.closeProgram();
if ( reponse == JOptionPane.YES_OPTION || reponse == JOptionPane.NO_OPTION ) { // Bug #348263
saveProperties();
System.exit(0);
}
if ( reponse == JOptionPane.CANCEL_OPTION ) // c'est fait exprès ( chemin tortueux à modifier )
return false ;
else
return true ; // Bug #348263
} |
bf3cdbc7-e378-4c03-8b8f-3e12c7250d12 | 2 | public Layer getActiveLayer(ArrayList<Layer> l) {
for (Layer layer : l) {
if (layer.isActive()) {
return layer;
}
}
return null;
} |
9013ec65-7782-4f23-99f2-bf7e0123ee07 | 0 | public TuringBruteParseAction(GrammarEnvironment environment) {
super("Parser for Converted Grammar from TM", null);
this.environment = environment;
this.frame = Universe.frameForEnvironment(environment);
} |
20c7989e-3f0f-4ecb-9eb2-b74a53866094 | 8 | public void updateParticle(Particle particle, int delta) {
particleCount++;
particle.adjustVelocity(windFactor.getValue(0) * 0.00005f * delta, gravityFactor
.getValue(0) * 0.00005f * delta);
float offset = particle.getLife() / particle.getOriginalLife();
float inv = 1 - offset;
float colOffset = 0;
float colInv = 1;
Color startColor = null;
Color endColor = null;
for (int i = 0; i < colors.size() - 1; i++) {
ColorRecord rec1 = (ColorRecord) colors.get(i);
ColorRecord rec2 = (ColorRecord) colors.get(i + 1);
if ((inv >= rec1.pos) && (inv <= rec2.pos)) {
startColor = rec1.col;
endColor = rec2.col;
float step = rec2.pos - rec1.pos;
colOffset = inv - rec1.pos;
colOffset /= step;
colOffset = 1 - colOffset;
colInv = 1 - colOffset;
}
}
if (startColor != null) {
float r = (startColor.r * colOffset) + (endColor.r * colInv);
float g = (startColor.g * colOffset) + (endColor.g * colInv);
float b = (startColor.b * colOffset) + (endColor.b * colInv);
float a;
if (alpha.isActive()) {
a = alpha.getValue(inv) / 255.0f;
} else {
a = ((startAlpha.getValue(0) / 255.0f) * offset)
+ ((endAlpha.getValue(0) / 255.0f) * inv);
}
particle.setColor(r, g, b, a);
}
if (size.isActive()) {
float s = size.getValue(inv);
particle.setSize(s);
} else {
particle.adjustSize(delta * growthFactor.getValue(0) * 0.001f);
}
if (velocity.isActive()) {
particle.setSpeed(velocity.getValue(inv));
}
if (scaleY.isActive()) {
particle.setScaleY(scaleY.getValue(inv));
}
} |
115e1d62-3a6a-4a91-9010-b22045eccf8b | 4 | private void resaveParamsShowCountry(SessionRequestContent request) {
String validCountryStatus = request.getParameter(JSP_COUNTRY_VALID_STATUS);
if(validCountryStatus != null) {
request.setSessionAttribute(JSP_COUNTRY_VALID_STATUS, validCountryStatus);
}
String invalidCountryStatus = request.getParameter(JSP_COUNTRY_INVALID_STATUS);
if(invalidCountryStatus != null) {
request.setSessionAttribute(JSP_COUNTRY_INVALID_STATUS, invalidCountryStatus);
}
String validCityStatus = request.getParameter(JSP_CITY_VALID_STATUS);
if(validCityStatus != null) {
request.setSessionAttribute(JSP_CITY_VALID_STATUS, validCityStatus);
}
String invalidCityStatus = request.getParameter(JSP_CITY_INVALID_STATUS);
if(invalidCityStatus != null) {
request.setSessionAttribute(JSP_CITY_INVALID_STATUS, invalidCityStatus);
}
} |
950d34e8-25ba-45a0-8e80-72e97bdc1c66 | 0 | public static boolean isEmpty() {
return buffer == EOF;
} |
c83aad51-7a9c-4787-9ced-4b52558c476b | 1 | public void dumpExpression(TabbedPrintWriter writer)
throws java.io.IOException {
if (!isInnerMost) {
writer.print(writer.getClassString(classInfo, Scope.AMBIGUOUSNAME));
writer.print(".");
}
writer.print("this");
} |
6fbb8986-5143-48ee-8b1e-e5e4bb1be607 | 6 | public String toBoardString() {
switch (this) {
case JACK_MUSTARD:
return "Y";
case KASANDRA_SCARLETT:
return "R";
case DIANE_WHITE:
return "W";
case JACOB_GREEN:
return "G";
case ELEANOR_PEACOCK:
return "B";
case VICTOR_PLUM:
return "P";
default:
throw new IllegalArgumentException();
}
} |
38ce9963-8e19-49eb-8eb0-c99e33a8f502 | 6 | protected void readSampleData()
{
boolean read_ready = false;
boolean write_ready = false;
int mode = header.mode();
int i;
do
{
for (i = 0; i < num_subbands; ++i)
read_ready = subbands[i].read_sampledata(stream);
do
{
for (i = 0; i < num_subbands; ++i)
write_ready = subbands[i].put_next_sample(which_channels,filter1, filter2);
filter1.calculate_pcm_samples(buffer);
if ((which_channels == OutputChannels.BOTH_CHANNELS) && (mode != Frame.SINGLE_CHANNEL))
filter2.calculate_pcm_samples(buffer);
} while (!write_ready);
} while (!read_ready);
} |
f8e2fa4f-8110-48e3-8c4f-9e8413e97278 | 5 | public int connect(String hostname, int port) {
int i;
synchronized (servlist) {
for (i = 0; i < mclients; i++) {
if (servlist[i] == null)
break;
}
if (i >= mclients) {
// double the list if its too big...
ajserverthread newlist[] = new ajserverthread[2*mclients];
for (i = 0; i < mclients; i++) {
newlist[i] = servlist[i];
}
servlist = newlist;
mclients = 2*mclients;
}
try {
servlist[i] = new ajserverthread(hostname, port, i, this);
} catch (IOException e) {
servlist[i] = null;
return -1;
}
(new Thread(servlist[i])).start();
return i;
}
} |
a8bb81e1-0778-4a3b-befb-a9a4e37e907a | 6 | public String type() {
final TinyELToken tok = lexer.token();
switch (tok) {
case BYTE:
case SHORT:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
lexer.nextToken();
return tok.name;
default:
return name().toString();
}
} |
c210147e-d6cd-4030-99d8-46c02ccf07d9 | 4 | @Override
public void update(GameContainer gc, int delta) throws SlickException {
switch (state) {
default:
case MENU:
menu.update(gc, delta);
case PAUSED:
break;
case PLAYING:
player.update(gc, delta);
break;
case QUIT:
gc.exit();
}
} |
7819d92d-d468-435b-a2fb-24a13ad34af9 | 5 | private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
} |
2805e369-b09d-47f2-8c23-91a0353fbf6c | 3 | public boolean checkBoard() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if(!checkCell(i, j)){
return false;
}
}
}
return true;
} |
d7a28e17-adcc-4b31-80bc-beae81dc82ae | 1 | void removeElement(Element element) {
if (element == null)
throw new IllegalArgumentException("Element can't be null!");
elements.remove(element);
} |
39197638-feba-4c92-8a3d-e0c35fa12180 | 3 | private void placeShips() {
ArrayList<Ship> shipsToPlace = new ArrayList<>();
shipsToPlace.add(new Ship(eShipType.aircraftcarrier));
shipsToPlace.add(new Ship(eShipType.battleship));
shipsToPlace.add(new Ship(eShipType.destroyer));
shipsToPlace.add(new Ship(eShipType.patrolboat));
shipsToPlace.add(new Ship(eShipType.submarine));
while (shipsToPlace.size() > 0) {
Ship toPlace = shipsToPlace.get(0);
toPlace.setStartPoint(getRandomCoordinates());
eOrientation orient = toPlace.getStartPoint().getX() % 2 == 0 ? eOrientation.Horizontal : eOrientation.Vertical;
toPlace.setOrientation(orient);
boolean canPlace = true;
//try place
// TO DO
canPlace = field.setShip(toPlace);
if (canPlace) {
shipsToPlace.remove(toPlace);
}
}
// when all ships are placed AI is ready
Message<ePlayerState> ready = new MessageFactory<ePlayerState>().createMessage(eMessageType.playerState, ePlayerState.Ready);
game.handleOponentMessage(ready);
} |
e5e1bad8-9b8c-43c1-8795-7f2a8c0e044e | 4 | @SuppressWarnings("unused")
private void create() { //créé un villageois
if (this.statue < 3){
if (this.stock >= 150){
this.statue++;
this.stock = this.stock-150;
if (this.statue == 3) {
this.al.caserne.remove(this.curent);
this.al.demande_ressource.add(this.curent);
}
}
}
else {
if (this.stock >= 150){
launchAgent(new Soldat(this.curent,this.al));
this.stock = this.stock-150;
}
}
} |
2db1b4da-bd51-40d7-a440-e04eb9528635 | 5 | public void updateSpreadsheetsList() {
URL metafeedUrl = null;
try {
metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
} catch (MalformedURLException e) {
guiRef.writeSysLog("E","The Google spreadsheets URL seems invalid. Nothing that you can do about it.");
e.printStackTrace();
}
SpreadsheetFeed feed;
try {
if(metafeedUrl != null) {
feed = client.getFeed(metafeedUrl, SpreadsheetFeed.class);
LinkedList<SpreadsheetEntry> spreadsheets = (LinkedList<SpreadsheetEntry>) feed.getEntries();
spreadsheetsList = new SpreadsheetEntry[spreadsheets.size()];
spreadsheetsList = spreadsheets.toArray(spreadsheetsList);
}
} catch (ServiceException e) {
guiRef.writeSysLog("E","Error in retrieving your spreadsheets list. Please try again!");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
spreadsheetsTitles = new String[spreadsheetsList.length];
int i=0;
for(SpreadsheetEntry s : spreadsheetsList) {
spreadsheetsTitles[i] = s.getTitle().getPlainText();
i++;
}
} |
109ccac7-88d9-49a2-a6a7-b130baa26d46 | 2 | @Override
public Citation getCitation(Integer id) {
for (Citation c : citations) {
if (id.equals(c.getId())) {
return c;
}
}
throw new IllegalArgumentException("No citation with such id!");
} |
6a70c87d-fd35-495a-8b1a-eaae7b803ad7 | 9 | public static boolean arePointsOnSameSideOfLine(Point p1, Point p2, Point l1, Point l2) {
if (GeometryUtils.isLineHorizontal(l1, l2)) {
if (p1.y() < l1.y() && p2.y() < l1.y()) return true;
if (p1.y() > l1.y() && p2.y() > l1.y()) return true;
return false;
}
boolean p1IsLeft = GeometryUtils.isPointLeftOfLine(p1, l1, l2);
boolean p2IsLeft = GeometryUtils.isPointLeftOfLine(p2, l1, l2);
if ((p1IsLeft && p2IsLeft) || (!p1IsLeft && !p2IsLeft))
return true;
return false;
} |
c917784d-ce7a-4cd5-a173-e2f39b0d6b55 | 7 | private void showErrorMessage(Thread t, Throwable e) {
String s1 = null, s2 = null, s3 = "";
switch (errorType) {
case LOAD_ERROR:
String s = Modeler.getInternationalText("LoadingError");
s1 = s != null ? s : "Loading Error";
s = Modeler.getInternationalText("EncounteredErrorInLoadingDataCausedBy");
s2 = s != null ? s : "Sorry, we have encountered errors in loading data, caused by:";
if (e instanceof OutOfMemoryError) {
s3 = "\n\nSuggestion:\nIt may be good to restart " + Modeler.NAME + " if this error keeps occuring.";
}
break;
case SCRIPT_ERROR:
s = Modeler.getInternationalText("ScriptError");
s1 = s != null ? s : "Script Error";
s = Modeler.getInternationalText("EncounteredErrorInScriptsCausedBy");
s2 = s != null ? s : "Sorry, we have encountered errors in scripts, caused by:";
break;
}
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(parent), s2 + "\n" + e + "\n in thread: "
+ t.getName() + s3, s1, JOptionPane.ERROR_MESSAGE);
} |
f8e0c155-56ae-484c-91f3-6660ec42da68 | 5 | @Override
public boolean borrarElemento(Object n) {
if (this.esVacia())
return false;
if (this.inicio.getObj().equals(n)) {
this.borrarInicio();
return true;
} else {
NodoLista aux = this.inicio;
while (aux.getSig() != null && !aux.getSig().getObj().equals(n))
aux = aux.getSig();
// lo encontro o lleguo al final de la lista
if (aux.getSig() != null) {
NodoLista borrar = aux.getSig();
aux.setSig(borrar.getSig());
borrar.setSig(null);
return true;
}
return false;
}
} |
82465465-945f-4a20-b4be-b49a8736b10d | 8 | final byte[] loadArchiveChild(int i, int i_5_, int[] is) {
anInt639++;
if (!isValidChild(i, i_5_))
return null;
if (childBuffers[i] == null || childBuffers[i][i_5_] == null) {
boolean bool = loadArchive(i, i_5_, is);
if (!bool) {
loadArchive(i);
bool = loadArchive(i, i_5_, is);
if (!bool)
return null;
}
}
byte[] is_7_ = Class50_Sub1.getByteArray(childBuffers[i][i_5_]);
if ((unpackSettings) == 1) {
childBuffers[i][i_5_] = null;
if ((indexTable.amountChildEntries[i]) == 1)
childBuffers[i] = null;
} else if (unpackSettings == 2)
childBuffers[i] = null;
return is_7_;
} |
4ae996a0-01fb-43ea-80d8-944e7cf4b813 | 5 | public void update(){
//Get number of frames that passed
double exactDF = Directory.spriteManager.getDeltaFrames();
if(exactDF >= 1){
int dF = 0;
dF = (int) Math.floor(exactDF);
Directory.spriteManager.flagDeltaFramesReset();
//If the current column is the last column
if(currentColumn == numColumns[currentRow] - 1){
//If there is another set of drawing instructions ready
if(animationQueue.size() > 0){
//Dequeue next set of instructions
AnimationInstruction instructionSet = animationQueue.poll();
//Load next animation
currentRow = instructionSet.animationRowIndex;
repeating = instructionSet.repeatAnimation;
//Set column to 0 to start animation from beginning
currentColumn = 0;
}
//Else there is nothing queued, if the current animation is set to repeat
else if(repeating){
//Set column to 0 to start animation from beginning
currentColumn = 0;
}
}
//Else not at last column of animation yet
else{
//If the current column + the change in frames is still not greater than the last column
if(currentColumn + dF < numColumns[currentRow]){
//Increment the current column by the number of frame changes
currentColumn += dF;
}
//Else, the current column + the changes in frames results in an out of bounds frame
else{
//Set current column to last column
currentColumn = numColumns[currentRow] - 1;
}
}
//Finally, once frame variables are ready, set the frame
setFrame();
}
} |
be30b3a1-0ae9-4fc5-b932-f4792753fc15 | 4 | private void write(String user, String event, int glID, String resName,
String status, double clock)
{
if (trace_flag == false) {
return;
}
// Write into a results file
FileWriter fwriter = null;
try
{
fwriter = new FileWriter(super.get_name(), true);
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while opening file " + super.get_name());
}
try
{
fwriter.write(event + "\t\t" + glID + "\t" + resName + "\t" + status +
"\t\t" + clock + "\n");
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while writing on file " + super.get_name());
}
try
{
fwriter.close();
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while closing file " + super.get_name());
}
} |
fb2209dc-f043-4074-8940-e22e580ee3dc | 1 | public static boolean stringToBoolean(String bool) {
if(bool.equals("ON"))
return true;
else
return false;
} |
f3fa6fff-f21a-4e0e-b189-696bb2891d1e | 9 | public static boolean isAfter(Date date1, Date date2) {
int[] dIng1 = getDateIngredients(date1);
int day1 = dIng1[0];
int month1 = dIng1[1];
int year1 = dIng1[2];
int[] dIng2 = getDateIngredients(date2);
int day2 = dIng2[0];
int month2 = dIng2[1];
int year2 = dIng2[2];
if (year1 > year2) {
return true;
}
if (year1 < year2) {
return false;
}
if (year1 == year2 && month1 > month2) {
return true;
}
if (year1 == year2 && month1 < month2) {
return false;
}
if (year1 == year2 && month1 == month2 && day1 > day2) {
return true;
}
return false;
} |
85787c51-34eb-4f5e-9514-ea1622fad378 | 0 | public Object peek() {
return getFirst();
} |
4a833d61-8dc6-410d-b86d-b61f51d75ca8 | 6 | public static void update() {
while (Keyboard.next()) {
int eventKey = Keyboard.getEventKey();
if (0 <= eventKey && eventKey < NUM_KEYCODES) {
lastKeys[eventKey] = Keyboard.getEventKeyState();
}
}
while (Mouse.next()) {
int eventButton = Mouse.getEventButton();
if (0 <= eventButton && eventButton < NUM_MOUSEBUTTONS) {
lastMouse[eventButton] = Mouse.getEventButtonState();
}
}
} |
a68d11fb-a82e-4d66-95ab-bb260c63a95e | 5 | WordNet(String sentiPath) {
System.out.println("Initializing Wordnet database...");
sentimentMap = new SentiMap();
// create BufferedReader
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(sentiPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// add pos/neg sentiment words
String line;
int cnt = 0;
try {
while ((line = br.readLine()) != null) {
cnt++;
if (line.substring(0, 1).equals("#")) { // skip commented out lines
continue;
} else {
String[] sentiLine = line.split("\t");
Double posVal = Double.valueOf(sentiLine[2]);
Double negVal = Double.valueOf(sentiLine[3]);
String synsetWords = sentiLine[4];
ArrayList<String> synsetWordList = getSynsetWords(synsetWords);
for (String word : synsetWordList) {
addSentiWord(word, posVal, negVal);
}
}
}
} catch (IOException e) {
System.out.println("Error in reading WordNet database");
e.printStackTrace();
}
} |
d0dd13dd-c0f7-419b-a435-4ca8cb40778a | 3 | protected int collapsesNeeded() {
State[] states = automaton.getStates();
int needed = 0;
for (int i = 0; i < states.length; i++)
for (int j = 0; j < states.length; j++)
if (automaton.getTransitionsFromStateToState(states[i],
states[j]).length > 1)
needed++;
return needed;
} |
dccd5335-a210-4da6-9485-ec14b516486b | 8 | public void run () {
try {
U.infoOut("Connection accepted: " + socket);
mConLineIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
mConLineOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
socket.setSoTimeout(MAIN_SERVER_TIMEOUT);
String recievedCommand = mConLineIn.readLine();
/* UPDATE */if (recievedCommand.equals(S.UPDATE_STRING))
try {
U.infoOut("Update requested from client "+socket);
// -------------------------------------
File file = new File(S.APP_DB_FOLDER_NAME+File.separator+Config.APP_DB_NAME);
FileInputStream fis = new FileInputStream(file);
String fileMD5 = DigestUtils.md5Hex(fis);
mConLineOut.println(Config.UPDATE_PORT);
mConLineOut.println(fileMD5);
mConLineOut.println(file.length());
fis = new FileInputStream(file);
InetSocketAddress listenAddress = new InetSocketAddress(Config.UPDATE_PORT);
ServerSocketChannel listener = ServerSocketChannel.open();
ServerSocket updateServer = listener.socket();
updateServer.setReuseAddress(true);
updateServer.bind(listenAddress);
SocketChannel updateConnection = listener.accept();
updateConnection.configureBlocking(true);
FileChannel fc = fis.getChannel();
long bytes_sent = fc.transferTo(0, file.length(), updateConnection);
fc.close();
fis.close();
updateServer.close();
listener.close();
U.infoOut("Update sent: size="+file.length()+"; bytes sent="+bytes_sent+"; MD5="+fileMD5);
// -------------------------------------
} catch (Exception e) {
U.errOut("An error occured while updating client's database!", e);
mConLineOut.println(S.ERROR_STRING);
mConLineOut.println("Server error:"+e.toString());
}
/* ORDER */ if (recievedCommand.equals(S.ORDER_STRING)) {
try {
// String orderTable = mConLineIn.readLine();
// String orderID = mConLineIn.readLine();
// String orderTime = mConLineIn.readLine();
// int orderSize = Integer.parseInt(mConLineIn.readLine());
// for (int i = 0; i < orderSize; i++) {
// order = mConLineIn.readLine();
// }
Gson gson = new Gson();
OrderHolder order = gson.fromJson(mConLineIn.readLine(), OrderHolder.class);
if (order!=null) {
File file = new File(S.APP_ORDERS_FOLDER_NAME+File.separator+"order_" + order.tableN + "_" + order.orderID + ".xls");
if (file.exists()) { file.delete(); }
file.createNewFile();
/*
* The code below is for adding lines to an existing workbook.
* I left it here because someday i will get use of it.
* Don't remove it.
*/
// Workbook wb;
// try {
// wb = WorkbookFactory.create(file);
// } catch (Exception e) {
// wb = new HSSFWorkbook();
// }
// Sheet sheet;
// try {
// sheet = wb.getSheetAt(0);
// } catch (Exception e) {
// sheet = wb.createSheet();
// }
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet();
int row = 0;
// int row = sheet.getLastRowNum() == 0 ? 0 : sheet.getLastRowNum()+1;
sheet.createRow(row).createCell(0).setCellValue("Order ID");
sheet.getRow(row).createCell(1).setCellValue(order.orderID);
sheet.createRow(++row).createCell(0).setCellValue("Order Table");
sheet.getRow(row).createCell(1).setCellValue(order.tableN);
sheet.createRow(++row).createCell(0).setCellValue("Order Price");
sheet.getRow(row).createCell(1).setCellValue(order.orderPrice.toString());
for (int i = 0; i < order.orderedItems.size(); i++) {
sheet.createRow(++row).createCell(0).setCellValue(order.orderedItems.get(i).getName());
sheet.getRow(row).createCell(1).setCellValue(order.orderedItems.get(i).getPrice().toString());
}
wb.write(new FileOutputStream(file));
}
} catch (Exception e) {
U.errOut("An error occured while recieving order from the client!", e);
}
}
} catch (Exception e) {
U.errOut("An error occured while communicating with the client!", e);
}
try {
socket.close();
} catch (IOException e) {
U.errOut("An error occured while trying to close client's connection", e);
}
} |
de1ccf84-53f5-4a89-9c5c-8eeff3c8d10d | 4 | public static int possibleMoves (int x, int y) {
// bottom up approach
// initialize the table
int[][] s = new int[x+1][y+1];
// top row
for ( int i=0; i <= x; ++i )
s[i][0] = 1;
// left column
for ( int i=1; i <= y; ++i )
s[0][i] = 1;
// build up the table
for ( int i=1 ; i <= x; ++i ) {
for ( int j=1; j <= y; ++j ) {
s[i][j] = s[i-1][j] + s[i][j-1];
}
}
return s[x][y];
} |
4f08d477-565d-4dcb-8d27-1abe2de28cac | 4 | @Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
OrthographicCamera camera = WidgetMgr.MAP_EDITOR.camera;
if(Gdx.input.isButtonPressed(Input.Buttons.RIGHT)){
Ray pickRay = camera.getPickRay(Gdx.input.getX(), Gdx.input.getY());
Intersector.intersectRayPlane(pickRay, XY_PLANE, curr);
if(!(last.x == -1 && last.y == -1 && last.z == -1)) {
pickRay = camera.getPickRay(last.x, last.y);
Intersector.intersectRayPlane(pickRay, XY_PLANE, delta);
delta.sub(curr);
camera.position.add(delta.x, delta.y, delta.z);
}
last.set(Gdx.input.getX(), Gdx.input.getY(), 0);
WidgetMgr.MAP_EDITOR.camPos.set(camera.position);
}
return false;
} |
f038f228-6eaa-42de-b782-c931c7982919 | 5 | private void openNothings()
{
int flags = 0;
final TileSet nothings = new TileSet(mField);
final int size = nothings.size();
for (int tile = 0; tile < size; tile++ )
{
final MaskValue mask = mField.getMaskValue(tile);
if (mask.isFlag()) flags++ ;
if (mask.isNothing()) nothings.add(tile);
}
if (mAnalyzer.getBombs() == flags) for (int tile : nothings)
mAnalyzer.userOpenTile(Tile.getX(tile), Tile.getY(tile));
} |
5da1e00f-2e9a-49c5-aa20-5ca5c84f9f12 | 4 | @DELETE()
@Path("release/{playerId}")
@Produces("application/json")
@SportService(ServiceType.MLB)
public Player releasePlayer(@PathParam("playerId") int iPlayerId)
{
Player p = new Player();
UserTransaction utx = null;
try
{
p = emNhl.find(Player.class, iPlayerId);
System.out.println("BEFORE: Player id : "+p.getId()+" Player name = "+p.getFirstName()+" "+p.getLastName()+" Position = "+p.getPosition()+" team ID = "+p.getTeamId());
utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
utx.begin();
emNhl.remove(emNhl.contains(p) ? p : emNhl.merge(p));
emNhl.flush();
utx.commit();
System.out.println("Removed: Player id : "+p.getId()+" Player name = "+p.getFirstName()+" "+p.getLastName()+" Position = "+p.getPosition()+" team ID = "+p.getTeamId());
}
catch (Exception e)
{
if (utx == null)
{}
else
{
try
{
utx.rollback();
}
catch (Exception ex)
{
System.out.println("Exception = "+ex.getMessage());
}
}
System.out.println("Exception = "+e.getMessage());
}
return p;
} |
1502a9a2-05d0-45b7-b784-0b66238f1b30 | 7 | String getLoginType() {
if (userName.equals("admin")) {
return "admin";
} else if (userName.equals("User")) {
return "user";
} else if (userName.equals("lab")) {
return "lab";
} else if (userName.equals("medical")) {
return "medical";
}else if(userName.equals("counter")){
return "counter";
}else if(userName.equals("register")){
return "register";
}else if(userName.equals("issue")){
return "issue";
} else {
return null;
}
} |
8ea122d3-9aef-4456-b567-4c1638adf3b2 | 2 | private static String getAttributeValue(Node node, String attribname) {
final NamedNodeMap attributes = node.getAttributes();
String value = null;
if (attributes != null) {
Node attribute = attributes.getNamedItem(attribname);
if (attribute != null) {
value = attribute.getNodeValue();
}
}
return value;
} |
2e93e871-80a3-4d3d-98b9-f1138bdfff5a | 8 | public static int findMaximumPathSum(){
String linestr;
String[] tokens;
int lines = 0, i = 0;
int j,temp;
try{
BufferedReader br = new BufferedReader(new FileReader("triangle"));
LineNumberReader reader = new LineNumberReader(new BufferedReader(new FileReader("triangle")));
while((reader.readLine()) != null){
lines++;
}
triangle = new int[lines][lines];
while(((linestr = br.readLine())) != null){
tokens = linestr.split(" ");
for(j = 0; j < tokens.length; j++){
temp = Integer.parseInt(tokens[j]);
triangle[i][j] = temp;
}
i++;
}
for(i = lines-1; i > 0; i--){
for(j = 0; j < lines - 1; j++){
triangle[i-1][j] += (triangle[i][j] > triangle[i][j+1]) ? triangle[i][j]: triangle[i][j+1];
}
}
return triangle[0][0];
} catch (FileNotFoundException e){
System.out.println(e);
} catch (IOException e){
System.out.println(e);
}
return 0;
} |
b24f8fe5-434b-4fd8-bbc4-a99980168f5c | 6 | private int parseSplit(char ch, int state) {
if (state == 0) {
switch (ch) {
case '\n': return 1;
case '\t': return 2;
case '\r': return 3;
case ' ': return 4;
case ';': return 5;
}
}
return -1;
} |
f8d8bffb-199d-47b7-981d-c49794a220be | 5 | @RequestMapping("/discountRead.do")
public ModelAndView discountShowInfo(Device device, HttpServletRequest req)
throws Exception {
ModelAndView mav = new ModelAndView();
// 공연 제목을 받아와 공연 제목의 해당하는 seq 값을 가져오기 위한 변수
String title = req.getParameter("title");
String mapPlace = req.getParameter("place");
// xml에 공연 제목을 넘겨주기 위한 변수
String keyword = null;
String address = null;
;
title = new String(title.getBytes("8859_1"), "utf-8");
mapPlace = new String(mapPlace.getBytes("8859_1"), "utf-8");
if (title != null) {
keyword = "&keyword=" + URLEncoder.encode(title, "utf-8");
}
if (mapPlace != null) {
address = "&keyword=" + URLEncoder.encode(mapPlace, "utf-8");
}
// 할인 되는 공연 제목에 따라 그 공연의 seq값을 가져오기 위한 메소드
String seq = showService.getShowSeq(keyword);
// 할인 되는 seq값을 통해 할인 되는 공연의 정보를 가져오기 위한 메소드
PerforInfoVO pfi = showService.showInfoView(seq, keyword);
PlaceVO pf = showService.mapView(address);
mav.addObject("perForInfo", pfi);
mav.addObject("place", pf);
String pc="basic";
if(req.getParameter("pc")!=null)
pc = req.getParameter("pc");
if (device.isMobile()) {
logger.info("discountRead mobile");
if(pc.equals("pc")){
mav.setViewName("showInfo");
}
else{
logger.info("isPCVersion");
mav.setViewName("m.showInfo");
}
} else {
logger.info("discountRead desktop");
mav.setViewName("showInfo");
}
return mav;
} |
b1b10da4-7c9e-4c59-99a8-a46c7c5889fe | 8 | void processaNada()
{
int vPresa, vPredador, vReciclador, vDefunto;
int i, j;
for(i = 0; i < l; i++)
for(j = 0; j < c; j++)
if(mapa_atual[i][j].tipo == NADA)
{
vPresa = ContaVizinhosR1(mapa_atual, PRESA, i, j);
vPredador = ContaVizinhosR1(mapa_atual, PREDADOR, i, j);
vReciclador = ContaVizinhosR1(mapa_atual, RECICLADOR, i, j);
vDefunto = ContaVizinhosR1(mapa_atual, DEFUNTO, i, j);
if( (vPresa == 2))
mapa_prox[i][j] = new Celula(PRESA, 20);
else if( (vPredador == 3) && (vPresa == 0) )
mapa_prox[i][j] = new Celula(PREDADOR, 20);
if((vReciclador == 1) && (vDefunto > 0))
mapa_prox[i][j] = new Celula(RECICLADOR, 20);
}
} |
718a0dc1-1b2f-40b5-957e-ec4c5424b79e | 3 | public HealthBar getHealthBarLength(HealthBar h8, int health, int maxHealth)
{
if (health < 0)
health = 0;
h8.percent = (double) health / (double) maxHealth;
double placeHolder = h8.percent * 144.0;
h8.length = (int) placeHolder;
if (h8.percent > .5)
h8 = HealthBar.GREEN;
else if (h8.percent > .2)
h8 = HealthBar.ORANGE;
else
h8 = HealthBar.RED;
return h8;
} |
9b95e44d-d677-4d4d-b50d-35f34ff91338 | 7 | public boolean isPalindrome1(String s) {
if (s == null || s.length() == 0 || s.trim().length() == 0) {
return true;
}
String newS = "";
for (char c : s.toLowerCase().toCharArray()) {
if (isCharNum(c)) {
newS += c;
}
}
for (int i = 0, j = newS.length() - 1; i < j; i++, j--) {
if (newS.charAt(i) != newS.charAt(j)) {
return false;
}
}
return true;
} |
e26cde75-0b0e-44b8-823c-c2fa00a4a37d | 3 | @Override
public boolean equals(Object object) {
if (object instanceof Rule) {
return (
this.ruleName.equals(((Rule)object).ruleName)
&& this.ruleURL.equals(((Rule)object).ruleURL)
&& this.ruleRegExpr.equals(((Rule)object).ruleRegExpr)
);
}
return false;
} |
cdf3cc11-af4e-4a19-a56c-6b26cfa6aba1 | 5 | @Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
/* Validate password. Make sure confirm password and password match */
String password = value.toString();
UIInput uiInputConfirmPassword = (UIInput) component.getAttributes().get("confirm");
String confirm = uiInputConfirmPassword.getSubmittedValue().toString();
if (password == null || password.isEmpty() || confirm == null || confirm.isEmpty()) {
return; // Let required="true" do its job.
}
// Compare the password with the confirm password.
if (!password.equals(confirm)) {
uiInputConfirmPassword.setValid(false);
FacesMessage facesMessage = new FacesMessage("Password must match confirm password");
throw new ValidatorException(facesMessage);
}
} |
a249c446-ca89-4a30-9165-6bbbbc72c773 | 3 | public Integer CheckHighestNumberOfTokenInLine(Position pos) {
Integer i = 0;
i = CheckVertical(pos);
if(CheckHorizontal(pos) > i){i = CheckHorizontal(pos);}
if(CheckMainDiagonal(pos) > i){i = CheckMainDiagonal(pos);}
if(CheckOffDiagonal(pos) > i){i = CheckOffDiagonal(pos);}
return i;
} |
86f22721-c390-4b35-ae84-7848624ae75b | 1 | public GekozenAntwoord(logic.GekozenAntwoord gk, ComboBoxModel comboBoxModel) {
gekozenAntwoord = gk;
File file = gk.getHuidigeOnderdeel().getPlaatje();
this.comboBoxModel = comboBoxModel;
try {
imagePanel = new ImagePanel(file);
imagePanel.setAutoResize(true);
imagePanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
} catch (IOException e1) {
e1.printStackTrace();
}
add(imagePanel, "grow");
setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill][]"));
combobox = new JComboBox();
combobox.setMaximumRowCount(9);
combobox.setModel(comboBoxModel);
add(combobox, "cell 0 1,growx");
} |
4f9f8e89-9d78-497a-a4e6-c1b4125ad933 | 8 | private boolean readCrossrefStream(PDFObject xrefStream, boolean followPrev) throws IOException {
// the xref stream will have an object number but since there's no
// decryption involved, it doesn't matter
if (xrefStream == null) {
xrefStream = readObject(fileBuf, -1, -1, IdentityDecrypter.getInstance());
if (!isXrefStream(xrefStream)) {
throw new PDFParseException("Object found at offset for cross" +
" reference stream is not a cross reference stream");
}
}
final int size = xrefStream.getDictRef("Size").getIntValue();
ensureXrefEntriesCapacity(size);
final PDFObject[] wObjs = xrefStream.getDictRef("W").getArray();
final int[] fieldLengths = new int[3];
int entryLength = 0;
for (int i = 0; i < 3; ++i) {
fieldLengths[i] = wObjs[i].getIntValue();
entryLength += fieldLengths[i];
}
final PDFObject[] index;
final PDFObject indexObj = xrefStream.getDictRef("Index");
if (indexObj != null) {
index = indexObj.getArray();
} else {
index = new PDFObject[] {
new PDFObject(0),
new PDFObject(size)
};
}
final ByteBuffer table = xrefStream.getStreamBuffer();
for (int i = 0; i < index.length; i += 2) {
final int start = index[i].getIntValue();
final int end = start + index[i + 1].getIntValue();
for (int objNum = start; objNum < end; ++objNum) {
if (xrefEntries[objNum] == null) {
PDFXrefEntry.Type type;
if (fieldLengths[0] == 0) {
type = PDFXrefEntry.Type.OBJ_IN_BODY;
} else {
type = PDFXrefEntry.Type.forTypeField(
readInt(table, fieldLengths[0]));
}
int field2 = readInt(table, fieldLengths[1]);
// note that this is supposed to default to 0 if field 3
// length is 0 for type 1 entries, and that will work just fine
int field3 = readInt(table, fieldLengths[2]);
xrefEntries[objNum] =
type.makeXrefStreamEntry(field2, field3);
} else {
table.position(table.position() + entryLength);
}
}
}
return processTrailerDict(xrefStream, true, followPrev);
} |
78294c04-516c-4842-aeca-3d89648ae622 | 5 | public void checkNeedMenu(JPanel panel, List<TabButton> tabs, TabButtonMenu menuTab){
boolean tabOutScreen = false;
int lastVisibleIndex = (getWidth()+TOTAL_BUTTON_WIDTH/2)/TOTAL_BUTTON_WIDTH - 1;
for(TabButton tab : tabs){
if(tab.data.index > lastVisibleIndex){
tabOutScreen = true;
break;
}
}
if(tabOutScreen){
List<TabButton> outScreenTabs = new ArrayList<TabButton>();
for(TabButton tab : tabs){
if(tab.data.index >= lastVisibleIndex){
outScreenTabs.add(tab);
panel.remove(tab);
}
}
menuTab.data.index = lastVisibleIndex;
menuTab.setLocation(menuTab.data.index*TOTAL_BUTTON_WIDTH+4, menuTab.getLocation().y);
menuTab.visible = true;
panel.add(menuTab);
menuTab.refresh(outScreenTabs);
}
else{
menuTab.visible = false;
panel.remove(menuTab);
menuTab.refresh(null);
}
} |
76b99454-3d48-415d-a02d-8f35e7224cf4 | 6 | public void run(CommandSender sender, String[] args) {
if(args.length == 0) {
sender.sendMessage(ChatColor.RED + "You didn't enter a user.");
return;
}
String p = args[0];
if(args.length < 2) {
if(SettingsManager.getInstance().getPermissions(p).size() == 0) {
sender.sendMessage(ChatColor.YELLOW + "No permissions for " + p + ".");
}
for(String permission : SettingsManager.getInstance().getPermissions(p)) {
sender.sendMessage(ChatColor.YELLOW + permission);
return;
}
} else {
if(args[1].equalsIgnoreCase("addperm")) {
SettingsManager.getInstance().addPermission(p, args[2]);
sender.sendMessage(ChatColor.GREEN + "Added " + args[2] + " to " + p + ".");
return;
}else if(args[1].equalsIgnoreCase("removeperm")) {
SettingsManager.getInstance().removePermission(p, args[2]);
sender.sendMessage(ChatColor.GREEN + "Removed " + args[2] + " from " + p + ".");
return;
}
}
} |
4fdb5b9a-1234-4ad7-ba1d-8aedf49ef78d | 4 | public static void main(String[] args){
// 输出重定向
BufferedOutputStream os = null;
PrintStream ps = null;
try {
os = new BufferedOutputStream(new FileOutputStream("result_other.txt"), 1024);
ps = new PrintStream(os, false);
System.setOut(ps);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PixelArray array = new PixelArray() {
int width,height;
int[] pix;
@Override
public void setSize(int width, int height) throws Exception {
this.width = width;
this.height = height;
pix = new int[width*height];
}
@Override
public void setPixel(int x, int y, int argb) {
pix[x+y*width]=argb;
}
};
try {
FileInputStream is = new FileInputStream("/Users/JaySon/Desktop/test.jpg");
OtherDecoder decoder = new OtherDecoder();
decoder.decode(is,array);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
if (ps != null){
ps.close();
}
}
} |
dfef42e5-6212-413b-9502-eab122fc3445 | 2 | private void loadBlockData(String x, String y, String z, String wn) {
try {
blockX = (ArrayList<Integer>) load(this.blockFileX);
blockY = (ArrayList<Integer>) load(this.blockFileY);
blockZ = (ArrayList<Integer>) load(this.blockFileZ);
this.loadedWorld = wn;
hasSaved = false;
} catch (EOFException e) {
} catch (Exception e) {
}
} |
1eadae97-582d-4d17-9225-ab3f5216c04d | 2 | public int turnWeek(String week) {
int i;
for (i = 0; i < 7; i++)
if (week.equalsIgnoreCase(stringWeekEn[i]))
break;
return i;
} |
a97ac74c-4aa7-476f-a807-480c81549920 | 8 | public void actionPerformed(ActionEvent ae)
{
//gets the password from the user
password = input.getText();
//call the strength check message
strengthCheck();
//display password strength
strength.setText("Password Strength: " + check);
//Change the color of the password strength based on strength
if(check >= 4)
strength.setForeground(new Color(57,132,57));
else if(check >= 2)
strength.setForeground(new Color(240,173,78));
else if(check >= 0)
strength.setForeground(new Color(212,63,58));
//change the color of the rules that are failed
if(ruleCheck[1] == false)
Rules[1].setForeground(new Color(212,62,58));
if(ruleCheck[2] == false)
Rules[2].setForeground(new Color(212,62,58));
if(ruleCheck[3] == false)
Rules[3].setForeground(new Color(212,62,58));
if(ruleCheck[4] == false)
Rules[4].setForeground(new Color(212,62,58));
if(ruleCheck[5] == false)
Rules[5].setForeground(new Color(212,62,58));
} |
a4796812-b0e9-48f8-b115-70d726fe7fdb | 0 | public VueLecture() {
// setBorder(new TitledBorder("Lecture")); // Titre du panel
/* Background */
// setBackground(Color.white);
// setOpaque(false);
// redimensionner
// ImageIcon icon = new ImageIcon(new
// ImageIcon("img//gdeFond2.jpg").getImage().getScaledInstance(this.getHeight(),
// this.getWidth(), Image.SCALE_DEFAULT));
// ImageIcon icon = new ImageIcon("img//gdeFond2.jpg");
ImageIcon icon = new ImageIcon("img//gdeFond2.jpg");
imgLecture = new JLabel(icon);
add(imgLecture);
} |
296b81a4-a1c8-4f12-afa7-798b2580d4d7 | 3 | public boolean readBoolean() throws IOException {
int code = readNextCode();
switch (code) {
case Codes.TRUE:
return true;
case Codes.FALSE:
return false;
default: {
Object result = read(code);
if (result instanceof Boolean) {
return (Boolean) result;
} else {
throw expected("boolean", code, result);
}
}
}
} |
68da0016-88ca-4ad5-ae54-84644f89474f | 0 | @Override
public ArrayList<Excel> getColoredExes() {
// TODO Auto-generated method stub
return coloredEx;
} |
d2fc2a35-06fa-4769-a49e-b40d1a3ab15a | 1 | public Object pull() {
if(top>0) {
return stack.remove(top-1);
}
else
return 0;
} |
e3df1ce0-7ff9-4179-8288-a948f280e2e3 | 1 | public boolean estReserve(){
if(this.situation == RESERVE){
return true ;
}
else {
return false ;
}
} |
639e03a4-b913-46c5-9e12-9b51c100022e | 5 | public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, (Integer) value + 1);
} else if (value instanceof Long) {
this.put(key, (Long) value + 1);
} else if (value instanceof Double) {
this.put(key, (Double) value + 1);
} else if (value instanceof Float) {
this.put(key, (Float) value + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} |
1dab97bb-9938-4a96-b67d-86d7f5a5db8c | 8 | @Override
public Set<Data> check(Player player) {
Set<Data> data = new HashSet<Data>();
PreparedStatement ps = null;
try {
ps = this.db().prepareStatement("SELECT * FROM `gatekeeper_player` WHERE `player` = ?");
ps.setString(1, player.getName());
ps.execute();
ResultSet rs = ps.getResultSet();
while(rs.next()) {
data.add(this.makeDataPlayer(rs));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
ps = this.db().prepareStatement("SELECT * FROM `gatekeeper_cidr` WHERE (`start` <= ? AND ? <= `end`)");
long ip = Util.ip2long(player.getAddress().getAddress().getHostAddress().toString());
ps.setLong(1, ip);
ps.setLong(2, ip);
ps.execute();
ResultSet rs = ps.getResultSet();
while(rs.next()) {
data.add(this.makeDataCIDR(rs));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return data;
} |
c4433783-f9c7-43b6-b0a9-88fe27fbce2c | 8 | public long nextLong() throws IOException {
int p = peeked;
if (p == PEEKED_NONE) {
p = doPeek();
}
if (p == PEEKED_LONG) {
peeked = PEEKED_NONE;
return peekedLong;
}
if (p == PEEKED_NUMBER) {
peekedString = new String(buffer, pos, peekedNumberLength);
pos += peekedNumberLength;
} else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) {
peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"');
try {
long result = Long.parseLong(peekedString);
peeked = PEEKED_NONE;
return result;
} catch (NumberFormatException ignored) {
// Fall back to parse as a double below.
}
} else {
throw new IllegalStateException("Expected a long but was " + peek()
+ " at line " + getLineNumber() + " column " + getColumnNumber());
}
peeked = PEEKED_BUFFERED;
double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
long result = (long) asDouble;
if (result != asDouble) { // Make sure no precision was lost casting to 'long'.
throw new NumberFormatException("Expected a long but was " + peekedString
+ " at line " + getLineNumber() + " column " + getColumnNumber());
}
peekedString = null;
peeked = PEEKED_NONE;
return result;
} |
6890b0da-5dd5-4ac6-a132-274d4995be5a | 3 | @Test
public void testAssignmentsConditions() throws ClassNotFoundException, NoSuchMethodException, SecurityException {
for(int i = 6; i <= 10; i++) {
for(int j = 1; j <= 7; j++ ) {
Class<?> assignment = AssesmentGetter.getAssignment(i, j);
assignment.getMethod("main", String[].class);
assignment.getMethod("printQuestions", SysOutPrinter.class);
}
}
} |
f8440994-34a3-4559-a7f2-5a7261e4a6cc | 0 | public List findByMemoryLimit(Object memoryLimit) {
return findByProperty(MEMORY_LIMIT, memoryLimit);
} |
30bf3f3f-2118-4aab-b375-8f888db795ef | 5 | public void walk(){
if(xPos + direction[0] > 9 || xPos + direction[0] < 0 || yPos + direction[1] > 9 || yPos + direction[1] < 0){
xPos += direction[0];
yPos += direction[1];
}
if(ownGarden.isAppleOnField(xPos, yPos)){
ownGarden.removeApple(xPos, yPos);
appleCache++;
}
} |
c83107e0-138f-493c-a1b2-697789c59933 | 6 | public void close(){
if(this.requestWithFile != null && this.requestWithFile.isReadFile()){
FileTransfer fr = requestWithFile.getFileReceiver();
if(fr != null && !fr.finishWrite()){
fr.forceClose();// 强制关闭删除损害的文件
}
}
// 关闭连接
SocketChannel socketChannel = (SocketChannel) this.key.channel();
try{
this.sockectServer.clearSocket(index);// 清除
unregiste();
this.key.attach(null);
this.key.cancel();
} catch (ClosedChannelException e) {
e.printStackTrace();
}finally{
try{
//socketChannel.socket().getOutputStream().flush();
socketChannel.close();
}catch(IOException e){
e.printStackTrace();
}
}
} |
a378e5de-f963-4d9d-851c-7a4747c43af9 | 0 | public double getY() {
return y;
} |
d07a45cc-4317-4f73-801e-96b302b41f8b | 3 | public void attribute(String aname, String value, boolean isSpecified)
{
if (aname.equals("id") && currentModule == null)
id = value;
if (currentModule != null) {
asiModuleHandler.attribute(aname, value, isSpecified);
}
} |
b60f7c6c-7e3e-4112-a546-539f58ec7be9 | 1 | public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
AnnotationVisitor av;
av = super.visitAnnotation(remapper.mapDesc(desc), visible);
return av == null ? null : createRemappingAnnotationAdapter(av);
} |
e92a5f04-a5fc-4c9e-9706-8812434391d1 | 1 | public T next() {
try {
return type.newInstance();
} catch (Exception e) {
throw new RuntimeException();
}
} |
4b8d7e25-e85e-433c-9588-56a9174c495e | 9 | private void processDay(HSSFWorkbook workbook, Day day) {
System.out.println("Processing " + day);
block = null;
HSSFSheet sheet = workbook.getSheet(day.name());
int maxRows = sheet.getPhysicalNumberOfRows();
int rowIndex = 0;
HSSFRow row = sheet.getRow(rowIndex++);
workingDay = new WorkingDay(stringFromCell(row, 0));
masterDocument.workingDays.add(workingDay);
boolean firstBlock = true;
int maxTeamCell = -1;
while (rowIndex < maxRows) {
row = sheet.getRow(rowIndex);
if (row != null) {
String entry = stringFromCell(row, 0);
if (StringUtils.isNotEmpty(entry)) {
if (block == null) {
block = DayBlock.fromLabel(stringFromCell(row, 0));
if (firstBlock) {
maxTeamCell = calculateMaximumTeamCell(row);
firstBlock = false;
}
} else if (DayBlock.fromLabel(entry) != null) {
block = DayBlock.fromLabel(entry);
} else {
if (block == DayBlock.OutdoorDisplays) {
processOutdoorDisplayRow(row, maxTeamCell);
} else if (block == DayBlock.Workshops) {
processWorkshopRow(row, maxTeamCell);
} else if (block == DayBlock.Other) {
processOther(row, maxTeamCell);
}
}
}
}
rowIndex++;
}
} |
c4738bdf-1fa7-44b4-987c-6428911c1446 | 7 | public void menuMain() throws MalformedURLException, InterruptedException, IOException {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("******************* Main Menu *************************");
System.out.println("* *");
System.out.println("* 1 - New site download *");
System.out.println("* 2 - Update site *");
System.out.println("* *");
System.out.println("* 0 - Exit *");
System.out.println("*******************************************************");
int aux = in.nextInt();
switch (aux) {
case 0:
System.exit(0);
case 1:
if (t.isAlive()) {
System.out.println("Must wait for previous site download be finished");
} else {
menuDownloadNew();
}
break;
case 2:
menuUpdate();
break;
case 7:
myController.pauseThread();
break;
case 8:
myController.resumeThread();
break;
default:
System.out.println("Invalid Command");
menuMain();
}
}
} |
18524969-6fa8-4e46-86dc-6cd6e9e2142a | 9 | @Test
public void testGetBooks() {
Integer testISBN = 400;
Set<StockBook> booksToAdd = new HashSet<StockBook>();
booksToAdd.add(new ImmutableStockBook(testISBN, "Book Name",
"Book Author", (float) 100, 5, 0, 0, 0, false));
try {
storeManager.addBooks(booksToAdd);
} catch (BookStoreException e) {
e.printStackTrace();
}
Set<Integer> ISBNList = new HashSet<Integer>();
ISBNList.add(testISBN);
List<Book> books = null;
try {
books = client.getBooks(ISBNList);
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
for (Book b : books) {
if (b.getISBN() == testISBN) {
assertTrue("Book ISBN", b.getISBN() == testISBN);
assertTrue("Book Price", b.getPrice() == 100);
}
}
List<StockBook> listBooks = null;
try {
listBooks = storeManager.getBooks();
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
Boolean exceptionThrown = false;
ISBNList = new HashSet<Integer>();
ISBNList.add(-1);
try {
books = client.getBooks(ISBNList);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
List<StockBook> currentList = null;
try {
currentList = storeManager.getBooks();
assertTrue(currentList.equals(listBooks));
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
exceptionThrown = false;
ISBNList = new HashSet<Integer>();
ISBNList.add(10000000);
try {
books = client.getBooks(ISBNList);
} catch (BookStoreException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
try {
currentList = storeManager.getBooks();
assertTrue(currentList.equals(listBooks));
} catch (BookStoreException e) {
e.printStackTrace();
fail();
}
} |
f99c7516-c156-41f9-8270-41e588fc1714 | 1 | public int executeSQLUpdate(String sqlStatement) {
try {
// Datenbankverbindung herstellen
connect = connectDB();
// PreparedStatement für den SQL-Befehl
myPreparedStatement = connect.prepareStatement(sqlStatement);
// SQL-Befehl wird ausgeführt
successful = myPreparedStatement.executeUpdate(sqlStatement);
} catch (Exception e) {
System.out.println(e.toString());
// Ein Dialogfenster mit entsprechender Meldung soll erzeugt werden
String errorText = "Datenbankabfrage Fehler!";
errorMessage.showMessage(errorText);
}
return successful;
} |
b6c41ef4-636b-4201-bdad-6e6e6e373802 | 4 | protected void setDirection(int dir) {
if (dir == RIGHT) {
moveDirection = RIGHT;
checkDirection = UP;
}
else if (dir == DOWN) {
moveDirection = DOWN;
checkDirection = RIGHT;
}
else if (dir == LEFT) {
moveDirection = LEFT;
checkDirection = DOWN;
}
else if (dir == UP) {
moveDirection = UP;
checkDirection = LEFT;
}
} |
8a3b3d44-fdc9-4a63-97fa-35adb55b8fc5 | 8 | protected void handleControlPropertyChanged(final String PROPERTY) {
if ("RESIZE".equals(PROPERTY)) {
resize();
} else if ("DESIGN".equals(PROPERTY)) {
updateDesign();
} else if ("SECOND_POINTER_VISIBLE".equals(PROPERTY)) {
secondPointerGroup.setOpacity(getSkinnable().isSecondPointerVisible() ? 1 : 0);
} else if ("DATE_TIME".equals(PROPERTY)) {
if (getSkinnable().isRunning()) updateTime(getSkinnable().getDateTime().plus(getSkinnable().getOffset()));
} else if ("RUNNING".equals(PROPERTY)) {
if (getSkinnable().isRunning()) {
timer.start();
} else {
timer.stop();
}
}
} |
25670846-8c71-4334-a769-3a44b33f7a66 | 4 | public long get_field_as_milliseconds( String section, String field )
throws NoSuchKeyException, NoSuchSectionException, BadFormatException {
String s;
long i;
s = get_field( section, field );
try {
i = Long.parseLong( s );
}
catch( Exception ex ) {
try {
StringTokenizer tok = new StringTokenizer( s, ":" );
// hours:minutes
i = Long.parseLong( tok.nextToken() ) * (1000*60*60) + Long.parseLong( tok.nextToken() ) * (1000*60 );
// seconds
if( tok.hasMoreTokens() ) {
i += Long.parseLong( tok.nextToken() ) * 1000;
}
// milliseconds
if( tok.hasMoreTokens() ) {
i += Long.parseLong( tok.nextToken() );
}
}
catch (Exception e2) {
throw new BadFormatException("Cannot parse integer: Section ["+section+"] Field ["+field+"] = ["+ s + "]");
}
}
return i;
} |
a819dda2-eae3-4692-b411-b2ebab1487bc | 0 | @Override
public byte[] getPayload() throws IOException {
byte[] frameData = super.getPayload();
return Arrays.copyOfRange(frameData, this.picDataFrameOffset, frameData.length);
} |
a7acdcf6-4419-414e-8233-095911c44329 | 7 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
BigInteger nine = new BigInteger("9");
BigInteger zero = BigInteger.ZERO;
while ((line = in.readLine()) != null && line.length() != 0) {
int degree = 0;
BigInteger n = new BigInteger(line.trim());
if(n.equals(zero))
break;
int sum = 0;
do{
char[] s = n.toString().toCharArray();
sum = 0;
degree++;
for (int i = 0; i < s.length; i++)
sum += s[i]-'0';
if(n.compareTo(nine)<0)
break;
n = BigInteger.valueOf(sum);
}while(!n.equals(nine));
if(n.equals(nine))
out.append(line+" is a multiple of 9 and has 9-degree "+degree+".\n");
else
out.append(line+" is not a multiple of 9.\n");
}
System.out.print(out);
} |
2ad538bc-ba7b-47f4-84e6-0b6e59a9709d | 7 | public void insertNonFull(int key, int value, BTreeNode startNode) {
int keyIndex = startNode.getNoOfKeys()-1;
if (startNode.isLeaf()) {
while( keyIndex >= 0 && key < startNode.getKeyAt(keyIndex)) {
startNode.setKeyAt(keyIndex+1, startNode.getKeyAt(keyIndex));
startNode.setValueAt(keyIndex+1, startNode.getValueAt(keyIndex));
keyIndex--;
}
startNode.setKeyAt(keyIndex+1, key);
startNode.setValueAt(keyIndex+1, value);
startNode.setNoOfKeys(startNode.getNoOfKeys() + 1);
}
else {
while( keyIndex >= 0 && key < startNode.getKeyAt(keyIndex)) {
keyIndex--;
}
keyIndex++;
if (startNode.getChildAt(keyIndex).getNoOfKeys() == 2*order - 1 ) {
splitChildOfNode(startNode, keyIndex);
if(key > startNode.getKeyAt(keyIndex))
keyIndex++;
}
insertNonFull(key, value, startNode.getChildAt(keyIndex));
}
} |
bf9e694e-a3f1-4d8c-8eeb-a93f368b7a22 | 5 | public static int[][] calcScoreMatrix(char[] st1, char[] st2) {
int[][] score = new int[st1.length+1][st2.length+1];
// расстояния между одной строкой и другой пустой
for (int i = 0; i <= st1.length; i++) {
score[i][0] = i;
}
for (int i = 0; i <= st2.length; i++) {
score[0][i] = i;
}
// заполним матрицу (кроме нулевой строки и нулевого столбца)
for (int i = 0; i < st1.length; i++) {
for (int j = 0; j < st2.length; j++) {
if (st1[i] == st2[j])// не нужно операции никакой
score[i + 1][j + 1] = score[i][j];
else {
// минимальный счёт
int delScore = score[i][j + 1] + 1;
int instScore = score[i + 1][j] + 1;
int subScore = score[i][j] + 1;
score[i + 1][j + 1] = NumberUtils.getMin(delScore, instScore, subScore);
}
}
}
return score;
} |
8f7ca267-384d-4cc6-bbf0-059dec2385ca | 2 | public String getSelectedValue() {
String result = "";
for (ComboboxItem ci : comboItems) {
if (ci.isSelected()) {
result = ci.getValue();
}
}
return result;
} |
6965e24c-dd50-4dd9-9997-25893f3c065b | 3 | public static List<Variable> getVariablesFromFileObfuscationStructure (List<FileObfuscationStructure> fileInstances) {
List<Variable> result = new ArrayList<Variable>();
for (FileObfuscationStructure file : fileInstances) {
for (VariableAppearance appearance : file.getFileVariablesAppearances()) {
String name = appearance.getOutOfContextName();
Variable variable = new Variable(name);
int index = existsIn(variable, result);
if (index >= 0) {
variable = result.get(index);
variable.addAppearance(appearance);
} else {
variable.addAppearance(appearance);
result.add(variable);
}
appearance.setVariableRelated(variable);
}
}
Collections.sort(result);
return result;
} |
7c03c8ac-a25e-4a9c-9208-534bba867b33 | 0 | public static void main(String[] args) {
BurstBalloons burstBalloons = new BurstBalloons();
int[] test = {3, 1, 5, 8};
System.out.println(burstBalloons.maxCoins(test));
} |
8451bf4e-045b-4d89-92e9-7a35237394c0 | 1 | @Test
public void resolve() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
sum += getLetterCount(i);
}
sum += "onethousand".length();
print(sum);
} |
b00521e0-33c3-4f9c-a584-c507436691f9 | 2 | public Factory(int num) {
Resource res = Utils.myres(this.getClass());
this.neg = res.layer(Resource.negc);
this.num = num;
ArrayList<Tex> strands = new ArrayList<Tex>();
for(Resource.Image img : res.layers(Resource.imgc)) {
if(img.id != -1)
strands.add(img.tex());
}
this.strands = strands.toArray(typebarda);
} |
d36e5341-21b7-4a63-9ad4-a130682e621f | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ItemReturn)) {
return false;
}
ItemReturn other = (ItemReturn) object;
if ((this.itemReturnPK == null && other.itemReturnPK != null) || (this.itemReturnPK != null && !this.itemReturnPK.equals(other.itemReturnPK))) {
return false;
}
return true;
} |
5f789395-35a6-4e86-9cb8-327fa7ab3008 | 0 | public void setEndStop(int value) {
this._endStop = value;
} |
9dd4c0f7-4a26-410b-85c2-c3d25129a30a | 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;
} |
1277cee9-d48c-469d-a7f6-0f9fe80c0d26 | 9 | public Instruction[][] readProgram(InputStream is) throws IOException, ProgramReaderException {
List<String> lines = IOUtils.readLines(is, "UTF-8");
int numLines = lines.size();
int numColumns = 0;
// First pass : get the words
String[][] parsedLines = new String[numLines][];
for (int currentLineIndex = 0; currentLineIndex < numLines; currentLineIndex++) {
String line = lines.get(currentLineIndex).trim();
if (!line.isEmpty()) {
String[] words = line.split(";");
if (words.length > numColumns) {
numColumns = words.length;
}
parsedLines[currentLineIndex] = words;
} else {
parsedLines[currentLineIndex] = new String[0];
}
}
// Second pass : get the whole program in a rectangular grid
Instruction[][] program = new Instruction[numColumns][numLines];
Instruction noop = new Instruction(InstructionType.NOOP);
// Go through the columns in a line first
for (int j = 0; j < numLines; j++) {
int i;
for (i = 0; i < parsedLines[j].length; i++) {
String word = parsedLines[j][i];
// First char of instruction is sufficient to determine its
// type
String char1 = word.substring(0, 1);
InstructionType iType = InstructionCache
.getInstructionRepresentationDictionary()
.get(char1);
if (iType == null) {
throw new ProgramReaderException("Unknown instruction: "
+ word);
}
Instruction instr = new Instruction(iType);
if (iType == InstructionType.INTEGER) {
// Integer has attached data: After 1st character
String intData = word.substring(1).trim();
instr.setAttachedData(Integer.valueOf(intData));
}
if(iType == InstructionType.SPAWN) {
// attach maximum number of times
if(word.length() > 2) {
String intData = word.substring(1).trim();
instr.setAttachedData(Integer.valueOf(intData));
} else {
instr.setAttachedData(20);
}
}
program[i][j] = instr;
}
// Fill the rest with NOOP (so the whole rectangle is filled
// with instructions)
filler.fillLine(program, j, i);
}
return program;
} |
08c53275-f7ba-4a77-890e-934ccd671621 | 6 | public static String getFirstColorCode(String minecraft){
String codes = "abcdef0123456789";
for(int i=0; i<minecraft.length(); i++){
if(minecraft.charAt(i) == '&'){
if(i == codes.length() - 1) return null;
if(minecraft.length() > 1 && i < minecraft.length() - 1 && codes.contains(minecraft.charAt(i + 1) + "")) return "&" + minecraft.charAt(i + 1);
}
}
return null;
} |
8911e8f7-da2c-4709-b052-4f9afd494dd2 | 6 | public boolean collisionCheck(Level level, int currentRoom) {
Boolean returnBool = false;
List<Float> obsLocations = new ArrayList<Float>();
for (int i = 0; i < level.getRoomList().get(currentRoom).getObsList().size(); i++) {
obsLocations.add(level.getRoomList().get(currentRoom).getObsList().get(i).getPos().getX());
obsLocations.add(level.getRoomList().get(currentRoom).getObsList().get(i).getPos().getX() + level.getRoomList().get(currentRoom).getObsList().get(i).getDx());
obsLocations.add(level.getRoomList().get(currentRoom).getObsList().get(i).getPos().getY());
obsLocations.add(level.getRoomList().get(currentRoom).getObsList().get(i).getPos().getY() + level.getRoomList().get(currentRoom).getObsList().get(i).getDy());
}
for (int i = 0; i < obsLocations.size()/4; i++) {
if(getPos().getX() >= obsLocations.get(i*4) && getPos().getX() <= obsLocations.get(i*4+1)){
if(getPos().getY() >= obsLocations.get(i*4+2) && getPos().getY() <= obsLocations.get(i*4+3)){
returnBool = true;
}
}
}
return returnBool;
} |
f5d88dbb-0eff-42a6-84f9-1746a67a7c03 | 3 | public String HapusHuruf(String strQty){
char [] data = TitikHanya2(strQty).toCharArray();
//char [] data = strQty.toCharArray();
String newStrQty = "";
for (char c : data){
if (Character.isDigit(c) || c == '.') {
newStrQty = newStrQty + String.valueOf(c);
}
}
return newStrQty;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.