method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
65bdc6e7-a77f-4125-8a56-f9021283bd95 | 5 | private boolean canSimpleCheckerFight(Cell fighter, Cell targetCell) {
if (targetCell == null || !targetCell.isEmpty()) {
return false;
}
StepDirection direction = chessBoardModel.getDirection(fighter, targetCell);
Cell victimCell = getRelativeCell(fighter, direction);
if (victimCell == null || victimCell.isEmpty() || victimCell.hasCheckerOf(fighter.getChecker().getOwner())) {
return false;
}
return targetCell == getRelativeCell(victimCell, direction);
} |
1abd8224-8121-4c73-82bc-2d3cf2db910c | 5 | private boolean jj_3R_14() {
if (jj_scan_token(STRING)) return true;
Token xsp;
xsp = jj_scanpos;
if (jj_3_67()) {
jj_scanpos = xsp;
if (jj_3_68()) {
jj_scanpos = xsp;
if (jj_3_69()) return true;
}
}
if (jj_3R_31()) return true;
return false;
} |
3e67045a-f29c-4f8d-b057-caa8376ec7d5 | 5 | private void asetaAKuva() {
if (noppa == 2 || noppa == 3){
ImageIcon raha1 = new ImageIcon(new ImageIcon(getClass().getResource("/kolikot.jpg")).getImage());
setIcon(raha1);
} else if (noppa == 4){
ImageIcon raha2 = new ImageIcon(new ImageIcon(getClass().getResource("/munneh.jpg")).getImage());
setIcon(raha2);
} else if (noppa == 5){
ImageIcon vp = new ImageIcon(new ImageIcon(getClass().getResource("/vp.jpg")).getImage());
setIcon(vp);
} else if (noppa == 6){
ImageIcon kortti = new ImageIcon(new ImageIcon(getClass().getResource("/kortti.jpg")).getImage());
setIcon(kortti);
}
} |
ec581d57-c20d-4237-ae30-e341bf96362d | 4 | public void repartirFichas(){
int k=10;
for (int i = 0; i < 14; i+=2) {
this.listaFichaPc.add(this.listaFicha.get(this.fichasBarajadas[i]));
this.listaFichaHumano.add(this.listaFicha.get(this.fichasBarajadas[i+1]));
int tlh = Domino.listaFichaHumano.size();
if(tlh!=1){
int x = Domino.listaFichaHumano.get(tlh-2).getX() + 90;
Domino.listaFichaHumano.get(tlh-1).posiocion(x, 433);
}
}
//Areglo auxiliar
int aux[] = new int[14];
for (int i = 0; i < 14; i++) {
aux[i] = this.fichasBarajadas[i];
}
//ordenar el arreglo en forma desendente
aux = this.ordenarDesc(aux);
//Eliminar las fichas repartidas
for (int i = 0; i < 14; i++) {
this.listaFicha.remove(aux[i]);
}
} |
87c66c11-fcdb-4c27-a0a8-15ebb78fbaaa | 2 | public void reactionAnalysis(){
//System.out.printf("%d\n", reactions.size());
for(int i=0; i<reactions.size(); i++){
if(reactions.get(i).getCount() > 1){
System.out.printf("%d\t", reactions.get(i).getCount());
System.out.printf(""+reactionToString(reactions.get(i))+"\n");
}
}
} |
e6aa970a-1232-4461-bd72-c894d38bcbd2 | 1 | public static void print(String s) {
if (verbose)
System.out.println(s);
} |
0c6e953c-440b-4aa0-8d57-b8b115d8dd46 | 5 | public boolean interact(EntityPlayer var1) {
ItemStack var2 = var1.inventory.getCurrentItem();
if(var2 != null && var2.itemID == Item.shears.shiftedIndex && !this.getSheared()) {
if(!this.worldObj.multiplayerWorld) {
this.setSheared(true);
int var3 = 2 + this.rand.nextInt(3);
for(int var4 = 0; var4 < var3; ++var4) {
EntityItem var5 = this.entityDropItem(new ItemStack(Block.cloth.blockID, 1, this.getFleeceColor()), 1.0F);
var5.motionY += (double)(this.rand.nextFloat() * 0.05F);
var5.motionX += (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F);
var5.motionZ += (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F);
}
}
var2.damageItem(1, var1);
}
return false;
} |
66dcb4b1-6f0a-43be-9e6d-a9acbe698fe1 | 7 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((adresse == null) ? 0 : adresse.hashCode());
result = prime * result
+ ((emailAdresse == null) ? 0 : emailAdresse.hashCode());
result = prime * result + geburtsjahr;
result = prime * result
+ ((geschlecht == null) ? 0 : geschlecht.hashCode());
result = prime
* result
+ ((laufveranstaltung == null) ? 0 : laufveranstaltung
.hashCode());
result = prime * result
+ ((mobilNummer == null) ? 0 : mobilNummer.hashCode());
result = prime * result
+ ((nachname == null) ? 0 : nachname.hashCode());
result = prime * result + ((vorname == null) ? 0 : vorname.hashCode());
return result;
} |
aaa4c0f2-a2c4-43ed-87c7-a5b781979b1f | 4 | public double getMAP() {
if (this.predictionData.size() != 0 && this.realData.size() != 0 && this.numFoundRelevantDocs != 0) {
double sum = 0.0;
for (int i = 1; i <= this.predictionData.size(); i++) {
sum += (getPrecisionK(i) * isCorrect(i - 1));
}
return sum / this.realData.size();
}
return 0.0;
} |
2dab0c4a-d1d5-4a58-bc11-e91cc8d76571 | 2 | public static void main(String[] args) {
ArrayList<Figura> figuras = new ArrayList();
fabricarFiguras(figuras);
for (Figura figura:figuras) {
figura.desenhar();
if (figura instanceof Figura2D) {
Figura2D figura2D = (Figura2D) figura;
System.out.println(" + Foi invocado calcularArea() e retornou " + figura2D.calcularArea());
System.out.println(" + Foi invocado calcularPerimetro() e retornou " + figura2D.calcularPerimetro());
} else {
Figura3D figura3D = (Figura3D) figura;
System.out.println(" + Foi invocado calcularVolume() e retornou " + figura3D.calcularVolume());
}
}
} |
ec6aea49-91cf-4e80-8ba7-44a97d36dd09 | 4 | public static void addWadToBlacklist(String filename, String sender) {
String query = "SELECT `md5`,`name` FROM `" + mysql_db + "`.`blacklist` WHERE `name` = ?";
try {
Connection con = getConnection();
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, filename);
ResultSet r = pst.executeQuery();
if (r.next()) {
bot.sendMessage(sender, "Wad '" + filename + "' already exists in blacklist.");
}
else {
query = "SELECT `md5`,`wadname` FROM `" + mysql_db + "`.`wads` WHERE `wadname` = ?";
pst = con.prepareStatement(query);
pst.setString(1, filename);
r = pst.executeQuery();
String name = "", md5 = "";
if (r.next()) {
name = r.getString("wadname");
md5 = r.getString("md5");
}
else {
bot.sendMessage(sender, "Wad '" + filename + "' was not found in our repository.");
return;
}
query = "INSERT INTO `" + mysql_db + "`.`blacklist` (`name`,`md5`) VALUES (?, ?)";
pst = con.prepareStatement(query);
pst.setString(1, name);
pst.setString(2, md5);
int result = pst.executeUpdate();
if (result == 1)
bot.sendMessage(sender, "Added '" + name + "' to the blacklist with hash " + md5);
else
bot.sendMessage(sender, "There was an error adding the wad to the blacklist. Please contact an administrator.");
}
} catch (SQLException e) {
e.printStackTrace();
logMessage(LOGLEVEL_IMPORTANT, "Could not blacklist wad (SQL Error)");
}
} |
0e7ef1f2-7cf2-4982-89ed-d3020347790d | 9 | public boolean isMatched(String str){
String[] s=str.split(" ");
Map<String,String> map= new HashMap<String,String>();
map.put(")","(");
map.put("}","{");
map.put("]","[");
for(String item : s){
System.out.println("handle "+item);
if(item.equals("(") || item.equals("[") ||item.equals("{"))
this.push(item);
else if(item.equals(")") || item.equals("]") || item.equals("}") )
if(!this.pop().equals(map.get(item)))
return false;
}
if(this.size()!=0)
return false;
return true;
} |
896309c1-d043-4f4e-abbf-e021d921d5ad | 9 | public PartList getPartList(InputStream is) throws Exception{
PartList partList;
Element root;
try {
root = getRootElement(is);
} catch (Exception e) {
throw e;
}
String bucketName = root.getElementsByTagName("Bucket").item(0).getTextContent();
String uploadId = root.getElementsByTagName("UploadId").item(0).getTextContent();
String objectKey = root.getElementsByTagName("Key").item(0).getTextContent();
String storageClass = root.getElementsByTagName("StorageClass").item(0).getTextContent();
String partNumberMarkerStr = root.getElementsByTagName("PartNumberMarker").item(0).getTextContent();
Integer partNumberMarker = null;
if(partNumberMarkerStr!=null&&partNumberMarkerStr.trim().length()>0)
partNumberMarker = Integer.valueOf(partNumberMarkerStr);
NodeList tmpNodelist = root.getElementsByTagName("NextPartNumberMarker");
Integer nextPartNumberMarker = null;
if(tmpNodelist!=null&&tmpNodelist.getLength()>0){
String nextPartNumberMarkerStr = tmpNodelist.item(0).getTextContent();
if(nextPartNumberMarkerStr!=null&&nextPartNumberMarkerStr.trim().length()>0)
nextPartNumberMarker = Integer.valueOf(nextPartNumberMarkerStr);
}
Integer maxParts = Integer.valueOf(root.getElementsByTagName("MaxParts").item(0).getTextContent());
Boolean isTruncated = Boolean.valueOf(root.getElementsByTagName("IsTruncated").item(0).getTextContent());
Element initiatorNode = (Element)root.getElementsByTagName("Initiator").item(0);
String displayName = initiatorNode.getElementsByTagName("DisplayName").item(0).getTextContent();
String id = initiatorNode.getElementsByTagName("ID").item(0).getTextContent();
Owner initiator = new Owner(displayName, id);
Element OwnerNode = (Element)root.getElementsByTagName("Owner").item(0);
displayName = OwnerNode.getElementsByTagName("DisplayName").item(0).getTextContent();
id = initiatorNode.getElementsByTagName("ID").item(0).getTextContent();
Owner owner = new Owner(displayName, id);
partList = new PartList(bucketName, objectKey, uploadId, maxParts, partNumberMarker, owner, initiator, storageClass, isTruncated, nextPartNumberMarker);
NodeList partListNodes = root.getElementsByTagName("Part");
int len = partListNodes.getLength();
try {
for (int i=0; i<len; i++)
{
Element node = (Element)partListNodes.item(i);
Node partNumberNode = node.getElementsByTagName("PartNumber").item(0);
Long partNumber = Long.valueOf(partNumberNode.getTextContent());
@SuppressWarnings("unused")
Node lastModifiedNode = node.getElementsByTagName("LastModified").item(0);
// Date lastModified = sdf.parse(lastModifiedNode.getTextContent());
Date lastModified = new Date();
Node eTagNumberNode = node.getElementsByTagName("ETag").item(0);
String eTag = eTagNumberNode.getTextContent();
Node sizeNode = node.getElementsByTagName("Size").item(0);
Long size = Long.valueOf(sizeNode.getTextContent());
partList.addPart(new PartInfo(partNumber.intValue(), lastModified, eTag, size));
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("response parse error");
}
finally{
IOUtils.safelyCloseInputStream(is);
}
return partList;
} |
92850c9e-111b-4f19-a7b3-b44250444d62 | 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(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu.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 Menu().setVisible(true);
}
});
} |
c2d12860-cff0-4256-816b-5fa7edf8d47a | 4 | static String toHex4String(int pValue)
{
String s = Integer.toString(pValue, 16);
//force length to be four characters
if (s.length() == 0) {return "0000" + s;}
else
if (s.length() == 1) {return "000" + s;}
else
if (s.length() == 2) {return "00" + s;}
else
if (s.length() == 3) {return "0" + s;}
else{
return s;
}
}//end of Log::toHex4String |
7fbeefff-50de-43f3-bd93-008f5ac130bf | 2 | public static BigInteger convertoToRepresentationNumber(String representationString, char[] alfabet){
Hashtable<Character,Integer> conversionFunction = new Hashtable<>();
BigInteger base = BigInteger.valueOf(alfabet.length);
BigInteger out = BigInteger.ZERO;
for(int i= 0; i < alfabet.length;i++){
conversionFunction.put(alfabet[i], i);
}
char[] chars = representationString.toCharArray();
for(int i= 0; i < chars.length ;i++ ){
char representationStringCharacter = chars[i];
BigInteger number = BigInteger.valueOf(conversionFunction.get(representationStringCharacter));
out = out.add(number.multiply(base.pow(i)));
}
return out;
} |
6e8e4407-816c-46f8-8616-4c91673eac64 | 7 | @Override
public double evaluate(int[][] board) {
int r = 0;
int n = board.length;
int m = board[0].length;
int x = 0, y = 0;
while (y != m) {
int nextX, nextY;
if (y % 2 == 0) {
if (x == n - 1) {
nextX = x;
nextY = y + 1;
} else {
nextX = x + 1;
nextY = y;
}
} else {
if (x == 0) {
nextX = x;
nextY = y + 1;
} else {
nextX = x - 1;
nextY = y;
}
}
if (board[x][y] != 0 && board[nextX][nextY] != 0 && board[x][y] >= board[nextX][nextY]) {
r -= board[x][y];
} else {
break;
}
x = nextX;
y = nextY;
}
return r;/**/
/*int r = 0;
int n = board.length;
int m = board[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
if(nextJ == m) {
continue;
}
if (board[i][j] < board[nextI][nextJ]) {
r++;
}
}
}
return r;/**/
} |
59399e22-5b8b-4fa8-8bf7-32ecdc9de0be | 0 | public void clickChooseSkills(Scanner scanchoice, ArrayList<MainMenuHeroSlot> heroies) {
System.out.println("You can't choose items, you haven't got any characters to put items on.");
} |
35b7efa7-02e2-42b9-aa3b-c6b1b9d16fac | 0 | public void setCode(String code) {
this.code = code;
} |
068c1eef-1807-4553-aaf8-25456fa1826d | 0 | @EventHandler
public void preInit(FMLPreInitializationEvent event)
{
} |
afbca138-9212-4e69-bbe6-7e386c6de9ad | 7 | private void FacturarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FacturarActionPerformed
// TODO add your handling code here:
List<Usuario> us = new Conectar().ConexionUs();
Usuario u = new Usuario();
String s1 = null;
try {
s1 = new UseUser().GetUser();
} catch (IOException ex) {
Logger.getLogger(Ventas.class.getName()).log(Level.SEVERE, null, ex);
}
for(Usuario u1 : us){
StringBuffer st = new StringBuffer(u1.getName());
st.setLength(30);
u1.setName(st.toString());
if(u1.getName().equalsIgnoreCase(s1)){
JOptionPane.showMessageDialog(this,s1);
u = u1;
}
}
dtm = (DefaultTableModel)jTable1.getModel();
Calendar c = Calendar.getInstance();
String Fecha = Integer.toString(c.get(Calendar.DATE));
Fecha+="/";
Fecha+= Integer.toString(c.get(Calendar.MONTH)+1);
Fecha+="/";
Fecha+= Integer.toString(c.get(Calendar.YEAR));
List<Producto> p2 = new ArrayList<>();
List<Factura> fc = new ArrayList<>();
for(int i = 0; i < dtm.getRowCount(); i++){
String x = (String)dtm.getValueAt(i,0);
for(Producto p1:prd){
int x2 = p1.getCantidad();
String y = ""+p1.getId();
y = new Search().SetLength(y);
if(y.equals(x)){
Producto prod1 = new Producto();
prod1 = p1;
Factura f = new Factura();
p2.add(p1);
p1.setCantidad((int)dtm.getValueAt(i,3));
f.setId(p1.getId());
f.setName(p1.getName());
s1 = s1.trim();
f.setUsuario(s1);
f.setFecha(Fecha);
f.setMarca(p1.getMarca());
f.setCantidad((int)dtm.getValueAt(i, 3));
f.setPrecio(p1.getPrecio());
f.setTotal((double)dtm.getValueAt(i,5));
fc.add(f);
new Conectar().InsertarVenta(p1, Fecha, s1);
int x1 = x2-(int)dtm.getValueAt(i,3);
prod1.setCantidad(x1);
new Conectar().ModificarProd(prod1);
}
}
}
new Conectar().Conect(fc);
Connection c1 = new Conectar().Conect();
try{
String s = System.getProperty("user.dir")+"/src/items/Factura.jasper";
JasperReport reporte = (JasperReport)JRLoader.loadObject(s);
JasperPrint p = JasperFillManager.fillReport(reporte, null, c1);
JasperViewer view = new JasperViewer(p,false);
view.setIconImage(new ImageIcon(this.getClass().getResource("")).getImage());
view.setTitle("Factura");
view.setVisible(true);
}catch(Exception e){}
}//GEN-LAST:event_FacturarActionPerformed |
9c038697-803b-40dc-8820-ba90acbcae48 | 6 | public static boolean isCompatibleWithThrowsClause(Throwable ex, Class<?>... declaredExceptions) {
if (!isCheckedException(ex)) {
return true;
}
if (declaredExceptions != null) {
for (Class<?> declaredException : declaredExceptions) {
if (declaredException.isInstance(ex)) {
return true;
}
}
}
return false;
} |
20215b11-0785-4864-b8db-f010b782694f | 6 | private static Node intersection(Node l1, Node l2){
int len1=findLength(l1);
int len2=findLength(l2);
if(len1>len2){
int diff = len1-len2;
while(diff-->0){
l1=l1.next;
}
} else {
int diff = len2-len1;
while(diff-->0){
l2=l2.next;
}
}
while(l1!=null && l2!=null){
if(l1 == l2) return l1;
l1=l1.next;
l2=l2.next;
}
return null;
} |
18ad34ec-ec4a-4a72-b11e-f3f3794f9e0f | 6 | public void calculateBobbing(){
float maxB = 3.5f;
float inc = 0.25f;
if(moving){
if(up){
if(bob + inc < maxB) bob += inc;
else bob = maxB;
if(bob == maxB) up = false;
}else{
if(bob - inc > 0.0f) bob -= inc;
else bob = 0.0f;
if(bob == 0.0f) up = true;
}
}else{
bob = 0.0f;
}
} |
22c1fb46-9c15-43a2-948a-86d79b24ac58 | 1 | public void setOutputChannels(OutputChannels out)
{
if (out==null)
throw new NullPointerException("out");
outputChannels = out;
} |
75db9862-9dca-4073-8c34-74f5e82c240a | 7 | static void tokenizeInstruction(String strLine)
{
StringTokenizer tt= new StringTokenizer(strLine,", \t");
stepins=tt.nextToken();
strLine = strLine.replace(",", " ");
if(frontend.FrontEnd.onconsole.isSelected())
{
System.out.println("Current Instruction -> "+strLine);
}
StringTokenizer st = null;
if (!strLine.contains("["))
{
st = new StringTokenizer(strLine, ", \t");
backend.Emit.execute(st);
}
else if (strLine.contains("["))
{
st = new StringTokenizer(strLine, " ");
ins = st.nextToken();
Emit.ins=ins;
String rd="";
String addressing_mode="";
if (backend.Emit.ht.get(ins) instanceof InsInterface3)
{
InsInterface3 obj1 = (InsInterface3) backend.Emit.ht.get(ins);
try
{
rd = st.nextToken();
}
catch(Exception e)
{
FrontEnd.appendToPane(FrontEnd.statuswindow,"ERROR(" + ScanFile.current_line + "): Destination Register Mising For Instruction "+ins+"\n",Color.RED);
frontend.FrontEnd.exceptionraised++;
}
try
{
addressing_mode = st.nextToken();
while (st.hasMoreTokens())
{
addressing_mode += st.nextToken();
}
}
catch(Exception e)
{ FrontEnd.appendToPane(FrontEnd.statuswindow,"ERROR(" + ScanFile.current_line + "): Source Register Mising For Instruction "+ins+"\n",Color.RED);
// frontend.FrontEnd.statuswindow.append("\n ERROR in line " + ScanFile.current_line + ": Unknown operation"+"\n");
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
frontend.FrontEnd.exceptionraised++;
}
obj1.execute(ins, rd, addressing_mode);
}
else
{
FrontEnd.appendToPane(FrontEnd.statuswindow,"ERROR(" + ScanFile.current_line + "): Invalid Instruction "+ins+"\n",Color.RED);
// frontend.FrontEnd.statuswindow.append("\n ERROR in line " + ScanFile.current_line + ": Unknown operation"+"\n");
//frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
frontend.FrontEnd.exceptionraised++;
return;
}
}
// else
// {
// FrontEnd.appendToPane(FrontEnd.statuswindow,"ERROR(" + ScanFile.current_line + "): Unknown Instruction"+"\n",Color.RED);
//// frontend.FrontEnd.statuswindow.append("\n ERROR in line " + ScanFile.current_line + ": Unknown operation ");
// //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length());
// frontend.FrontEnd.exceptionraised++;
//// return;
// }
} |
82ec9084-b810-4c99-a737-691d4b2a412f | 5 | public void cambiarPassword(String newpass, String nick){
try {
String queryString = "UPDATE Usuarios SET password=? WHERE nick=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, newpass);
ptmt.setString(2, nick);
ptmt.executeUpdate();
System.out.println("Password cambiando");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null) {
ptmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
8dce9061-5107-495f-a983-c03c1e276070 | 2 | public int isFriend(User user) {
try {
String statement = new String("SELECT * FROM " + FriendDBTable + " WHERE uid1 = ? AND uid2 = ?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, userID);
stmt.setInt(2, user.userID);
ResultSet rs = stmt.executeQuery();
if (rs.next())
return IS_FRIEND;
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
// otherwise return not_friend
return NOT_FRIEND;
} |
a082facf-032c-4996-809d-ecb3ee8f0c06 | 3 | synchronized void doDelay(int milliseconds) {
// ожидает указанное время, или пока не прервет управляющее сообщение присланное через setMessage()
// для неопределенно длительного ожидания < 0
if (milliseconds < 0) {
try {
wait();
}
catch (InterruptedException e) {
}
}
else {
try {
wait(milliseconds);
}
catch (InterruptedException e) {
}
}
} |
5bd997d1-1e08-40f4-aa75-dda6d45d94ed | 7 | public Simulator() {
e = new Employee[6];
r = new Random();
for (int g = 0; g < 6; g++) {
if (g < 2) {
e[g] = new TastebudStylist();
} else if (g < 4) {
e[g] = new Moover();
} else {
e[g] = new Shaker();
}
}
for (int i = 0; i < 24; i++) {
for (int j = 0; j < e.length; j++) {
for (int x = 0; x < 7; x++) {
e[j].work();
}
e[j].earnPaycheck();
e[j].setEM(1);
}
print(i);
if (i % 4 == 0) {
System.out.println("New Month");
rndm = r.nextInt(6);
e[rndm].earnBonus();
}
}
} |
c7c2395b-27b5-4c9a-b467-049ec253a65a | 1 | public long skip(long n) throws IOException
{
long skip = in.skip(n);
if (available > 0)
{
available -= skip;
}
return skip;
} |
a1c8caf7-0fdf-4f87-b764-cf4389ca790e | 5 | public static char two(int r, int c, int f) {
if (s2(r, c, f) || s5(r, c, f))
return '|';
else if (s3(r, c, f) || s6(r, c, f) || s7(r, c, f))
return '_';
return '.';
} |
24f82428-4e0a-492b-8e07-1e60732ab9dc | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
95113eb0-9fd3-4be0-a693-185f08002537 | 1 | public boolean autoBitrateSize(){
if (prop.getProperty("autoBitrateSize").equals("true"))
return true;
else
return false;
} |
1e04af4f-7141-469f-898b-a5e08eca18ef | 6 | @EventHandler(priority = EventPriority.LOWEST)
public void onKickServer(ServerKickEvent e) {
ProxiedPlayer p = e.getPlayer();
if (p == null) {
return;
}
if (plugin.maintenanceEnabled && !p.hasPermission("bungeeutils.bypassmaintenance")) {
p.disconnect(new ComponentBuilder("").append(plugin.messages.get(EnumMessage.KICKMAINTENANCE)).create());
return;
}
if (p.getServer() != null && e.getCancelServer() != null && p.getServer() != e.getCancelServer()) {
//This will send them to the e.getCancelServer()
e.setCancelled(true);
p.sendMessage(new ComponentBuilder("").append(ChatColor.AQUA + "You were disconnected for: " + ChatColor.DARK_RED + e.getKickReason()).create());
return;
}
} |
1aac85a5-5ff0-444c-bf0a-fe3fbd68a53e | 0 | public Dysk dawajDysk(){
System.out.println("Dodaje: " + name);
return new DyskDlaLaptopa();
} |
03a12965-bdd3-46f3-8f0f-4704d80726db | 0 | @Override
public int compareTo(DoublyLinkedList<E> o) {
return this.size - o.getSize();
} |
471d3d84-041b-463d-9797-e6a88d5ceef8 | 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(frmVeicDisponivel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmVeicDisponivel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmVeicDisponivel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmVeicDisponivel.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 frmVeicDisponivel().setVisible(true);
}
});
} |
e07b4011-c80f-4467-b003-6b8d34ce0902 | 7 | private static String reformatTimezone(String str, int signIdx) {
String str2 = str;
if (signIdx >= 0 &&
signIdx + 5 < str.length() &&
Character.isDigit(str.charAt(signIdx + 1)) &&
Character.isDigit(str.charAt(signIdx + 2)) &&
str.charAt(signIdx + 3) == ':' &&
Character.isDigit(str.charAt(signIdx + 4)) &&
Character.isDigit(str.charAt(signIdx + 5))) {
str2 = str.substring(0, signIdx + 3) + str.substring(signIdx + 4);
}
return str2;
} |
dcae4a3b-77bd-4508-bf83-26b9635a7410 | 9 | void actionAwardFilter() {
if (isEmpty(awardFilterTxt.getText()) &&
!achievedOkFilter.isSelected() &&
!achievedKoFilter.isSelected() &&
!secretFilter.isSelected() &&
!multiFilter.isSelected() &&
!addedFilter.isSelected())
{
awardListModel.filter(null);
}
else {
if (achievedOkFilter.isSelected() && achievedKoFilter.isSelected()) {
achievedOkFilter.setSelected(!isOkFilterSelected);
achievedKoFilter.setSelected(isOkFilterSelected);
}
isOkFilterSelected = achievedOkFilter.isSelected();
awardListModel.filter(awardFilter);
}
Award award = awardListModel.getSelection();
if (award == null) {
awardList.clearSelection();
}
else {
awardList.setSelectedValue(award, true);
}
logger.debug("Filtering Awards" + refreshAwardFilterTitle());
} |
fb26cc1b-5148-4659-8cbf-e80af1272d75 | 0 | public void setMinLength(Long value) {
this.minLength = value;
} |
0a1a59a8-3ec7-4210-9757-e10f25c1e351 | 3 | public Whitelist addAttributes(String tag, String... keys) {
Validate.notEmpty(tag);
Validate.notNull(keys);
Validate.isTrue(keys.length > 0, "No attributes supplied.");
TagName tagName = TagName.valueOf(tag);
if (!tagNames.contains(tagName))
tagNames.add(tagName);
Set<AttributeKey> attributeSet = new HashSet<AttributeKey>();
for (String key : keys) {
Validate.notEmpty(key);
attributeSet.add(AttributeKey.valueOf(key));
}
if (attributes.containsKey(tagName)) {
Set<AttributeKey> currentSet = attributes.get(tagName);
currentSet.addAll(attributeSet);
} else {
attributes.put(tagName, attributeSet);
}
return this;
} |
43de8b51-f10f-45c5-9c32-e6916d0e3d28 | 4 | private static void send() {
wLabel.setText("- VOID -");
lLabel.setText("- VOID -");
GWCAOperation operationToInvoke = (GWCAOperation) cb.getSelectedItem();
String parameterType = (String) cbType.getSelectedItem();
String wInput = wTextField.getText();
String lInput = lTextField.getText();
LOG.debug("Invoking {}", operationToInvoke);
LOG.debug("Parameter types: {}", parameterType);
byte[] w = null, l = null;
if (HEX.equals(parameterType)) {
w = hexToByteArray(wInput);
l = hexToByteArray(lInput);
} else if (INT.equals(parameterType)) {
w = intToByteArray(wInput);
l = intToByteArray(lInput);
} else if (FLOAT.equals(parameterType)) {
w = floatToByteArray(wInput);
l = floatToByteArray(lInput);
} else {
LOG.error("Impossible!");
}
try {
gwcaConnection.sendPacket(new GWCAPacket(operationToInvoke, w, l));
} catch (IOException ex) {
LOG.warn("Failed: ", ex);
}
LOG.debug("Invoked");
} |
0786c1b1-f6af-4b4e-a016-e055dcb87479 | 9 | public void paintComponent(Graphics gfx) {
super.paintComponent(gfx);
Graphics2D g = (Graphics2D) gfx;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(font);
//g.setColor(Color.gray);
//g.drawRect (0,0,getWidth(), getHeight());
//Joining all the points into lines
for(int i = 0; i < (items.length - 1); i++){
lines[i] = new Line2D.Float(p[i], p[i+1]);
}
//g.setPaint(Color.blue);
//Draw all the lines
for(int i = 0; i < (items.length - 1); i++){
g.draw(lines[i]);
}
Shape[] s;
s = new Shape[items.length];
String temp;
g.setColor(Color.DARK_GRAY);
for(int i = 0; i < items.length; i++){
temp = String.valueOf(weights[i]);
g.setFont(new Font ("Arial", Font.BOLD, 6));
if (getHeight() > 20){
g.drawString(temp.substring(0,3), (p[i].x + 5), p[i].y < getHeight() - BOTTOM - 3 ? p[i].y + 5 : p[i].y);
}
s[i] = p[i].getShape();
}
g.setColor(color);
//g.fill(s0); g.fill(s1);
for(int i = 0; i < items.length; i++){
g.fill(s[i]);
}
g.setColor(Color.black);
// g.draw(s0); g.draw(s1);
//for(int i = 0; i < items.length; i++){
// g.draw(s[i]);
//}
//Draw the Line axis
g.drawLine(5, 0, 5, getHeight()-getBottom()); //y-axis
g.drawLine(5, getHeight()-getBottom(), getWidth() - 5, getHeight()-getBottom()); //x-axis
g.setFont(font);
//Draw the static labels
if (getHeight() > MIN_HEIGHT - 5){
String utility_upper_bound = new String("1");
g.drawString(utility_upper_bound, 1, 5);
String utility_lower_bound = new String("0");
g.drawString(utility_lower_bound, 1, getHeight()-getBottom());
}
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
if (getHeight() > MIN_HEIGHT - 8){
for(int i = 0; i < items.length; i++){
DecimalFormat df = acell.obj.decimalFormat;
String num = df.format(items[i]);
g.drawString(num, ((int)(((items[i]-items[0])/((items[(items.length)-1])-items[0]))*(getWidth()-15)))+5 - (num.length()*2), getHeight()-1);
}
}
} |
e0d753f8-4f7a-45f8-bfe2-32b822b68ce8 | 2 | public static void insertCompte(Compte compte) {
PreparedStatement stat;
try {
stat = ConnexionDB.getConnection().prepareStatement("insert into compte (typeCompte, solde, dateCreation, fk_id_utilisateur) values (?,?,?,?)");
stat.setString(1, compte.getTypeCompte());
stat.setDouble(2, compte.getSolde());
stat.setString(3, compte.getDateCreation());
stat.setInt(4, compte.getFk_id_utilisateur());
stat.executeUpdate();
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
} |
4c760745-bb30-4c69-a5ee-5d4a4565811d | 9 | @Test
public void reTest2() {
userInput.add("hi");
userInput.add("my name is meng meng");
userInput.add("i want to go to the canteen");
userInput.add("can i eat at line one");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("handle the error");
userInput.add("handle the error somehow");
userInput.add("handle this error");
userInput.add("yes");
this.runMainActivityWithTestInput(userInput);
assertTrue((nlgResults.get(4).contains("again") || nlgResults.get(4).contains("repeat"))
&& (nlgResults.get(6).contains("again") || nlgResults.get(6).contains("repeat"))
&& nlgResults.get(7).contains("rephrase")
&& nlgResults.get(9).contains("rephrase")
&& (nlgResults.get(10).contains("you like") || nlgResults.get(10).contains("prefer")
|| nlgResults.get(10).contains("you mean"))
&& nlgResults.get(11).contains("else"));
} |
e926962f-2f20-4176-b802-1e1e229bb816 | 2 | @Override
public IssueStatus getStatus() {
if (statusValue == null || isEmpty(statusValue.getText())) {
return null;
}
return IssueStatus.valueOf(statusValue.getText().trim());
} |
9fb91af5-8f40-4e4d-abae-9ff99f5be41a | 5 | public void mouseDragged(MouseEvent me)
{
if (this.isEnabled())
{
this.wasDragged = true;
int tool = tools.getSelectedDrawingTool();
if (!(tool == Toolset.TOOL_EYEDROPER
|| tool == Toolset.TOOL_PAINT_BUCKET || tool == Toolset.TOOL_PENCIL)
|| tool == Toolset.TOOL_SELECTION)
{
// other tools need to be undo'd before drawing again
undo(false);
addUndo();
}
doTool(sx, sy, getImgXY(me.getX()), getImgXY(me.getY()));
getNewImage();
}
} |
b0414681-d395-40e4-8601-81166589c952 | 5 | public void update(float delta) {
for (Plant plant : this.plants) {
plant.update(delta);
}
for (Rock rock : this.rocks) {
rock.update(delta);
}
for (Light light : this.lights) {
light.update(delta);
}
for (Nutrients nutrient : this.nutrients) {
nutrient.update(delta);
}
for (Water water : this.waters) {
water.update(delta);
}
} |
917f2414-98a0-4614-9859-61e8f35b1658 | 3 | static int dfs(int node, int num){
if(visited[node]) return num;
num++;
visited[node]=true;
for(int neighbor: g.get(node)){
if(!visited[neighbor]){
num = dfs(neighbor, num);
}
}
return num;
} |
3dd6474f-099a-4976-ae89-c9b56ffad622 | 7 | static public <T> ConstructorAccess<T> get (Class<T> type) {
try {
type.getConstructor((Class[])null);
} catch (Exception ex) {
if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
throw new RuntimeException("Class cannot be created (non-static member class): " + type.getName());
else
throw new RuntimeException("Class cannot be created (missing no-arg constructor): " + type.getName());
}
AccessClassLoader loader = AccessClassLoader.get(type);
String className = type.getName();
String accessClassName = className + "ConstructorAccess";
if (accessClassName.startsWith("java.")) accessClassName = "reflectasm." + accessClassName;
Class accessClass = null;
try {
accessClass = loader.loadClass(accessClassName);
} catch (ClassNotFoundException ignored) {
}
if (accessClass == null) {
String accessClassNameInternal = accessClassName.replace('.', '/');
String classNameInternal = className.replace('.', '/');
ClassWriter cw = new ClassWriter(0);
cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, accessClassNameInternal, null,
"com/esotericsoftware/reflectasm/ConstructorAccess", null);
MethodVisitor mv;
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "com/esotericsoftware/reflectasm/ConstructorAccess", "<init>", "()V");
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "()Ljava/lang/Object;", null, null);
mv.visitCode();
mv.visitTypeInsn(NEW, classNameInternal);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, classNameInternal, "<init>", "()V");
mv.visitInsn(ARETURN);
mv.visitMaxs(2, 1);
mv.visitEnd();
}
cw.visitEnd();
byte[] data = cw.toByteArray();
accessClass = loader.defineClass(accessClassName, data);
}
try {
return (ConstructorAccess)accessClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Error constructing constructor access class: " + accessClassName, ex);
}
} |
1511cd0d-38d1-4ebd-b000-a1925d3f6a66 | 0 | public void placeDisk(String position){
board = board.placeDisk(position);
this.passedBefore = false;
} |
3cfcea07-4f03-4c74-90ff-c69f1d68eae9 | 5 | Object[] parameterForType(String typeName, String value, Widget widget) {
if (value.equals("")) return new Object[] {new TabItem[0]};
if (typeName.equals("org.eclipse.swt.widgets.TabItem")) {
TabItem item = findItem(value, ((TabFolder) widget).getItems());
if (item != null) return new Object[] {item};
}
if (typeName.equals("[Lorg.eclipse.swt.widgets.TabItem;")) {
String[] values = split(value, ',');
TabItem[] items = new TabItem[values.length];
for (int i = 0; i < values.length; i++) {
items[i] = findItem(values[i], ((TabFolder) widget).getItems());
}
return new Object[] {items};
}
return super.parameterForType(typeName, value, widget);
} |
c0679dc9-9d68-4334-8e04-3ca1f33a4129 | 9 | public Matrix solve (Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
throw new RuntimeException("Matrix is singular.");
}
// Copy right hand side with pivoting
int nx = B.getColumnDimension();
Matrix Xmat = B.getMatrix(piv,0,nx-1);
double[][] X = Xmat.getArray();
// Solve L*Y = B(piv,:)
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
// Solve U*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
return Xmat;
} |
6bb55b99-e4f3-47bf-8eae-7575a9b392b6 | 4 | public int compareTo(Point that)
{
if (this.y < that.y)
{
return -1;
}
else if (this.y > that.y)
{
return 1;
}
else if (this.x < that.x)
{
return -1;
}
else if (this.x > that.x)
{
return 1;
}
else
{
return 0;
}
/* YOUR CODE HERE */
} |
acb9532a-2fd5-4c28-9e96-f90bed62a897 | 9 | public long transfer(
final FileChannel dst,
long position,
long count) throws IOException {
if (dst == null) {
return 0;
}
if (this.completed) {
return 0;
}
long bytesRead;
if (this.buffer.hasData()) {
dst.position(position);
bytesRead = this.buffer.read(dst);
} else {
if (this.channel.isOpen()) {
if (position > dst.size()) {
throw new IOException("Position past end of file [" + position +
" > " + dst.size() + "]");
}
bytesRead = dst.transferFrom(this.channel, position, count);
if (count > 0 && bytesRead == 0) {
bytesRead = this.buffer.fill(this.channel);
}
} else {
bytesRead = -1;
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
} |
c7913bb4-ed09-48fd-9bcc-a7d70db3bd32 | 3 | public void rendererCheckboard(CPRect r) {
CPRect rect = new CPRect(0, 0, width, height);
rect.clip(r);
for (int j = rect.top; j < rect.bottom; j++) {
for (int i = rect.left; i < rect.right; i++) {
if ((i & 0x8) != 0 ^ (j & 0x8) != 0) {
data[i + j * width] = 0xffffffff;
} else {
data[i + j * width] = 0xffcccccc;
}
}
}
} |
0957be74-843a-414b-a05f-bf0fdf5bf87b | 8 | protected double renderThread(Graphics2D g2d, Thread[] threads, int height, int width, int tdiam, int tradius,
double angle, Thread t, Map<String, Integer> actorIdMap) {
try {
int x = width / 2 + (int) (Math.cos(angle) * tradius);
int y = height / 2 + (int) (Math.sin(angle) * tradius);
ActorRunnable ar = actorManager.getRunnable(t.getName());
if (ar != null) {
g2d.setColor(ar.hasThread ? Color.GREEN.darker() : Color.YELLOW);
g2d.fillRect(x - tdiam / 2, y - tdiam / 2, tdiam, tdiam);
Actor a = ar.actor;
if (ar.hasThread && a != null) {
int theight = tdiam / 2;
Color c = actorColorMap.get(a.getClass().getName());
if (c != null) {
g2d.setColor(c);
g2d.fillOval(x - theight / 2, y - theight / 2, theight, theight);
}
Integer count = actorIdMap.get(a.getName());
if (count != null) {
g2d.setColor(Color.BLACK);
g2d.drawString(Integer.toString(count), x - tdiam / 2, y
+ (y > height / 2 ? tdiam + 10 : -tdiam - 10));
}
}
}
angle += 2 * Math.PI / threads.length;
} catch (Exception e) {
paintError("thread", g2d, e);
}
return angle;
} |
7ba572ac-766a-4bc6-b69e-2fdbfe2ac8ad | 6 | private boolean isBankCommand(CommandName input) {
return input == CommandName.newAccount
|| input == CommandName.getAccount
|| input == CommandName.deleteAccount
|| input == CommandName.deposit
|| input == CommandName.withdraw
|| input == CommandName.balance || input == CommandName.list;
} |
8fee1ecd-4539-4082-add7-1dccf87ca31e | 0 | public VertexChain(Graph g)
{
vertices = new ArrayList();
graph = g;
} |
c7f1291d-e613-462e-834c-83e7bb55767a | 2 | public static TreeMap<Double,Integer> rhythmRound(TreeMap<Double,Integer> rhythmTreeIn){
TreeMap<Double,Integer> rhythmTreeOut = new TreeMap<Double,Integer>();
Iterator<Double> rhythmIterator = rhythmTreeIn.keySet().iterator();
while(rhythmIterator.hasNext()){
double origKey = rhythmIterator.next();
double newKey = Math.round(origKey*(double)100)/(double)100;
int curValue = 0;
if(rhythmTreeOut.get(newKey)!= null) curValue = rhythmTreeOut.get(newKey);
rhythmTreeOut.put(newKey, (rhythmTreeIn.get(origKey)+curValue));
}
return rhythmTreeOut;
} |
28467cd1-a537-4935-8253-42e4cbe0494c | 9 | public static ArrayList<String> getTrackList(){
JsonParser jp = null;
boolean leadingKEY = false;
String ldKEY = null;
ArrayList<String> trackID = new ArrayList<String>();
try {
jp = Json.createParser(new FileReader(DaemonMainController.getDatabasePath()));
while(jp.hasNext()){
JsonParser.Event event = jp.next();
switch(event){
case START_OBJECT:
while(event.toString() != "END_OBJECT"){
event = jp.next();
switch(event){
case KEY_NAME:
if(!leadingKEY){
trackID.add(jp.getString()) ;
leadingKEY = true;
}
break;
case START_OBJECT:
break;
}
}
break;
case KEY_NAME:
trackID.add(jp.getString()) ;
break;
case END_OBJECT:
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jp.close();
return trackID;
} |
1bfbae0a-84ed-41be-bd64-d6049f3f9454 | 2 | @RequestMapping(method = RequestMethod.GET, value = "/login")
public String getLoginPage(@RequestParam(value = "error", required = false) String errorMsg,
@RequestParam(value = "msg", required = false) String msg,
Model uiModel){
if (errorMsg != null){
uiModel.addAttribute("error", "Incorrect credentials! Please, try again");
}
if (msg !=null){
uiModel.addAttribute("msg", "Logged out");
}
return "/login";
} |
3ec0531e-62da-42c0-9d78-654d186634d8 | 2 | public String toString(){
String txt = "[";
for (String[] values : allLines) {
String line = " [";
for (String value : values) {
line += " \"" + value + "\",";
}
txt += line.substring(0, line.length()-1) + " ],";
}
txt = txt.substring(0,txt.length()-1) + " ]";
return txt;
} |
a53beb62-5515-418e-a396-8344c5fcca44 | 4 | public void unreadFrame() throws BitstreamException
{
if (wordpointer==-1 && bitindex==-1 && (framesize>0))
{
try
{
source.unread(frame_bytes, 0, framesize);
}
catch (IOException ex)
{
throw newBitstreamException(STREAM_ERROR);
}
}
} |
d04f77f2-ab68-48f7-a5eb-268eb455a192 | 1 | private static boolean isInteger(String s)
{
try
{
Integer.valueOf(s);
}
catch(NumberFormatException e)
{
return false;
}
return true;
} |
13ff8180-2ab1-4e04-a644-400f5d09bb63 | 2 | public void execute() {
final int initialTurns = (int) Math.ceil(3.0 / State.coolingRate) + 4;
double safeTurns = state.robotGunHeat / State.coolingRate;
if(state.time < initialTurns) {
/*
* Do we have enough time to move around before they can start
* firing?
*/
if(safeTurns > 4) {
doMovement();
} else {
/*
* Stop down and face perpendicular to them to get ready for them to fire.
*/
move.path.calculatePath(state.robotPosition, getTargetPosition(),
state.robotBodyHeading, state.robotVelocity, state.robotOrbitDirection);
bot.setTurnBody(move.path.getAngleToTurn());
bot.setMaxVelocity(0);
bot.setMove(0);
move.updateNextPosition(move.path.getAngleToTurn(), 0, 1);
}
} else {
doMovement();
}
} |
ba1f5f53-6a9b-458f-b9dc-0f7779a95c01 | 9 | static final void method2131(int i) {
if (i == 0) {
if (Npc.anInt10503 == 2) {
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[0]);
Class348_Sub40_Sub34.aClass293Array9432[1]
.method2206(GfxLoader.aClass315Array3982[1]);
} else if (Npc.anInt10503 == 3) {
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[0]);
Class348_Sub40_Sub34.aClass293Array9432[1]
.method2206(GfxLoader.aClass315Array3982[1]);
Class348_Sub40_Sub34.aClass293Array9432[2]
.method2206(GfxLoader.aClass315Array3982[2]);
} else {
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[0]);
Class348_Sub40_Sub34.aClass293Array9432[1]
.method2206(GfxLoader.aClass315Array3982[1]);
Class348_Sub40_Sub34.aClass293Array9432[2]
.method2206(GfxLoader.aClass315Array3982[2]);
Class348_Sub40_Sub34.aClass293Array9432[3]
.method2206(GfxLoader.aClass315Array3982[3]);
}
} else if (i == 1) {
if (Npc.anInt10503 == 2)
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[2]);
else if (Npc.anInt10503 == 3) {
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[3]);
Class348_Sub40_Sub34.aClass293Array9432[1]
.method2206(GfxLoader.aClass315Array3982[4]);
} else {
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[4]);
Class348_Sub40_Sub34.aClass293Array9432[1]
.method2206(GfxLoader.aClass315Array3982[5]);
Class348_Sub40_Sub34.aClass293Array9432[2]
.method2206(GfxLoader.aClass315Array3982[6]);
}
} else if (i == 2) {
if (Npc.anInt10503 == 2)
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[3]);
else if (Npc.anInt10503 == 3)
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[5]);
else
Class348_Sub40_Sub34.aClass293Array9432[0]
.method2206(GfxLoader.aClass315Array3982[7]);
}
} |
ef4186ff-6f3a-4d5f-b7cb-2b8d0506f26c | 6 | public void finalWinSimu(int total, int count){
int leftNum = total;
int[] allPeople = new int[total];
int nextGoIndex = -1;
for(int i=0;i<allPeople.length;i++){
allPeople[i]=i;
}
while(leftNum>1){
for(int i=1;i<=count;i++){
nextGoIndex = getNextIndex(nextGoIndex,total);
while(allPeople[nextGoIndex]<0){
nextGoIndex= getNextIndex(nextGoIndex,total);
}
}
allPeople[nextGoIndex]=-1;
leftNum--;
}
for(int i=0;i<total;i++){
if(allPeople[i]>=0){
System.out.println(allPeople[i]+1);
}
}
} |
9181b0b4-4653-4bc5-bad0-0a9c6ba12752 | 7 | public void obfuscate(RawCorpus corpus) throws UndefinedException{
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
System.out.println("obfuscating corpus ...");
if(corpus==null || corpus.getData()==null || corpus.getSize()==0){
System.err.println("non-input corpus...");
return ;
}
ret = new ArrayList<ArrayList<String>>();
int error_line = 0;
for(ArrayList<String> sample : corpus.getData()){ //取出数据集中的每条样本
// if(sample.size()!= rules.size()){ //字段数目不对
// error_line++;
// System.err.println("size mismatch error in line: "+sample);
// continue;
// }
ArrayList<String> out = new ArrayList<String>();
for(int i=0; i<sample.size();i++){ // 处理样本中的每个字段
String col = sample.get(i);
SuperType type = definer.getType(i);
String colname = type.getColumnName();
MappingRule rule = rules.get(colname);
type.setRule(rule);
//加密函数名为空时,不加密
if(rule.getFuncname()==null || rule.getFuncname().length()==0){
ArrayList<String> orig = new ArrayList<String>();
orig.add(col);
out.addAll(orig);
}else{
out.addAll( type.obfuscate(col) );
}
}
ret.add(out);
}
System.out.println("Found "+error_line+" error lines");
result = ret;
} |
f921cb9c-3338-4c30-bceb-4e93790e6bc5 | 7 | public void move(int xa, int ya) {
if (xa != 0 && ya != 0) {
move(xa, 0);
move(0, ya);
return;
}
if (ya < 0) direction = 0;
if (ya > 0) direction = 1;
if (xa < 0) direction = 2;
if (xa > 0) direction = 3;
if (!checkCollision(xa, ya)) {
x += xa;
y += ya;
}
} |
945764df-30ec-4118-bbed-4e70960d5c04 | 0 | protected Icon getIcon() {
java.net.URL url = getClass().getResource("/ICON/transition.gif");
return new javax.swing.ImageIcon(url);
} |
17009ed5-af73-4e9a-83b8-f5293eae31ab | 6 | public static int checkLogin(Db db, LogAc logAc, String userName, char[] password){
int i = 0;
while (logAc.getDoctor(i)!=null){
if (logAc.getDoctor(i).getUserName().equals(userName)){
if (Arrays.equals(logAc.getDoctor(i).getPassword().toCharArray(),password))
return 1;
}
i++;
}
i = 0;
while (logAc.getAdmin(i)!=null){
if (logAc.getAdmin(i).getUserName().equals(userName)){
if (Arrays.equals(logAc.getAdmin(i).getPassword().toCharArray(),password))
return 2;
}
i++;
}
return 0;
} |
f8ff0925-4c36-4e4a-b5a9-d721352534be | 3 | @EventHandler
public void crafting(PrepareItemCraftEvent e){
Player p = (Player)e.getViewers().get(0);
ItemStack[] items = e.getInventory().getContents();
ArrayList<ItemStack> correct = new ArrayList<ItemStack>();
for(ItemStack i : items){
correct.add(i);
}
correct.remove(0);
ItemStack result = e.getRecipe().getResult();
Recipe r = new Recipe(plugin);
ItemStack fail = new ItemStack(Material.SKULL);
ItemStack rc = r.recipeCheck(correct);
if(!rc.isSimilar(fail)){
e.getInventory().setItem(0,rc);
}else{
}
if(plugin.cantCraft(result) == false){
e.getInventory().setItem(0, plugin.getFailedDish());
}
} |
bc98b8c5-78ad-4368-a603-4ddf3463fe67 | 9 | void Load(GL2 gl2,String fname) {
name=fname;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(fname)));
String line;
int j=0;
while( ( line = br.readLine() ) != null ) {
if( line.length() < 16 ) continue;
j++;
if(j==4) {
j=0;
num_triangles++;
}
}
VBO = new int[NUM_BUFFERS];
gl2.glGenBuffers(NUM_BUFFERS, VBO, 0); // 2 = one for vertexes, one for normals
int totalBufferSize = num_triangles*3*3;
FloatBuffer vertices = FloatBuffer.allocate(totalBufferSize); // num_triangles * points per triangle * float per point
FloatBuffer normals = FloatBuffer.allocate(totalBufferSize); // num_triangles * normal per triangle (1) * float per point
br.close();
br = new BufferedReader(new FileReader(new File(fname)));
j=0;
while( ( line = br.readLine() ) != null ) {
if( line.length() < 16 ) continue;
String c[] = line.substring(15).split(" ");
float x=Float.parseFloat(c[0]);
float y=Float.parseFloat(c[1]);
float z=Float.parseFloat(c[2]);
if(j==0) {
normals.put(x);
normals.put(y);
normals.put(z);
normals.put(x);
normals.put(y);
normals.put(z);
normals.put(x);
normals.put(y);
normals.put(z);
} else {
vertices.put(x);
vertices.put(y);
vertices.put(z);
}
j = (j+1)%4;
}
int s=(Float.SIZE/8); // bits per float / bits per byte = bytes per float
// bind a buffer
vertices.rewind();
gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[0]);
// Write out vertex buffer to the currently bound VBO.
gl2.glBufferData(GL2.GL_ARRAY_BUFFER, totalBufferSize*s, vertices, GL2.GL_STATIC_DRAW);
// repeat for normals
normals.rewind();
gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[1]);
gl2.glBufferData(GL2.GL_ARRAY_BUFFER, totalBufferSize*s, normals, GL2.GL_STATIC_DRAW);
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try {
if(br != null) br.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
} |
b660c452-6d15-4c58-be56-1312f3eb935f | 6 | public static String trimTrailingZerosAfterDecimal(String buffer, boolean localized) {
if (buffer != null) {
buffer = buffer.trim();
int dot = buffer.indexOf(localized ? DecimalFormatSymbols.getInstance().getDecimalSeparator() : '.');
if (dot != -1) {
int pos = buffer.length() - 1;
while (true) {
if (buffer.charAt(pos) != '0') {
break;
}
pos--;
}
if (dot != pos) {
pos++;
}
buffer = buffer.substring(0, pos);
}
}
return buffer;
} |
91c547bf-188b-49a7-8ad3-b1c9b611f9ab | 6 | public Book getBook(long isbn) {
//TODO
Book ret = null;
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
st=conn.createStatement();
rs = st.executeQuery("SELECT isbn, title, description, currentQuantity, totalQuantity, "
+ "publisherYear, typeName, idNumber FROM Book WHERE isbn = " + isbn);
if(rs.next()) {
ret = new Book();
ret.setIsbn(rs.getLong(1));
ret.setTitle(rs.getString(2));
ret.setDescription(rs.getString(3));
ret.setCurrentQuantity(rs.getInt(4));
ret.setTotalQuantity(rs.getInt(5));
ret.setPublishYear((Integer)rs.getObject(6));
ret.setTypeName(rs.getString(7));
ret.setIdNumber(rs.getInt(8));
//Get authors
ret.setAuthor(getAuthors(ret.getIsbn(), st, rs));
//Get publishers
ret.setPublisher(getPublishers(ret.getIsbn(), st, rs));
//Get search genres
ret.setSearchGenre(getSearchGenres(ret.getIsbn(), st, rs));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
try {
if(conn != null)
conn.close();
if(st != null)
st.close();
if(rs != null)
rs.close();
} catch (Exception e) { }
}
return ret;
} |
c5321341-db24-4883-80ab-66aa30b1805a | 5 | @Override
public void keyReleased(KeyEvent e) {
//only checks for user input if the game has started
if(gameStarted){
if (KeyEvent.getKeyText(e.getKeyCode()).equals("Escape")) {
// if the in game menu is up, close it
if (ingameMenuActive) {
closeIngameMenu();
} else {
// otherwise bring up the ingame menu
showIngameMenu();
}
}
if (KeyEvent.getKeyText(e.getKeyCode()).equals("Enter")) {
// if the in game menu is up, close it
if (chatActive) {
closeChat();
} else {
// otherwise bring up the ingame menu
showChat();
}
}
//resets descriptiontext
descriptionLabel.setText("");
gamePanel.update();
}
} |
f66e2430-b46a-4e4b-a15b-738d96ba9772 | 5 | @Override
public boolean gainPassage(Oergi oergi) {
if (jumpheight == 3) { //a wall, no real corridor
return false;
}
Element element = oergi.getElement();
ElementMovability elementMovability = new ElementMovability();
Movability movability = elementMovability.getMovability(this.getBiotype(), element);
if (movability == Movability.NO) {
return false;
}
else if (movability == Movability.LIMITED) {
if (this.getBiotype() == Biotype.CLOUD || this.getBiotype() == Biotype.TREE) {
return false;
}
else {
return true;
}
}
else {
return true;
}
} |
a5226e07-2e0a-497c-918e-4d96040269eb | 0 | @Override
public <T extends PersistentObject> T update(T entity) {
return (T) dataStore.put(entity.getId(), entity);
} |
2c06d6b4-3578-4f75-944d-4703885b5277 | 4 | public void set(String counterName, long[] countersValue) {
if(counterName.equals("Reduce input groups")) {
Reduce_input_groups = countersValue;
}
else if(counterName.equals("Combine output records")) {
Combine_output_records = countersValue;
}
else if(counterName.equals("Map input records")) {
Map_input_records = countersValue;
}
else if(counterName.equals("Reduce shuffle bytes")) {
Reduce_shuffle_bytes = countersValue;
}
else if(counterName.equals("Reduce output records")) {
Reduce_output_records = countersValue;
}
else if(counterName.equals("Spilled Records")) {
Spilled_Records = countersValue;
}
else if(counterName.equals("Map output bytes")) {
Map_output_bytes = countersValue;
}
else if(counterName.equals("Map input bytes")) {
Map_input_bytes = countersValue;
}
else if(counterName.equals("Map output records")) {
Map_output_records = countersValue;
}
else if(counterName.equals("Combine input records")) {
Combine_input_records = countersValue;
}
else if(counterName.equals("Reduce input records")) {
Reduce_input_records = countersValue;
}
} |
619a3d56-c600-48d8-a288-0ac936eb6ad5 | 7 | @Override
public void actionPerformed(ActionEvent e) {
// New button clicked
if (e.getSource() == newPersonButton) {
submitButton.setVisible(true);
newPersonButton.setVisible(false);
deletePersonButton.setEnabled(false);
editPersonButton.setEnabled(false);
cancelButton.setVisible(true);
if (submitButtonMode != 3)
submitButtonMode = 1;
comboBox.setEnabled(false);
if (emptiedList) {
idNumberLabel.setText("" + Person.getUniqueId());
}
}
// Edit button clicked
if (e.getSource() == editPersonButton) {
submitButtonMode = 2;
editPersonButton.setVisible(false);
submitButton.setVisible(true);
cancelEditButton.setVisible(true);
newPersonButton.setEnabled(false);
deletePersonButton.setEnabled(false);
comboBox.setEnabled(false);
}
// Cancel button clicked
if (e.getSource() == cancelButton) {
submitButton.setVisible(false);
newPersonButton.setVisible(true);
cancelButton.setVisible(false);
comboBox.setEnabled(true);
if (!emptiedList) {
deletePersonButton.setEnabled(true);
editPersonButton.setEnabled(true);
}
emailLabel.setForeground(Color.black);
nameLabel.setForeground(Color.black);
contactNumberLabel.setForeground(Color.black);
addressLabel.setForeground(Color.black);
}
// Cancel button clicked in edit mode
if (e.getSource() == cancelEditButton) {
submitButton.setVisible(false);
cancelEditButton.setVisible(false);
deletePersonButton.setEnabled(true);
newPersonButton.setEnabled(true);
editPersonButton.setEnabled(true);
editPersonButton.setVisible(true);
comboBox.setEnabled(true);
emailLabel.setForeground(Color.black);
nameLabel.setForeground(Color.black);
contactNumberLabel.setForeground(Color.black);
addressLabel.setForeground(Color.black);
}
// Refresh the view
revalidate();
repaint();
} |
596706fb-0bd1-44b7-829d-791b018d961a | 0 | public int numCasesTotal()
{
return myAllCases.size();
} |
5a06a214-124c-4578-b01f-8ad4605abe65 | 8 | private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
} |
d8d62a15-c80f-46d0-bc8d-ebc4f814f949 | 7 | public void spawnEtoile()
{
if(timer > 0)
timer --;
else
{
int x = 0;
int y = 0;
while(carte[x][y] == '1' || carte[x][y] == '4' || carte[x][y] == '2' || carte[x][y] == '5')
{
x = (int)(Math.random()*(width-2)+1);
y = (int)(Math.random()*(height-2)+1);
}
if(carte[x][y]=='3')
carte[x][y] = '2';
if(carte[x][y] == '0')
carte[x][y]='5';
timer = 2000;
}
} |
24135201-66ab-4d76-ba89-823d81181b2e | 1 | public void updateProduct(Product product) {
try {
beginTransaction();
session.update(product);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeSesion();
}
} |
01722c95-211c-4ee6-a6a1-f0eef92bae14 | 9 | @Override
public boolean equals( Object toCompare ) {
//only deal with PolynomialTerm comparison
if ( toCompare instanceof PolynomialTerm ) {
//check for equaling to zero
if ( toCompare instanceof Numerical ) {
if ( toCompare.equals( Numerical.ZERO ) ) {
for ( Monomial aTerm : this.m_numerator ) {
if ( aTerm.equals( Numerical.ZERO ) ) {
return true;
}
}
return this.m_numerator.size() == 0;
}
if ( toCompare.equals( Numerical.ONE ) ) {
return this.m_numerator.equals( Numerical.ONE.getNumerator() );
}
}
PolynomialTerm polynomialToCompare = ( PolynomialTerm ) toCompare;
//make sure numerators are the same
if ( this.getNumerator().equals( polynomialToCompare.getNumerator() ) ) {
//continue
} else {
return false;
}
//make sure denominators are the same
if ( this.getDenominator().equals( polynomialToCompare.getDenominator() ) ) {
//continue
} else {
return false;
}
//make sure exponents are the same
if ( this.getPolynomialTermExponent().equals( polynomialToCompare.getPolynomialTermExponent() ) ) {
//continue
} else {
return false;
}
//if all conditions satisfied, then the two PolynomialTerms are equal
return true;
} else {
return super.equals( toCompare );
}
} |
b1d837dc-59a6-4c01-8a7b-503c8044e124 | 7 | private void addSongsToPlaylistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSongsToPlaylistActionPerformed
JPanel panel = new JPanel();
JList list = new JList();
Map<String, Library> playlists = currUser.getLibrary().getPlayLists();
Vector<String> tmp = new Vector<String>();
for (Map.Entry<String, Library> entry : playlists.entrySet()) {
tmp.add(entry.getKey());
}
List<Song> songsToAdd = ownedList.getSelectedValuesList();
if (!songsToAdd.isEmpty()) {
if (!tmp.isEmpty()) {
list.setListData(tmp.toArray());
panel.add(list);
int result = JOptionPane.showOptionDialog(this, panel, "Add to playlist: ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
String Playlist = (String) list.getSelectedValue();
for (Song s : songsToAdd) {
currUser.getLibrary().getPlaylist(Playlist).addSong(s);
}
}
playlists = currUser.getLibrary().getPlayLists();
Vector<String> tmp2 = new Vector<String>();
for (Map.Entry<String, Library> entry : playlists.entrySet()) {
tmp2.add(entry.getKey());
List<Song> tmpSongs = entry.getValue().owned();
for (Song s : tmpSongs) {
tmp2.add(" " + s.toString());
}
}
this.playListList.setListData(tmp2.toArray());
} else {
JOptionPane.showMessageDialog(this, "No playlists available.");
}
} else {
JOptionPane.showMessageDialog(this, "No songs selected.");
}
}//GEN-LAST:event_addSongsToPlaylistActionPerformed |
b96184ef-3ef5-402e-bc76-86f64f562c51 | 2 | public static boolean deleteNode(ListNode node){
if(node == null || node.next ==null)
return false;
ListNode next = node.next;
node.val = next.val;
node.next =next.next;
return true;
} |
5a845985-20ed-466a-8752-dc4f2d52edfd | 6 | public static void loadFromFile(File f) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String inlin = ""; int line = 0;
while((inlin = in.readLine()) != null) {
String lin = comment.matcher(inlin).replaceAll("");
String spl[] = lin.split(" ");
if(spl.length != 2)
throw new IOException("Invalid line format on line "+line);
String var = spl[0];
String sval = spl[1];
Number val;
try {
val = new Integer(sval);
} catch (NumberFormatException nfe) {
try {
val = new Double(sval);
} catch (NumberFormatException nfe2) {
throw new IOException("Invalid number on line "+line);
}
}
try {
Constants.class.getDeclaredField(var).set(null, val);
} catch (NoSuchFieldException nsfe) {
//throw new IOException("Not a recognized constant: " +var);
System.err.println("Not a recognized constant: "+var);
} catch (ReflectiveOperationException re) {
throw new IOException("Couldn't set value of field: "+var);
}
}
} |
80bb0bc9-ff88-47b9-a32d-7116237ba14d | 1 | public static double[][] identity( int n )
{
double[][] res = newMatrix(n, n, 0.0);
for ( int i = 0; i < n; ++i )
res[i][i] = 1.0;
return(res);
} |
e5404cbc-7ec2-4511-94e3-8acbe252059c | 4 | private static void sendMsgToClient(Process process, BufferedReader buffer,
IoSession session, boolean isNormal) throws IOException {
String msg;
try {
buffer = new BufferedReader(new InputStreamReader(
isNormal ? process.getInputStream()
: process.getErrorStream()));
while ((msg = buffer.readLine()) != null) {
session.write(msg);
}
log.info("write msg to client has run over!");
} catch (IOException e) {
log.error("write {} msg to client error!", isNormal ? "normal"
: "error", e);
throw e;
} finally {
IOUtils.closeQuietly(buffer);
}
} |
fae553d6-798f-449f-8beb-3113f5d8a82b | 2 | public static void processSpherePlaneCollision(RigidBody plane,
RigidBody sphere, double restitution, double timeStep) {
// Predicted positions
Vector3d planePosition = new Vector3d();
Vector3d spherePosition = new Vector3d();
Quat4d planeRotation = new Quat4d();
Quat4d sphereRotration = new Quat4d();
sphere.predictCollisionPosition(timeStep, spherePosition,
sphereRotration);
plane.predictCollisionPosition(timeStep, planePosition, planeRotation);
// Collision normal
Matrix3d planeRotationMatrix = new Matrix3d();
planeRotationMatrix.set(planeRotation);
// Non-interpenetrating pair
if (((PlaneObject) plane.getCollisionObject()).getLocalSignedDistance(
planePosition, planeRotationMatrix, spherePosition) > ((SphereObject) sphere
.getCollisionObject()).getRadius()) {
return;
}
Vector3d normal = new Vector3d(
((PlaneObject) plane.getCollisionObject()).getNormal(null,
planeRotationMatrix));
// Intersecting points
Vector3d relativePosition = new Vector3d(spherePosition);
relativePosition.sub(planePosition);
Vector3d rPlane = new Vector3d(normal);
Vector3d rSphere = new Vector3d(normal);
rPlane.scale(-((PlaneObject) plane.getCollisionObject())
.getLocalSignedDistance(planePosition, planeRotationMatrix,
spherePosition));
rPlane.add(relativePosition);
rSphere.scale(-((SphereObject) sphere.getCollisionObject()).getRadius());
Matrix3d crossSphere = new Matrix3d(0, -rSphere.z, rSphere.y,
rSphere.z, 0, -rSphere.x, -rSphere.y, rSphere.x, 0);
// Relative velocity
Vector3d relativeVelocity = new Vector3d();
relativeVelocity.cross(sphere.getAngularVelocity(), rSphere);
Vector3d angularVelocity = new Vector3d();
angularVelocity.cross(plane.getAngularVelocity(), rPlane);
relativeVelocity.sub(angularVelocity);
relativeVelocity.add(sphere.getLinearVelocity());
relativeVelocity.sub(plane.getLinearVelocity());
// Separating velocity
if (relativeVelocity.dot(normal) > 0) {
return;
}
/*
* K = I/m + transpose(r*) I^-1 r*
*/
Matrix3d k = new Matrix3d(crossSphere);
k.transpose();
k.mul(sphere.getInertiaLocalInverse());
k.mul(crossSphere);
k.add(new Matrix3d(1 / sphere.getMass(), 0, 0, 0, 1 / sphere.getMass(),
0, 0, 0, 1 / sphere.getMass()));
processCollision(plane, rPlane, sphere, rSphere, relativeVelocity,
normal, k, restitution, timeStep);
} |
9caa9612-c665-481a-bdca-3cf479690f82 | 5 | private void sumNumbersRec(TreeNode root, int tmp) {
if(root == null) return;
if(root.left == null && root.right == null){
this.res += tmp + root.val;
}
if(root.left != null){
sumNumbersRec(root.left, (tmp + root.val) * 10);
}
if(root.right != null){
sumNumbersRec(root.right, (tmp + root.val) * 10);
}
} |
4dc8c8b2-7f5e-43d9-81d4-29c83941293a | 5 | public void updateLookAndFeel(String newlnfClassName) {
if(newlnfClassName != null) {
try {
UIManager.setLookAndFeel(newlnfClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(Gui_StreamRipStar.this);
}
} |
8d1102ac-7bb8-4ee9-a6cb-8765f44d09b6 | 2 | public void run() {
double t = 5; //timeScale;
int i = 0;
while (true) {
rungeKutta(t);
if (i>1000){
System.out.println(bodies.get(3).position);
i = 0;
}
i++;
}
} |
3f984524-a9da-4177-9fa8-26315e835e65 | 0 | @Override
public double getHig() {
return hight;
} |
ac28450e-9fab-4053-83ab-1f7b09871822 | 2 | private SootMethod getMethodFromHierarchyEx(SootClass c, String methodSignature) {
if (c.declaresMethod(methodSignature))
return c.getMethod(methodSignature);
if (c.hasSuperclass())
return getMethodFromHierarchyEx(c.getSuperclass(), methodSignature);
throw new RuntimeException("Could not find method");
} |
47ba463c-eabc-4633-a972-527988a2ae4c | 8 | private void build_map(HashMap<Character,String> m1,HashMap<String,Character> m2)
{
int i=1;
int j=1;
int k=1;
boolean[] filled=new boolean[26];
for(int m=0;m<keyword.length();m++)
{
char cur_c=keyword.charAt(m);
int char_pos=cur_c-'A';
if(!filled[char_pos])
{
String tri=generate_triple_str(i,j,k);
filled[char_pos]=true;
m1.put(Character.valueOf(cur_c),tri);
m2.put(tri,Character.valueOf(cur_c));
}
else
{
continue;
}
if(k==3)
{
if(j==3)
{
i++;
j=1;
k=1;
}
else
{
j++;
k=1;
}
}
else
{
k++;
}
}
for(int m=0;m<26;m++)
{
char cur_c=(char)('A'+m);
// int char_pos='A'+m;
if(!filled[m])
{
String tri=generate_triple_str(i,j,k);
filled[m]=true;
m1.put(Character.valueOf(cur_c),tri);
m2.put(tri,Character.valueOf(cur_c));
}
else
{
continue;
}
if(k==3)
{
if(j==3)
{
i++;
j=1;
k=1;
}
else
{
j++;
k=1;
}
}
else
{
k++;
}
}
String tri=generate_triple_str(i,j,k);//3,3,3
m1.put('#',tri);
m2.put(tri,'#');
} |
893aa04d-6571-40eb-ad41-ba9c46c38a3a | 2 | private void paintBoard(PaintEvent event) {
for (int xCoordinate = 0; xCoordinate < game.getBoardWidth(); xCoordinate++) {
for (int yCoordinate = 0; yCoordinate < game.getBoardHeight(); yCoordinate++) {
paintCell(event, xCoordinate, yCoordinate);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.