method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
27161562-3f57-48c9-9196-3e4e79433b15 | 4 | public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java KnockKnockServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
} |
47e0b259-283c-4198-9d48-893dbd6c2e0b | 7 | public void update()
{
if (playing)
{
long time = System.currentTimeMillis();
if ( time - lastTime > frameDuration[currFrame] && finalFrame != 0)
{
currFrame++;
lastTime = time;
}
if (currFrame == finalFrame && loop)
{
currFrame = initialFrame;
}
else
if( (!loop) && (currFrame+1 >= finalFrame) )
{
currFrame = finalFrame - 1;
playing = false;
}
}
} |
5106f9a3-0ed3-4899-b1b0-355bbff5da9f | 7 | @Override
public List<Method> findMethodsCalled(String methodName, InputStream data) {
ArrayList<Method> listMethods = new ArrayList<>();
XMLInputFactory xmlif = XMLInputFactory.newInstance();
try {
XMLStreamReader xmlsr = xmlif.createXMLStreamReader(data);
SAXBuilder builder = new SAXBuilder();
int eventType;
while (xmlsr.hasNext()) {
eventType = xmlsr.next();
if (eventType != XMLEvent.START_ELEMENT
|| !xmlsr.getLocalName().matches("^function[_A-Za-z]*")) {
continue;
}
// some method found
// Build a DOM string
String builderDOMStructure = Util
.builDOMMethodStructureString(xmlsr);
// log.trace(builderDOMStructure);
// Build DOM Structure from string
InputStream inputStreamDOM = new ByteArrayInputStream(
builderDOMStructure.getBytes());
try {
Document document = (Document) builder
.build(inputStreamDOM);
Element rootNode = document.getRootElement();
// this is the right method ?
String name = rootNode.getChildText("name");
if (!name.equals(methodName)) {
builderDOMStructure = null;
continue;
}
// method found
// log.debug(name);
listMethods.add(Util.buildMethodFromDOM(rootNode));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (JDOMException e) {
throw new RuntimeException(e);
}
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return listMethods;
} |
527cbe9e-6dc1-4d34-9d19-a3d2ebc6a42c | 5 | protected int upgradeHP() {
if (upgrades == null) return 0 ;
int numUsed = 0 ;
for (int i = 0 ; i < upgrades.length ; i++) {
if (upgrades[i] != null && upgradeStates[i] != STATE_INSTALL) numUsed++ ;
}
if (numUsed == 0) return 0 ;
return (int) (baseIntegrity * UPGRADE_HP_BONUSES[numUsed]) ;
} |
98bf68e8-8330-4155-b392-79dd6fce5f66 | 2 | public static JSONArray fetchByNumber(final String token, final String objType, final Long number)
throws IOException {
String url = ApiProperties.get().getUrl() + objType + "/number/" + number;
String obj = fetchData(url).toString();
JSONObject jsonObject = new JSONObject(obj);
JSONArray results = new JSONArray();
if (jsonObject != null && jsonObject.has("result")) {
results.put(jsonObject.getJSONObject("result"));
}
return results;
} |
23833729-b1d0-425b-b019-9085e9c4adef | 2 | public
List<Class<? extends Data>> getAllDataTypesFromEntity( long someId ) {
//
return new ArrayList<Class<? extends Data>>(
_dataCenter.getDataCore().getEntity_Data_Table().get( someId ).keySet() );
} |
0b140b15-1e8f-4a4c-ae30-711d2b3a9604 | 9 | private static final Object number(CharacterIterator it,StringBuilder buf) {
int length = 0;
boolean isFloatingPoint = false;
buf.setLength(0);
char c = it.current();
if (c == '-') {
buf.append(c);
c = it.next();
}
length += addDigits(it,c,buf);
if (c == '.') {
buf.append(c);
c = it.next();
length += addDigits(it,c,buf);
isFloatingPoint = true;
}
if (c == 'e' || c == 'E') {
buf.append(c);
c = it.next();
if (c == '+' || c == '-') {
buf.append(c);
c = it.next();
}
addDigits(it,c,buf);
isFloatingPoint = true;
}
String s = buf.toString();
return isFloatingPoint
? (length < 17) ? (Object)Double.valueOf(s) : new BigDecimal(s)
: (length < 19) ? (Object)Long.valueOf(s) : new BigInteger(s);
} |
87419e82-338a-4705-8862-bfd1a2caa4fd | 7 | public final void initUI() {
amiListe = new JComboBox<UserProfile>(); //liste déroulante servant à stocker les amis.
panel = new JPanel(); //panel principal servant à stocker tous les autres éléments.
getContentPane().add(panel); //On le rajoute à la fenêtre.
/* Défini les caractéristiques du panel principal. */
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBackground(Color.WHITE);
/* Une zone de texte et un bouton pour ajouter un ami */
addFriend = new JTextField(40);
addFriend.setMaximumSize(new Dimension(Integer.MAX_VALUE, addFriend.getMinimumSize().height));
panel.add(addFriend);
JButton addButton = new JButton("Add");
addButton.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(addButton);
/* Une zone de texte et un bouton pour poster */
postText = new JTextField(40);
postText.setMaximumSize(new Dimension(Integer.MAX_VALUE, postText.getMinimumSize().height));
panel.add(postText);
JButton postButton = new JButton("Post");
JButton postImageButton = new JButton("Post an image.");
//Action associée au bouton add.
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
String infoFriend = addFriend.getText(); //on récupère le texte
addFriend.setText("");//on l'enlève
String[] infoFriendTrie = infoFriend.split(":");//on recupere l'adresse et le port.
//création du podLocation correspondant.
PodLocation friendLocation = new PodLocation(InetAddress.getByName(infoFriendTrie[0]),
Integer.parseInt(infoFriendTrie[1]));
//création du podLocation correspondant à mon adresse.
PodLocation myLocation = new PodLocation(InetAddress.getLocalHost(),pod.getListeningPort());
//on vérifie si l'adresse est valable.
if(pod.hasPendingFriend(friendLocation))
afficherErreur("Inivtation déjà envoyé (en attente de réponse).");
else if(pod.hasFriend(friendLocation))
afficherErreur("Ami déjà ajouté.");
else if(myLocation.equals(friendLocation))
afficherErreur("Vous ne pouvez pas vous ajoutez.");
else
pod.addPendingFriend(friendLocation);
}catch(Exception e){
//l'ajout n'a pas été demandé de la bonne façon
afficherErreur("Erreur ajout d'ami. \nUsage : w.x.y.z:p avec w.x.y.z adresse ip et p le port.");
}
}
});
//action associée au bouton post.
postButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String myMsg = postText.getText(); //on récupère le text
postText.setText("");
Message message = new Message(myMsg, new Date()); //on crée l'objet message correspondant.
pod.addMessage(message); //on le rajoute au pod.
JLabel label = new JLabel(myMsg); //on crée l'objet servant à le stocker dans l'interface.
me.add(label); //on l'affiche
panel.validate();
}
});
//action associée au bouton post image.
postImageButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser choix = new JFileChooser(); //on demande où se trouve l'image;
int retour=choix.showOpenDialog(panel); //code de retour
if(retour==JFileChooser.APPROVE_OPTION){ //si un fichier a été choisi
try {
JLabel imagePanel = new JLabel(); //on crée l'objet stockant l'image.
ImageIcon image = new ImageIcon(choix.getSelectedFile().getAbsolutePath()); //on crée l'image
imagePanel.setText(null);
imagePanel.setIcon(image);
me.add(imagePanel); //on rajoute l'image
panel.validate();
pod.addImage((new File(choix.getSelectedFile().getAbsolutePath())).toURI().toURL()); //on envoie l'image
}catch(Exception e){
e.printStackTrace();
}
}
}
});
postButton.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(postButton);
postImageButton.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(postImageButton);
/* Un panel horizontal pour les gens */
JPanel people = new JPanel();
panel.add(people);
people.setAlignmentX(Component.LEFT_ALIGNMENT);
/* Les personnes sont affichées de gauche à droite */
people.setLayout(new GridLayout(1,3));
/* Moi */
me = new JPanel();
me.setBackground(Color.WHITE);
me.setBorder(new LineBorder(Color.black));
/* Mes commentaires sont affichés de haut en bas */
me.setLayout(new BoxLayout(me, BoxLayout.Y_AXIS));
me.setAlignmentY(Component.TOP_ALIGNMENT);
JScrollPane meScroll = new JScrollPane(me);
people.add(meScroll);
me.add(new JLabel("Mes posts :"));
panel.validate();
/* Les ami */
them = new JPanel();
them.setBackground(Color.WHITE);
them.setBorder(new LineBorder(Color.black));
them.setLayout(new BoxLayout(them, BoxLayout.Y_AXIS));
them.setAlignmentY(Component.TOP_ALIGNMENT);
JScrollPane themScroll = new JScrollPane(them);
people.add(themScroll);
them.add(new JLabel("Les posts de mes amis :"));
panel.validate();
//la liste des amis
ami = new JPanel();
ami.setBackground(Color.WHITE);
ami.setBorder(new LineBorder(Color.black));
ami.setLayout(new BoxLayout(ami, BoxLayout.Y_AXIS));
ami.setAlignmentY(Component.TOP_ALIGNMENT);
JScrollPane amiScroll = new JScrollPane(ami);
people.add(amiScroll);
ami.add(new JLabel("Mes amis :"));
ami.add(amiListe);
JButton deleteButton = new JButton("Supprimer");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
UserProfile oldFriend = (UserProfile) amiListe.getSelectedItem(); //on récupère l'ami sélectionné dans la liste
pod.sendCommand(pod.getFriend(oldFriend.getUUID()).getLocation().getAddress(),
pod.getFriend(oldFriend.getUUID()).getLocation().getPort(),
"DEL",
pod.getOwner().toJSON()); //on envoie la commande "DEL"
pod.removeFriend(oldFriend.getUUID()); //on le retire du pod.
amiListe.removeItem(oldFriend); //on le retire de l'interface
afficherSuppression(oldFriend.getName(), false); //on indique la suppression.
} catch (JSONException e) {
afficherErreur("Erreur suppression d'ami.");
e.printStackTrace();
}
}
});
ami.add(deleteButton);
panel.validate();
/* Le reste de l'interface */
setTitle(pod.getOwner().getName());
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} |
58d85691-1e9f-4a07-9a65-3287f3fcf80e | 2 | public double calculateCommission()
{
this.commision = 0;
this.commision = this.speaker.getRate() * this.duration;
int dayOfWeek = this.getDayOfWeek(this.eventDate);
if(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY)
{
this.commision = this.commision * 1.25;
}
// add transportation fee of 500 kr
this.commision += 500;
return this.commision;
} |
bda25179-cce6-4831-9a85-5f9cdd90a649 | 2 | @Override
public String toString()
{
String g = G().V() + " vertices " + G().E() + " edges\n";
for (int v = 0; v < G().V(); v++)
{
g += name(v) + "(" + v + "): ";
for (int w : G().adj(v))
g += name(w) + "(" + w + "), ";
g += "\n";
}
return g;
} |
46307761-4c0c-436b-bd3e-6c146d24728e | 8 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
int isbn=Integer.parseInt(jTextField9.getText());
String title=jTextField10.getText();
int num=Integer.parseInt(jTextField23.getText());
ArrayList<String> fName=new ArrayList<String>();
fName.add(jTextField11.getText());
ArrayList<String> lName=new ArrayList<String>();
lName.add(jTextField12.getText());
ArrayList<Long> phone=new ArrayList<Long>();
phone.add(Long.parseLong(jTextField13.getText()));
ArrayList<String> street=new ArrayList<String>();
street.add(jTextField14.getText());
ArrayList<String> city=new ArrayList<String>();
city.add(jTextField15.getText());
ArrayList<String> state=new ArrayList<String>();
state.add(jTextField16.getText());
ArrayList<Integer> zip=new ArrayList<Integer>();
zip.add(Integer.parseInt(jTextField17.getText()));
if(jTextField18.getText().length()>0){
String names[]=jTextField18.getText().split(",");
String phones[]=jTextField19.getText().split(",");
String adds[]=jTextArea2.getText().split(";");
for(int it=0;it<names.length;it++){
fName.add(names[it].split(" ")[0]);
lName.add(names[it].split(" ")[1]);
phone.add(Long.parseLong(phones[it]));
String adLine[]=adds[it].split(",");
street.add(adLine[0]);
city.add(adLine[1]);
state.add(adLine[2]);
zip.add(Integer.parseInt(adLine[3]));
}
}
String authorsThis="";
List<Author> thisBookAuth=new ArrayList<Author>();
for(int p=0;p<fName.size();p++){
Author a=new Author(fName.get(p), lName.get(p), phone.get(p),jTextField24.getText(),jTextField25.getText()+" scholar");
String sep=(p==fName.size()-1)?"":",";
authorsThis+=(fName.get(p)+" "+lName.get(p)+sep);
a.setAddress(new Address(street.get(p), city.get(p), state.get(p), zip.get(p)));
thisBookAuth.add(a);
// add to file
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/data/authors.txt", true)))) {
out.println(fName.get(p)+";"+ lName.get(p)+";"+ phone.get(p)+";"+street.get(p)+";"+ city.get(p)+";"+ state.get(p)+";"+ zip.get(p)+";"+jTextField24.getText()+";"+jTextField25.getText()+" scholar");
}catch (IOException e) {
System.out.println("Data not written to file!");
}
}
auths.addAll(thisBookAuth);
Book newBok=new Book(title, isbn);
newBok.setAuthors(thisBookAuth);
books.add(newBok);
// add to file
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/data/books.txt", true)))) {
out.println(title+";"+isbn+";"+authorsThis);
}catch (IOException e) {
System.out.println("Data not written to file!");
}
for(int k=0;k<num;k++){
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/data/copies.txt", true)))) {
copies.add(new Copy(k, (Publication)newBok));
out.println(k+";"+title+";available");
}catch (IOException e) {
System.out.println("Data not written to file!");
}
}
dummy=title;
}//GEN-LAST:event_jButton2ActionPerformed |
4e83e763-1399-4c78-9ced-1d40b3c81bee | 9 | @Override
public Class<?> getColumnClass(int indiceColuna) {
switch (indiceColuna) {
case 0:
return String.class; //fornecedor
case 1:
return String.class; //job
case 2:
return String.class; //setor origem
case 3:
return String.class; //componente
case 4:
return Double.class; //Quantidade Rejeitado
case 5:
return Double.class; //Quantidade Rejeitado Lancado
case 6:
return String.class; //defeito
case 7:
return String.class; //rejeicao
default:
//Se a coluna especificada não existir é lançada uma exceção
throw new IndexOutOfBoundsException("A coluna com o índice:"+indiceColuna+" não existe!");
}
} |
f0cf29f8-5f5c-451d-8fdd-b1cb59b4396a | 0 | public TBShopFetcher(RequestWrapper requestWrapper) {
super(requestWrapper);
} |
f20f1d5f-3317-463c-8581-fe62016c8434 | 9 | public static List<Event> load(){
Connection conn = null;
Statement stat = null;
ResultSet result = null;
List<Event> list = new ArrayList<Event>();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gent?user=root&password=root");
stat = conn.createStatement();
result = stat.executeQuery("select name, create_time, flag from event;");
while(result.next()){
Event evt = new Event();
evt.setName(result.getString("name"));
evt.setFlag(result.getInt("flag"));
evt.setCreateTime(result.getDate("create_time"));
list.add(evt);
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(result != null){
try {
result.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = null;
}
if(stat != null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stat = null;
}
}
return list;
} |
8f0860bd-6716-4648-8704-775db08ad54b | 9 | public List<String> complete(final String prefix, final int count) {
// 1. Find the position of the prefix in the sorted set in Redis
if (null == prefix) {
return Collections.emptyList();
}
int prefixLength = prefix.length();
Long start = redis.zrank(redisKey, prefix);
if (start < 0 || prefixLength == 0) {
return Collections.emptyList();
}
List<String> results = new ArrayList<String>();
int found = 0, rangeLength = 50, maxNeeded = count;
while (found < maxNeeded) {
Set<String> rangeResults = redis.zrange(redisKey, start, start + rangeLength - 1);
start += rangeLength;
if (rangeResults.isEmpty()) {
break;
}
for (final String entry : rangeResults) {
int minLength = Math.min(entry.length(), prefixLength);
if (!entry.substring(0, minLength).equalsIgnoreCase(prefix.substring(0, minLength))) {
maxNeeded = results.size();
break;
}
if (entry.endsWith("*") && results.size() < maxNeeded) {
results.add(entry.substring(0, entry.length() - 2));
}
}
}
return results;
} |
52b2160b-60ca-4ed9-98a8-3cf4b38792a6 | 5 | private static <T extends Comparable<T>> void maxHeapify(T array[], int index, int heapSize){
int leftIndex = getLeftChildIndex(index);
int rightIndex = getRightChildIndex(index);
int largestIndex = index;
if(leftIndex <= heapSize && array[index].compareTo(array[leftIndex]) == -1)
largestIndex = leftIndex;
if(rightIndex <= heapSize && array[index].compareTo(array[rightIndex]) == -1)
largestIndex = rightIndex;
if(largestIndex != index){
CollectionsHelper.swapValues(array, largestIndex, index);
maxHeapify(array, largestIndex, heapSize);
}
} |
b61c8509-0bfe-4d4b-8ab6-ef7b5546bbb3 | 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 Designation)) {
return false;
}
Designation other = (Designation) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
08ba5351-f6e4-4de9-a0e2-e8bdb7c5cff8 | 8 | public void consume(final Throwable eMain)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Throwable e = getRootCause(eMain);
// Get the last bit of the Java console stdout
String outMsg = "";
if (stdoutDoc != null) {
try {
int nsave = 4000;
int docLen = stdoutDoc.getLength();
int start = docLen - nsave;
if (start < 0) start = 0;
outMsg = stdoutDoc.getText(start, docLen - start);
} catch(BadLocationException ee) {
}
}
// Get the stack trace
StringWriter ss = new StringWriter();
PrintWriter pw = new PrintWriter(ss);
pw.print(getNestedMessages(eMain));
e.printStackTrace(pw);
// URL url = null;
// try {
// url = app.getConfigResource("");
// } catch(Exception e2) {
// url = null;
// }
String msgText =
"Bug in: " + programName + " " + app.version() + "\n" +
"Version: " + app.version() + "\n" +
"User: " + System.getProperty("user.name") + "\n" +
"Config Name: " + app.config().getName() + "\n\n" +
// e.toString() + "\n" +
ss.getBuffer().toString() + "\n" +
"=================================================\n" +
outMsg + "\n";
System.out.println(ss.toString());
// System.err.println(msgText);
// Get other info
String userName = System.getProperty("user.name");
// Let user fiddle with the stack trace
boolean askUser = app.props().getProperty("mail.bugs.askuser").toLowerCase().equals("true");
askUser = askUser && !(e instanceof AppError);
final MailExpDialog dialog = new MailExpDialog(null, programName,
e, msgText, askUser,
app.swingPrefs(), app.guiRoot().node("MailExpDialog"));
dialog.setVisible(true);
if (e instanceof FatalAppError) System.exit(-1);
if (askUser && !dialog.isReportError()) return;
new Thread() {
public void run() {
try {
// Define message
MimeMessage msg = new MimeMessage(app.mailSender().getSession());
//msg.setFrom(new InternetAddress("[email protected]"));
msg.setSubject("Bug in " + programName);
msg.setText(dialog.getMsg());
msg.addRecipient(Message.RecipientType.TO, bugRecipient);
app.mailSender().sendMessage(msg);
} catch(Exception ee) {
System.out.println("Could not send bug report!!!");
ee.printStackTrace(System.out);
}
}}.start();
}});
} |
7c6e95a5-74be-4275-8069-8be3f3caa2b1 | 3 | public List getEntitiesWithinAABB(Class var1, AxisAlignedBB var2) {
int var3 = MathHelper.floor_double((var2.minX - 2.0D) / 16.0D);
int var4 = MathHelper.floor_double((var2.maxX + 2.0D) / 16.0D);
int var5 = MathHelper.floor_double((var2.minZ - 2.0D) / 16.0D);
int var6 = MathHelper.floor_double((var2.maxZ + 2.0D) / 16.0D);
ArrayList var7 = new ArrayList();
for (int var8 = var3; var8 <= var4; ++var8) {
for (int var9 = var5; var9 <= var6; ++var9) {
if (this.chunkExists(var8, var9)) {
this.getChunkFromChunkCoords(var8, var9).getEntitiesOfTypeWithinAAAB(var1, var2, var7);
}
}
}
return var7;
} |
83c2e0fe-d2ce-4128-988b-65cdbf39f4b1 | 4 | public void insert(BinaryTreeNode n) {
BinaryTreeNode runner = this.root;
BinaryTreeNode parentPostion = null;
while (runner != null) {
parentPostion = runner;
if (n.compareTo(runner) <= 0) {
runner = runner.left;
} else {
runner = runner.right;
}
}
n.parent = parentPostion;
if (parentPostion == null) {
this.root = n;
} else if (n.compareTo(parentPostion) <= 0) {
parentPostion.left = n;
} else {
parentPostion.right = n;
}
} |
5e6e4e24-4d89-414d-96ce-24fb6e245821 | 7 | private boolean load() {
boolean returnval = true;
try {
if (locFile.exists() & locFile.canRead()) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(locFile), Charset.forName("UTF-8")));
String line;
data.clear();
data = new HashMap<String, String>();
while ((line = br.readLine()) != null) {
String[] kv = line.split(":", 2);
while(kv[1].startsWith(" ")) {
kv[1] = kv[1].substring(1);
}
data.put(kv[0], kv[1].replaceAll("(&([a-f0-9]))", "\u00A7$2"));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Localization.class.getName()).log(Level.SEVERE, null, ex);
returnval = false;
} catch (IOException ex) {
Logger.getLogger(Localization.class.getName()).log(Level.SEVERE, null, ex);
returnval = false;
} finally {
try {
br.close();
} catch (Exception e) {
}
}
} else {
RealWeather.log("Locale file " + lang + ".lang is not accessible!");
returnval = false;
}
} catch (Exception e) {
RealWeather.log.log(Level.SEVERE, null, e);
RealWeather.sendStackReport(e);
returnval = false;
}
return returnval;
} |
811bdc27-3c0f-4bb4-8dc7-8c049e34555d | 4 | public boolean collisionCheck(int posX, int posY) {
if(posX > this.posX && this.posX+width > posX && posY > this.posY && this.posY+height > posY) {
return true;
}else {
return false;
}
} |
6859683b-14f8-4325-b2dc-8fcfeef2f0c5 | 6 | @SuppressWarnings("unchecked")
public static List<Card> deSerialiseCards(){
List<Card> deser_members = null;
try {
FileInputStream input_file = new FileInputStream("cards.ser");
ObjectInputStream input = new ObjectInputStream(input_file);
deser_members = (List<Card>) input.readObject();
input.close();
} catch (FileNotFoundException e) {
int chouse = JOptionPane.showConfirmDialog(null, e.getMessage()+" Ошибка: Не найден десереализуемый файл, создать?");
if(chouse==0){
try {
new File("cards.ser").createNewFile();
cards.add(new Card(0, "null", "null", false));
serialiseCards();
JOptionPane.showMessageDialog(null, "Перезапустите программу");
System.exit(0);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, e.getMessage()+" Критическая ошибка, невозможно создать файл");
}
}
} catch (IOException e) {
int chouse = JOptionPane.showConfirmDialog(null, e.getMessage()+" Ошибка: Файл невозможно десереализовать, сбросить файл?");
if(chouse==0){
cards.add(new Card(0, "null", "null", false));
serialiseCards();
}
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage()+" Критическая Ошибка: Певрежедены файлы программы");
}
return deser_members;
} |
32feb27a-49ec-4b78-a520-5182aa1dc8b6 | 1 | private boolean jj_2_20(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_20(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(19, xla); }
} |
3d8a922e-2fd4-4edb-9850-7218dbfd2c49 | 4 | private Node parseDecision() {
Decision result = new Decision(this);
Expression expr = new Expression(this);
result.append(expr);
while (offset < input.length()) {
char c = input.charAt(offset);
if (c == ')') {
offset++;
break;
}
else if (c == '|') {
offset++;
expr = new Expression(this);
result.append(expr);
}
else {
Node node = decide();
if (node != null) {
expr.append(node);
}
}
}
parseQuantifier(result);
return result;
} |
a85fab3a-9491-4bb1-8f2a-bfaa7115c065 | 4 | public int setLoyalty(String playerName, double loyalty) {
String SQL = "UPDATE " + tblSkills + " SET " + "`leadership` = ? WHERE `player` LIKE ? ;";
int updateSuccessful = 0;
Connection con = getSQLConnection();
PreparedStatement statement = null;
try {
statement = con.prepareStatement(SQL);
statement.setDouble(1, loyalty);
statement.setString(2, playerName);
updateSuccessful = statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if (updateSuccessful == 0) {
SQL = "INSERT INTO " + tblSkills + " (`id` ,`player` ,`leadership` ,`loyalty`) VALUES (NULL , ?, NULL, ?);";
try {
statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
statement.setDouble(2, loyalty);
updateSuccessful = statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
statement.close();
con.close();
} catch (SQLException e) {
}
loyaltyCache.put(playerName, loyalty);
return updateSuccessful;
} |
9af9c90d-8845-48aa-af01-b2b18c652d1f | 2 | public void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture.id);
glTranslatef(1*HouseGenerator.tWidth*globalWidth2*0.5f, 0f, 1*HouseGenerator.tDepth*globalHeight2*0.5f);
glRotatef(-1, 0, 1, 0);
glTranslatef(-1*HouseGenerator.tWidth*globalWidth2*0.5f, 0f, -1*HouseGenerator.tDepth*globalHeight2*0.5f);
System.out.println("X " + globalX + " Y " + globalY);
//System.out.println(globalWidth2);
//glTranslatef(-1*HouseGenerator.tWidth*globalWidth2, 0, -1*HouseGenerator.tDepth*globalHeight2);
//globalX += -1*HouseGenerator.tWidth*globalWidth2;
//globalY += -1*HouseGenerator.tDepth*globalHeight2;
//System.out.println(vboVertexIDs.length);
for (int i = 0; i < vboVertexIDs.length; i++)
{
glTranslatef(HouseGenerator.tWidth, 0, 0);
//glTranslatef(0, 0, HouseGenerator.depthS);
//glTranslatef(HouseGenerator.widthS, 0, HouseGenerator.depthS);
globalX += HouseGenerator.tWidth;
int vboVertexID = vboVertexIDs[i];
int vertCount = vertCounts[i];
glBindBuffer(GL_ARRAY_BUFFER, vboVertexID);
glVertexPointer(3, GL_FLOAT, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, vboTexID);
glTexCoordPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawArrays(GL_QUADS, 0, vertCount);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if((i+1) % globalWidth2 == 0)
{
//System.out.println("X " + globalX + " Y " + globalY);
glTranslatef(-1*HouseGenerator.tWidth*(globalWidth2), 0, HouseGenerator.tDepth);
globalX += -1*HouseGenerator.tWidth*(globalWidth2);
globalY += HouseGenerator.tDepth;
//System.out.println(i);
//System.out.println("X " + globalX + " Y " + globalY);
}
//System.out.println("X " + globalX + " Y " + globalY);
}
glTranslatef(0, 0, -1*HouseGenerator.tDepth*(globalHeight2));
globalY += -1*HouseGenerator.tDepth*(globalHeight2);
Util.checkGLError();
} |
6068a589-3ba5-4f75-b83d-1058035da5a2 | 7 | public int method544(int i, float f)
{
if(i == 0)
{
float f1 = (float)anIntArray668[0] + (float)(anIntArray668[1] - anIntArray668[0]) * f;
f1 *= 0.003051758F;
aFloat671 = (float)Math.pow(0.10000000000000001D, f1 / 20F);
anInt672 = (int)(aFloat671 * 65536F);
}
if(anIntArray665[i] == 0)
return 0;
float f2 = method541(i, 0, f);
aFloatArrayArray669[i][0] = -2F * f2 * (float)Math.cos(method543(f, 0, i));
aFloatArrayArray669[i][1] = f2 * f2;
for(int k = 1; k < anIntArray665[i]; k++)
{
float f3 = method541(i, k, f);
float f4 = -2F * f3 * (float)Math.cos(method543(f, k, i));
float f5 = f3 * f3;
aFloatArrayArray669[i][k * 2 + 1] = aFloatArrayArray669[i][k * 2 - 1] * f5;
aFloatArrayArray669[i][k * 2] = aFloatArrayArray669[i][k * 2 - 1] * f4 + aFloatArrayArray669[i][k * 2 - 2] * f5;
for(int j1 = k * 2 - 1; j1 >= 2; j1--)
aFloatArrayArray669[i][j1] += aFloatArrayArray669[i][j1 - 1] * f4 + aFloatArrayArray669[i][j1 - 2] * f5;
aFloatArrayArray669[i][1] += aFloatArrayArray669[i][0] * f4 + f5;
aFloatArrayArray669[i][0] += f4;
}
if(i == 0)
{
for(int l = 0; l < anIntArray665[0] * 2; l++)
aFloatArrayArray669[0][l] *= aFloat671;
}
for(int i1 = 0; i1 < anIntArray665[i] * 2; i1++)
anIntArrayArray670[i][i1] = (int)(aFloatArrayArray669[i][i1] * 65536F);
return anIntArray665[i] * 2;
} |
84cf80a5-4708-4c16-a900-ec0c3ece7c59 | 7 | public static IMac getInstance(String name) {
if (name == null) {
return null;
}
name = name.trim();
name = name.toLowerCase();
if (name.startsWith(HMAC_NAME_PREFIX)) {
return HMacFactory.getInstance(name);
}
IMac result = null;
if (name.equalsIgnoreCase(UHASH32)) {
result = new UHash32();
} else if (name.equalsIgnoreCase(UMAC32)) {
result = new UMac32();
} else if (name.equalsIgnoreCase(TMMH16)) {
result = new TMMH16();
}
// else if (name.equalsIgnoreCase(TMMH32)) {
// result = new TMMH32();
// }
if (result != null && !result.selfTest()) {
throw new InternalError(result.name());
}
return result;
} |
4c08af21-584b-4a5a-88f3-99f84057edcc | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
SpanTermQuery other = (SpanTermQuery) obj;
if (term == null) {
if (other.term != null)
return false;
} else if (!term.equals(other.term))
return false;
return true;
} |
097c153d-58c1-4c38-a09f-c96601000e2a | 4 | public static void main(String args[]) throws Exception {
try {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("Attemping to connect to " + IPAddress +
") via UDP port 9876");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.print("Enter Message: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
System.out.println ("Sending data to " + sendData.length +
" bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From server at: " + returnIPAddress +
":" + port);
System.out.println("Message: " + modifiedSentence);
}
catch (SocketTimeoutException ste) {
System.out.println ("Timeout Occurred: Packet assumed lost");
}
clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
} |
df957d1f-7fc8-4a8e-8d36-65caf5c70ef8 | 3 | @Override
public void deserialize(Buffer buf) {
cellId = buf.readShort();
if (cellId < 0 || cellId > 559)
throw new RuntimeException("Forbidden value on cellId = " + cellId + ", it doesn't respect the following condition : cellId < 0 || cellId > 559");
objectGID = buf.readShort();
if (objectGID < 0)
throw new RuntimeException("Forbidden value on objectGID = " + objectGID + ", it doesn't respect the following condition : objectGID < 0");
} |
6f259fe4-15f4-4be4-a36b-4d9ab2fa673f | 7 | protected void generateMoves(List<Movement> movesList, Piece piece)
{
/************** GENERACIÓN DE LOS MOVIMIENTOS *************/
bbPieceOccupation = bbPiecesOccupation[piece.index];
numPieces = Long.bitCount(bbPieceOccupation);
for(int i = 0; i < numPieces; i++)
{
pieceSquareIndex = Long.numberOfTrailingZeros(bbPieceOccupation);
//Se obtienen las casillas que ataca la pieza
bbAttacked = bbAttackedFromSquare[pieceSquareIndex];
bbAttacked &= ~bbTurnOccupied;
//Se comprueba si hay conexión entre la casilla del rey y la casilla de la pieza
//Si no la hay se generan los movimientos de forma normal
bbConnection = bbInclusiveConnection[pieceSquareIndex][kingSquareIndex];
if(bbConnection != 0)
{
//Si hay conexión, se comprueba si hay alguna pieza en las casillas
//que unen la casilla del rey y la casilla de la pieza
//Si sí que hay alguna pieza se generan los movimientos de la pieza de forma normal
bbConnection = bbExclusiveConnection[pieceSquareIndex][kingSquareIndex];
if((bbConnection & bbOccupation) == 0)
{
//Si no hay casillas se comprueba si hay alguna pieza de ataque de largo alcance
//que ataque a la pieza en la misma línea que el rey y la pieza
//Si no hay ninguna se generan los movimientos de la pieza de forma normal
bbAttacker = bbFullConnection[pieceSquareIndex][kingSquareIndex] &
bbAttackerToSquare[pieceSquareIndex] & bbOppositeOccupied;
if(bbAttacker != 0)
{
genericPiece = pieceInSquare[Long.numberOfTrailingZeros(bbAttacker)].genericPiece;
if(genericPiece != GenericPiece.PAWN && genericPiece != GenericPiece.KING)
{
//Si hay alguna pieza atacando en esa línea quiere decir que la pieza
//sólo se podrá mover a las casillas entre la pieza clavada y el rey y las
//que se encuentran entre la pieza clavada y la pieza que provoca la clavada
bbConnection = bbExclusiveConnection[pieceSquareIndex][Long.numberOfTrailingZeros(bbAttacker)] | bbAttacker;
bbConnection |= bbExclusiveConnection[pieceSquareIndex][kingSquareIndex];
bbAttacked = bbAttacked & bbConnection;
}
}
}
}
//En este momento en bitboardAtacadas se encuentran las casillas a las que legarmente puede ir
//la dama
numAttacked = Long.bitCount(bbAttacked);
for(int j = 0; j < numAttacked; j++)
{
attackedSquareIndex = Long.numberOfTrailingZeros(bbAttacked);
capture = pieceInSquare[attackedSquareIndex];
mov = new Movement(square[pieceSquareIndex], square[attackedSquareIndex], piece, capture);
movesList.add(mov);
bbAttacked ^= bbSquare[attackedSquareIndex];
}
bbPieceOccupation ^= bbSquare[pieceSquareIndex];
}
/************** FIN DE GENERACIÓN DE LOS MOVIMIENTOS *************/
} |
282dcd3f-f667-4e76-8475-8f08a1659310 | 5 | public static int[] computeBuying(int[] arr) {
int[] results = { -1, -1, -1 };
// error check - only one data point
if (arr.length == 1) {
results[0] = results[1] = results[2] = 0;
return results;
}
int min = 0;
int max = 0;
int prof = 0;
int tempMin = 0;
int tempMax = 0;
int tempProf = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[i - 1]) {
tempMax = i;
tempProf = arr[tempMax] - arr[tempMin];
} else if (arr[i] < arr[i - 1]) {
tempMin = i;
tempMax = i;
}
if (tempProf > prof) {
max = tempMax;
min = tempMin;
prof = tempProf;
}
}
results[0] = min;
results[1] = max;
results[2] = prof;
return results;
} |
6c1d8229-0abc-46c0-9ac0-d3f890e63cd1 | 5 | public Map<Integer, Integer> getGeneSpans(String text) {
Map<Integer, Integer> begin2end = new HashMap<Integer, Integer>();
Annotation document = new Annotation(text);
pipeline.annotate(document);
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
List<CoreLabel> candidate = new ArrayList<CoreLabel>();
for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
String pos = token.get(PartOfSpeechAnnotation.class);
if (pos.startsWith("NN")) {
candidate.add(token);
} else if (candidate.size() > 0) {
int begin = candidate.get(0).beginPosition();
int end = candidate.get(candidate.size() - 1).endPosition();
begin2end.put(begin, end);
candidate.clear();
}
}
if (candidate.size() > 0) {
int begin = candidate.get(0).beginPosition();
int end = candidate.get(candidate.size() - 1).endPosition();
begin2end.put(begin, end);
candidate.clear();
}
}
return begin2end;
} |
828fc2fc-e6be-49cc-b105-ce8515141a56 | 3 | public TrainListFrame(Title myTitle, TrainSchedule TS, String filePath) throws IOException {
setBackground(new Color(173, 216, 230));
setLayout(null);
JButton btnUpload = new JButton("Upload another schedule");
btnUpload.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
myTitle.setContentPane(BrowseFrame.previousBrowseContent);
myTitle.invalidate();
myTitle.validate();
BrowseFrame.txtBrowse.setText("Browse...");
}
});
btnUpload.setBounds(987, 597, 214, 64);
add(btnUpload);
JButton btnQuit = new JButton("Quit");
btnQuit.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
System.exit(0);
}
});
btnQuit.setBounds(81, 597, 141, 64);
add(btnQuit);
//===================================== THIS TAKES THE OUTPUT FROM THE DISPLAY =========================================================
TS.upload(filePath);
JTable lblTableOfTrains = TS.display();
JScrollPane scrollPane = new JScrollPane(lblTableOfTrains);
lblTableOfTrains.addMouseListener(new MouseAdapter() {
@Override
//===================================== TAKE WHICH TRAIN IS SELECTED, "SEND" THIS TO THE SELECT METHOD =============================
public void mouseClicked(MouseEvent e) {
int[] selected = lblTableOfTrains.getSelectedRows();
for(int i = 0; i < selected.length; i++){
selectedTrain = (String) lblTableOfTrains.getValueAt(selected[i], i);
}
try {
ClickedTrainListFrame lblTrainClicked = new ClickedTrainListFrame(myTitle, TS, selectedTrain);
previousTrainListContent = (JPanel) myTitle.getContentPane();
myTitle.setContentPane(lblTrainClicked);
myTitle.invalidate();
myTitle.validate();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
scrollPane.setBounds(81, 73, 1120, 513);
add(scrollPane, BorderLayout.CENTER);
txtSearch = new JTextField();
txtSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchTerm = txtSearch.getText();
try {
SearchedTrainListFrame txtSearched = new SearchedTrainListFrame(myTitle, TS, searchTerm);
previousTrainListContent = (JPanel) myTitle.getContentPane();
myTitle.setContentPane(txtSearched);
myTitle.invalidate();
myTitle.validate();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
txtSearch.setText("Search...");
txtSearch.setBounds(1115, 42, 86, 20);
add(txtSearch);
txtSearch.setColumns(10);
//This label takes which schedule was uploaded.
JLabel lblSelectedTrain = new JLabel(filePath);
lblSelectedTrain.setBounds(81, 16, 400, 64);
add(lblSelectedTrain);
//fit text to label
Font labelFont = lblSelectedTrain.getFont();
String labelText = lblSelectedTrain.getText();
int stringWidth = lblSelectedTrain.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = lblSelectedTrain.getWidth();
// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;
int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = lblSelectedTrain.getHeight();
// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);
// Set the label's font size to the newly determined size.
lblSelectedTrain.setFont(new Font("Lucida Grande", lblSelectedTrain.getFont().getStyle(), lblSelectedTrain.getFont().getSize() + 10));
} |
16fb17c2-3742-44ab-b9f7-3242579f49d8 | 9 | private static <T extends Comparable<T>, E> void printNodeInternal(List<Node<T,E>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
printWhitespaces(firstSpaces);
List<Node<T,E>> newNodes = new ArrayList<Node<T,E>>();
for (Node<T,E> node : nodes) {
if (node != null) {
System.out.print(node.getValue());
newNodes.add(node.getLeftNode());
newNodes.add(node.getRightNode());
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).getLeftNode() != null)
System.out.print("/");
else
printWhitespaces(1);
printWhitespaces(i + i - 1);
if (nodes.get(j).getRightNode() != null)
System.out.print("\\");
else
printWhitespaces(1);
printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
} |
b4d3cac0-a825-4f64-83a1-f9db8c4bf029 | 9 | public void testNeighbourshipSimple() {
// the middle segment ("segmentB") has whether "segmentA" or "segmentC"
// as its left or right neighbour (depending on orientation):
assertTrue((segmentB.getNeighbour(0) == segmentA && segmentB
.getNeighbour(1) == segmentC)
|| (segmentB.getNeighbour(0) == segmentC && segmentB
.getNeighbour(1) == segmentA));
assertTrue((segmentA.getNeighbour(0) == segmentB && segmentA
.getNeighbour(1) == null)
|| (segmentA.getNeighbour(1) == segmentB && segmentA
.getNeighbour(0) == null));
assertTrue((segmentC.getNeighbour(0) == segmentB && segmentC
.getNeighbour(1) == null)
|| (segmentC.getNeighbour(1) == segmentB && segmentC
.getNeighbour(0) == null));
} |
8e7d92c2-c714-47cd-954a-8bce15dd6524 | 6 | private int handleJumpBankRelative(int address, int jumpAddress, CPUState s, int jumpType, boolean reachable) {
if(jumpAddress < 0x4000) // home bank jump
return handleJumpFull(address,jumpAddress,s, jumpType, reachable);
else if(jumpAddress >= 0x8000) // non-ROM jump
System.out.println("jump to non-ROM address "+Integer.toHexString(jumpAddress)+" at "+Integer.toHexString(address));
else {
int bank = address / 0x4000; // test for intra-bank jump
if(s.loadedBank != -1) {
if(bank > 0 && bank != s.loadedBank)
System.err.println("ERROR: loadedBank "+Integer.toHexString(s.loadedBank)+" does not match address bank "+Integer.toHexString(bank)+" at "+Integer.toHexString(address));
else
bank = s.loadedBank;
}
if(bank > 0)
return handleJumpFull(address, jumpAddress+(bank-1)*0x4000, s, jumpType, reachable);
else
System.out.println("cannot determine ROM bank for jump address "+Integer.toHexString(jumpAddress)+" at "+Integer.toHexString(address));
}
return -1;
} |
51cbe6bb-74e4-458d-b2b5-36295b48deaf | 2 | public boolean isMt() {
String iduc = id.toUpperCase();
return iduc.equals("M") //
|| iduc.startsWith("MT") //
|| (iduc.indexOf("MITO") >= 0) //
;
} |
d0ee8231-8226-4990-b188-0760cef4c686 | 6 | public void printAllCombinationNonRecur(String number){
int[] answer=new int[number.length()];
for(int i=0;i<answer.length;i++){
answer[i]=0;
}
while(true){
for(int i=0;i<number.length();i++){
System.out.print(mapping[Integer.parseInt(number.substring(i,i+1))].charAt(answer[i]));
}
System.out.println();
int k=number.length()-1;
while(k>=0){
if(answer[k]<mapping[Integer.parseInt(number.substring(k,k+1))].length()-1){
answer[k]++;
break;
}else{
answer[k]=0;
k--;
}
}
if(k<0) break;
}
} |
3a3d2734-a64f-4af8-98ee-f4444717cc61 | 4 | public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
init(args);
} |
ad027d68-dc19-442f-aaae-62f60e753372 | 8 | public MOB getJudgeIfHere(MOB mob, MOB target, Room R)
{
LegalBehavior B=null;
if(R!=null)
B=CMLib.law().getLegalBehavior(R);
final Area legalA=CMLib.law().getLegalObject(R);
if((B!=null)&&(R!=null))
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M!=null)&&(M!=mob)&&(M!=target)&&(B.isJudge(legalA,M)))
return M;
}
return null;
} |
40c30ba5-593f-4ede-b4b0-bb1a4c7ec1fa | 5 | public TreeSet<Assign> extractBest(int num, TreeSet<Assign> used) {
// Sanity check
assert num <= numLectures : "Attempting to extract more assignments than possible";
HashMap<String, Assign> fixedAssignments = (HashMap<String, Assign>)environment.getFixedAssignments();
TreeSet<Assign> bestAssignments = new TreeSet<Assign>();
// We want to start with the first assignment, i.e. the best one
for (int count = 0, index = 0; count < num && index < numLectures; ++ count) {
Assign best = rankedAssignments.get(index);
// Make sure we're not grabbing a fixed assignment or an assignment for a lecture which has already been assigned, and also that we don't go out of bounds
while (fixedAssignments.values().contains(best) && used.contains(best) && index < numLectures) {
best = rankedAssignments.get(index);
++index;
}
// System.out.println("Adding " + best.getName() + "," + best.getSession().getName());
// Add the assignment to our set
bestAssignments.add(best);
// Increment our index
++index;
}
return bestAssignments;
} |
80c5d6d8-f8eb-4da6-bd1e-b2b5cf98b7a5 | 7 | private void initSegments(double With,double Height,double radius) {
SegmentModel bsegments = new SegmentModel(base.getInterpolated(With,Height,radius));
segments = new SegmentModel[n];
double angle = 2*Math.PI/n;
for (int i = 0; i<segments.length;i++){
segments[i] = SegmentModel.RotateSegmentByX(bsegments,angle*i);
segments[i].color = this.color;
}
circles = new SegmentModel[m+1];
SegmentModel sm;
double step = (double)(bsegments.points.length)/m;
for (int i = 0; i<circles.length; i++){
sm = new SegmentModel();
sm.points = new Point3D[(segments.length + 1)*k];
circles[i] = sm;
sm.color = this.color;
}
Point3D origin;
ArrayList<Point3D> origins = new ArrayList<Point3D>();
double cirStep = 2*Math.PI/circles[0].points.length;
for (int i = 0; i<circles.length;i++){
// origin = new Point3D(segments[0].points[(int)Math.round(step*i)]);
for (int j = 0; j<segments.length;j++){
if(step*i<segments[j].points.length) origin = segments[j].points[(int)Math.round(step*i)];
else origin = segments[j].points[segments[j].points.length-1];
origins.add(origin);
for (int z = 0; z<=k*2-1;z++){
circles[i].points[k*j + z] = MatrixArifmetikModel.RotateByX(origin,angle/k*z);
}
// circles[i].points[j] = MatrixArifmetikModel.RotateByX(origin,cirStep*j);
}
}
TriangleContainer tc;
double[] kd = new double[3];
kd[0] = 300.1;
kd[1] = 300.1;
kd[2] = 300.1;
for (int i = 0; i<origins.size() - segments.length-1;i++){
tc = new TriangleContainer();
tc.leftAnglePoint = origins.get(i);
tc.rightAnglePoint =origins.get(i+segments.length);
tc.topAnglePoint = origins.get(i+segments.length+1);
tc.Kd = kd;
tc.Kf = kd;
tc.currentTriangleColor = new Color(125,125,125);
triangleContainer.add(tc);
tc = new TriangleContainer();
tc.leftAnglePoint = origins.get(i);
tc.rightAnglePoint = origins.get(i+1);
tc.topAnglePoint = origins.get(i+segments.length+1);
tc.Kd = kd;
tc.Kf = kd;
tc.currentTriangleColor = new Color(125,125,125);
triangleContainer.add(tc);
}
// for(int i = 0; i<circles.length; i++){
// for (int j = 0; j<circles[i].points.length; j++){
// if(i<circles.length-1){
// if(j != circles[i].points.length-1) circles[i].points[j] = segments[j].points[(int)Math.round(step*i)];
// else circles[i].points[j] = circles[i].points[0];
// }else {
// if(j != circles[i].points.length-1) circles[i].points[j] = segments[j].points[bsegments.points.length-1];
// else circles[i].points[j] = circles[i].points[0];
// }
//
// }
// }
} |
3e0b852b-2e5c-4be1-b610-27e4a789e1a6 | 9 | @Override public void paint( Graphics g ) {
if( hdrImage == null ) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
} else {
int scale = 2;
while( hdrImage.getWidth()*scale <= getWidth() && hdrImage.getHeight()*scale <= getHeight() ) {
++scale;
}
--scale;
int left = (getWidth() - hdrImage.getWidth() *scale) / 2;
int top = (getHeight() - hdrImage.getHeight()*scale) / 2;
int right = hdrImage.getWidth() *scale + left;
int bottom= hdrImage.getHeight()*scale + top ;
g.setColor(Color.BLACK);
g.fillRect(0, 0, left, getHeight());
g.fillRect(right, 0, getWidth()-right, getHeight());
g.fillRect(left, 0, right - left, top);
g.fillRect(left, bottom, right - left, getHeight() - bottom);
g.drawImage(bImg, left, top, left+hdrImage.getWidth()*scale, top+hdrImage.getHeight()*scale, 0, 0, hdrImage.getWidth(), hdrImage.getHeight(), null);
}
int line = 1;
if( overlayTextMode >= 1 ) {
g.setColor(Color.WHITE);
g.drawString(String.format("Exposure: %12.4f", exposure), 4, 16*line++ );
g.drawString(String.format("Gamma: %12.4f", gamma ), 4, 16*line++ );
g.drawString("Dithering: " +(dither ? "enabled" : "disabled"), 4, 16*line++ );
if( extraStatusLines.length > 0 ) {
++line;
for( String text : extraStatusLines ) {
g.drawString(text, 4, 16*line++ );
}
}
}
if( overlayTextMode == 1 ) {
g.drawString("Hit F1 for help", 4, 16*line++ );
}
if( overlayTextMode >= 2 ) {
++line;
g.drawString("Keys:", 4, 16*line++);
g.drawString(" F1 - toggle overlay text", 4, 16*line++);
g.drawString(" X - export image", 4, 16*line++);
g.drawString(" E - change exposure", 4, 16*line++);
g.drawString(" G - change gamma", 4, 16*line++);
g.drawString("Hold shift to decrease exposure/gamma", 4, 16*line++);
g.drawString("Hold control to change values more slowly", 4, 16*line++);
}
} |
7ef98fb9-dfd8-44ba-89b2-96771b263c4f | 9 | private Point getTargetBlock(Point cur){
int cnt = 0;
if (this.maze[cur.x][cur.y + 1] == false) {cnt++;}
if (this.maze[cur.x][cur.y - 1] == false) {cnt++;}
if (this.maze[cur.x + 1][cur.y] == false) {cnt++;}
if (this.maze[cur.x - 1][cur.y] == false) {cnt++;}
if (cnt == 1) {
if (this.maze[cur.x][cur.y + 1] == false) {return new Point(cur.x, cur.y - 1);}
if (this.maze[cur.x][cur.y - 1] == false) {return new Point(cur.x, cur.y + 1);}
if (this.maze[cur.x + 1][cur.y] == false) {return new Point(cur.x - 1, cur.y);}
if (this.maze[cur.x - 1][cur.y] == false) {return new Point(cur.x + 1, cur.y);}
}
return null;
} |
510b429d-f030-4288-80f1-bf4cb157b5f9 | 6 | 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(RegistrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegistrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegistrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegistrarUsuario.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 RegistrarUsuario().setVisible(true);
}
});
} |
8785998d-aed5-41fd-8d47-3a02528e4a0a | 0 | public static void main(String[] args) throws ClassNotFoundException, IOException {
Worm w1 = new Worm(6, 'a');
System.out.println("w1 = " + w1);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("worm.out"));
out.writeObject("Worm storage\n");
out.writeObject(w1);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("worm.out"));
String s = (String)in.readObject();
Worm w2 = (Worm)in.readObject();
System.out.println(s + "w2 = " + w2);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out2 = new ObjectOutputStream(bout);
out2.writeObject("Object Worm in Memory\n");
out2.writeObject(w1);
out2.flush();
ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
s = (String)in2.readObject();
Worm w3 = (Worm)in2.readObject();
System.out.println(s + "w3 = " + w3);
} |
0f73bc77-d3e4-4a71-82a5-599c8fa1f44a | 0 | private boolean _hasBeenModified() {
File config_file = new File(ConfigurationManager.config_file_path);
Long this_time = config_file.lastModified();
return (this_time > this.read_time);
} |
eee1ec04-fa83-4387-bdae-df32588d90f8 | 1 | public static void sort(int[] array, int start, int end) {
if(start >= end) {
return;
}
int i = sortUtil(array, start, end);
sort(array, start, i - 1);
sort(array, i + 1, end);
} |
784b9706-4e74-498f-8baa-cbdec4b3f3f6 | 8 | private Map<String, String> validateFields(Map<String, String> validationMap){
Map<String, String> resultsMap=new HashMap<String, String>();
int intValue=0;
for( Map.Entry<String, String> entry:validationMap.entrySet()){
if(entry.getKey().equals("healthrec")){
try{
intValue=Integer.parseInt(entry.getValue());
} catch(Exception e){
if(entry.getValue()!=""){
resultsMap.put("healthrec", "*Health Record should be a number.");
}else{
resultsMap.put("healthrec","*Health Record must be filled.");
}
}
}else if(entry.getKey().equals("age")){
try{
intValue=Integer.parseInt(entry.getValue());
} catch(Exception e){
if(entry.getValue()!=""){
resultsMap.put("age", "*Age should be a number.");
}else{
resultsMap.put("age","*Age must be filled.");
}
}
if(intValue<0){
resultsMap.put("age","*Age should not be negative.");
}
}
}
return resultsMap;
} |
585bbd0a-a01d-4ea3-9ee0-57b3460b74c2 | 3 | @Override
public void execute( CommandSender sender, String[] args ) {
if ( !( sender.hasPermission( "bungeesuite.reload" ) || sender.hasPermission( "bungeesuite.admin" ) ) ) {
if ( sender instanceof ProxiedPlayer ) {
ProxiedPlayer p = ( ProxiedPlayer ) sender;
p.chat( "/bsreload" );
}
} else {
Messages.reloadMessages();
MainConfig.reloadConfig();
Announcements.reloadAnnouncements();
sender.sendMessage( "config.yml, announcements.yml and messages.yml reloaded!" );
}
} |
a5d66c5e-56dd-459e-a2a5-752f9a65327e | 0 | public Tool getCurrentTool(){
return currentTool;
} |
6fa7044c-1bd3-447d-b42f-3ff49ac3f7da | 8 | public ArrayList<Integer> generateWhitePawnDestinations( int position ) {
ArrayList<Integer> destinations = new ArrayList<Integer>();
if ( !hasPieceMoved( pieceAt( position ) ) && squareEmpty( position + 16 ) && squareEmpty( position + 32 ) ) {
destinations.add( position + 32 );
}
if ( !squareEmpty( position + 15 ) || whiteCanEnPassantLeft( position ) ) {
destinations.add( position + 15 );
}
if ( !squareEmpty( position + 17 ) || whiteCanEnPassantRight( position ) ) {
destinations.add( position + 17 );
}
if ( squareEmpty( position + 16 ) ) {
destinations.add( position + 16 );
}
return ( destinations );
} |
7639e250-eefb-4727-9a14-3313d2b66461 | 5 | public boolean equals(Reaction R){
boolean result = (reactants.length==R.getReactants().length) &&
(products.length==R.getProducts().length);
int i=0;
boolean finish=false;
while(result && !finish){
if(i<reactants.length){
result = (reactants[i] == R.getReactants()[i]);
finish=false;
}
else{finish=true;}
if(i<products.length){
result &= (products[i] == R.getProducts()[i]);
finish=false;
}
else{finish &= true;}
i++;
}
return result;
} |
32a14ad5-dadf-41c9-8cf9-4885b14a51f4 | 2 | private ArrayList<Chunk> getVillageChunks()
{
ArrayList<Chunk> villageChunks = new ArrayList<Chunk>();
chunksLock.readLock().lock();
try {
for (Chunk c : chunks)
{
if (c.hasVillage())
{
villageChunks.add(c);
}
}
} finally {
chunksLock.readLock().unlock();
}
return villageChunks;
} |
ab11ba49-5a65-41a8-9c67-19a34f27619f | 8 | public FileStream(RandomAccessFile source) throws OggFormatException, IOException {
this.source=source;
ArrayList po=new ArrayList();
int pageNumber=0;
try {
while(true) {
po.add(new Long(this.source.getFilePointer()));
// skip data if pageNumber>0
OggPage op=getNextPage(pageNumber>0);
if(op==null) {
break;
}
LogicalOggStreamImpl los=(LogicalOggStreamImpl)getLogicalStream(op.getStreamSerialNumber());
if(los==null) {
los=new LogicalOggStreamImpl(this, op.getStreamSerialNumber());
logicalStreams.put(new Integer(op.getStreamSerialNumber()), los);
}
if(pageNumber==0) {
los.checkFormat(op);
}
los.addPageNumberMapping(pageNumber);
los.addGranulePosition(op.getAbsoluteGranulePosition());
if(pageNumber>0) {
this.source.seek(this.source.getFilePointer()+op.getTotalLength());
}
pageNumber++;
}
}
catch(EndOfOggStreamException e) {
// ok
}
catch(IOException e) {
throw e;
}
//System.out.println("pageNumber: "+pageNumber);
this.source.seek(0L);
pageOffsets=new long[po.size()];
int i=0;
Iterator iter=po.iterator();
while(iter.hasNext()) {
pageOffsets[i++]=((Long)iter.next()).longValue();
}
} |
1f03b76a-c30f-4edb-a5a7-31a2598342ef | 1 | public CtField getDeclaredField(String name) throws NotFoundException {
CtField f = getDeclaredField2(name);
if (f == null)
throw new NotFoundException("field: " + name + " in " + getName());
else
return f;
} |
533cbc1e-b18d-4d74-b192-751b8af5ef47 | 6 | private void copyRGBtoBGRA(ByteBuffer buffer, byte[] curLine) {
if(transPixel != null) {
byte tr = transPixel[1];
byte tg = transPixel[3];
byte tb = transPixel[5];
for(int i=1,n=curLine.length ; i<n ; i+=3) {
byte r = curLine[i];
byte g = curLine[i+1];
byte b = curLine[i+2];
byte a = (byte)0xFF;
if(r==tr && g==tg && b==tb) {
a = 0;
}
buffer.put(b).put(g).put(r).put(a);
}
} else {
for(int i=1,n=curLine.length ; i<n ; i+=3) {
buffer.put(curLine[i+2]).put(curLine[i+1]).put(curLine[i]).put((byte)0xFF);
}
}
} |
24e41d7f-faab-42bb-ada8-ce064e4d4a4e | 8 | public String determBacktrack(int start,int end){
String seq="";
int max = this.maxBasepairs[start][end];
if(start == end)
return ".";
if(start > end)
return "";
if(isValidPair(start,end) && this.maxBasepairs[start+1][end-1]+1 == max)
return "("+determBacktrack(start+1,end-1)+")";
if(this.maxBasepairs[start][end-1]==max)
return determBacktrack(start,end-1)+".";
if(this.maxBasepairs[start+1][end]==max)
return "."+determBacktrack(start+1,end);
for(int k = start +1;k<end;k++){
if(this.maxBasepairs[start][k]+this.maxBasepairs[k+1][end]==max)
return determBacktrack(start,k)+determBacktrack(k+1,end);
}
return seq;
} |
de959a60-f0cd-4448-b822-b385b4ea232b | 7 | static final public void expression() throws ParseException {
simpleExpr();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case EGAL:
case DIFF:
case INF:
case INFEGAL:
case SUP:
case SUPEGAL:
opRel();
simpleExpr();
expression.testRel();
expression.executerOpRel();
break;
default:
jj_la1[17] = jj_gen;
;
}
} |
4c19284c-b881-4afb-9e71-ef6a7457169d | 2 | public int cardPosition(Game g, Rack r, int card)
{
int index = indexer.index(g, r, card);
int newPlayState = index;
int newPlayAction = playStates[index].getLeastVisited();
if (oldPlayState != -1)
{
playStates[oldPlayState].updateReward(playStates[newPlayState], oldPlayAction);
}
oldPlayState = newPlayState;
oldPlayAction = newPlayAction;
if (!playStates[index].allVisitedMore(stoppingVisits))
gamesSinceBelowMin++;
else
gamesSinceBelowMin = 0;
return playStates[index].getLeastVisited();
} |
5522f49f-b642-42cf-aa82-f354c9ef1c2b | 5 | public String validaFormulario() {
String strMsg = "";
if (jrbAdaptativa.isSelected() == false && jrbCorretiva.isSelected() == false && jrbPerfectiva.isSelected() == false) {
jrbAdaptativa.setForeground(Color.red);
jrbCorretiva.setForeground(Color.red);
jrbPerfectiva.setForeground(Color.red);
strMsg += "Favor Escolher um Tipo de Manutenção\n";
} else {
jrbAdaptativa.setForeground(Color.black);
jrbCorretiva.setForeground(Color.black);
jrbPerfectiva.setForeground(Color.black);
}
if (jrbUrgenteSim.isSelected() == false && jrbUrgenteNao.isSelected() == false) {
jrbUrgenteSim.setForeground(Color.red);
jrbUrgenteNao.setForeground(Color.red);
strMsg += "Favor Escolher a Necessidade da Manutenção\n";
} else {
jrbUrgenteSim.setForeground(Color.black);
jrbUrgenteNao.setForeground(Color.black);
}
return strMsg;
} |
e32e63d1-a204-4de0-b895-405fc7695323 | 3 | public void body() {
logger.log(Level.INFO, super.get_name() + " is starting...");
boolean success = sendFailures();
if(success) {
Sim_event ev = new Sim_event();
while (Sim_system.running()) {
super.sim_get_next(ev);
// if the simulation finishes then exit the loop
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION) {
break;
}
}
}
else {
logger.log(Level.SEVERE, super.get_name() + " was unable to send the failures.");
}
// shut down all the entities, including GridStatistics entity since
// we used it to record certain events.
shutdownGridStatisticsEntity();
shutdownUserEntity();
terminateIOEntities();
logger.log(Level.INFO, super.get_name() + " is exiting...");
} |
becec958-78a7-4ecc-83f6-71c6b8cd30fd | 9 | ImportBinding[] getDefaultImports() {
// initialize the default imports if necessary... share the default java.lang.* import
Binding importBinding = environment.defaultPackage;
// if (importBinding != null)
// importBinding = ((PackageBinding) importBinding).getTypeOrPackage(JAVA_LANG[1]);
// abort if java.lang cannot be found...
if (importBinding == null || !importBinding.isValidBinding()) {
// create a proxy for the missing BinaryType
// MissingBinaryTypeBinding missingObject = environment.cacheMissingBinaryType(JAVA_LANG_OBJECT, this.referenceContext);
// importBinding = missingObject.fPackage;
}
ImportBinding systemJSBinding = null;
if (environment.defaultImports != null)
{
systemJSBinding=environment.defaultImports[0];
}
// else
// {
// systemJSBinding=new ImportBinding(new char[][] {SystemLibraryLocation.SYSTEM_LIBARAY_NAME}, true, importBinding, (ImportReference)null);
// environment.defaultImports=new ImportBinding[]{systemJSBinding};
// }
ImportBinding[] defaultImports=null;
String[] contextIncludes=null;
// InferrenceProvider[] inferenceProviders = InferrenceManager.getInstance().getInferenceProviders(this.referenceContext);
// if (inferenceProviders!=null &&inferenceProviders.length>0)
// {
// contextIncludes = inferenceProviders[0].getResolutionConfiguration().getContextIncludes();
// }
if (contextIncludes!=null && contextIncludes.length>0)
{
ArrayList list = new ArrayList();
list.add(systemJSBinding);
for (int i = 0; i < contextIncludes.length; i++) {
String include=contextIncludes[i];
if (include!=null)
{
int index=Util.indexOfJavaLikeExtension(include);
if (index>=0)
include=include.substring(0,index);
include=include.replace('.', FILENAME_DOT_SUBSTITUTION);
char [][] qualifiedName=CharOperation.splitOn('/', include.toCharArray());
Binding binding=findImport(qualifiedName, qualifiedName.length);
if (binding.isValidBinding())
{
list.add(new ImportBinding(qualifiedName, true, binding, null));
}
}
}
defaultImports = ( ImportBinding[])list.toArray( new ImportBinding[list.size()]);
}
else
defaultImports = new ImportBinding[] {systemJSBinding};
return defaultImports ;
} |
4efed489-3233-4ed4-8976-07a9134e8b53 | 1 | public void build() throws Exception {
if (build != null) {
build.run();
} else {
System.err.println(" No build file to run.");
}
} |
07b8eeac-839c-4308-aab6-0ab0b70eca2f | 0 | public MyButton() {
super();
setBorderPainted(false);
setFocusPainted(false);
addMouseListener(this);
} |
071cb09a-f4cf-40e3-b954-dcd704159e16 | 6 | @Override
public boolean equals(Object obj){
if (obj.getClass() != this.getClass()) {
return false;
}
if (this == obj) {
return true;
}
if (obj == null) {
//DEBUG - System.out.println("Object is null");
return false;
}
//Cast other object to type Contact
Contact otherContact = (Contact) obj;
if (otherContact.getId() != this.id){
// DEBUG System.out.println("ID mismatch");
return false;
}
if (!this.name.equals(otherContact.getName())) {
// DEBUG System.out.println("Name mismatch");
return false;
}
if (!this.notes.equals(otherContact.getNotes())){
//DEBUG System.out.println("Notes mismatch");
return false;
}
return true;
} |
d7af29f3-5fae-4cbc-aa75-4d485a89a6aa | 0 | public CFDao getCfDao() {
return cfDao;
} |
c1ea9500-703c-45ed-ae35-d7a1d31818ad | 9 | public void onKeyPressed(int key)
{
if(key == Input.KEY_A)
this.addFacing(new Vector2f(-1.0F, 0));
else if(key == Input.KEY_D)
this.addFacing(new Vector2f(1.0F, 0));
else if(key == Input.KEY_W)
this.addFacing(new Vector2f(0, -1.0F));
else if(key == Input.KEY_S)
this.addFacing(new Vector2f(0, 1.0F));
else if(key == Input.KEY_1)
{
this.inventory.selectSlot(0);
}
else if(key == Input.KEY_2)
{
this.inventory.selectSlot(1);
}
else if(key == Input.KEY_3)
{
this.inventory.selectSlot(2);
}
if(key == Input.KEY_E && hoverTile != null)
hoverTile.interact(this);
} |
289234d7-e862-4a84-83b3-18990e9874a6 | 9 | public void stop()
{
if (state < 2) return;
if (Score.size() < settings.getInt(Setting.MinimumPlayers))
{
String message = settings.getString(Setting.FinishMessageNotEnoughPlayers);
message = message.replace("<World>", name);
Util.Broadcast(message);
}
else
{
RewardManager.RewardWinners(this);
}
for (Entry<Player, Location> e : tplocations.entrySet())
{
Player player = e.getKey();
if (player == null || !player.isOnline()) continue;
player.teleport(e.getValue());
}
state = 0;
for (String i : Score.keySet())
{
Integer hs = InputOutput.getHighScore(i);
if (hs == null) hs = 0;
int score = Score.get(i);
if (score > hs)
{
InputOutput.UpdateHighScore(i, score);
Player player = MonsterHunt.instance.getServer().getPlayer(i);
if (player != null)
{
String message = settings.getString(Setting.HighScoreMessage);
message = message.replace("<Points>", String.valueOf(score));
Util.Message(message, player);
}
}
}
lastScore.putAll(Score);
Score.clear();
properlyspawned.clear();
} |
83f73e14-84c7-4a1a-ab2d-d968d3b8df7f | 2 | @Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned) {
Set<ServerEndpointConfig> result = new HashSet<>();
if (scanned.contains(UserEndpoint.class)) {
result.add(ServerEndpointConfig.Builder.create(UserEndpoint.class, "/socket/listen").build());
result.add(ServerEndpointConfig.Builder.create(WatchEndpoint.class, "/socket/watch").build());
}
System.out.println("WebSocket endpoints initiated");
return result;
} |
7d6d2a44-5572-4358-a268-a0e5494d1998 | 8 | private void defaultStudent(HSSFRow row, CourseBean course) {
HSSFCell cell = null;
cell = row.getCell(0);
Integer i = null;
Long L = null;
List<StudentBean> list = course.getStudents();
StudentBean student = new StudentBean();
String first = getCellValue(cell);
if (first != null && first.length() > 0) {
L = Long.parseLong(getCellValue(cell));
student.setXh(L);
cell = row.getCell(1);
student.setXm(getCellValue(cell));
cell = row.getCell(2);
i = getIntegerValue(cell);
student.setPszp(i);
cell = row.getCell(3);
i = getIntegerValue(cell);
student.setQzcj(i);
cell = row.getCell(4);
i = getIntegerValue(cell);
student.setZhcs(i);
cell = row.getCell(5);
try {
i = getIntegerValue(cell);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.debug(e);
i = null;
}
if (i == null) {
student.setSzpcj(cell.getRichStringCellValue().toString());
}
student.setZpcj(i);
cell = row.getCell(6);
i = getIntegerValue(cell);
student.setBkcj(i);
cell = row.getCell(7);
i = getIntegerValue(cell);
student.setCxcj(i);
list.add(student);
student = new StudentBean();
cell = row.getCell(9);
String tmp = getCellValue(cell);
if (tmp != null && tmp.length() > 0) {
L = Long.parseLong(tmp);
student.setXh(L);
cell = row.getCell(10);
student.setXm(getCellValue(cell));
cell = row.getCell(11);
i = getIntegerValue(cell);
student.setPszp(i);
cell = row.getCell(12);
i = getIntegerValue(cell);
student.setQzcj(i);
cell = row.getCell(13);
i = getIntegerValue(cell);
student.setZhcs(i);
cell = row.getCell(14);
try {
i = getIntegerValue(cell);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
i = null;
}
if (i == null) {
student.setSzpcj(cell.getRichStringCellValue().toString());
}
student.setZpcj(i);
cell = row.getCell(15);
i = getIntegerValue(cell);
student.setBkcj(i);
cell = row.getCell(16);
i = getIntegerValue(cell);
student.setCxcj(i);
list.add(student);
}
}
log.debug(" student size " + course.getStudents().size());
} |
a8d87794-7a5f-4ca8-a630-bec0e838bba2 | 7 | public static SequenceIndex selectIsaPropositions(Cons pattern) {
{ Stella_Object renamed_Object = pattern.rest.rest.value;
SequenceIndex index = Logic.unfilteredDependentIsaPropositions(renamed_Object);
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(index), Logic.SGT_LOGIC_PAGING_INDEX)) {
{ PagingIndex index000 = ((PagingIndex)(index));
if (((Keyword)(index000.selectionPattern.value)) == Logic.KWD_ISA) {
return (index000);
}
}
}
else {
}
{ Cons sequence = index.theSequence;
Cons filteredsequence = Stella.NIL;
if (sequence == Stella.NIL) {
return (Logic.NIL_NON_PAGING_INDEX);
}
{ Proposition prop = null;
Cons iter000 = sequence;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
prop = ((Proposition)(iter000.value));
if ((prop.kind == Logic.KWD_ISA) &&
(!prop.deletedP())) {
filteredsequence = Cons.cons(prop, filteredsequence);
}
}
}
if (filteredsequence == Stella.NIL) {
return (Logic.NIL_NON_PAGING_INDEX);
}
else {
{ NonPagingIndex self000 = NonPagingIndex.newNonPagingIndex();
self000.theSequence = filteredsequence;
{ NonPagingIndex value000 = self000;
return (value000);
}
}
}
}
}
} |
112339ea-f022-4b06-9346-359bf07d3c0b | 0 | public void setFesCedula(long fesCedula) {
this.fesCedula = fesCedula;
} |
d1ba6a75-40ca-44da-825f-601910501f72 | 7 | public static HandshakeBuilder translateHandshakeHttp( ByteBuffer buf, Role role ) throws InvalidHandshakeException , IncompleteHandshakeException {
HandshakeBuilder handshake;
String line = readStringLine( buf );
if( line == null )
throw new IncompleteHandshakeException( buf.capacity() + 128 );
String[] firstLineTokens = line.split( " ", 3 );// eg. HTTP/1.1 101 Switching the Protocols
if( firstLineTokens.length != 3 ) {
throw new InvalidHandshakeException();
}
if( role == Role.CLIENT ) {
// translating/parsing the response from the SERVER
handshake = new HandshakeImpl1Server();
ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake;
serverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) );
serverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] );
} else {
// translating/parsing the request from the CLIENT
ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client();
clienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] );
handshake = clienthandshake;
}
line = readStringLine( buf );
while ( line != null && line.length() > 0 ) {
String[] pair = line.split( ":", 2 );
if( pair.length != 2 )
throw new InvalidHandshakeException( "not an http header" );
handshake.put( pair[ 0 ], pair[ 1 ].replaceFirst( "^ +", "" ) );
line = readStringLine( buf );
}
if( line == null )
throw new IncompleteHandshakeException();
return handshake;
} |
cbc3e1f5-9eb0-407b-a324-a84c56c9ced1 | 7 | private String calculate(String x) throws MathParsingException
{
Matcher m;
x = x.replaceAll("[ ]+", " ");
// Cas de base : un chiffre
if(this.regex(x, "^ [-]?[0-9.]+ $").matches())
return " " + x + " ";
// Traitement des log
m = this.regex(x, "^(.*)log ([-]?[0-9.]+)(.*)$");
if(m.matches())
return calculate(m.group(1) + " " + String.valueOf(Math.log10(Double.parseDouble(m.group(2)))) + " " + m.group(3));
// Traitement des parenthèses en premier
m = this.regex(x, "^(.*)\\(([^)]*)\\)(.*)$");
if(m.matches())
return calculate(m.group(1) + " " + calculate(m.group(2)) + " " + m.group(3));
// Traitement des ^
m = this.regex(x, "^(.*) ([-]?[0-9.]+) \\^ ([-]?[0-9.]+)(.*)$");
if(m.matches())
return calculate(m.group(1) + " " + String.valueOf(Math.pow(Double.parseDouble(m.group(2)),Double.parseDouble(m.group(3)))) + " " + m.group(4));
// Traitement des *
m = this.regex(x, "^(.*) ([-]?[0-9.]+) \\* ([-]?[0-9.]+)(.*)$");
if(m.matches())
return calculate(m.group(1) + " " + String.valueOf(Double.parseDouble(m.group(2))*Double.parseDouble(m.group(3))) + " " + m.group(4));
// Traitement des /
m = this.regex(x, "^(.*) ([-]?[0-9.]+) \\/ ([-]?[0-9.]+)(.*)$");
if(m.matches())
return calculate(m.group(1) + " " + String.valueOf(Double.parseDouble(m.group(2))/Double.parseDouble(m.group(3))) + " " + m.group(4));
// Somme
m = this.regex(x, "^[-0-9.*/+ ]+$");
if(m.matches())
{
return somme(x);
}
throw new MathParsingException(x);
} |
6e597c55-1fd9-44c9-8146-38b7b095a397 | 4 | public void rota(){
switch(orientacio){
case NORD:
orientacio = Orientacio.EST;
break;
case EST:
orientacio = Orientacio.SUD;
break;
case SUD:
orientacio = Orientacio.OEST;
break;
case OEST:
orientacio = Orientacio.NORD;
break;
}
} |
8d48f056-e3bb-43aa-bcde-02db9e1a94d1 | 3 | public void init() {
// pocet portov a ich hodnoty
in.print("* ports : " + ports.size());
ArrayList<Integer> portsz = new ArrayList<Integer>();
for (Integer i : ports)
portsz.add(i);
long seed = System.nanoTime();
Collections.shuffle(portsz, new Random(seed));
for (int p : portsz) {
in.print(" " + p);
}
in.println();
in.println("* id : " + ((GUI.player.model.settings.isProperty(Property.anonym)) ? "0" : id));
in.println("* initvalue : " + vertex.getInitial());
in.flush();
} |
de39d780-8b5c-4d8d-9098-91049ede9e3f | 8 | private void writeJSON(Object value) throws JSONException {
if (JSONObject.NULL.equals(value)) {
write(zipNull, 3);
} else if (Boolean.FALSE.equals(value)) {
write(zipFalse, 3);
} else if (Boolean.TRUE.equals(value)) {
write(zipTrue, 3);
} else {
if (value instanceof Map) {
value = new JSONObject((Map) value);
} else if (value instanceof Collection) {
value = new JSONArray((Collection) value);
} else if (value.getClass().isArray()) {
value = new JSONArray(value);
}
if (value instanceof JSONObject) {
writeObject((JSONObject) value);
} else if (value instanceof JSONArray) {
writeArray((JSONArray) value);
} else {
throw new JSONException("Unrecognized object");
}
}
} |
8bced71d-f762-44e8-a50b-74d8d484324c | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> protection from curses."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) a blessed mind and body."):L("^S<S-NAME> @x1 for protection from curses.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for protection from curses, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} |
2e27810e-854e-4b9e-b60b-ec4cd223d3a7 | 4 | public boolean isNearlyUpperTriagonal(double tolerance){
boolean test = true;
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
if(j<i && Math.abs(this.matrix[i][j])>Math.abs(tolerance))test = false;
}
}
return test;
} |
ab6c8ef2-047d-420b-b96e-76510db8c705 | 8 | static final public void Q2() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case MULTIPLY:
case DIVIDE:
case MODULO:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case MULTIPLY:
jj_consume_token(MULTIPLY);
R();
Q2();
break;
case DIVIDE:
jj_consume_token(DIVIDE);
R();
Q2();
break;
case MODULO:
jj_consume_token(MODULO);
R();
Q2();
break;
default:
jj_la1[29] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
jj_la1[30] = jj_gen;
;
}
} |
ab443154-8af2-43f1-8794-0c7dcdf3fd1a | 8 | public long startEvolution(long cycleLimit) {
long cycle = 0;
boolean finalForm = false;
List <E>newList = null;
A : while(cycle < cycleLimit && finalForm == false){
int maxFitness = problemSet.getProblems().size();
//calculate fitness values
for(E c : candidates){
//c.checkViabilityAndResetIfNeeded();
c.setFitness(c.fitness(problemSet));
}
Collections.sort(candidates);
if(newList == null){
newList = new LinkedList<E>();
}else{
newList.clear();
}
for(int i = 0;i < (candidates.size())/2;i++){
if(candidates.get(i).getFitness() == maxFitness){
//System.out.println("Winner candidate found..stresstesting it");
if(candidates.get(i).checkValidity(reference)){
winner = candidates.get(i);
finalForm = true;
break A;
}
}
if(candidates.get(i).getFitness() > maxC){
maxC = candidates.get(i).getFitness();
}
newList.add(candidates.get(i)); //add old object
newList.add((E)candidates.get(i).cloneWithMutation()); //add mutated clone
}
//continue with new list
candidates.clear();
candidates.addAll(newList);
//evolve problem set
problemSet.evolve(0.5);
cycle++;
}
return cycle;
} |
88baa347-2a25-4e3e-b504-783122fccf0e | 4 | @Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Contexto oContexto = (Contexto) request.getAttribute("contexto");
switch (oContexto.getSearchingFor()) {
case "hilo": {
oContexto.setVista("jsp/hilo/list.jsp");
oContexto.setClase("hilo");
oContexto.setMetodo("list");
oContexto.setFase("1");
oContexto.setSearchingFor("hilo");
oContexto.setClaseRetorno("entrada");
oContexto.setMetodoRetorno("new");
oContexto.setFaseRetorno("1");
oContexto.removeParam("id_hilo");
HiloList1 oHilo = new HiloList1();
return oHilo.execute(request, response);
}
case "usuario": {
oContexto.setVista("jsp/usuario/list.jsp");
oContexto.setClase("usuario");
oContexto.setMetodo("list");
oContexto.setFase("1");
oContexto.setSearchingFor("usuario");
oContexto.setClaseRetorno("entrada");
oContexto.setMetodoRetorno("new");
oContexto.setFaseRetorno("1");
oContexto.removeParam("id_usuario");
UsuarioList1 oOperacion = new UsuarioList1();
return oOperacion.execute(request, response);
}
default:
oContexto.setVista("jsp/mensaje.jsp");
EntradaBean oEntradaBean = new EntradaBean();
EntradaDao oEntradaDao = new EntradaDao(oContexto.getEnumTipoConexion());
EntradaParam oEntradaParam = new EntradaParam(request);
oEntradaBean = oEntradaParam.loadId(oEntradaBean);
try {
oEntradaBean = oEntradaParam.load(oEntradaBean);
} catch (NumberFormatException e) {
return "Tipo de dato incorrecto en uno de los campos del formulario";
}
try {
oEntradaDao.set(oEntradaBean);
} catch (Exception e) {
throw new ServletException("EntradaController: Update Error: Phase 2: " + e.getMessage());
}
String strMensaje = "Se ha añadido la información de entrada con id=" + Integer.toString(oEntradaBean.getId()) + "<br />";
strMensaje += "<a href=\"Controller?class=entrada&method=list&filter=id_usuario&filteroperator=equals&filtervalue=" + oEntradaBean.getUsuario().getId() + "\">Ver entradas de este usuario</a><br />";
strMensaje += "<a href=\"Controller?class=entrada&method=view&id=" + oEntradaBean.getId() + "\">Ver entrada creada en el formulario</a><br />";
return strMensaje;
}
} |
64216ed2-8986-4aec-963c-0ca0376f8832 | 7 | private void flipColors(IntervalNode h) {
// h must have opposite color of its two children
assert (h != null) && (h.left != null) && (h.right != null);
assert (!isRed(h) && isRed(h.left) && isRed(h.right))
|| (isRed(h) && !isRed(h.left) && !isRed(h.right));
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
} |
374792b0-107e-4163-8fbf-a89fdb5974da | 2 | private void buildSpecialTrees(final Map catchBodies, final Map labelPos) {
Tree tree;
tree = new Tree(srcBlock, new OperandStack());
srcBlock.setTree(tree);
tree = new Tree(snkBlock, new OperandStack());
snkBlock.setTree(tree);
tree = new Tree(iniBlock, new OperandStack());
iniBlock.setTree(tree);
if (method.codeLength() > 0) {
tree.initLocals(methodParams(method));
tree.addInstruction(new Instruction(Opcode.opcx_goto, method
.firstBlock()));
// (pr)
if (catchBodies != null) {
addHandlerEdges(iniBlock, catchBodies, labelPos, null,
new HashSet());
}
}
} |
b994da9e-fc2f-4c19-bce0-95d7c28cc62b | 5 | private void permuteImp(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] num, boolean[] visited) {
//if all checked, return
if (tmp.size() == num.length) {
res.add(new ArrayList<Integer>(tmp));
return;
}
for (int i = 0; i < num.length; i++) {
if (!visited[i]) {
tmp.add(num[i]);
visited[i] = true;
//will recall the function, and the loop will jump the visited one
permuteImp(res, tmp, num, visited);
visited[i] = false;
//after pass the list to the recall function, remove the add up element. in order to continue the loop to add next element.
//backtracking
tmp.remove(tmp.size() - 1);
//if the ducplicate, jump that element
while (i + 1 < num.length && num[i + 1] == num[i]) {
i++;
}
}
}
} |
f14e16ca-1dd6-4d13-b6a8-51d4532e9fae | 1 | public static boolean areMoreVariablesThatBelongInUsefulVariableSet(
Grammar grammar, Set set) {
if (getVariableThatBelongsInUsefulVariableSet(grammar, set) == null)
return false;
return true;
} |
b913fb80-2bf6-4c76-a21b-3b41790e6616 | 4 | @Override
public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game)
{
ArrayList<Integer> subtypes = game.getSubTypes(itype);
for (Integer i: subtypes) {
Iterator<VGDLSprite> spriteIt = game.getSpriteGroup(i);
if (spriteIt != null) while (spriteIt.hasNext()) {
try {
VGDLSprite s = spriteIt.next();
s.speed = value;
} catch (ClassCastException e) {
e.printStackTrace();
}
}
}
} |
802bf101-3ba1-4a52-9ab2-8f9dba866162 | 2 | public void paint(Graphics g){
//g.drawImage(this.bodypart.getIcon(), 0, 0, null);
g.drawString(this.bodypart.getName(), 8, 18);
g.setColor(Color.ORANGE);
Upgrade[] upgrades = this.bodypart.getUpgrades();
for(int i = 0; i < upgrades.length; i++){
if(upgrades[i] == null) continue;
g.drawString(upgrades[i].getName(), 8, (i+2)*18);
}
} |
fb99f732-dc4b-4b07-a314-c756e12475c3 | 1 | public int deleteBook(String bookID) {
try {
// Erforderlicher SQL-Befehl
String sqlStatement = "DELETE FROM bookworm_database.books WHERE id = "
+ bookID + ";";
// SQL-Befehl wird ausgeführt
successful = mySQLDatabase.executeSQLUpdate(sqlStatement);
return successful;
} catch (Exception e) {
System.out.println(e.toString());
// Ein Dialogfenster mit entsprechender Meldung soll erzeugt werden
String errorText = "Datenbank-Fehler beim Löschen eines Datensatzes.";
errorMessage.showMessage(errorText);
successful = 0;
return successful;
} finally {
// offene Verbindungen werden geschlossen
mySQLDatabase.closeConnections();
}
} |
22da4070-748e-4107-83c8-065a7a8f183b | 0 | protected void initialize() {
_timer.start();
} |
70d2259b-f82a-456f-ba20-a0f2d18171b0 | 3 | public Ul(HtmlMidNode parent, HtmlAttributeToken[] attrs){
super(parent, attrs);
for(HtmlAttributeToken attr:attrs){
String v = attr.getAttrValue();
switch(attr.getAttrName()){
case "compact":
compact = Compact.parse(this, v);
break;
case "type":
type = Type.parse(this, v);
break;
}
}
} |
c67ac29e-7a01-4c52-974f-3bfcd43d21af | 9 | public int getClueNumber(int x, int y) {
int foundMines = 0;
for(int j = y - 1; j <= y + 1; j++) {
for(int i = x - 1; i <= x + 1; i++) {
if(j == y && i == x) {
continue;
} else if(j < 0 || i < 0 ||
!(j < mineFieldGrid.length) || !(i < mineFieldGrid[j].length)) {
continue;
} else {
if(mineFieldGrid[j][i].hasMine()) {
++foundMines;
}
}
}
}
return foundMines;
} |
a7ab76f5-d9ce-412f-a274-cefa0b349bd5 | 8 | public static String stripEnd(String str, String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
} |
5c0ddf4d-a662-4173-b327-5458852e440a | 3 | public String fourthFieldTrans(String field, int min, int max)
{
String newField = "";
System.out.println("test");
if(field.substring(0, 1).equals("*"))
{
newField = "EVERY";
}
else if(field.length() > 1)
{
if(!isWeekLetter(field.substring(0, 2)))
{
newField = secondFieldTrans(field, 1, 7, false);
}
else
{
newField = weekInLetters(field);
}
}
else
{
newField = secondFieldTrans(field, 1, 7, false);
}
return newField;
} |
6521029d-5cf4-40c6-8a39-e6c6c5c019ec | 4 | public Chunk(World w, int x, int y, int z) {
data = new boolean[chunkW * chunkH * chunkD];
chunkX = x;
chunkY = y;
chunkZ = z;
for (int xx = 0; xx < chunkW; xx++) {
for (int yy = 0; yy < chunkH; yy++) {
for (int zz = 0; zz < chunkD; zz++) {
if(noiseGen(((float)xx + (float)chunkX), ((float)yy + (float)chunkY), ((float)zz + (float)chunkZ)) < 0) {
data[xx + (yy * chunkW) + (zz * chunkW * chunkH)] = true;
}
}
}
}
terrainChange = true;
world = w;
model = new BufferObject();
} |
c44eaf43-8f0d-460f-a4f7-d90d7025835f | 3 | public Scan(String args[]) { // the constructor
// open an input file if one specified on command line.
// o.w., use standard input.
try {
if (args.length == 0) {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
}
else if (args.length > 1) {
System.err.println("too many command line arguments("+
args.length+"); want 0 or 1" );
System.exit(1);
}
else {
FileReader fr = new FileReader(args[0]);
br = new BufferedReader(fr);
}
}
catch (Exception oops) {
System.err.println("Exception opening file "+args[0]+"\n");
oops.printStackTrace();
}
// initially, we pretend that we just read a newline.
// hence linenumber is initialized to 0.
c = '\n';
linenumber = 0;
putback = true;
got_eof = false;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.