text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public int castingQuality(MOB mob, Physical target)
{
if((mob!=null)&&(target!=null))
{
if(CMLib.flags().isSleeping(mob))
return Ability.QUALITY_INDIFFERENT;
if(!CMLib.flags().isAliveAwakeMobileUnbound(mob,false))
return Ability.QUALITY_INDIFFERENT;
final Item cloth=CMLib.materials().findMostOfMaterial(mob,RawMaterial.MATERIAL_CLOTH);
if((cloth==null)||CMLib.materials().findNumberOfResource(mob,cloth.material())<1)
return Ability.QUALITY_INDIFFERENT;
final Item wood=CMLib.materials().findMostOfMaterial(mob,RawMaterial.MATERIAL_WOODEN);
if((wood==null)||CMLib.materials().findNumberOfResource(mob,wood.material())<2)
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
} | 8 |
private Object readDelimitedField()throws IOException,EOR{
//read starting delimiter
int i=reader.read();
if(i!=delimiter){//fail
reader.unread(i);
throw new EOR();
}
//Inside the field ...
boolean inside=true;
StringBuilder builder=new StringBuilder();
while(inside){
i=reader.read();
if(i<0){
//In fact, the CSV file is bad. Fail.
throw new EOR();
}
char c=(char)i;
if(c==delimiter){
i=reader.read();
if(i==delimiter){
//"" -> one escaped "
builder.append(delimiter);
}else{
if(0<=i)reader.unread(i);
//else System.out.println("here");
reader.unread(delimiter);
inside=false;
}
}else{
builder.append(c);
}
}
//read final delimiter
i=reader.read();
if(i!=delimiter){//fail
reader.unread(i);
throw new EOR();
}
String field=builder.toString();
return parseField(field);
} | 7 |
public void run() {
try {
boolean eos = false;
while (!eos) {
OggPage op = OggPage.create(source);
synchronized (drainLock) {
int listSize = pageOffsets.size();
long pos = listSize > 0 ? pageOffsets.get(listSize - 1) + pageLengths.get(listSize - 1) : 0;
byte[] arr1 = op.getHeader();
byte[] arr2 = op.getSegmentTable();
byte[] arr3 = op.getData();
if (drain != null) {
drain.seek(pos);
drain.write(arr1);
drain.write(arr2);
drain.write(arr3);
} else {
System.arraycopy(arr1, 0, memoryCache, (int) pos, arr1.length);
System.arraycopy(arr2, 0, memoryCache, (int) pos + arr1.length,
arr2.length);
System.arraycopy(arr3, 0, memoryCache, (int) pos + arr1.length
+ arr2.length, arr3.length);
}
pageOffsets.add(pos);
pageLengths.add((long) arr1.length + arr2.length + arr3.length);
}
if (!op.isBos()) {
bosDone = true;
// System.out.println("bosDone=true;");
}
if (op.isEos()) {
eos = true;
}
LogicalOggStreamImpl los = (LogicalOggStreamImpl) getLogicalStream(op
.getStreamSerialNumber());
if (los == null) {
los = new LogicalOggStreamImpl(CachedUrlStream.this);
logicalStreams.put(op.getStreamSerialNumber(), los);
los.checkFormat(op);
}
los.addPageNumberMapping(pageNumber);
los.addGranulePosition(op.getAbsoluteGranulePosition());
pageNumber++;
cacheLength = op.getAbsoluteGranulePosition();
// System.out.println("read page: "+pageNumber);
}
} catch (EndOfOggStreamException e) {
// ok
} catch (IOException e) {
e.printStackTrace();
}
} | 8 |
public void run()
{
try
{
this.MPrio.acquire();
this.MReading.acquire();
this.MPrioR.acquire();
if(this.counter == 0)
this.MWriting.acquire();
this.counter++;
this.MPrioR.release();
this.MReading.release();
this.MPrio.release();
System.out.println("Lecture");
Thread.sleep(100);
this.MPrioR.acquire();
this.counter--;
if(this.counter == 0)
this.MWriting.release();
this.MPrioR.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} | 3 |
private static Map<String, RectBound> prepareGrid(Document iDoc) throws Exception {
Map<String, RectBound> map = new HashMap<String, RectBound>();
Node iSvg = iDoc.getChildNodes().item(1);
Node iG = iSvg.getChildNodes().item(3);
NodeList childNodes = iG.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
try {
i = findNodeIndex(iG, NodeName.PATH, ATTR_STYLE, BORDER_STYLE, i);
Node iBorderNode = childNodes.item(i);
RectBound borderRect = toRectBound(iBorderNode.getAttributes().getNamedItem("d").getNodeValue());
i = i + 1;
Node iNextBorderNode = childNodes.item(i);
if (!isBorder(iNextBorderNode)) {
throw new IllegalStateException("Was expecting a second border after " + iBorderNode.getAttributes().getNamedItem("id").getNodeValue());
}
NamedNodeMap attributes = iNextBorderNode.getAttributes();
RectBound textRect = toRectBound(attributes.getNamedItem("d").getNodeValue());
StringBuilder sb = new StringBuilder();
boolean hasMore = false;
List<Node> iTextList = findTextNodeInRect(iG, textRect);
for (Node iText : iTextList) {
Node iTspan = iText.getFirstChild();
if (!nodeEquals(NodeName.TSPAN, iTspan)) {
throw new IllegalStateException("Was expecting a tspan after text");
}
if (hasMore) {
sb.append(" ");
}
sb.append(iTspan.getTextContent());
hasMore = true;
}
String name = sb.toString();
name = name.toLowerCase().replaceAll(" ", "_").replaceAll("/", "_").replaceAll("\\.\\.\\.", "_").replaceAll("\\.", "").replaceAll(",", "").replaceAll("\\+", "plus").replaceAll("&", "and").replaceAll("__", "_");
if (name.equals("c__cplusplus")) {
name = "c_cplusplus";
}
else if (name.equals("façade")) {
name = "facade";
}
else if (name.equals("file")) {
name = "text_document";
}
name = ensureUnique(map, name);
map.put(name, borderRect);
}
catch (NotFoundException e) {
i = childNodes.getLength();
}
}
return map;
} | 9 |
private String BoardPiece(int i, int j) {
assert(i>0 && i<rows && j>0 && j< cols);
String str = new String();
if(this.cell[i][j] == CellEntry.inValid){
str = " ";
}
else if(this.cell[i][j] == CellEntry.empty){
str = " _ ";
}
else if(this.cell[i][j] == CellEntry.white){
str = " W ";
}
else if(this.cell[i][j] == CellEntry.black){
str = " B ";
}
else if(this.cell[i][j] == CellEntry.whiteKing){
str = " W+ ";
}
else if(this.cell[i][j] == CellEntry.blackKing){
str = " B+ ";
}
return str;
} | 9 |
private void list_movesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_list_movesMousePressed
current_move=null;
current_frame=null;
current_hitbox=null;
hitbox_index_selected=-1;
frame_index_selected=-1;
//Add frames
listOfMoves_main_file = main_doc.getElementsByTagName("Move");
DefaultListModel model = new DefaultListModel();
for(int s=0; s<listOfMoves_main_file.getLength() ; s++)
{
Node move_node = listOfMoves_main_file.item(s);
Element move_element = (Element)move_node;
if(move_element.getAttribute("name").equals(list_moves.getSelectedValue()))
{
int frames = Integer.parseInt(move_element.getAttribute("frames"));
for(int i=0;i<frames;i++)
{
model.add(i, "frame "+(i+1));
}
break;
}
}
list_frames.setModel(model);
//Clear hitboxes list
DefaultListModel clean_model = new DefaultListModel();
list_red_hitboxes.setModel(clean_model);
list_blue_hitboxes.setModel(clean_model);
//Upadate current_move
listOfMoves_hitboxes_file = hitboxes_doc.getElementsByTagName("Move");
for(int s=0; s<listOfMoves_hitboxes_file.getLength() ; s++)//Move loop
{
Node move_node = listOfMoves_hitboxes_file.item(s);
Element move_element = (Element)move_node;
if(move_element.getAttribute("name").equals(list_moves.getSelectedValue()))
{
current_move=move_element;
}
}
}//GEN-LAST:event_list_movesMousePressed | 5 |
public void updatePathInfo() {
this.romDisplay.setText(" No Rom Path Set");
this.boxDisplay.setText(" No Box Art Path Set");
this.cartDisplay.setText(" No Cart Art Path Set");
this.wheelDisplay.setText(" No Wheel Art Path Set");
this.videoDisplay.setText(" No Video Path Set");
if (this.activeSystem!=null) {
if (this.activeSystem.getRomPath()!=null) {
this.romDisplay.setText(" " + this.activeSystem.getRomPath());
}
if (this.activeSystem.getBoxPath()!=null) {
this.boxDisplay.setText(" " + this.activeSystem.getBoxPath());
}
if (this.activeSystem.getCartPath()!=null) {
this.cartDisplay.setText(" " + this.activeSystem.getCartPath());
}
if (this.activeSystem.getWheelPath()!=null) {
this.wheelDisplay.setText(" " + this.activeSystem.getWheelPath());
}
if (this.activeSystem.getVideoPath()!=null) {
this.videoDisplay.setText(" " + this.activeSystem.getVideoPath());
}
}
} | 6 |
@Test
public void twoTablespoonPlusOneOunceEqualTwelveTeaspoon(){
ArithmeticQuantity two_tbsp = new ArithmeticQuantity(2, Volume.TABLESPOON);
ArithmeticQuantity one_oz = new ArithmeticQuantity(1, Volume.OUNCE);
assertEquals(two_tbsp.add(one_oz), new ArithmeticQuantity(12, Volume.TEASPOON));
} | 0 |
public EnvironmentalWidget(String titleIn, boolean hasField, boolean canEdit)
{
setBackground(Color.WHITE);
JPanel fieldPanel = new JPanel();
JPanel titlePanel = new JPanel();
fieldPanel.setBackground(Color.WHITE);
fieldPanel.setLayout(new BorderLayout());
titlePanel.setBackground(Color.WHITE);
titlePanel.setLayout(new BorderLayout());
title = new JLabel(titleIn);
unit = new JLabel();
field = new JTextField();
field.setBorder(new MatteBorder(1, 1, 1, 1, Color.LIGHT_GRAY));
field.setEditable(false);
field.setBackground(Color.WHITE);
field.setPreferredSize(new Dimension(80, 20));
field.setHorizontalAlignment(JTextField.RIGHT);
field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
update();
CurrentLaunchInformation.getCurrentLaunchInformation().update("Manual Entry");
}
});
field.setHorizontalAlignment(JTextField.RIGHT);
isEditable = new JCheckBox();
isEditable.setBackground(Color.WHITE);
isEditable.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{
field.setEditable(true);
field.setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
}
else
{
field.setEditable(false);
field.setBorder(new MatteBorder(1, 1, 1, 1, Color.LIGHT_GRAY));
update();
}
}
});
setLayout(new BorderLayout());
titlePanel.setPreferredSize(new Dimension(185,20));
fieldPanel.setPreferredSize(new Dimension(185,20));
//setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
//setPreferredSize(new Dimension(185, 37));
titlePanel.add(title, BorderLayout.LINE_START);
fieldPanel.add(field, BorderLayout.LINE_START);
fieldPanel.add(unit, BorderLayout.CENTER);
if(canEdit) titlePanel.add(isEditable, BorderLayout.LINE_END);
add(titlePanel, BorderLayout.PAGE_START);
if(hasField)
{
add(fieldPanel, BorderLayout.PAGE_END);
}
} | 3 |
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Airport other = (Airport) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} | 6 |
private static void printLayerDetails(Model model, String mode) {
System.out.println("***************************************************************************");
System.out.println("****************************** Layer Details ******************************");
System.out.println("***************************************************************************");
/**
* Print Layer details
*/
ArrayList<Layer> layers = new ArrayList<Layer>(model.getLayer());
//Collections.sort(layers);
for (Iterator<Layer> iterator = layers.iterator(); iterator.hasNext();) {
Layer lay = iterator.next();
float layperc = Constants.round2digits(lay.getTimeAccel()/(model.getTimeaccel()/100));
if(lay.isPrinted() && mode.contains("p")){
System.out.println("--------------------------------------------------");
System.out.println(lay.getLayerDetailReport()+"\n Percent of time:"+layperc+"%");
if(mode.contains("s")){
System.out.println(lay.getLayerSpeedReport());
}
}else if(!lay.isPrinted() && mode.contains("n")){
System.out.println("--------------------------------------------------");
System.out.println(lay.getLayerDetailReport()+"\n Percent of time:"+layperc+"%");
if(mode.contains("s")){
System.out.println(lay.getLayerSpeedReport());
}
}
}
} | 7 |
public LinearInterpolation(double[] x, double[] y){
this.nPoints=x.length;
this.nPointsOriginal = this.nPoints;
if(this.nPoints!=y.length)throw new IllegalArgumentException("Arrays x and y are of different length "+ this.nPoints + " " + y.length);
if(this.nPoints<3)throw new IllegalArgumentException("A minimum of three data points is needed");
this.x = new double[nPoints];
this.y = new double[nPoints];
for(int i=0; i<this.nPoints; i++){
this.x[i]=x[i];
this.y[i]=y[i];
}
this.orderPoints();
this.checkForIdenticalPoints();
} | 3 |
public Day getDayStored ()
{
return dayStored;
} | 0 |
public void setA(int a) {
this.a = a;
} | 0 |
public static boolean isPrime(int number) {
if (number < 0) {
throw new IllegalArgumentException("Error: int cannot be < 0!");
}
int sqrt = (int) (Math.sqrt(number) + 1);
if (number == 2) {
return true;
}
if (number == 1) {
return false;
}
for (int j = 2; j <= sqrt; j += 1) {
if (number % j == 0) {
return false;
}
}
return true;
} | 5 |
public void checkPrinterStatus() {
int HOW_MANY_INSTALLED_PRINTERS = 3;
for (int i = 0; i < HOW_MANY_INSTALLED_PRINTERS; i++) {
String usbId;
byte[] array = new byte[32];
int returnedVal;
if (i == 0) {
returnedVal = eZioLib.FindFirstUSB(array);
usbId = new String(array).trim();
} else {
returnedVal = eZioLib.FindNextUSB(array);
usbId = new String(array).trim();
}
if (returnedVal == 1) {
eZioLib.sendcommand("^XSET,ACTIVERESPONSE,1");
String printerStatusCode = sendCheckCommand(eZioLib);
System.out.println("printerStatusCode = " + printerStatusCode);;
eZioLib.closeport();
return;
} else {
eZioLib.closeport();
System.out.println(String.format("Printer %s is not connected", usbId));
}
eZioLib.closeport();
}
} | 3 |
private Slot getSlot(String name, int index, int accessType)
{
Slot slot;
// Query last access cache and check that it was not deleted.
lastAccessCheck:
{
slot = lastAccess;
if (name != null) {
if (name != slot.name)
break lastAccessCheck;
// No String.equals here as successful slot search update
// name object with fresh reference of the same string.
} else {
if (slot.name != null || index != slot.indexOrHash)
break lastAccessCheck;
}
if (slot.wasDeleted)
break lastAccessCheck;
if (accessType == SLOT_MODIFY_GETTER_SETTER &&
!(slot instanceof GetterSlot))
break lastAccessCheck;
return slot;
}
slot = accessSlot(name, index, accessType);
if (slot != null) {
// Update the cache
lastAccess = slot;
}
return slot;
} | 8 |
public boolean cadastrarBanca(int matriculaAluno, String data, String horario,
String local, String usuarioOrientador,
String professor1, String professor2, String professor3) {
Aluno aluno = procurarAluno(matriculaAluno);
Professor professor = procurarProfessor(usuarioOrientador);
Pessoa convidado1 = procurarPessoa(professor1);
Pessoa convidado2 = procurarPessoa(professor2);
Pessoa convidado3 = procurarPessoa(professor3);
Banca banca = new Banca();
if(aluno == null){
return false;
}
if (convidado1 != null && convidado2 != null
&& professor != null) {
banca.setData(data);
banca.setLocal(local);
banca.setHorario(horario);
banca.setPessoaByConvidado1IdPessoa(convidado1);
banca.setPessoaByConvidado2IdPessoa(convidado2);
banca.setPessoaByConvidado3IdPessoa(convidado3);
banca.setAluno(aluno);
banca.setProfessor(professor);
SESSAO.save(banca);
SESSAO.getTransaction().commit();
return true;
}
return false;
} | 4 |
public void close() {
EIError.debugMsg("Closing");
if (serverReceiveThread != null) {
serverReceiveThread.setRunning(false);
}
if (socket != null) {
try {
sendData("goodbye");
socket.close();
} catch (IOException e) {
//oh well, ain't no thang
}
}
keepRunning = false;
socket = null;
} | 3 |
private void paivitaPelaajaKomponentit(int pelaajanumero) {
if (pelaajanumero == 0){
try{
ui.getPpanel().paivitaKomponentit();
}catch(Exception e){}
}
if (pelaajanumero == 1){
try{
ui.getN1panel().paivitaKomponentit();
}catch(Exception e){}
}
if (pelaajanumero == 2){
try{
ui.getN2panel().paivitaKomponentit();
}catch(Exception e){}
}
if (pelaajanumero == 3){
try{
ui.getN3panel().paivitaKomponentit();
}catch(Exception e){}
}
} | 8 |
public void run(){
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Initializing the current time and the Random object
startTime = System.currentTimeMillis();
Random r = new Random();
//System.out.println("CLOCK STARTED");
int numOfQuestions = 0;
while(this.getTime() <= 5400){ //Simulation starts at 800 (time 0000) and ends at 1700 (time 5400).
synchronized(timeRegistry){
Iterator<Long> iter = timeRegistry.iterator();
while(iter.hasNext()){
Long t = iter.next();
if(this.getTime() >= t && office != null){
iter.remove();
office.notifyWorking();
}
}
}
int random = r.nextInt(5000000);
if(random == 0 && office != null){ // Firing random questions.
numOfQuestions++;
office.notifyWorking();
}
}
//System.out.println(numOfQuestions);
//System.out.println("CLOCK ENDED");
office.notifyWorking();
synchronized(office.getManager().getQuestionLock()){
office.getManager().getQuestionLock().notifyAll();
}
} | 7 |
public void move(int dx, int dy) {
AffineTransform at = new AffineTransform();
at.translate(dx, dy);
((GeneralPath) shape).transform(at);
canvas.repaint();
} | 0 |
@Override
public boolean equals(Object o) {
if (!(o instanceof TokenTuple))
return false;
TokenTuple t = (TokenTuple)o;
return tokenType.equals(t.tokenType) && token.equals(t.token);
} | 2 |
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String data = "";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
String dbDriver = "org.postgresql.Driver";
try {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':'
+ dbUri.getPort() + dbUri.getPath();
Class.forName(dbDriver);
con = DriverManager.getConnection(dbUrl, username, password);
Statement st = con.createStatement();
String väljund = "select nimi,tüüp,kohad,algus,asula,aadress,looja from sundmused order by id desc limit 3";
ResultSet rs = st.executeQuery(väljund);
ResultSetMetaData rsmd = rs.getMetaData();
//Stringid tulpade väärtuste jaoks, et muus järjekorras datasse pressida koos htmliga
String nimi = "";
String tuup = "";
String kohad = "";
String algus = "";
String asula = "";
String aadress = "";
String looja = "";
data += "<h2>Hiljutised uuendused</h2>";
while (rs.next()) {
/*
for (int i = 1; i <= columnsNumber; i++) {
data += rs.getString(i) + " ";
}
data += "<br>";*/
nimi = rs.getString(1);
tuup = rs.getString(2);
kohad = rs.getString(3);
algus = rs.getString(4);
asula = rs.getString(5);
aadress = rs.getString(6);
looja = rs.getString(7);
/*
data += nimi + " "+ tuup + " "+ "<br>"+ kohad + " "+ algus
+ " "+ asula + " "+ aadress + " "+ looja + "<br>";*/
data += "<p>";
if (tuup.equals("Lauamäng")){
data += "<img class=\"event_type\" src=\"icons/cards.png\" alt=\"type_logo\"/>";
}
else {
data += "<img class=\"event_type\" src=\"icons/pc.png\" alt=\"type_logo\"/>";
}
data += tuup + ": " + nimi + " - " + looja + "<br>";
data += "Aadress: "+ aadress +", "+ asula + "; algus: " + algus +"<br>";
data += "Lisainfo: " +"<br>";
data += "Kohtade arv: "+ kohad +"<br>";
data += "</p>" + "<br>" + "<br>";
nimi = tuup = kohad = algus = asula = aadress = looja = "";
}
writer.write(data);
con.close();
} catch (SQLException e) {
writer.println(e.toString());
} catch (ClassNotFoundException e) {
writer.println("ClassNotFoundException");
} catch (URISyntaxException e) {
e.printStackTrace();
}
} | 5 |
public void buildGraph(HashMap<String, LiveRange> liveRanges, HashMap<String, Integer> spillCosts)
{
for(String key: liveRanges.keySet())
{
InterferenceNode node = new InterferenceNode(key);
node.setSpillCost(spillCosts.get(key));
nodes.add(node);
}
for(InterferenceNode node: nodes)
{
String key = node.getName();
for(InterferenceNode otherNode: nodes)
{
String otherKey = otherNode.getName();
if(!key.equals(otherKey))
{
//This is a potential neighbor, check it and if it is adjacent, add it as a neighbor to the newNode
LiveRange x = liveRanges.get(key);
LiveRange y = liveRanges.get(otherKey);
if(!(x.getStart() < y.getStart() && x.getEnd() < y.getStart()) || !(x.getStart() > y.getEnd() && x.getEnd() > y.getEnd()))
{
//These two interfere, add it as a neighbor to this node
node.addNeighbor(otherNode);
}
}
}
}
} | 8 |
private void resaveParamsCountrySelected(SessionRequestContent request) throws ServletLogicException {
String page = (String) request.getSessionAttribute(JSP_PAGE);
String editHotelPage = ConfigurationManager.getProperty("path.page.edithotel");
String editDirectionPage = ConfigurationManager.getProperty("path.page.editdirection");
String searchingPage = ConfigurationManager.getProperty("path.page.tours");
if (page != null) {
if (page.equals(editHotelPage)) {
new HotelCommand().resaveParamsSaveHotel(request);
} else if (page.equals(editDirectionPage)) {
new DirectionCommand().resaveParamsSaveDirection(request);
} else if (page.equals(searchingPage)) {
new TourCommand().resaveParamsSearchTour(request);
}
}
} | 4 |
public void testSet_DateTimeFieldType_int3() {
MutableDateTime test = new MutableDateTime(TEST_TIME1);
try {
test.set(DateTimeFieldType.monthOfYear(), 13);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(TEST_TIME1, test.getMillis());
} | 1 |
public ArrayList<String> process(InputStream in) throws IOException
{
if(this._queue == null)
{
throw new ParserNotInitialized();
}
byte[] byteArray = null;
//to bypass problem with loading a pdf doc from stream which has been used before by Tika
byteArray = IOUtils.toByteArray(in);
InputStream input = new ByteArrayInputStream(byteArray);
InputStream check = new ByteArrayInputStream(byteArray);
ArrayList<String> URLsList = new ArrayList<String>();
ArrayList<String> textList = new ArrayList<String>();
Tika tike = new Tika();
String type = null;
try {
type = tike.detect(check);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(type.compareTo("text/html") == 0)
{
try {
Document doc = Jsoup.parse(in,null,"");
Elements links = doc.select("a[href]");
for(Element link : links)
{
URLsList.add(link.attr("abs:href"));
textList.add(link.text());
}
textList.add(doc.body().text());
URLsList.removeAll(temp);
this._queue.add(textList);
return URLsList;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(type.compareTo("application/pdf") == 0)
{
PdfReader reader = new PdfReader(input);
String rawTextFromPdf = "";
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
rawTextFromPdf += PdfTextExtractor.getTextFromPage(reader, i);
}
System.out.println(rawTextFromPdf);
/*
* To do:
* extract urls from rawText
*/
return URLsList;
}
if(type.compareTo("text/plain") == 0)
{
System.out.println("txt");
return null;
}
return null;
} | 8 |
void renderWorldFX(Rendering rendering) {
final Target
HS = (hovered == null) ? null : hovered .subject(),
SS = (selected == null) ? null : selected.subject() ;
if (HS != null && HS != SS) {
//renderSelectFX(hovered, HS, Colour.transparency(0.5f), rendering) ;
hovered.renderSelection(rendering, true) ;
}
if (SS != null) {
selected.renderSelection(rendering, false) ;
//renderSelectFX(selected, SS, Colour.WHITE, rendering) ;
}
} | 5 |
@Override
public boolean equals(Object o)
{
if (o instanceof Pair<?, ?>)
{
Pair<?, ?> p1 = (Pair<?, ?>) o;
if (p1.Key_.equals(this.Key_) && p1.Value_.equals(this.Value_))
{
return (true);
}
}
return (false);
} | 9 |
@Override
public void updateSymptom(SymptomDTO symptom) throws SQLException {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(symptom);
session.getTransaction().commit();
}
catch (Exception e) {
System.err.println("Error while adding an symptom!");
}
finally {
if (session != null && session.isOpen())
session.close();
}
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Colore other = (Colore) obj;
if (blue != other.blue)
return false;
if (green != other.green)
return false;
if (red != other.red)
return false;
return true;
} | 6 |
private void updateGui()
{
updateDisplay();
if (!itemSelected)
{
for (int i = 0; i<pockets.length; i++)
{
pockets[i].setVisible(true);
pages[i].setVisible(true);
}
for (JButton aDisplay : display) {
aDisplay.setVisible(true);
}
information.setVisible(true);
closeButton.setVisible(true);
moneyDisplay.setVisible(true);
buySellButton.setVisible(true);
buyButton.setVisible(false);
amountField.setVisible(false);
amountDisplay.setVisible(false);
totalAmount.setVisible(false);
buyButton.setVisible(false);
sellButton.setVisible(false);
moneyDisplay.setText("Money: $" + Inventory.money);
updatePageButtons();
}
else
{
if (state == State.BUY)
{
buyButton.setVisible(true);
sellButton.setVisible(false);
}
else
{
buyButton.setVisible(false);
sellButton.setVisible(true);
}
amountDisplay.setVisible(true);
totalAmount.setVisible(true);
buySellButton.setVisible(false);
for (int i = 1; i<display.length; i++)
{
display[i].setVisible(false);
}
amountField.setVisible(true);
for (int i = 0; i<pockets.length; i++)
{
pockets[i].setVisible(false);
pages[i].setVisible(false);
}
moneyDisplay.setText("Money: $" + Inventory.money);
}
} | 6 |
public boolean isindb(final Location sign) throws SQLException {
boolean a = false;
long time = 0;
plugin.getLoggerUtility().log("Checking if in table!", LoggerUtility.Level.DEBUG);
time = System.nanoTime();
Statement st = null;
String sql;
ResultSet result;
try {
st = connector.getConnection().createStatement();
} catch (SQLException e) {
DatabaseTools.SQLErrorHandler(plugin, e);
}
sql = "SELECT COUNT(Name) from PaypassageSigns WHERE " + "Sign_X=" + sign.getBlockX() + " AND Sign_Y=" + sign.getBlockY() + " AND Sign_Z=" + sign.getBlockZ();
try {
result = st.executeQuery(sql);
} catch (SQLException e1) {
DatabaseTools.SQLErrorHandler(plugin, e1);
return false;
}
try {
result.next();
int b = result.getInt(1);
plugin.getLoggerUtility().log("Lines: " + b, LoggerUtility.Level.DEBUG);
if (b > 0) {
a = true;
}
connector.getConnection().commit();
result.close();
st.close();
} catch (SQLException e2) {
DatabaseTools.SQLErrorHandler(plugin, e2);
}
time = (System.nanoTime() - time) / 1000000;
plugin.getLoggerUtility().log("Finished in " + time + " ms!", LoggerUtility.Level.DEBUG);
return a;
} | 4 |
void initTypes() {
ArrayList<String> typeList = new ArrayList<String>();
boolean exonsAdded = false;
for (String type : DEFAULT_TYPES) {
// Add exons or introns?
if (type.equals(Exon.class.getSimpleName()) || type.equals(Intron.class.getSimpleName())) {
if (!exonsAdded) {
// Add all exons and introns
for (int ex = 1; ex <= exons; ex++) {
typeList.add(Exon.class.getSimpleName() + ":" + ex + ":" + exons);
if (ex < exons) typeList.add(Intron.class.getSimpleName() + ":" + ex + ":" + exons);
}
exonsAdded = true;
}
} else if (type.equals(Intergenic.class.getSimpleName())) {
// Do not add intergenic
} else typeList.add(type);
}
// convert to array
types = typeList.toArray(new String[0]);
} | 7 |
private void copyGrid(int[][] int1, int[][] int2) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
int1[i][j] = int2[i][j];
}
}
} | 2 |
private boolean checaSeExisteVariavelEmRegistro(String nomeVariavel) {
System.out.println("ACOLAA:"+ nomeVariavel);
if(!listaVariveisRegistro.isEmpty()){
if(!listaDeBlocos.isEmpty()){
for(int j=0;j< listaDeBlocos.size();j++){
String [] tabela1 = listaDeBlocos.get(j).split("~");
String nomeReg = tabela1[1];
// System.out.println("NOMEREG 1:"+ tabela1[1]);
if(nomeReg.equals(tipoDoToken[1])){
String [] tabela2 = tabela1[2].split(":");
for(int i=0;i< tabela2.length;i++){
String indice = tabela2[i];
for(int z=0;z<listaVariveisRegistro.size();z++){
String ind = listaVariveisRegistro.get(z).split(":")[0];
if(indice.equals(ind)){
String nomeVar = listaVariveisRegistro.get(z).split(":")[2];
if(nomeVar.equals(nomeVariavel)){
return true;
}
}
}
}
}
}
}
}
return false;
} | 8 |
public void removeNeighboor(Ways w) {
switch (w) {
case NORTH:
if (north != null)
north.south = null;
north = null;
break;
case SOUTH:
if (south != null)
south.north = null;
south = null;
break;
case EAST:
if (east != null)
east.west = null;
east = null;
break;
case WEST:
if (west != null)
west.east = null;
west = null;
break;
}
} | 8 |
private static String getUserCommand() {
String command = null;
while (command == null) {
try {
System.out.println("Чтобы открыть ячейку введите координаты: " + FieldBorder.VerticalAxisName +
SaveLoad.WIGHT_HEIGHT_SPLITTER + FieldBorder.HorizontalAxisName + "\n" +
"Чтобы установить флаг введите: " + FLAG_COMMAND + " " +
FieldBorder.VerticalAxisName + SaveLoad.WIGHT_HEIGHT_SPLITTER +
FieldBorder.HorizontalAxisName + "\n" +
"Чтобы сохранить игру введите: " + SAVE_COMMAND + "; \n" +
"Для завершения введите: " + SURRENDER_COMMAND);
command = BR.readLine();
command = command.trim().toLowerCase();
if (!command.equals(SAVE_COMMAND) && !command.equals(SURRENDER_COMMAND) &&
!command.contains(SaveLoad.WIGHT_HEIGHT_SPLITTER)) {
command = null;
throw new IOException();
}
} catch (IOException exc) {
System.out.println(INPUT_ERROR_MESSAGE);
}
}
return command;
} | 5 |
public void setGestureOk(boolean gestureOk) {
this.gestureOk = gestureOk;
} | 0 |
private static void testCase2(){
CellEntry[][] cell = new CellEntry[][]{
{CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.white, CellEntry.inValid},
{CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.white},
{CellEntry.black, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid},
{CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.empty},
{CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.empty, CellEntry.inValid},
{CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.black},
{CellEntry.empty,CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.black, CellEntry.inValid},
{CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.black}
};
Board board = new Board(cell);
board.whitePieces = 5;
board.blackPieces = 6;
Board newBoard = board.duplicate();
System.out.println(newBoard.CheckGameComplete());
Vector<Move> resultantMoveSeq = new Vector<Move>();
//
alphaBeta(board, Player.black, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, resultantMoveSeq);
board.Display();
displayMovesInVector(resultantMoveSeq);
//Apply the move to the game board.
for(Move m:resultantMoveSeq){
board.genericMakeWhiteMove(m);
}
resultantMoveSeq.clear();
alphaBeta(board, Player.white, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, resultantMoveSeq);
board.Display();
displayMovesInVector(resultantMoveSeq);
} | 1 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EmployeeForm employeeForm = new EmployeeForm();
employeeForm.setName(request.getParameter("name"));
employeeForm.setSurname(request.getParameter("surname"));
employeeForm.setBirthday(request.getParameter("birthday"));
employeeForm.setEmail(request.getParameter("email"));
employeeForm.setPassword(request.getParameter("password"));
employeeForm.setPassword_confirm(request.getParameter("pass_confirm"));
List errorsList = employeeForm.validate();
boolean hasError = errorsList.size() > 0;
if (hasError) {
Employee employee = new Employee(employeeForm.getName(), employeeForm.getSurname(), employeeForm.getBirthday(), employeeForm.getEmail(), employeeForm.getPassword());
request.setAttribute("errorsList", errorsList);
request.setAttribute("employee", employee);
request.getRequestDispatcher("loginForm.jsp").include(request, response);
return;
}
logger.info(request.getParameterValues("save_in")[0]);
boolean saveInXmlFile = request.getParameterValues("save_in")[0].equals("xml");
boolean saveInDatabase = request.getParameterValues("save_in")[0].equals("database");
if (saveInXmlFile) {
EmployeeModel employeeModelXml = new EmployeeModel(employeeForm, ProviderFactory.ProviderType.XML);
employeeModelXml.save();
}
if (saveInDatabase) {
EmployeeModel employeeModelDb = new EmployeeModel(employeeForm, ProviderFactory.ProviderType.DB);
employeeModelDb.save();
}
response.sendRedirect("/employeeList");
} | 3 |
public void createFirst() {
// Initialize first with empty set
first = initFirst();
Map<Symbol, Set<Symbol>> prevFirst = initFirst();
Map<Symbol, Set<Symbol>> nextFirst = new HashMap<Symbol, Set<Symbol>>();
boolean hasChanged = false;
do {
nextFirst = initFirst();
for (NonterminalSymbol A : grammar.getNonterminals()) {
for (List<Symbol> prod : grammar.getProductions(A)) {
Set<Symbol> tempSet = new HashSet<Symbol>();
//tempSet.add(grammar.EPSILON);
boolean emptyPervFirst = false;
for(Symbol s : prod) {
if(prevFirst.get(s).isEmpty()) {
emptyPervFirst = true;
break;
}
else {
if (tempSet.isEmpty()) {
tempSet.addAll(prevFirst.get(s));
} else {
tempSet = plus(tempSet,prevFirst.get(s));
}
}
}
nextFirst.get(A).addAll(prevFirst.get(A));
if (!emptyPervFirst) {
nextFirst.get(A).addAll(tempSet);
}
}
}
hasChanged = false;
for (Symbol s : prevFirst.keySet()) {
if (prevFirst.get(s).size() != nextFirst.get(s).size()) {
hasChanged = true;
}
}
prevFirst = nextFirst;
} while (hasChanged);
first = nextFirst;
} | 9 |
public static void main(String[] args) {
int x = 1;
if (x == 1) {
// empty statement
} else {
while (true) {
//empty statement
}
}
} | 2 |
public KeyUtils(AlgoCryptType algo, int keySize) {
if ((algo != AlgoCryptType.RSA) && (algo != AlgoCryptType.DSA)) {
throw new IllegalArgumentException("Invalid algo type (" + algo + ").");
}
this.keySize = keySize;
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Categoria other = (Categoria) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nombre == null) {
if (other.nombre != null)
return false;
} else if (!nombre.equals(other.nombre))
return false;
return true;
} | 9 |
@Override
public String getColumnName(int column) {
switch (column) {
case 0:return "ID";
case 1:return "Nom";
case 2:return "Prénom";
case 3:return "E-mail";
case 4: return "Nb signalisation";
default:return "Autres";
}
} | 5 |
public static Color makeHSBColor(
double hue, double saturation, double brightness) {
float h = (float)hue;
float s = (float)saturation;
float b = (float)brightness;
h = (h < 0)? 0 : ( (h > 1)? 1 : h );
s = (s < 0)? 0 : ( (s > 1)? 1 : s );
b = (b < 0)? 0 : ( (b > 1)? 1 : b );
return Color.getHSBColor(h,s,b);
} | 6 |
public static long playerNameToInt64(String s) {
long l = 0L;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
l *= 37L;
if (c >= 'A' && c <= 'Z') {
l += (1 + c) - 65;
} else if (c >= 'a' && c <= 'z') {
l += (1 + c) - 97;
} else if (c >= '0' && c <= '9') {
l += (27 + c) - 48;
}
}
while (l % 37L == 0L && l != 0L) {
l /= 37L;
}
return l;
} | 9 |
@Test
public void hello() throws Exception {
Integer[] states;
double[] distributionTheorique;
AlgorithmMCMC<Integer> algo;
MarkovChain mc ;
double[] distributionExperimentale;
//
int i = 0;
while (i < 100) {
int N = rand.nextInt(10) + 1;
states = new Integer[N];
for (int j = 0; j < N; j++) {
states[j] = j;
}
// distributionTheorique = Alea.createRandomDistribution(N, N*100);
distributionTheorique = Alea.createRandomDistributionProbabilistWithNoZero(N, N*100);
Myst.afficherTableau(distributionTheorique);
// System.out.println("ok");
algo = AlgorithmFactory.getInstance().getAlgorithm(AlgorithmFactory.METROPOLIS_HASTING, states, distributionTheorique);
mc = algo.constructChain();
mc.computeStationaryDistributionUntilStabilityFitness(0.000001, 0.001);
distributionExperimentale = mc.getStationary_distribution();
for (int j = 0; j < N; j++) {
//assertEquals(distributionExperimentale[j],distributionTheorique[j],0.05);
}
i++;
}
} | 3 |
private void addValidators() {
quantityoutlet.setInputVerifier(new AbstractValidator(this, quantityoutlet, "Ongeldige waarde! Verwacht formaat: x.y, groter dan 0.0") {
@Override
protected boolean validationCriteria(JComponent c) {
if (autobox.getSelectedIndex() == 0) {
return true;
}
try {
return Double.parseDouble(((JTextField) c).getText()) > 0;
} catch (Exception e) {
return false;
}
}
});
txtReduction.setInputVerifier(new AbstractValidator(this, txtReduction, "Ongeldige waarde! Kies een positief getal tussen 0 en 100 of laat dit veld leeg (=0 % korting)") {
@Override
protected boolean validationCriteria(JComponent c) {
if (txtReduction.getText().isEmpty()) {
return true;
}
try {
double s = Double.parseDouble(((JTextField) c).getText());
return s >= 0.0 && s <= 100.0;
} catch (Exception e) {
return false;
}
}
});
} | 5 |
private void ReadProperty(String cfile) throws IOException{
String line = "";
FileInputStream fileinputstream = new FileInputStream(cfile);
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(fileinputstream));
do {
if ((line = bufferedreader.readLine()) == null)
break;
if (line.indexOf("#") == 0 || line.indexOf("=") < 0)
continue;
String key=line.substring(0,line.indexOf("="));
String value=line.substring(line.indexOf("=")+1);
//System.out.println("key:"+key);
//System.out.println("value:"+value);
configproperty.put(key,value);
} while(true);
} | 4 |
public void readFile() throws IOException {
BufferedReader fileIn;
try {
fileIn = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e){
File points = new File(fileName);
PrintWriter fileOut = new PrintWriter(points);
fileOut.println("0");
fileOut.close();
fileIn = new BufferedReader(new FileReader(fileName));
}
String dato = fileIn.readLine();
while(dato != null) {
int number = (Integer.parseInt(dato));
scorelist.add(number);
dato = fileIn.readLine();
}
fileIn.close();
} | 2 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VueConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VueConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VueConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VueConnexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*VueAbstrait vueA = null;
CtrlAbstrait CtrlA = null;
VueConnexion vue = new VueConnexion(CtrlA);
CtrlConnexion ctrl = new CtrlConnexion(vue, vueA);
vue.setVisible(true);*/
// Pour lancer l'application, instancier le contrôleur principal
CtrlPrincipal ctrlPrincipal;
ctrlPrincipal = new CtrlPrincipal();
ctrlPrincipal.action();
} | 6 |
public URL getUkeplan(String ID, int week, int x, int y) {
String adresse = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=72150/nb-no&type=3&id={" + ID + "}&period=&week=" + week + "&mode=3&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width=" + x + "&height=" + y + "&maxwidth=" + x + "&maxheight=" + y;
URL url = null;
try {
url = new URL(adresse);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
url = new URL("http://www.vg.no");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return url;
} | 2 |
private void paintPuzzle(Graphics g) {
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 1000, 1000);
if (menu != null) {
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 20));
g.setColor(Color.WHITE);
int yPos = 150;
int xPos = 80;
for (String curString : getMenuTitle()) {
g.drawString( curString, xPos, yPos);
yPos += 20;
}
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 40));
yPos += 150;
xPos += 10;
for (String curString : menu) {
g.drawString( curString, xPos, yPos);
yPos += 50;
}
} else {
if (pieces != null) {
for(Piece nextPiece : pieces) {
drawPiece(nextPiece, g);
}
}
if (playBoard != null) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (!playBoard[i][j]) {
drawSpace(i, j, g);
}
}
}
}
}
} | 9 |
public static void main(String args[]){
PrestataireDeService p=new PrestataireDeService("lodsdggg", "pwwwd");
PrestataireDeService p1=new PrestataireDeService("lo", "pwwwd");
p.setAdresse("sqddqs");
p.setTelephone(123);
PrestataireDeServiceDAO prestataireDeServicedao =new PrestataireDeServiceDAO();
System.out.println(prestataireDeServicedao.ChercherPrestataireDeService("lodsdggg").getTelephone());
// //test ajout réussi
prestataireDeServicedao.AjouterPrestataireDeService(p);
p.setSociete("jjjjjj");
prestataireDeServicedao.AjouterPrestataireDeService(p1);
prestataireDeServicedao.ModifierPrestataireDeService(p, "lodsdggg");
prestataireDeServicedao.SupprimerPrestataireDeService("lodsdggg");
// // test update réussi
// client.setNom("nomjdid");
// clientdao.ModifierClient(client, "loggg");
// // test delete réussi
// // System.out.println(clientdao.SupprimerClient("loggg"));
List<PrestataireDeService> l = prestataireDeServicedao.ListerPrestatairesDeService();
for (int i=0; i< l.size();i++)
{
System.out.println(l.get(i).getStatut()+" "+l.get(i).getLogin());
}
// System.out.println(prestataireDeServicedao.ChercherClient("loggg").getPrenom());
} | 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JGenerator().setVisible(true);
}
});
} | 6 |
public void setMainWindowModel(MainWindowModel mainWindowModel) {
this.mainWindowModel = mainWindowModel;
} | 0 |
public static void main(String... args) {
Map<String, List<PathPattern<ServletAction>>> map = new HashMap<String, List<PathPattern<ServletAction>>>();
//init one servlet action
ServletAction servletAction = new ServletAction("profile.jsp", ServletAction.Type.REDIRECT);
PathPattern<ServletAction> pattern = new PathPattern<ServletAction>(servletAction, "/profile/$Username/$Age", true, 3);
String key = pattern.getKey();
List<PathPattern<ServletAction>> list = new ArrayList<PathPattern<ServletAction>>();
map.put(key, list);
list.add(pattern);
// init map over .
PathInput input = new PathInput("/profile/aaa/bbb", 1);
String key___ = input.value();
List<PathPattern<ServletAction>> list___ = map.get(key___);
for (PathPattern<ServletAction> pattern___ : list___) {
if (pattern___.match(input)) {
System.out.println(pattern___.getTarget().target);
Map<String, String> params = new HashMap<String, String>();
List<String> paramsKeys = new ArrayList<String>();
List<String> paramsValues = new ArrayList<String>();
for (String s___ : input.items) {
paramsKeys.add(s___);
}
for (Element e : pattern___.elements) {
if (e instanceof StringElement) {
paramsValues.add(((StringElement) e).getProperties());
}
}
for (int i = 0; i < paramsValues.size(); i++) {
params.put(paramsKeys.get(i + 1), paramsValues.get(i));
}
System.out.println(params);
}
}
} | 6 |
public boolean hasChanged(){
if(parent!=null && parent.hasChanged())
return true;
if(!position.equals(oldPosition) || !rotation.equals(oldRotation) || !scale.equals(oldScale))
return true;
return false;
} | 5 |
public static String runAllTests() throws ConnectionException,
RemoteException {
StringBuffer sbuff = new StringBuffer("");
ConnectorConfig config = new ConnectorConfig();
config.setUsername("asawant02@dev.com");
config.setPassword("test@234");
config.setAuthEndpoint("https://login.salesforce.com/services/Soap/c/27.0");
econnection = new EnterpriseConnection(config);
config.setServiceEndpoint(config.getServiceEndpoint());
// display some current settings
sbuff.append("Auth EndPoint: " + config.getAuthEndpoint());
sbuff.append("Service EndPoint: " + config.getServiceEndpoint());
sbuff.append("Username: " + config.getUsername());
ConnectorConfig config1 = new ConnectorConfig();
config1.setUsername("asawant02@dev.com");
config1.setPassword("test@234");
config1.setAuthEndpoint("https://login.salesforce.com/services/Soap/c/27.0");
config1.setSessionId(econnection.getSessionHeader().getSessionId());
config1.setServiceEndpoint("https://ap1-api.salesforce.com/services/Soap/s/27.0");
connection = Connector.newConnection(config1);
long start = System.currentTimeMillis();
RunTestsResult res = null;
RunTestsRequest rtr = new RunTestsRequest();
rtr.setAllTests(true);
res = connection.runTests(rtr);
int totalLines = 0;
int linesCoveredByTests = 0;
sbuff.append("Number of tests: " + res.getNumTestsRun());
sbuff.append("Number of failures: " + res.getNumFailures());
Code_Coverage__c ccResult = new Code_Coverage__c();
ccResult.setNumber_of_Failures__c((double) res.getNumFailures());
ccResult.setNumber_of_Tests__c((double) res.getNumTestsRun());
SaveResult[] createResult = econnection.create(new SObject[]{ccResult});
String parentId = createResult[0].getId();
sbuff.append(createResult[0].getSuccess());
Coverage_Line_Item__c []ccLineItems = new Coverage_Line_Item__c[res.getCodeCoverage().length+res.getFailures().length];
int p = 0;
String testFailureDetails = "";
if (res.getNumFailures() > 0) {
for (RunTestFailure rtf : res.getFailures()) {
testFailureDetails += "Failure: "
+ (rtf.getNamespace() == null ? "" : rtf.getNamespace()
+ ".") + rtf.getName() + "."
+ rtf.getMethodName() + ": " + rtf.getMessage() + "\n"
+ rtf.getStackTrace();
sbuff.append(testFailureDetails);
Coverage_Line_Item__c ccLineItem = new Coverage_Line_Item__c();
ccLineItem.setCoverage_Line_Item__c(parentId);
ccLineItem.setTotal_Lines__c((double) 0);
ccLineItem.setLines_Not_Covered__c((double) 0);
ccLineItem.setSource_File_Name__c(rtf.getName());
ccLineItem.setType__c(rtf.getType());
ccLineItem.setTest_Failure_Details__c(testFailureDetails);
ccLineItems[p++]=ccLineItem;
}
}
if (res.getCodeCoverage() != null) {
for (CodeCoverageResult ccr : res.getCodeCoverage()) {
String coverageDetails = "Code coverage for " + ccr.getType() +
(ccr.getNamespace() == null ? "" : ccr.getNamespace() + ".")
+ ccr.getName() + ": "
+ ccr.getNumLocationsNotCovered()
+ " locations not covered out of "
+ ccr.getNumLocations();
double coverage = ccr.getNumLocations() != 0 ? (ccr
.getNumLocations() - ccr.getNumLocationsNotCovered())
* 100 / ccr.getNumLocations() : 0;
System.out.println("Coverage % for "
+ ccr.getName()
+ ": "
+ coverage
+ " Lines Covered: "
+ (ccr.getNumLocations() - ccr
.getNumLocationsNotCovered()) + " of "
+ ccr.getNumLocations());
totalLines += ccr.getNumLocations();
linesCoveredByTests += (ccr.getNumLocations() - ccr
.getNumLocationsNotCovered());
Coverage_Line_Item__c ccLineItem = new Coverage_Line_Item__c();
ccLineItem.setCoverage_Line_Item__c(parentId);
ccLineItem.setTotal_Lines__c((double) ccr.getNumLocations());
ccLineItem.setLines_Not_Covered__c((double) ccr.getNumLocationsNotCovered());
ccLineItem.setSource_File_Name__c(ccr.getName());
ccLineItem.setType__c(ccr.getType());
ccLineItem.setCoverage_Details__c(coverageDetails);
ccLineItems[p++]=ccLineItem;
// if (ccr.getNumLocationsNotCovered() > 0) {
// for (CodeLocation cl : ccr.getLocationsNotCovered())
// System.out.println("\tLine " + cl.getLine());
// }
}
}
SaveResult[] cliResult = econnection.create(ccLineItems);
sbuff.append(cliResult.length);
sbuff.append("Overall Org Coverage: " + linesCoveredByTests * 100
/ totalLines);
sbuff.append("Finished in "
+ (System.currentTimeMillis() - start) + "ms");
return sbuff.toString();
} | 7 |
private static Image getImage(String filename) {
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
} catch (Exception e) { /* not a url */ }
}
// in case file is inside a .jar
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = StdDraw.class.getResource(filename);
if (url == null) {
throw new IllegalArgumentException("image " + filename + " not found");
}
icon = new ImageIcon(url);
}
return icon.getImage();
} | 6 |
public void setW(Integer value, boolean status_effect) {
if((value == 0) && status_effect) {
status.setBit(bits.Z);
PIC_Logger.logger.info("Flag: Zero");
}
else if(value > 255) {
value -= 256;
if(status_effect){
status.setBit(bits.C);
PIC_Logger.logger.info("Flag: C");
}
}
else if(value < 0) {
value += 256;
if(status_effect){
status.setBit(bits.DC);
PIC_Logger.logger.info("Flag: DC");
}
}
gui.show_W_Register(Integer.toHexString(value));
this.w.setWert(value);
} | 6 |
public static void console() {
Fachada fachada = Fachada.getInstance();
Scanner console = new Scanner(System.in);
boolean stop = false;
while(!stop) {
System.out.println("Escolha a opcao:\n" + "1. Indexar\n" + "2. Buscar\n" + "3. Encerrar");
int opcao = console.nextInt();
// ACTION 1 => INDEXER
if(opcao == 1) {
TelaIndexar.console();
}
// ACTION 2 => SEARCHER
else if(opcao == 2) {
TelaBusca.console();
}
else if(opcao == 3) {
stop = true;
fachada.finalizar();
}
System.out.println();
}
} | 4 |
public void update(BufferedImage bimg) {
int[] pixels = new int[bimg.getWidth() * bimg.getHeight()];
bimg.getRGB(0, 0, bimg.getWidth(), bimg.getHeight(), pixels, 0,
bimg.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(bimg.getWidth()
* bimg.getHeight() * 4);
for (int y = 0; y < bimg.getHeight(); y++) {
for (int x = 0; x < bimg.getWidth(); x++) {
int pixel = pixels[y * bimg.getWidth() + x];
buffer.put((byte) ((pixel >> 16) & 0xFF));
buffer.put((byte) ((pixel >> 8) & 0xFF));
buffer.put((byte) (pixel & 0xFF));
buffer.put((byte) ((pixel >> 24) & 0xFF));
}
}
buffer.flip();
glBindTexture(GL_TEXTURE_2D, this.getTextureID());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, bimg.getWidth(), bimg.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
} | 2 |
public void append(char c) {
if (c != '0' && c != '1') {
throw new IllegalArgumentException("Argument must be '0' or '1'");
}
path_ = path_ + c;
} | 2 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
int n = Integer.parseInt(line.trim());
if (n == 0)
break;
p = new Point[n];
for (int i = 0; i < n; i++) {
long[] xy = readLongs(in.readLine());
p[i] = new Point(xy[0], xy[1]);
}
double total = 0;
for (int i = 0; i < n; i++)
total += turn(p[i], p[(i + 1) % n], p[(i + 2) % n]);
out.append(String.format("%.0f\n", total / (Math.PI * 2)));
}
System.out.print(out);
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
if (!firstName.equals(person.firstName)) return false;
if (!mail.equals(person.mail)) return false;
if (!phone.equals(person.phone)) return false;
if (!secondName.equals(person.secondName)) return false;
return true;
} | 6 |
public String getCountry() {
return super.getCountry();
} | 0 |
public void run() {
while (!isInterrupted()) {
// hier wird die Zieladresse (target) aus der Nachricht extrahiert
try {
String message = receive();
// System.out.println("ServerThread "+myNumber+":"+" "+message);
if (message != null) {
StringTokenizer ST = new StringTokenizer(message);
int target = Integer.parseInt(ST.nextToken());
System.out.println("sending message from " + myNumber + " to " + target);
// falls target="-1": Nachricht an Server; sonst Nachricht an Spieler x
if (target >= -1) {
server.forward(gameID, message);
} else {
send("1exit");
server.deletePlayer(message + " " + gameID);
interrupt();
try {
connection.close();
} catch (IOException ex) {
}
}
} else {
String log = "Aborting game! Player " + (myNumber + 1) + " has left the game\n";
System.out.print(log);
server.log(log, server.getPort());
interrupt();
server.shutdown(nameOfTheGame + " " + myNumber + " " + gameID, log);
}
} catch (InterruptedIOException e) {
String log = "Aborting game! TimeOut while receiving message" + " from player " + (myNumber + 1) + "\n";
System.out.print(log);
server.log(log, server.getPort());
interrupt();
server.shutdown(nameOfTheGame + " " + myNumber + " " + gameID, log);
} catch (IOException e) {
String log = "Aborting game! Player " + (myNumber + 1) + " has left the game\n";
System.out.print(log);
server.log(log, server.getPort());
interrupt();
server.shutdown(nameOfTheGame + " " + myNumber + " " + gameID, log);
}
}
} | 6 |
private int winnerIs(int WeaponOne, int WeaponTwo) {
if(WeaponOne<0 || WeaponOne>2 || WeaponTwo<0 || WeaponTwo>2) return-1;
int resultNum=(3+WeaponOne-WeaponTwo)%3;
int winningPlayerIsNum=resultNum;
return winningPlayerIsNum;
} | 4 |
public static void main(String[] args) {
com.proxious.jdblib.mysql.MySQL mySQL = new com.proxious.jdblib.mysql.MySQL("localhost", "3306", "root", "root", "test");
mySQL.openConnection();
if (mySQL.isOpen()) {
System.out.println("Connection open.");
}
else {
System.out.println("Connection not open.");
}
System.out.println("Truncating users table...");
mySQL.update("TRUNCATE TABLE `users`");
int x = 0;
System.out.println("Generating users...");
while (x < 11) {
mySQL.update("INSERT INTO `users`(`ID`, `username`, `password`) VALUES (?,?,?)", String.valueOf(x), UUID.randomUUID().toString(), UUID.randomUUID().toString());
x++;
}
System.out.println("Selecting users...");
ResultSet result = mySQL.query("SELECT * FROM `users`");
try {
if (result == null) {
if (!mySQL.isOpen()) {
System.out.println("The connection isn't open.");
}
else {
System.out.println("Nothing was returned from the query.");
}
return;
}
while (result.next()) {
System.out.println(result.getInt("ID") + " " + result.getString("username") + " " + result.getString("password"));
}
}
catch (SQLException ex) {
Logger.getLogger(MySQL.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Closing connection...");
mySQL.closeConnection();
} | 6 |
public List listar() {
String sql = "SELECT * FROM PEDIDO as r inner join cliente as c on r.idCliente = c.idCliente";
try {
conn = GerenciaConexaoBD.getInstance().getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<Reserva> listarReserva = new ArrayList<Reserva>();
while (rs.next()) {
Reserva reserva = new Reserva();
reserva.setIdReserva(rs.getInt("r.idReserva"));
reserva.setIdProduto(rs.getInt("r.idProduto"));
reserva.setIdCliente(rs.getInt("r.idCliente"));
reserva.setReservaEstado(ReservaFactory.create(rs.getString("r.estadoReserva")));
reserva.setNomeCliente(rs.getString("c.nome"));
listarReserva.add(reserva);
}
stmt.close();
return listarReserva;
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} | 2 |
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) return head;
int length = n - m +1;
if (length == 1) return head;
ListNode tail = head;
for (int i = 0;i<n ;i++) tail = tail.next;
if (m == 1)
{
return reverse(head,tail, length);
}
ListNode p = head;
ListNode q = null;
for (int i = 1;i< m ;i++)
{
q = p;
p=p.next;
}
q.next = reverse(p,tail,length);
return head;
} | 5 |
public void dropClient(int clientId, String reason) {
logger.finer("Dropping client " + clientId + ": " + reason);
boolean clientDropped = false;
synchronized(CONNECTION_LOCK) {
if(clients.containsKey(clientId)) {
ClientInfo client = clients.get(clientId);
try {
sendPacket(Packet.createForceDisconnectPacket(clientId, reason), client);
} catch (CouldNotSendPacketException e) {
//no need to report that we couldn't ask the client to disconnect--we're dropping the client regardless
}
clients.remove(clientId);
clientDropped = true;
}
else {
logger.finer("Client " + clientId + " could not be dropped: Client not connected.");
}
}
if(clientDropped)
onClientDisconnected(clientId, Server.DROPPED_BY_SERVER);
} | 3 |
public BigInteger[][] getEncryptionKeys(BigInteger[] keyArray) {
// String keyString
BigInteger[] outputArray = new BigInteger[52];
// BigInteger[] keyArray = Helper.stringToBigIntegerArray(keyString);
BigInteger key = Helper.bigIntegerArraySum(keyArray, 8);
BigInteger[] shortKeyArray = Helper.extractValues(key, 16, 8);
// get keys
int i = 0;
while (i != 52) {
for (int j = 0; j < shortKeyArray.length; j++) {
BigInteger tmp = shortKeyArray[j];
outputArray[i++] = tmp;
if (i == 52) {
break;
}
}
if (i != 52) {
key = Helper.shift(key, 16, 25);
shortKeyArray = Helper.extractValues(key, 16, 8);
}
}
// get as 2d array
BigInteger[][] nicerArray = new BigInteger[9][6];
int counter = 0;
for (int zeile = 0; zeile < nicerArray.length; zeile++) {
for (int spalte = 0; spalte < nicerArray[zeile].length; spalte++) {
nicerArray[zeile][spalte] = outputArray[counter++];
if (counter == 52) {
return nicerArray;
}
}
}
return nicerArray;
} | 7 |
public static void main(String[] args) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int i = 0; i < isPrime.length; i++)
if (isPrime[i])
primes.add(i);
int first = 0, second = 0, third = 0;
for (int i = 0; i < primes.size(); i++)
for (int j = i + 1; j < primes.size(); j++){
int k = 2 * primes.get(j) - primes.get(i);
if (k < 10000 && isPrime[k] && checkPermutation(primes.get(i), primes.get(j), k)){
first = primes.get(i);
second = primes.get(j);
third = k;
if (first != 1487)
i = primes.size();
break;
}
}
System.out.println(first + "" + second + "" + third);
// Solution: 296962999629
} | 8 |
private void begin() {
int[] i = new int[101];
int[] v = new int[101];
int[] x = new int[101];
int[] l = new int[101];
int[] c = new int[101];
for ( int n = 1; n <= 100; n++ ) {
i[n] = i[n-1];
v[n] = v[n-1];
x[n] = x[n-1];
l[n] = l[n-1];
c[n] = c[n-1];
String roman = romanize(n);
for ( int chr = 0; chr < roman.length(); chr++ ) {
switch (roman.charAt(chr)) {
case 'i': i[n]++; break;
case 'v': v[n]++; break;
case 'x': x[n]++; break;
case 'l': l[n]++; break;
case 'c': c[n]++; break;
}
}
}
int e = Integer.parseInt(readLn());
while ( e != 0 ) {
System.out.println(e+": "+i[e]+" i, "+v[e]+" v, "+x[e]+" x, "+l[e]+" l, "+c[e]+" c");
e = Integer.parseInt(readLn());
}
} | 8 |
private void hSplit() {
boolean keepReading = true;
int index;
while (keepReading) {
try {
String line = null;
Tuple t = null;
while ((line = input.getNextString()) != null) {
if (line.indexOf("END") == 0) {
keepReading = false;
}
else {
t = Tuple.makeTupleFromPipeData(line);
index = BMap.myhash(t.get(joinKey));
writeMap[index].putNextString(line);
}
}
}
catch (Exception e) {
}
}// end of while
//Notify that there are no more messages to send
for (WriteEnd wEnd : writeMap ) {
try{
wEnd.putNextString("END");
} catch(IOException e) {
ReportError.msg(this, e);
}
}
} | 6 |
private void updateStateExit(List<Keyword> keywords, List<String> terms) {
for (Keyword kw: keywords) {
for (DialogState d : kw.getReference()) {
if (d.getCurrentState() == Start.S_EXIT) {
Main.giveMain().setUserLoggedIn(false);
return;
}
}
}
} | 3 |
private float limit(float eq)
{
if (eq==BAND_NOT_PRESENT)
return eq;
if (eq > 1.0f)
return 1.0f;
if (eq < -1.0f)
return -1.0f;
return eq;
} | 3 |
public static int luma(int color)
{
int red = (color & RED_MASK) >> 16;
int green = (color & GREEN_MASK) >> 8;
int blue = (color & BLUE_MASK);
double y = 0.3*red + 0.59*green + 0.11*blue;
return (int)y;
} | 0 |
public static void main(String[] args) {
final A a = new A();
for (int i = 0; i < 3; i++) {
new Thread() {
@Override
public void run() {
while (true) {
a.get();
}
}
}.start();
}
for (int i = 0; i < 3; i++) {
new Thread() {
@Override
public void run() {
while (true) {
a.write();
}
}
}.start();
}
} | 4 |
public boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof ArrayType) {
ArrayType type = (ArrayType) o;
return type.elementType.equals(elementType);
}
return false;
} | 2 |
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_D) p1.stop();
if(e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) p2.stop();
} | 4 |
@Test
public void nullAndEmptyStringsAreIgnored_whenAdded() {
trie.add(null);
trie.add("");
//assertFalse(trie.contains(null));
assertFalse(trie.contains(""));
} | 0 |
public int getX() {
return x;
} | 0 |
public BufferedImage load(String path)
{
try
{
return ImageIO.read(getClass().getResource(path));
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
return null;
} | 1 |
private boolean startSprinkler(StartReason reason) {
if (DeviceStatus.humidityStatus >= 80 && reason != StartReason.MOTION) {
Log.log(reason.toString() + ": humidity too high, sprinkler not started", deviceName);
return false;
} else if (DeviceStatus.weatherStatus == DeviceStatus.WeatherStatus.HEAVY_RAIN || DeviceStatus.weatherStatus == DeviceStatus.WeatherStatus.LIGHT_RAIN) {
if (DeviceStatus.humidityStatus > 10) {
Log.log(reason.toString() + ": it's going to rain, sprinkler not started", deviceName);
return false;
} else {
Log.log("It's going to rain, but humidity is very low. Trying to start sprinkler.", deviceName);
}
}
if (DeviceStatus.sprinklerStatus == DeviceStatus.SprinklerStatus.OFF) {
DeviceStatus.sprinklerStatus = DeviceStatus.SprinklerStatus.ON;
try {
sprinkler.startSprinkler();
} catch (Exception e) {
Log.log("Exception occured during service usage: " + e, deviceName);
}
Log.log(reason.toString() + ": sprinkler started", deviceName);
return true;
} else if (DeviceStatus.sprinklerStatus == DeviceStatus.SprinklerStatus.ON) {
Log.log(reason.toString() + ": failed to start sprinkler: already on", deviceName);
} else {
Log.log(reason.toString() + ": failed to start sprinkler: no sprinkler registered", deviceName);
}
return false;
} | 8 |
private boolean isWord( String s ) {
return ( !"/".equals( s ) && !SPECIAL.contains( s ) && !SPACE
.contains( s ) );
} | 2 |
protected void processTextAreaBlocks(List<String> taBlocks) {
if(generateStatistics) {
for(String block : taBlocks) {
statistics.setPreservedSize(statistics.getPreservedSize() + block.length());
}
}
} | 2 |
public static URL loadResourceAsURL(String resourcePath) {
if(resourcePath.startsWith("/")){
return ResourceLoader.class.getResource(resourcePath);
}else{
System.err.println("A resource path must(!) begin with a \"/\"");
return null;
}
} | 1 |
public static String loadFromFile() throws IOException {
Map<String, UserEntity> map = new HashMap<String, UserEntity>();
String webRoot = Utils.getWebRoot();//this.getServletConfig().getServletContext().getRealPath("/");
File file = new File(webRoot + "account.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
StringBuffer content = new StringBuffer();
String[] data = null;
UserEntity user = null;
String[] dataTmp = null;
while ((line = reader.readLine()) != null) {
if (StringUtil.isBlank(line) || line.startsWith("#"))
continue;
content.append("\r\n" + line);
user = new UserEntity();
data = line.split("=");
user.setUsername(data[0]);
dataTmp = data[1].split(":");
user.setPassword(dataTmp[0]);
user.setEmail(dataTmp.length > 1 ? dataTmp[1] : user.getUsername());
// user.setStatus(dataTmp.length > 2 ? Byte.valueOf(dataTmp[2] ): null);
map.put(user.getUsername(), user);
}
Scheduler.setUsers(map);
return content.toString();
} | 4 |
public Set<Map.Entry<Float,Byte>> entrySet() {
return new AbstractSet<Map.Entry<Float,Byte>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TFloatByteMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TFloatByteMapDecorator.this.containsKey(k)
&& TFloatByteMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Float,Byte>> iterator() {
return new Iterator<Map.Entry<Float,Byte>>() {
private final TFloatByteIterator it = _map.iterator();
public Map.Entry<Float,Byte> next() {
it.advance();
float ik = it.key();
final Float key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
byte iv = it.value();
final Byte v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Float,Byte>() {
private Byte val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Float getKey() {
return key;
}
public Byte getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Byte setValue( Byte value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Float,Byte> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Float key = ( ( Map.Entry<Float,Byte> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Float, Byte>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TFloatByteMapDecorator.this.clear();
}
};
} | 8 |
public void resetAP(MapleClient c, byte stat) {
MapleCharacter player = c.getPlayer();
short amount = 0;
switch (stat) {
case 1: // STR
amount = (short) (player.getStat().getStr() - 4);
if ((player.getRemainingAp() + amount) > 32767) {
c.showMessage("Trying to get negative AP? you cannot have more than 32767 free AP. now go fap");
return;
}
player.getStat().setStr(4);
player.updateSingleStat(MapleStat.STR, 4);
break;
case 2: // DEX
amount = (short) (player.getStat().getDex() - 4);
if ((player.getRemainingAp() + amount) > 32767) {
c.showMessage("Trying to get negative AP? you cannot have more than 32767 free AP. now go fap");
return;
}
player.getStat().setDex(4);
player.updateSingleStat(MapleStat.DEX, 4);
break;
case 3: // INT
amount = (short) (player.getStat().getInt() - 4);
if ((player.getRemainingAp() + amount) > 32767) {
c.showMessage("Trying to get negative AP? you cannot have more than 32767 free AP. now go fap");
return;
}
player.getStat().setInt(4);
player.updateSingleStat(MapleStat.INT, 4);
break;
case 4: // LUK
amount = (short) (player.getStat().getLuk() - 4);
if ((player.getRemainingAp() + amount) > 32767) {
c.showMessage("Trying to get negative AP? you cannot have more than 32767 free AP. now go fap");
return;
}
player.getStat().setLuk(4);
player.updateSingleStat(MapleStat.LUK, 4);
break;
}
player.setRemainingAp(player.getRemainingAp() + amount);
player.updateSingleStat(MapleStat.AVAILABLEAP, player.getRemainingAp());
} | 8 |
@Override
public void onEnable() {
if (!beenEnabled) {
PluginManager pm = getServer().getPluginManager();
log.debug("Registering events:");
// The "UI", checks for hits against controller blocks
log.debug(" - BLOCK_DAMAGE");
pm.registerEvent(Event.Type.BLOCK_DAMAGE, blockListener, Event.Priority.Highest, this);
// Block protection/controller cleanup/block editing
log.debug(" - BLOCK_BREAK");
pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Event.Priority.Highest, this);
// Block editing
log.debug(" - BLOCK_PLACE");
pm.registerEvent(Event.Type.BLOCK_PLACE, blockListener, Event.Priority.Monitor, this);
// Block protection/fallback anti-dupe while editing
log.debug(" - BLOCK_PHYSICS");
pm.registerEvent(Event.Type.BLOCK_PHYSICS, blockListener, Event.Priority.Highest, this);
// Block protection
log.debug(" - BLOCK_FROMTO"); // TODO: Change this to LIQUID_DESTROY
pm.registerEvent(Event.Type.BLOCK_FROMTO, blockListener, Event.Priority.Highest, this);
log.debug("Scheduling tasks:");
// New hotness for anti-dupe while editing, more accurate than BLOCK_PHYSICS
log.debug(" - Anti-dupe/changed-block edit check");
if (getServer().getScheduler().scheduleSyncRepeatingTask(this, blockListener, 1, 1) == -1) {
log.warning("Scheduling BlockListener anti-dupe check failed, falling back to old BLOCK_PHYSICS event");
blockPhysicsEditCheck = true;
}
if (config.getBool(Option.DisableEditDupeProtection)) {
log.warning("Edit dupe protection has been disabled, you're on your own from here");
}
// New redstone check, the more natural check
if (!config.getBool(Option.QuickRedstoneCheck)) {
log.debug(" - Redstone check");
log.info("Enabling full redstone check");
if (getServer().getScheduler().scheduleSyncRepeatingTask(this, checkRunner, 1, 1) == -1) {
log.warning("Scheduling CBlockRedstoneCheck task failed, falling back to quick REDSTONE_CHANGE event");
config.setOpt(Option.QuickRedstoneCheck, true);
}
}
// Fallback/quick REDSTONE_CHANGE check
if (config.getBool(Option.QuickRedstoneCheck)) {
log.info("Enabling 'quick' redstone check - this mode of operation is depreciated and may be removed later");
pm.registerEvent(Event.Type.REDSTONE_CHANGE, blockListener, Event.Priority.Monitor, this);
}
if (getServer().getScheduler().scheduleSyncDelayedTask(this, this, 1) == -1) {
log.severe("Failed to schedule loadData, loading now, will probably not work with multiworld plugins");
loadData();
}
log.info("Events registered");
beenEnabled = true;
}
} | 7 |
private int buildJump(int xo, int maxLength) {
gaps++;
//jl: jump length
//js: the number of blocks that are available at either side for free
int js = random.nextInt(4) + 2;
int jl = random.nextInt(2) + 2;
int length = js * 2 + jl;
boolean hasStairs = random.nextInt(3) == 0;
int floor = height - 1 - random.nextInt(4);
//run for the from the start x position, for the whole length
for (int x = xo; x < xo + length; x++) {
if (x < xo + js || x > xo + length - js - 1) {
//run for all y's since we need to paint blocks upward
for (int y = 0; y < height; y++) { //paint ground up until the floor
if (y >= floor) {
setBlock(x, y, GROUND);
}
//if it is above ground, start making stairs of rocks
else if (hasStairs) { //LEFT SIDE
if (x < xo + js) { //we need to max it out and level because it wont
//paint ground correctly unless two bricks are side by side
if (y >= floor - (x - xo) + 1) {
setBlock(x, y, ROCK);
}
} else { //RIGHT SIDE
if (y >= floor - ((xo + length) - x) + 2) {
setBlock(x, y, ROCK);
}
}
}
}
}
}
return length;
} | 9 |
protected void computeInitialFeasibleSolution() {
for (int j = 0; j < dim; j++) {
labelByJob[j] = Double.POSITIVE_INFINITY;
}
for (int w = 0; w < dim; w++) {
for (int j = 0; j < dim; j++) {
if (costMatrix[w][j] < labelByJob[j]) {
labelByJob[j] = costMatrix[w][j];
}
}
}
} | 4 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.