text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Room) {
Room room = (Room)obj;
if (this.id != room.id) {
if (this.id == null || !this.id.equals(room.id)) {
return false;
}
}
return true;
}
return false;
} | 5 |
public List<String> getProductNames(String proMgrName){
PreparedStatement stmt = null;
ResultSet rs = null;
List<String> proNames=null;
try {
stmt = conn
.prepareStatement("select proName from ProductInfo where productManager = ? ");
stmt.setString(1, proMgrName);
rs = stmt.executeQuery();
String name="";
proNames=new ArrayList<String>();
while (rs.next()) {
name=rs.getString(1);
proNames.add(name);
}
if (stmt != null)
stmt.close();
if (rs != null)
rs.close();
} catch (Exception e) {
// TODO: handle exception
logger.debug(e.getMessage());
}
return proNames;
} | 4 |
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.botaoImprimir){
ArrayList<Reputacao> reputacoes = agente.getTodasReputacoes();
System.out.println("****************************");
System.out.println("Imprimindo todas as reputacoes");
System.out.println("********************************");
for(Reputacao reputacao : reputacoes){
if(reputacao != null){
System.out.println("Agente : " + reputacao.getAidAgente().getLocalName());
System.out.println("Reputacao: " + reputacao.getValor());
System.out.println("******************************");
}
}
}
} | 3 |
public void create(Bitacora bitacora) throws PreexistingEntityException, RollbackFailureException, Exception {
if (bitacora.getId() == null) {
bitacora.setId(new BitacoraId());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(bitacora);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findBitacora(bitacora.getId()) != null) {
throw new PreexistingEntityException("Bitacora " + bitacora + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} | 5 |
public boolean getReceiveDateByBookID(IssueBookVO issueBookVO)
throws LibraryManagementException {
boolean returnValue = true;
ConnectionFactory connectionFactory = new ConnectionFactory();
Connection connection;
try {
connection = connectionFactory.getConnection();
} catch (LibraryManagementException e) {
throw e;
}
PreparedStatement preparedStatement = null;
ResultSet resultSet;
try {
preparedStatement = connection
.prepareStatement("select * from ISSUE_BOOK"
+ " where STUDENT_ID = ? and BOOK_ID = ? and RECEIVE_DATE is null");
preparedStatement.setString(1, issueBookVO.getStudentID());
preparedStatement.setString(2, issueBookVO.getBookID());
resultSet = preparedStatement.executeQuery();
if (!resultSet.next()) {
returnValue = false;
throw new LibraryManagementException(
ExceptionCategory.BOOK_ALREADY_RECEIVED);
}
} catch (SQLException e) {
throw new LibraryManagementException(ExceptionCategory.SYSTEM);
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new LibraryManagementException(
ExceptionCategory.SYSTEM);
}
}
connectionFactory.closeConnection(connection);
}
return returnValue;
} | 5 |
private static void setDefaults()
{
// variables that always must be set
if ( encoding == null )
encoding = Charset.defaultCharset().name();
if ( groupName == null )
groupName = "top level";
if ( longName == null )
longName = "version "+Short.toString(version);
if ( shortName == null )
shortName = Short.toString(version);
if ( mvdFile == null )
mvdFile = "untitled.mvd";
if ( folderId == 0 )
folderId = 1;
if ( xmlFile == null )
{
int dotPos = mvdFile.indexOf(".");
xmlFile = mvdFile.substring( 0,dotPos )+".xml";
}
} | 7 |
public void laggTillFramfor (Punkt hornet, String hornNamn)
{
Punkt[] h = new Punkt[this.horn.length + 1];
int pos = 0;
for (int i = 0; i < this.horn.length; i++){
h[i] = this.horn[i];
if(hornNamn == this.horn[i].getNamn()){
pos = i;
h[pos] = hornet;
}
}
for(int i = pos + 1; i < this.horn.length + 1; i++){
h[i] = this.horn[i - 1];
}
this.horn = h;
} | 3 |
public static String numberToString(Number number)
throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 6 |
static int DFS(int r, int c, int t) {
int s = side(r, c);
for (int[] d : dir)
if (inside(r + d[0], c + d[1]) && v[r + d[0]][c + d[1]] != t && on[r + d[0]][c + d[1]]) {
v[r + d[0]][c + d[1]] = t;
s |= DFS(r + d[0], c + d[1], t);
}
return s;
} | 4 |
public void insertarEnMedio( E pData, Nodo<E> pNodoPrevio){
if (pNodoPrevio == cabeza){
this.insertar(pData);
return;
}
Nodo<E> nuevoNodo = new Nodo<>(pData);
Nodo<E> nodoTmp = pNodoPrevio.getSiguiente();
pNodoPrevio.siguiente = nuevoNodo;
nuevoNodo.previo = pNodoPrevio;
nuevoNodo.siguiente = nodoTmp;
nodoTmp.previo = nuevoNodo;
this.talla++;
} | 1 |
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
DoTurn(pw);
pw.FinishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
}
} | 4 |
public static boolean search2DMatrix(int[][] matrix, int target) {
int start = 0;
int end = matrix.length-1;
int row=0;
while(start<=end)
{
int midrow = (start + end)/2;
if(target<matrix[midrow][0])
{
end = midrow-1;
}else if(target>=matrix[midrow][0] && (midrow==matrix.length-1 || target<matrix[midrow+1][0]))
{
row = midrow;
break;
}else
{
start = midrow+1;
}
}
start = 0;
end = matrix[0].length-1;
while(start<=end)
{
int mid = (start + end)/2;
if(target<matrix[row][mid])
{
end = mid-1;
}else if(target==matrix[row][mid])
{
return true;
}else
{
start = mid+1;
}
}
return false;
} | 8 |
private StartupContainer(final String[] args) {
boolean disableGUI = false;
for (final String param : args) {
if ((param != null) && param.equals(stone.Main.NO_GUI_ID)) {
disableGUI = true;
}
}
this.io = new IOHandler(disableGUI ? null : Main.TOOLNAME);
boolean jar_ = false;
Path workingDirectory_ = null;
try {
final Class<?> loaderClass = StartupContainer.loader.getClass();
jar_ = (boolean) loaderClass.getMethod("wdIsJarArchive").invoke(
StartupContainer.loader);
workingDirectory_ = Path.getPath(loaderClass
.getMethod("getWorkingDir").invoke(StartupContainer.loader)
.toString().split("/"));
} catch (final Exception e) {
e.printStackTrace();
}
this.workingDirectory = workingDirectory_;
this.jar = jar_;
} | 6 |
private String findCommonPrefix(String common, String str) {
if (common.length() == 0 || str.length() == 0) return "";
int i = 0;
while (i < common.length() && i < str.length() && common.charAt(i) == str.charAt(i)) {
i++;
}
if (i == 0) return "";
return common.substring(0, i);
} | 6 |
public static void copyRecursively(File src, File dest) throws IOException {
Assert.isTrue(src != null && (src.isDirectory() || src.isFile()), "Source File must denote a directory or file");
Assert.notNull(dest, "Destination File must not be null");
doCopyRecursively(src, dest);
} | 2 |
private void interpolateBones(SpriterKeyFrame firstFrame, SpriterKeyFrame secondFrame, float xOffset, float yOffset){
for (int i = 0; i < firstFrame.getBones().length; i++) {
SpriterBone bone1 = firstFrame.getBones()[i];
this.tempBones[i].setName(bone1.getName());
this.moddedBones[i].setName(bone1.getName());
SpriterBone bone2 = null;
boolean found = false;
for(int j = 0; j < secondFrame.getBones().length && !found; j++){//Get the right bone to interpolate with
found = secondFrame.getBones()[j].getTimeline() == bone1.getTimeline();
if(found) bone2 = secondFrame.getBones()[j];
}
float x=bone1.getX(),y=bone1.getY(),scaleX=bone1.getScaleX(),scaleY=bone1.getScaleY(),rotation=bone1.getAngle();
if(bone2 != null){
x = SpriterCalculator.calculateInterpolation(bone1.getX(), bone2.getX(), firstFrame.getStartTime(), secondFrame.getStartTime(), this.frame);
y = SpriterCalculator.calculateInterpolation(bone1.getY(), bone2.getY(), firstFrame.getStartTime(), secondFrame.getStartTime(), this.frame);
scaleX = SpriterCalculator.calculateInterpolation(bone1.getScaleX(), bone2.getScaleX(), firstFrame.getStartTime(), secondFrame.getStartTime(), this.frame);
scaleY = SpriterCalculator.calculateInterpolation(bone1.getScaleY(), bone2.getScaleY(), firstFrame.getStartTime(), secondFrame.getStartTime(), this.frame);
rotation = SpriterCalculator.calculateAngleInterpolation(bone1.getAngle(), bone2.getAngle(), firstFrame.getStartTime(), secondFrame.getStartTime(), this.frame);
}
rotation += this.moddedBones[i].getAngle();
scaleX *= this.moddedBones[i].getScaleX();
scaleY *= this.moddedBones[i].getScaleY();
this.tempBones[i].setAngle(rotation);
this.tempBones[i].setScaleX(scaleX);
this.tempBones[i].setScaleY(scaleY);
this.tempBones[i].setX(x);
this.tempBones[i].setY(y);
this.tempBones[i].setId(bone1.getId());
this.tempBones[i].setTimeline(bone1.getTimeline());
this.tempBones[i].setParent(bone1.getParent());
this.tempBones[i].setName(bone1.getName());
this.tempBones[i].setSpin(bone1.getSpin());
if(this.transitionFixed){
this.tempBones[i].copyValuesTo(this.lastFrame.getBones()[i]);
if(!found) this.tempBones[i].setTimeline(-1);
}
if (this.tempBones[i].getParent() != null) {
this.tempBones[i].setAngle(this.tempBones[i].getAngle() + tempBones[this.tempBones[i].getParent()].getAngle());
this.tempBones[i].setScaleX(this.tempBones[i].getScaleX() * tempBones[this.tempBones[i].getParent()].getScaleX());
this.tempBones[i].setScaleY(this.tempBones[i].getScaleY() * tempBones[this.tempBones[i].getParent()].getScaleY());
float[] newstuff = SpriterCalculator.rotatePoint(tempBones[this.tempBones[i].getParent()], this.tempBones[i].getX(), this.tempBones[i].getY());
this.tempBones[i].setX(newstuff[0]);
this.tempBones[i].setY(newstuff[1]);
}
else{
this.tempBones[i].setAngle(this.tempBones[i].getAngle() + this.rootParent.getAngle());
this.tempBones[i].setScaleX(this.tempBones[i].getScaleX() * this.rootParent.getScaleX());
this.tempBones[i].setScaleY(this.tempBones[i].getScaleY() * this.rootParent.getScaleY());
float[] newstuff = SpriterCalculator.rotatePoint(this.rootParent, this.tempBones[i].getX(), this.tempBones[i].getY());
this.tempBones[i].setX(newstuff[0]);
this.tempBones[i].setY(newstuff[1]);
}
this.moddedBones[i].setX(this.tempBones[i].getX()+xOffset);
this.moddedBones[i].setY(this.tempBones[i].getY()+yOffset);
}
} | 8 |
public static int[][][] readmodel(String path){
int[][][] out = new int[3][aa][windowsize];
//Letzte Zeile des Modells auf 0 setzen
try{
FileReader input = new FileReader(path);
BufferedReader br = new BufferedReader(input);
String line;
line = br.readLine();
if(line.startsWith("//")){
br.readLine();
}
int k = -1;
while((line = br.readLine()) != null){
if(line.startsWith("=")) {k++; br.readLine();}
else if(line.startsWith("Y")) {
String[] s = line.split("\t");
char c = s[0].charAt(0);
for(int i = 0; i < s.length - 1; i++){
out[k][19][i] = Integer.parseInt(s[i+1]);
}
br.readLine(); br.readLine();
} else {
String[] s = line.split("\t");
char c = s[0].charAt(0);
for(int i = 0; i < s.length - 1; i++){
out[k][aaint(c)][i] = Integer.parseInt(s[i+1]);
}
}
}
br.close();
} catch(FileNotFoundException e){
//System.out.println("Hallo");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out;
} | 8 |
private static void direct_range_search(finger_print fp, double dis,
Data data) {
ArrayList<Integer> lst1 = new ArrayList<Integer>();
HashMap<Integer, Integer> potent = new HashMap<Integer, Integer>();
ArrayList<Integer> lst2 = new ArrayList<Integer>();
// to be commented
/*for (int i : data.data_set.keySet()) {
if (fp.getDistance(data.data_set.get(i)) < dis) {
lst2.add(i);
//System.out.print(" " + fp.getDistance(data.data_set.get(i)));
}
}
System.out.println(lst2);
lst2.clear();
*/
for (Integer fid : fp.feature_map.keySet()) {
if (finger_print.invert_index.containsKey(fid)) {
for (Integer id : finger_print.invert_index.get(fid).keySet()) {
if (!potent.containsKey(id)) {
potent.put(id, 1);
lst1.add(id);
}
}
}
}
for (int i = 0; i < lst1.size(); i++) {
if (fp.getDistance(data.data_set.get(lst1.get(i))) < dis) {
lst2.add(lst1.get(i));
}
}
//System.out.println(lst1.size());
//System.out.println();
} | 6 |
public void siguienteRegla() throws IOException
{
String antecedentes[] = new String[Ante.length];
String consecuentes[] = new String[Cons.length];
char etiqueta[] = new char[15];
for(int j = 0; j < antecedentes.length;j++)
{
for (int i = 0; i < 15; i++)
etiqueta[i] = lectorMaestro.readChar();
antecedentes[j] = new String(etiqueta);
System.out.print(antecedentes[j]+" ");
}
System.out.print("-> ");
for(int i = 0; i < consecuentes.length; i ++)
{
for (int j = 0; j < 15; j++)
{
etiqueta[j] = lectorMaestro.readChar();
}
consecuentes[i] = new String(etiqueta);
System.out.print(consecuentes[i]+" ");
}
System.out.println();
tempA = antecedentes;
tempB = consecuentes;
puntMaestro = lectorMaestro.getFilePointer();
} | 4 |
final public void AndExpression() throws ParseException {
Token t=null;
EqualityExpression();
label_11:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case BIT_AND:
case BIT_ANDX:
;
break;
default:
break label_11;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case BIT_AND:
t = jj_consume_token(BIT_AND);
break;
case BIT_ANDX:
t = jj_consume_token(BIT_ANDX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
EqualityExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
} | 8 |
public void test_15_DnaCoder_copy_1() {
DnaCoder dnaCoder = DnaCoder.get();
// Rand
long seed = 20100809;
Random rand = new Random(seed);
int numTests = 10000;
int maxLen = 1000;
for( int i = 1; i < numTests; i++ ) {
int seqlen = rand.nextInt(maxLen) + 10;
String srcStr = randSeq(seqlen, rand);
String dstStr = randSeq(seqlen, rand);
// Create sequences
DnaSequence src = new DnaSequence(srcStr);
DnaSequence dst = new DnaSequence(dstStr);
// Random start & length
int srcStart = rand.nextInt(src.length());
int dstStart = srcStart;
int len = rand.nextInt((Math.min(src.length() - srcStart, dst.length() - dstStart)));
// Sub strings to compare
String subStr = srcStr.substring(srcStart, srcStart + len);
String dstBefore = dst.getSequence().substring(0, dstStart);
String dstAfter = dst.getSequence().substring(dstStart + len);
if( verbose ) {
System.out.println("\n-----------------------------------------------------------------------------------------------");
System.out.println("src:\t" + src);
System.out.println("dst:\t" + dst);
System.out.println("sub:\t" + subStr);
System.out.println("bef:\t" + dstBefore);
System.out.println("aft:\t" + dstAfter);
}
// Copy test
dnaCoder.copyBases(src.getCodes(), dst.getCodes(), srcStart, len);
String subStrDst = dst.getSequence().substring(dstStart, dstStart + len);
String dstBefore2 = dst.getSequence().substring(0, dstStart);
String dstAfter2 = dst.getSequence().substring(dstStart + len);
if( verbose ) {
System.out.println("\ndst:\t" + dst);
System.out.println("sub:\t" + subStrDst);
}
if( !subStr.equals(subStrDst) ) { throw new RuntimeException("Substrings do not match!"); }
if( !dstBefore2.equals(dstBefore) ) { throw new RuntimeException("Substrings 'before' do not match!\n\tdstBefore:\t" + dstBefore + "\n\tdstBefore2:\t" + dstBefore2); }
if( !dstAfter2.equals(dstAfter) ) { throw new RuntimeException("Substrings 'after' do not match!"); }
Gpr.showMarkStderr(i, 1000);
}
} | 6 |
public void cargarListaBorrar(){
try{
r_con.Connection();
String puntoVenta=combo_pto_venta.getSelectedItem().toString();
ResultSet rs=r_con.Consultar("select tc_codigo,tc_descripcion,vxc_numero "
+ " from punto_venta,tipo_comprobante,ptoventa_x_tipocomprobante "
+ " where pv_codigo=vxc_id_pto_venta and tc_codigo=vxc_id_tipo_comprobante and pv_codigo="+puntoVenta);
DefaultListModel modelo = new DefaultListModel();
while(rs.next()){
String cadena=rs.getString(1)+" - "+rs.getString(2);
cadena=validar.soloPrimerMayus(cadena);
modelo.addElement(cadena);
}
listaComprobantes.setModel(modelo);
// ##################### Multiple seleccion ####################
// me permite seleccionar varios elementos dentro de la lista
listaComprobantes.setSelectionModel(new DefaultListSelectionModel() {
private int i0 = -1;
private int i1 = -1;
public void setSelectionInterval(int index0, int index1) {
if(i0 == index0 && i1 == index1){
if(getValueIsAdjusting()){
setValueIsAdjusting(false);
setSelection(index0, index1);
}
}else{
i0 = index0;
i1 = index1;
setValueIsAdjusting(false);
setSelection(index0, index1);
}
}
private void setSelection(int index0, int index1){
if(super.isSelectedIndex(index0)) {
super.removeSelectionInterval(index0, index1);
}else {
super.addSelectionInterval(index0, index1);
}
}
});
// ############################################################
} catch (SQLException ex) {
Logger.getLogger(IGUI_Asignar_Pto_Venta_Comprobante.class.getName()).log(Level.SEVERE, null, ex);
} finally {
r_con.cierraConexion();
}
} | 6 |
@Override
public boolean equals(Object obj) {
// generated
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Measurement other = (Measurement) obj;
if (temperature == null) {
if (other.temperature != null)
return false;
} else if (!temperature.equals(other.temperature))
return false;
if (timestamp == null) {
if (other.timestamp != null)
return false;
} else if (!timestamp.equals(other.timestamp))
return false;
return true;
} | 9 |
public GameHistory() {
history = new Field[MAX_NUMBER_OF_STEPS];
for (int i = 0; i < MAX_NUMBER_OF_STEPS; i++){
history[i] = new Field();
history[i].emptyField();
}
} | 1 |
private static void detectFirstCycle(ArrayList<Integer> numSeq){
int length = numSeq.size();
ArrayList<Integer> subSeq = new ArrayList<Integer>();
subSeq.add(numSeq.get(0));
int size = 1;
for(int i = 1; i<length; i++){
for(int j=0; j<size; j++){
if(subSeq.get(j)==numSeq.get(i)){
int k = j;
int g = i;
while(k<size){
if(subSeq.get(k)!=numSeq.get(g))
break;
k++;
g++;
}
if(k==size){
System.out.print("" + numSeq.get(i));
for(int m=i+1; m<(i+size-j); m++){
System.out.print(" " + numSeq.get(m));
}
System.out.println();
return;
}
}
}
subSeq.add(numSeq.get(i));
size++;
}
System.out.println("No cycles detected.");
} | 7 |
@Override
public void update(long deltaMs) {
if(ai != null) {
ai.update(deltaMs);
}
} | 1 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof AgencyAndId))
return false;
AgencyAndId other = (AgencyAndId) obj;
if (!agencyId.equals(other.agencyId))
return false;
if (!id.equals(other.id))
return false;
return true;
} | 5 |
public treeNode getNextInsertParent() {
treeNode parent = this.lastInsertNode.parent;
// last insert is right child of parent
// scenario 1锛�current node is not the right most on its level, then
// parent's next right sibling's left child is the next spot to insert
if (!isRightMost(this.lastInsertNode)) {
return getNextRightSibling(parent);
} else {// scenario 2: parent is the right most on its level, then next
// insert spot should be the left child of the left most node on
// current node level
return this.getLeftMostNode(this.root);
}
} | 1 |
public int getType() {
return type;
} | 0 |
private ArcDef createArcDef() {
ConsolFun consolFun = (ConsolFun) consolFunCombo.getSelectedItem();
double xff;
try {
xff = Double.parseDouble(xffField.getText());
if (xff < 0 || xff >= 1D) {
throw new NumberFormatException();
}
}
catch (NumberFormatException nfe) {
Util.error(this, "X-files factor must be a number not less than 0.0 and less than 1.0");
return null;
}
int steps;
try {
steps = Integer.parseInt(stepsField.getText());
if (steps <= 0) {
throw new NumberFormatException();
}
}
catch (NumberFormatException nfe) {
Util.error(this, "Number of steps must be a positive integer");
return null;
}
int rows;
try {
rows = Integer.parseInt(rowsField.getText());
if (rows <= 0) {
throw new NumberFormatException();
}
}
catch (NumberFormatException nfe) {
Util.error(this, "Number of rows must be a positive integer");
return null;
}
try {
return new ArcDef(consolFun, xff, steps, rows);
}
catch (Exception e) {
// should not be here ever!
Util.error(this, e);
return null;
}
} | 8 |
public String getTypeAlias(String typeSig) {
String alias = (String) aliasesHash.get(typeSig);
if (alias == null) {
StringBuffer newSig = new StringBuffer();
int index = 0, nextindex;
while ((nextindex = typeSig.indexOf('L', index)) != -1) {
newSig.append(typeSig.substring(index, nextindex + 1));
index = typeSig.indexOf(';', nextindex);
String typeAlias = getClassAlias(typeSig.substring(
nextindex + 1, index).replace('/', '.'));
newSig.append(typeAlias.replace('.', '/'));
}
alias = newSig.append(typeSig.substring(index)).toString().intern();
aliasesHash.put(typeSig, alias);
}
return alias;
} | 2 |
final void method624(int i, int i_195_, int i_196_, int i_197_) {
anInt5534++;
for (int i_198_ = 0; anInt5632 > i_198_; i_198_++) {
int i_199_ = 0xffff & aShortArray5580[i_198_];
int i_200_ = (i_199_ & 0xfd9e) >> 1107300586;
int i_201_ = i_199_ >> -942433721 & 0x7;
if ((i ^ 0xffffffff) != 0)
i_200_ = (i_197_ * (-i_200_ + i) >> -838697721) + i_200_;
int i_202_ = i_199_ & 0x7f;
if (i_195_ != -1)
i_201_ = (i_197_ * (i_195_ - i_201_) >> 369627111) + i_201_;
if ((i_196_ ^ 0xffffffff) != 0)
i_202_ += (i_196_ + -i_202_) * i_197_ >> -1261204825;
aShortArray5580[i_198_]
= (short) (Class273.bitOr
(Class273.bitOr(i_201_ << 1165960167,
i_200_ << -3437622),
i_202_));
}
if (aClass118Array5621 != null) {
for (int i_203_ = 0;
(anInt5536 ^ 0xffffffff) < (i_203_ ^ 0xffffffff); i_203_++) {
Class118 class118 = aClass118Array5621[i_203_];
Class48 class48 = aClass48Array5596[i_203_];
((Class48) class48).anInt858
= ((0xffffff
& (Class10.anIntArray179
[0xffff & (aShortArray5580
[((Class118) class118).anInt1783])]))
| ((Class48) class48).anInt858 & ~0xffffff);
}
}
if (aClass123_5610 != null)
((Class123) aClass123_5610).anInterface2_1811 = null;
} | 7 |
private void lsSort (final int ISA, final int n, final int depth) {
final int[] SA = this.SA;
int ISAd;
int first, last, i;
int t, skip;
for (ISAd = ISA + depth; -n < SA[0]; ISAd += (ISAd - ISA)) {
first = 0;
skip = 0;
do {
if ((t = SA[first]) < 0) {
first -= t;
skip += t;
} else {
if (skip != 0) {
SA[first + skip] = skip;
skip = 0;
}
last = SA[ISA + t] + 1;
lsIntroSort (ISA, ISAd, ISA + n, first, last);
first = last;
}
} while (first < n);
if (skip != 0) {
SA[first + skip] = skip;
}
if (n < (ISAd - ISA)) {
first = 0;
do {
if ((t = SA[first]) < 0) {
first -= t;
}
else {
last = SA[ISA + t] + 1;
for (i = first; i < last; ++i) {
SA[ISA + SA[i]] = i;
}
first = last;
}
} while (first < n);
break;
}
}
} | 9 |
@Override
public boolean activate() {
return (Constants.BEAR_AREA.contains(Players.getLocal())
&& !Inventory.isFull() && !Widgets.get(13, 0).isOnScreen()
&& !isTalking() && !isAnswering() && !isListening() && !Settings.noob
);
} | 6 |
public void close() {
if (USE_INTERNET) {
try {
AddressProvider.disconnect();
} catch (MalformedURLException ex) {
System.err.println("Could not discconnect correctly... MalformedURLException.");
} catch (IOException ex) {
System.err.println("Could not discconnect correctly... IOException.");
}
}
if (gameClient != null) {
gameClient.close();
}
if (gameServer != null) {
gameServer.close();
}
if (padServer != null) {
padServer.closeConnection();
}
} | 6 |
public boolean setOptionsbarHeight(int height) {
boolean ret = true;
if (height < 0) {
this.optionsbar_Height = UISizeInits.OPTIONSBAR.getHeight();
ret = false;
} else {
if (height > UISizeInits.OPTIONSBAR.getHeight()) {
this.wrapBtnAccInNewElement = true;
} else {
this.wrapBtnAccInNewElement = false;
}
this.optionsbar_Height = height;
}
somethingChanged();
return ret;
} | 2 |
@Override
public DataTable generateDataTable (Query query, HttpServletRequest request) throws DataSourceException
{
DataTable dataTable = null;
try (final Reader reader = new FilterCsv (new BufferedReader (new InputStreamReader (new URL (this.urlYahoo).openStream()))))
{
TableRow row = new TableRow ();
dataTable = CsvDataSourceHelper.read(reader, this.column, false);
dataTable.addColumn(new ColumnDescription (FieldIndice.DAX30.toString(), ValueType.TEXT, FieldIndice.DAX30.toString()));
for (int i = 0; i < dataTable.getNumberOfRows(); i++)
{
String lastPriceDataTable = dataTable.getCell(i, 0).toString();
String changePercentDataTable = dataTable.getCell(i, 1).toString();
if (! lastPriceDataTable.matches(".*\\d.*"))
lastPriceDataTable = "0";
if (! changePercentDataTable.matches(".*\\d.*"))
changePercentDataTable = "0";
String lastPriceString = this.formatter.format(Double.parseDouble(lastPriceDataTable));
String changePercentString = this.formatter.format(Double.parseDouble(changePercentDataTable));
row.addCell(lastPriceString + " (" + changePercentString + "%)");
}
dataTable.addRow(row);
}
catch (MalformedURLException e)
{
System.out.println("TableIndiceEU generateDataTable() MalformedURLException " + "URL : " + this.urlYahoo + " " + e);
}
catch (IOException e)
{
System.out.println("TableIndiceEU generateDataTable() IOException " + e);
}
return dataTable;
} | 5 |
@Override
public void advanceMinute() {
for(int i = 0; i < cashiers; i++){
lines[i].get(0).servedMinute();
if(lines[i].get(0).getExpectedServiceTime() <= 0){
lines[i].remove(lines[i].get(0));
}
}
} | 2 |
@Override
public void setValueAt(Object value, int row, int column) {
// Get the selected Pair
final Pair<Boolean, String> selected = data.get(row);
// Mark the sync status on the actual object
folderLoop: for (final FolderConfig folderConfig : GuiUtils.syncConfig.getConfigs()) {
for (final SongConfig songConfig : folderConfig.getSongs()) {
if (songConfig.getSongUrl().equals(selected.getElement1())) {
songConfig.setSyncOn((Boolean) value);
break folderLoop;
}
}
}
// Reset the GUI
data.set(row, Pair.createPair((Boolean) value, selected.getElement1()));
} | 3 |
private BitSet selectRBonds(String str) {
int n = model.rBonds.size();
if (n == 0)
return null;
BitSet bs = new BitSet(n);
if ("selected".equalsIgnoreCase(str)) {
synchronized (model.rBonds) {
for (int i = 0; i < n; i++) {
if (model.getRBond(i).isSelected())
bs.set(i);
}
}
return bs;
}
String strLC = str.toLowerCase();
if (strLC.indexOf("involve") != -1) {
str = str.substring(7).trim();
strLC = str.toLowerCase();
if (strLC.indexOf("atom") != -1) {
str = str.substring(4).trim();
if (selectRbondsInvolving(str, bs)) {
model.setRBondSelectionSet(bs);
return bs;
}
}
else {
out(ScriptEvent.FAILED, "Unrecognized expression: " + str);
return null;
}
}
if (selectFromCollection(str, n, bs)) {
model.setRBondSelectionSet(bs);
return bs;
}
out(ScriptEvent.FAILED, "Unrecognized expression: " + str);
return null;
} | 8 |
public void read(String filename) throws FileNotFoundException, IOException {
String curRow[];
BufferedReader file = new BufferedReader(new FileReader(filename));
try {
int n = Integer.valueOf(file.readLine());
L = new int[n][n];
for (int i = 0; i < n; i++) {
curRow = file.readLine().split(delim);
for (int j = 0; j < n; j++)
L[i][j] = Integer.valueOf(curRow[j]);
}
urls = new String[n];
for (int i = 0; i < n; i++)
urls[i] = file.readLine();
} catch (IOException e) {
throw e;
} finally {
file.close();
}
} | 4 |
private MessungInfo lookupMessung(int station_id, Date date) throws SQLException
{
try
{
MessungInfo messung = new MessungInfo();
ResultSet setMinDate = connection.query(
"select *" +
"from dbsp_wettermessung\n" +
"where station_id = " + station_id + "\n" +
"order by datum ASC\n" +
"limit 1\n" +
";",
false
);
if( !setMinDate.next())
{
return null;
}
ResultSet setMaxDate = connection.query(
"select *" +
"from dbsp_wettermessung\n" +
"where station_id = " + station_id + "\n" +
"order by datum DESC\n" +
"limit 1\n" +
";",
false
);
setMaxDate.next();
PreparedStatement stmt = connection.prepareStmt(
"select *" +
"from dbsp_wettermessung\n" +
"where station_id = " + station_id + "\n" +
"and datum = ?\n" +
"order by datum ASC\n" +
"limit 1\n" +
";"
);
java.sql.Date sQLDate = new java.sql.Date(date.getTime());
//System.out.println("sqlDatum: " + sQLDate.toString());
stmt.setDate(1, sQLDate);
ResultSet set = stmt.executeQuery();
/*ResultSet set = connection.query(
"select *" +
"from dbsp_wettermessung\n" +
"where station_id = " + station_id + "\n" +
"and datum >= " + date.toString() + "\n" +
"order by datum ASC\n" +
"limit 10\n" +
";",
false
);*/
if( !set.next())
{
System.out.println("no entries found! the date must be between " +
setMinDate.getDate("datum") + " and " +
setMaxDate.getDate("datum")
);
return null;
}
messung.station_id = set.getInt("station_id");
messung.datum = set.getDate("datum");
messung.qualitaet = set.getInt("qualitaet");
messung.min_5cm = set.getDouble("min_5cm");
messung.min_2m = set.getDouble("min_2m");
messung.mittel_2m = set.getDouble("mittel_2m");
messung.max_2m = set.getDouble("max_2m");
messung.relative_feuchte = set.getDouble("relative_feuchte");
messung.mittel_windstaerke = set.getDouble("mittel_windstaerke");
messung.max_windgeschwindigkeit = set.getDouble("max_windgeschwindigkeit");
messung.sonnenscheindauer = set.getDouble("sonnenscheindauer");
messung.mittel_bedeckungsgrad = set.getDouble("mittel_bedeckungsgrad");
messung.niederschlagshoehe = set.getDouble("niederschlagshoehe");
messung.mittel_luftdruck = set.getDouble("mittel_luftdruck");
return messung;
}
catch(SQLException e)
{
throw e;
}
} | 3 |
private static String[][] parseCSV(String text) {
Logger.log("Starting parsing on text:\n" + text);
String[] lines = text.split("\n");
ArrayList<String[]> array = new ArrayList<>();
for (String line : lines) {
array.add(line.split(","));
}
String[][] out = new String[array.size()][array.get(0).length];
for (int i = 0; i < out.length; i++) {
out[i] = array.get(i);
}
return out;
} | 2 |
public static List<Cromossomo> roleta(List<Cromossomo> cromossomos, int nElementos) {
int dimensao = cromossomos.size();
double fitnessTotal = 0;
double[] fitness = new double[dimensao];
//pegar o primeiro fitness como menor temporariamente
double menorFitness = 1 / cromossomos.get(0).getFitness();
for (int i = 0; i < dimensao; i++) {
double fitnessAtual = 1 / cromossomos.get(i).getFitness();
if (fitnessAtual < menorFitness) {
menorFitness = fitnessAtual;
}
fitness[i] = fitnessAtual;
}
//faz o escalonamento
for (int i = 0; i < dimensao; i++) {
fitness[i] = fitness[i] + menorFitness;
fitnessTotal += fitness[i];
fitness[i] = fitnessTotal;
}
ArrayList<Cromossomo> cromossomosSelecionados = new ArrayList<>();
for (int i = 0; i < nElementos; i++) {
double rand = 0 + (Math.random() * ((fitnessTotal - 0)));
for (int j = 0; j < dimensao; j++) {
if (rand <= fitness[j]) {
cromossomosSelecionados.add(cromossomos.get(i));
}
}
}
if (cromossomosSelecionados.size() != nElementos) {
//throw new RuntimeException("Nao foi achado o fitness na roleta");
}
return cromossomosSelecionados;
} | 7 |
public void set(Object t) {
this.t = t;
} | 0 |
@Override
public void readAssemblyFile() {
String line;
Scanner s = null;
boolean leadingCommentsFinished = false; //To signal end of any leading comments
try {
s = new Scanner(new BufferedReader(new FileReader(fileReference)));
while (s.hasNextLine()) {
line = s.nextLine();
if (!leadingCommentsFinished && line.length() != 0) {
if (line.startsWith("#")) {
leadingComments.add(line); //Add any comments at beginning of file to separate list for better display
}
else {
leadingCommentsFinished = true;
}
}
if (leadingCommentsFinished) { //Don't add leading comments to programString
if (line.matches("[\\s]*")) { //Detect lines consisting of only blank spaces
displayProgram.add(line); //Ok to add blank lines to the list of code for GUI display
}
else { //Do not add lines consisting of only blank spaces to programString
programString.add(line);
displayProgram.add(line);
}
}
}
}
catch (FileNotFoundException ex) {
this.fileReference = null;
JOptionPane.showMessageDialog(null, "File not found!", "Error!", JOptionPane.WARNING_MESSAGE);
}
finally {
if (s != null) {
s.close();
}
}
} | 8 |
@Override
public void update(Observable o, Object arg) {
ServerModel model = presenter.getClientModel().getServerModel();
Player player = model.getPlayerByID(presenter.getPlayerInfo().getID());
getView().setElementAmount(ResourceBarElement.BRICK, player.getBrick());
getView().setElementAmount(ResourceBarElement.ORE, player.getOre());
getView().setElementAmount(ResourceBarElement.SHEEP, player.getSheep());
getView().setElementAmount(ResourceBarElement.WHEAT, player.getWheat());
getView().setElementAmount(ResourceBarElement.WOOD, player.getWood());
getView().setElementAmount(ResourceBarElement.CITY, player.getCities());
getView().setElementAmount(ResourceBarElement.SETTLEMENT, player.getSettlements());
getView().setElementAmount(ResourceBarElement.ROAD, player.getRoads());
getView().setElementAmount(ResourceBarElement.SOLDIERS, player.getSoldiers());
if(presenter.isPlayersTurn()) {
if(player.canBuildCity()){
getView().setElementEnabled(ResourceBarElement.CITY, true);
}else{
getView().setElementEnabled(ResourceBarElement.CITY, false);
}
if(player.canBuildRoad()){
getView().setElementEnabled(ResourceBarElement.ROAD, true);
}else{
getView().setElementEnabled(ResourceBarElement.ROAD, false);
}
if(player.canBuildSettlement()){
getView().setElementEnabled(ResourceBarElement.SETTLEMENT, true);
}else{
getView().setElementEnabled(ResourceBarElement.SETTLEMENT, false);
}
if(model.getDeck().getTotalDevCardCount()>0&&player.canBuyDevCard()){
getView().setElementEnabled(ResourceBarElement.BUY_CARD, true);
}else{
getView().setElementEnabled(ResourceBarElement.BUY_CARD, false);
}
}
else {
getView().setElementEnabled(ResourceBarElement.CITY, false);
getView().setElementEnabled(ResourceBarElement.ROAD, false);
getView().setElementEnabled(ResourceBarElement.SETTLEMENT, false);
}
} | 6 |
public static void loadResources()
{
log.info("loading resources...");
// load servericon
final String iconPath = "server-icon.png";
final File serverIcon = new File(iconPath);
if (!serverIcon.exists())
{
log.warning("icon file '" + iconPath + "' not found");
icon = null;
}
else
{
final String base64 = FileHelper.decodeBase64(serverIcon);
if (base64 == null || base64.isEmpty())
{
log.warning("something went wrong while decoding '" + iconPath + "'");
icon = null;
}
else
{
icon = "data:image/png;base64," + base64;
log.info("icon file '" + iconPath + "' successfully loaded");
}
}
// load version
verText = parseColors(
getFileString("version.txt")
);
// load motd
motd = parseColors(
getFileString("motd.txt")
);
// kick message
kickMessage = parseColors(
getFileString("kickmessage.txt")
);
// players
{
final String str = getFileString("players.txt");
if(str != null)
{
final List<String> list = new ArrayList<String>();
for(final String player : str.replace("\r", ",").replace("\n", ",").split(","))
{
if(player == null || player.isEmpty())
continue;
list.add(parseColors(player));
}
players = list.toArray(new String[0]);
}
}
// maxplayers
{
final String str = getFileString("maxplayers.txt");
try
{
maxPlayers = (str == null ? null : new Integer(Integer.parseInt(str)));
}
catch (NumberFormatException e)
{
log.warning("invalid number in 'maxplayers.txt'");
maxPlayers = null;
}
}
} | 9 |
@Override
public void replaceArgument(Value replace, Value i, boolean throwOnError)
throws Exception {
boolean found = false;
if(arg1.equals(replace)) {
arg1 = i;
found = true;
}
if(arg2.equals(replace)) {
arg2 = i;
found = true;
}
if(!found && throwOnError) {
throw new Exception("error replacing argument, argument not present in instruction");
}
} | 4 |
public boolean portsAreValid(){
if(reciever == null || sender == null){
return false;
}
return true;
} | 2 |
public void updateWantedGoods() {
List<GoodsType> goodsTypes = new ArrayList<GoodsType>(getSpecification().getGoodsTypeList());
Collections.sort(goodsTypes, wantedGoodsComparator);
int wantedIndex = 0;
for (GoodsType goodsType : goodsTypes) {
// The natives do not trade military or non-storable goods.
if (goodsType.isMilitaryGoods() || !goodsType.isStorable())
continue;
if (getNormalGoodsPriceToBuy(goodsType, GoodsContainer.CARGO_SIZE)
<= GoodsContainer.CARGO_SIZE * TRADE_MINIMUM_PRICE
|| wantedIndex >= wantedGoods.length) break;
wantedGoods[wantedIndex] = goodsType;
wantedIndex++;
}
for (; wantedIndex < wantedGoods.length; wantedIndex++) {
wantedGoods[wantedIndex] = null;
}
} | 6 |
public boolean dropTetrominoe(){
for(int x=emplacement.getNombreColonne()-1 ; x>=0 ; x--)
for(int y=emplacement.getNombreRangee()-1 ; y>=0 ; y--)
if(!emplacement.IsEmpty(x, y))
try{
emplacement.setCoordonee(x, y, false);
emplacement.setCoordonee(x, y+1, true);
}catch(Exception e){
isFalling=false;
return false;
}
return true;
} | 4 |
private JPanel getPanCodes() {
if (panCodes == null) {
panCodes = new JPanel();
panCodes.setLayout(new BoxLayout(getPanCodes(), BoxLayout.Y_AXIS));
ButtonGroup group=new ButtonGroup();
for(int i=0;i<Interface.CODES.values().length;i++) {
final int t=i;
JRadioButton temp=new JRadioButton(Interface.CODES.values()[i].getNom());
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionne=Interface.CODES.values()[t];
if(selectionne.creerCode() instanceof ICodeClePublique) {
if(decrypte) {
labSaisieCle.setText("Ou saisie manuelle de la cl (prive ou complte):");
}
else {
labSaisieCle.setText("Ou saisie manuelle de la cl (publique ou complte):");
}
}
else {
labSaisieCle.setText("Ou saisie manuelle de la cl:");
}
cleManu=true;
getTextCheminCle().setEnabled(false);
getTextSaisieCle().setEnabled(true);
getTextSaisieCle().requestFocus();
bloque=false;
if(!decrypte) {
getButGenererCle().setEnabled(true);
}
if(selectionne.creerCode() instanceof Rot13 || selectionne.creerCode() instanceof Rot47) {
if(selectionne.creerCode() instanceof Rot13) {
getTextSaisieCle().setText("13");
}
else {
getTextSaisieCle().setText("47");
}
getTextSaisieCle().setEnabled(false);
if(!decrypte) {
getButGenererCle().setEnabled(false);
}
bloque=true;
}
}
});
group.add(temp);
panCodes.add(temp);
tabRad[i]=temp;
}
panCodes.setBorder(BorderFactory.createTitledBorder("Code :"));
}
return panCodes;
} | 9 |
public Double getLoyalty(String playerName) {
if (loyaltyCache.containsKey(playerName))
return loyaltyCache.get(playerName);
Double loyalty = Config.leadershipSkillDefault;
String SQL = "SELECT `loyalty` FROM " + tblSkills + " WHERE `player` = ? AND `leadership` IS NOT NULL";
Connection con = getSQLConnection();
try {
PreparedStatement statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
ResultSet result = statement.executeQuery();
while (result.next()) {
loyalty = result.getDouble(1);
}
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
loyaltyCache.put(playerName, loyalty);
return loyalty;
} | 3 |
public void run(){
Scanner uScan;
String sMsg;
String sStatus = "";
String sPrevStatus = "";
while(true){
//Check to see if the player is in an active game:
uScan = new Scanner(Client.sendMsg("GET_PLAYER_STATUS"));
uScan.next();
sStatus = uScan.next();
if(sStatus.equals("ACTIVE") && sPrevStatus.equals("WAITING")){
new GameUI();
dispose();
}
sPrevStatus = sStatus;
//Update the list boxes every second:
//Thread.sleep(1000);
//Update the players in game:
//Get the game index:
sMsg = Client.sendMsg("GET_PLAYER_GAME_INDEX");
if(sMsg.equals("GET_PLAYER_GAME_INDEX FAILURE")){
continue;
}
uScan = new Scanner(sMsg);
uScan.next();
int nGameIndex = uScan.nextInt();
if(nGameIndex < 0){
continue;
}
sMsg = Client.sendMsg("GET_GAME_AVAILABLE_NUM_PLAYERS " + nGameIndex);
if(sMsg.equals("GET_GAME_AVAILABLE_NUM_PLAYERS FAILURE")){
continue;
}
vPlayersInGameUsernames.clear();
vPlayersInGameCharacters.clear();
uScan.close();
uScan = new Scanner(sMsg);
uScan.next();
int nNumPlayersInGame = Integer.parseInt(uScan.next());
uScan.close();
for(int i=0; i<nNumPlayersInGame; i++){
sMsg = Client.sendMsg("GET_GAME_AVAILABLE_PLAYER " + nGameIndex + " " + i);
if(sMsg.equals("GET_GAME_AVAILABLE_PLAYER FAILURE")){
continue;
}
uScan = new Scanner(sMsg);
uScan.next();
vPlayersInGameUsernames.add(uScan.next());
vPlayersInGameCharacters.add(uScan.next());
uScan.close();
}
populateListStrings(uModelPlayersInGame, vPlayersInGameUsernames, vPlayersInGameCharacters);
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TClassout other = (TClassout) obj;
if (!Objects.equals(this.kodeClass, other.kodeClass)) {
return false;
}
return true;
} | 3 |
public CompiledExpression compileExpression(String expressionDefinition)
throws CompilationException
{
Syntax syntax = getSyntax();
String whiteSpaces = syntax.getWhiteSpaceCharacters() != null ? syntax
.getWhiteSpaceCharacters() : "";
StringTokenizer rechStr = new StringTokenizer(expressionDefinition,
whiteSpaces);
if (!rechStr.hasMoreTokens())
throw new CompilationException(CompilationException.SYNTAX_ERROR, 0);
// The hashtable will be filled with parameters during parsing
Hashtable parameters = new Hashtable(1);
int assignmentIndex = 0;
if (syntax.getAssignmentOperator() != null
&& syntax.getAssignmentOperator().length() > 0)
{
rechStr = new StringTokenizer(expressionDefinition, whiteSpaces);
if (!rechStr.hasMoreTokens()
|| !rechStr.nextToken().startsWith(
syntax.getAssignmentOperator()))
throw new CompilationException(
CompilationException.SYNTAX_ERROR, 0);
assignmentIndex = expressionDefinition.indexOf(syntax
.getAssignmentOperator());
}
// Expression can't be empty
if (assignmentIndex == expressionDefinition.length() - 1)
throw new CompilationException(CompilationException.SYNTAX_ERROR,
assignmentIndex + 1);
// Reuse the parser that parse the expressions of functions
ExpressionNode expressionTree = (ExpressionNode) parseExpression(
expressionDefinition,
assignmentIndex
+ (syntax.getAssignmentOperator() != null ? syntax
.getAssignmentOperator().length() : 0),
parameters);
// Return the instance of CompiledExpression matching
// expressionDefinition
return new CompiledExpression(expressionDefinition, parameters,
expressionParameter, expressionTree);
} | 8 |
public static void main(String[] args) throws Exception
{
/*
gdb.addNode("regionName", null,null);
gdb.addNode("regionName", "agentName",null);
gdb.addNode("regionName", "agentName","pluginName");
gdb.addNode("regionName", "agentName","pluginName2");
gdb.addNode("regionName", "agentName2",null);
gdb.addNode("regionName", "agentName","pluginName");
*/
try
{
String configFile = checkConfig(args);
//Make sure config file
config = new Config(configFile);
commandExec = new CommandExec(); //create command channel
gdb = new GraphDBEngine(); //create graphdb connector
while(!ControllerEngine.GDBActive)
{
System.out.println("Waiting on DGBActive...");
Thread.sleep(1000);;
}
regionalMsgMap = new ConcurrentHashMap<String,ConcurrentLinkedQueue<MsgEvent>>();
resourceScheduleQueue = new ConcurrentLinkedQueue<MsgEvent>();
System.out.println("Starting Futura");
fe = new FuturaEngine();
Thread fe_thread = new Thread(fe);
fe_thread.start();
while(!ControllerEngine.FuturaActive)
{
System.out.println("Waiting on FuturaActive...");
Thread.sleep(1000);;
}
System.out.println("Starting TopologyEngine");
te = new TopologyEngine();
Thread te_thread = new Thread(te);
te_thread.start();
while(!ControllerEngine.TopologyActive)
{
System.out.println("Waiting on TopologyActive...");
Thread.sleep(1000);;
}
/*
System.out.println("Starting Broker");
BrokerEngine be = new BrokerEngine();
*/
System.out.println("Starting SR Scheduler");
se = new SchedulerEngine();
Thread se_thread = new Thread(se);
se_thread.start();
while(!ControllerEngine.SchedulerActive)
{
System.out.println("Waiting on SchedulerActive...");
Thread.sleep(1000);;
}
System.out.println("Starting HTTPInternal Service");
httpServerEngineDownloads httpEngineDownloads = new httpServerEngineDownloads();
Thread httpServerThreadDownloads = new Thread(httpEngineDownloads);
httpServerThreadDownloads.start();
System.out.println("Starting HTTPInternal Service");
httpServerEngineInternal httpEngineInternal = new httpServerEngineInternal();
Thread httpServerThreadInternal = new Thread(httpEngineInternal);
httpServerThreadInternal.start();
System.out.println("Starting HTTPInternal Service");
httpServerEngineExternal httpEngineExternal = new httpServerEngineExternal();
Thread httpServerThreadExternal = new Thread(httpEngineExternal);
httpServerThreadExternal.start();
System.out.println("Starting HTTPPerf Service");
httpServerEnginePerf httpEnginePerf = new httpServerEnginePerf();
Thread httpServerThreadPerf = new Thread(httpEnginePerf);
httpServerThreadPerf.start();
//
/*
System.out.println("adding msg for test2 and test3");
ConcurrentLinkedQueue<MsgEvent> cmq = new ConcurrentLinkedQueue<MsgEvent>();
MsgEvent me = new MsgEvent(MsgEventType.EXEC,"test2","controller2",null,"test message for test2");
me.setParam("src_region", "test2");
me.setParam("dst_region", "test2");
me.setParam("dst_agent", "controller2");
cmq.add(me);
regionalMsgMap.put("test2", cmq);
*/
//
}
catch(Exception ex)
{
System.out.println("Unable to Start HTTP Service : " + ex.toString());
}
} | 5 |
public static void stop(long uid) {
UserNotificationBuffer buffer = getMonitorFor(uid);
buffer.stopNotification();
} | 0 |
@Override
public String process(HttpServletRequest request)
throws MissingRequiredParameter {
ResultSet resultSet = null;
String email = request.getParameter("email");
if (email == null) {
throw new MissingRequiredParameter();
}
String result = null;
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
String query = "SELECT * FROM usuarios WHERE email='" + email
+ "'";
resultSet = statement.executeQuery(query);
result = "{\"status\":\"OK\", \"result\":" + resultSet.next() + "}";
} catch (SQLException e) {
e.printStackTrace();
result = "{\"status\":\"KO\", \"result\": \"Error en el acceso a la base de datos.\"}";
} finally {
try {
if (null != resultSet)
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != statement)
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != connection)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
} | 8 |
@Override
public void paint(Graphics2D g, int width, int height) {
double dividerPercentage = getCaseWidth(g) / (double) getLabelledWidth(g);
int divider = (int) (width * dividerPercentage);
int titleHeight = getTitleHeight(g);
g.drawRect(0, 0, width, height);
g.drawLine(0, 0, divider, titleHeight);
g.drawLine(divider, titleHeight, width, 0);
if (defaultLabelled != null) {
int offset = (int) ((double) divider / width * expression.getWidth(g));
expression.paint(g, divider - offset, 5);
} else {
expression.paint(g, width - expression.getWidth(g) - 10, 5);
}
int labelHeight = 5 + expression.getHeight(g) + 5;
int offset = 0;
for (int i = 0; i < cases.size(); i++) {
Labelled caseLabelled = cases.get(i);
int caseWidth;
if (i != cases.size() - 1) {
double casePercentage = caseLabelled.getWidth(g) / (double) getLabelledWidth(g);
caseWidth = (int) (casePercentage * width);
} else {
caseWidth = divider - offset;
}
if (i != cases.size() - 1) {
int lineOffset = (int) (titleHeight * ((offset + caseWidth) / (double) divider));
g.drawLine(offset + caseWidth, lineOffset, offset + caseWidth, titleHeight);
}
g.translate(offset, titleHeight);
Text label = caseLabelled.getLabel();
label.paint(g, (caseWidth - label.getWidth(g)) / 2, -5 - label.getHeight(g));
caseLabelled.getChild().paint(g, caseWidth, height - titleHeight);
g.translate(-offset, -titleHeight);
offset += caseWidth;
}
if (defaultLabelled != null) {
int position = divider + (width - divider - defaultLabelled.getLabel().getWidth(g)) / 2;
defaultLabelled.getLabel().paint(g, position, labelHeight);
g.translate(divider, titleHeight);
defaultLabelled.getChild().paint(g, width - divider, height - titleHeight);
g.translate(-divider, -titleHeight);
}
} | 5 |
public String getUrl() {
return url;
} | 0 |
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(JanelaCadastroFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JanelaCadastroFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JanelaCadastroFornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JanelaCadastroFornecedor.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 JanelaCadastroFornecedor().setVisible(true);
}
});
} | 6 |
private boolean r_more_than_one_syllable_word() {
int v_1;
int v_3;
// (, line 445
// test, line 446
v_1 = cursor;
// (, line 446
// atleast, line 446
{
int v_2 = 2;
// atleast, line 446
replab0: while(true)
{
v_3 = cursor;
lab1: do {
// (, line 446
// gopast, line 446
golab2: while(true)
{
lab3: do {
if (!(in_grouping(g_vowel, 97, 305)))
{
break lab3;
}
break golab2;
} while (false);
if (cursor >= limit)
{
break lab1;
}
cursor++;
}
v_2--;
continue replab0;
} while (false);
cursor = v_3;
break replab0;
}
if (v_2 > 0)
{
return false;
}
}
cursor = v_1;
return true;
} | 7 |
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.groupId != null ? this.groupId.hashCode() : 0);
hash = 31 * hash + (this.artifactId != null ? this.artifactId.hashCode() : 0);
// ignore type
hash = 31 * hash + (this.version != null ? this.version.hashCode() : 0);
return hash;
} | 3 |
private final String getChunk(String s, int slength, int marker)
{
StringBuilder chunk = new StringBuilder();
char c = s.charAt(marker);
chunk.append(c);
marker++;
if (isDigit(c))
{
while (marker < slength)
{
c = s.charAt(marker);
if (!isDigit(c))
break;
chunk.append(c);
marker++;
}
} else
{
while (marker < slength)
{
c = s.charAt(marker);
if (isDigit(c))
break;
chunk.append(c);
marker++;
}
}
return chunk.toString();
} | 5 |
@SuppressWarnings("unused")
public void run() {
Socket s2;
try {
s2 = new Socket("localhost",
InitiationDispatcher.LOGGING_SERVER_CONNECTION_PORT);
LogManager.getLogger(Lab6Test1.class).log(Level.DEBUG,
"connected: {}, addr: {}, remote: {}", s2.isConnected(),
s2.getLocalAddress(), s2.getRemoteSocketAddress());
long startTime = System.currentTimeMillis();
for (long i = 0; i < R.REQUESTS_COUNT; ++i) {
s2.getOutputStream().write(randomString(400).getBytes());
s2.getOutputStream().flush();
if (i % 1000 == 0) {
LogManager.getLogger(Lab6Test3.class).debug(
"sent {} logs time {}", i,
System.currentTimeMillis() - startTime);
}
if (R.SLEEP_BETWEEN_RECORDS > 0) {
TimeUnit.SECONDS.sleep(R.SLEEP_BETWEEN_RECORDS);
}
}
s2.close();
LogManager.getLogger(Lab6Test3.class).debug("sender {} ends", this);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} | 5 |
public void setCheckboxIcons( JCheckBox box, String baseImagePath ) {
InputStream stream = null;
try {
stream = DataManager.get().getResourceInputStream(baseImagePath);
Image scaled = getScaledImage(stream);
int scaledYoffset = (maxIconHeight-scaled.getHeight(null))/2;
BufferedImage unlocked = new BufferedImage(maxIconWidth, maxIconHeight, BufferedImage.TYPE_INT_ARGB);
unlocked.getGraphics().drawImage(scaled, 0, scaledYoffset, null);
BufferedImage locked = new BufferedImage(maxIconWidth, maxIconHeight, BufferedImage.TYPE_INT_ARGB);
locked.getGraphics().drawImage(scaled, 0, scaledYoffset, null);
locked.getGraphics().drawImage(iconShadeImage, 0, 0, null);
box.setSelectedIcon( new ImageIcon( unlocked ) );
box.setIcon( new ImageIcon( locked ) );
} catch (IOException e) {
log.error( "Error reading checkbox image (" + baseImagePath + ")" , e );
} finally {
try {if (stream != null) stream.close();}
catch (IOException f) {}
}
} | 3 |
private void StartRide() {
V10Dragon d = null;
for (Entity e : player.getNearbyEntities(20, 20, 20)) {
if (!(e instanceof EnderDragon)) {
continue;
}
EntityEnderDragon eed = ((CraftEnderDragon) e).getHandle();
if (eed instanceof V10Dragon) {
d = (V10Dragon)eed;
if (d.player.equalsIgnoreCase(playerName)) {
player.setAllowFlight(true);
break;
} else {
d = null;
}
}
}
if (d == null) {
sender.sendMessage(ChatColor.RED + "You dragon is to far away!");
} else {
d.getBukkitEntity().setPassenger(player);
}
} | 5 |
public StringBuffer format(final CommandSender target) {
// format all dates with time zone for target
TimeZone timeZone = null;
final Format[] formats = this.getFormatsByArgumentIndex();
for(int i = 0; i < formats.length; i++) {
if (!(formats[i] instanceof DateFormat)) continue;
if (timeZone == null) timeZone = Recipients.getTimeZone(target);
final DateFormat sdf = (DateFormat) formats[i];
sdf.setTimeZone(timeZone);
this.setFormatByArgumentIndex(i, sdf);
}
return this.format(this.arguments, new StringBuffer(), null);
} | 3 |
public static void main(String args[]) {
long begin = System.currentTimeMillis();
int total = 338614;
int limit = 22574;
ExecutorService executorService = Executors.newFixedThreadPool(total
/ limit);
for (int i = 0; i <= total / limit; i++) {
executorService.execute(new SetCitedIDList(i * limit, limit));
}
executorService.shutdown();
while(!executorService.isTerminated()) {}
long end = System.currentTimeMillis();
System.out.println("total time: " + (end - begin) / 1000 + " seconds.");
} | 2 |
public static String replace(String inString, String oldPattern, String newPattern) {
if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
return inString;
}
StringBuffer stringBuffer = new StringBuffer();
int pos = 0;
int index = inString.indexOf(oldPattern);
int patLen = oldPattern.length();
while (index >= 0) {
stringBuffer.append(inString.substring(pos, index));
stringBuffer.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
stringBuffer.append(inString.substring(pos));
return stringBuffer.toString();
} | 4 |
@Override
public void sampleOccurred(SampleEvent e) {
if (e.getResult().isSuccessful()){
if (isErrorsOnly()){
return;
}
} else {
if (isSuccessOnly()){
return;
}
}
JMeterVariables variables = JMeterContextService.getContext().getVariables();
MongoDBConfig config = (MongoDBConfig)variables.getObject(this.getMongoDBConfigName());
if(config == null){
log.error("can not find mongo db config with name:"+this.getMongoDBConfigName());
}else{
log.info("save result to mongodb :"+config.toString());
String result = null;
if(StringUtils.isBlank(this.getResultVarName())){
result = e.getResult().getResponseDataAsString();
}else{
result = variables.get(this.getResultVarName());
}
if(StringUtils.isBlank(result)||"NULL".equalsIgnoreCase(result)){
log.error("result is blank.");
}else{
if(log.isDebugEnabled()){
log.debug("result:"+result);
}
JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
DBCollection collection = config.getCollection(this.getMongoDBCollectionName());
try {
Object obj = parser.parse(result);
saveObject(obj, collection);
} catch (ParseException ex) {
log.error("parse json error:"+ex.getMessage()+", responseStr:"+result);
}
}
}
} | 9 |
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (debug) {
log("LoginFilter:doFilter()");
}
doBeforeProcessing(request, response);
HttpServletRequest servletRequest = (HttpServletRequest) request;
if (filter(servletRequest)) {
HttpServletResponse servletResponse = (HttpServletResponse) response;
HttpSession session = servletRequest.getSession();
Object user = session.getAttribute("sessionUser");
if (user == null || !(user instanceof Usuarios)) {
if (redirectForLogin(servletRequest)) {
servletResponse.sendRedirect("/carrinho/login");
return;
}
servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Sua sessão expirou.");
return;
}
}
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
} | 9 |
private List<File> getMinifyFiles(List<File> filesToMinify, List<File> outFiles) {
if (outFiles != null && outFiles.size() > 0) {
getLog().info("About to exclude the following files: " + FileUtilities
.getCommaSeparatedListOfFileNames(outFiles));
List<File> filesToMinifyMinusDestFile = Lists.newArrayList();
for (File file : filesToMinify) {
if (file.isDirectory()) {
filesToMinifyMinusDestFile.addAll(FileUtilities.directoryToFileList(file));
} else {
filesToMinifyMinusDestFile.add(file);
}
}
for (File outFile : outFiles) {
if (outFile.isDirectory()) {
if (outFile.isDirectory()) {
filesToMinifyMinusDestFile.removeAll(FileUtilities.directoryToFileList(outFile));
} else {
filesToMinifyMinusDestFile.remove(outFile);
}
}
}
return filesToMinifyMinusDestFile;
} else {
getLog().info("No file to exclude.");
return filesToMinify;
}
} | 7 |
public static void clearTable(PatientProfilePage profileP){
int rows= profileP.getPrescriptionHistory().getRowCount();
int i=0;
while(i<rows){
profileP.getPrescriptionHistory().setValueAt("",i,0);
profileP.getPrescriptionHistory().setValueAt("",i,1);
profileP.getPrescriptionHistory().setValueAt("",i,2);
profileP.getPrescriptionHistory().setValueAt("",i,3);
profileP.getPrescriptionHistory().setValueAt("",i,4);
profileP.getPrescriptionHistory().setValueAt("",i,5);
profileP.getPrescriptionHistory().setValueAt("",i,6);
profileP.getPrescriptionHistory().setValueAt("",i,7);
i++;
}
} | 1 |
private void readAndSetCards() throws IOException {
//reset cards if there are any
cardList.clear();
String line;
//read in the cards for the answer
for (int cardRow = 0; cardRow < 4; cardRow++) {
line = reader.readLine();
String[] temp = line.split(" ");
for(String s: temp) {
cardList.add(new Card(Integer.parseInt(s)));
}
}
} | 2 |
public static boolean isDiffChar(String a, String b) {
int diff = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != b.charAt(i)) {
diff++;
if (diff >= 2) return false;
}
}
return diff == 1;
} | 3 |
@Override
public double predict(int userID, int itemID) {
double prediction = 0;
if (data.getAverageUserRatings().get(userID) != null) {
prediction = data.getAverageUserRatings().get(userID);
}
ArrayList<Double> similaritiesList = new ArrayList<Double>();
ArrayList<Double> ratingsList = new ArrayList<Double>();
ArrayList<Double> averageList = new ArrayList<Double>();
// If item has not been rated yet, return the user's average rating
// over all items
if (itemSimilarities.get(itemID) == null) {
return prediction;
}
for (Map.Entry<Integer, Double> item : itemSimilarities.get(itemID)
.entrySet()) {
if (data.getUserItemRatings().get(userID).get(item.getKey()) != null) {
similaritiesList.add(item.getValue());
ratingsList.add(data.getUserItemRatings().get(userID)
.get(item.getKey()));
averageList.add(data.getAverageItemRatings()
.get(item.getKey()));
}
}
if (pMetric.equals("weighted")) {
prediction = Prediction.calculateWeightedSum(similaritiesList,
ratingsList);
} else if (pMetric.equals("adjusted")) {
prediction = Prediction.calculateAdjustedSum(data
.getAverageItemRatings().get(itemID), averageList,
ratingsList);
} else if (pMetric.equals("adjweighted")) {
prediction = Prediction.calculateAdjustedWeightedSum(data
.getAverageItemRatings().get(itemID), averageList,
ratingsList, similaritiesList);
}
if (prediction == 0) {
return data.getAverageItemRatings().get(itemID);
}
return prediction;
} | 8 |
public static void main(String args[]) {
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(EliminarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EliminarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EliminarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EliminarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
EliminarCliente dialog = new EliminarCliente(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(args.length >= 1) {
if(args[0].equals("sell") || args[0].equals("s")) {
return plugin.com_sell.onCommand(sender, command, label, ArrayManip.arraySub(args, 1));
} else if(args[0].equals("sellagain") || args[0].equals("sa")) {
return plugin.com_sell.onCommand(sender, plugin.getCommand("sellagain"), label, ArrayManip.arraySub(args, 1));
} else if(args[0].equals("buy") || args[0].equals("b")) {
return plugin.com_buy.onCommand(sender, command, label, ArrayManip.arraySub(args, 1));
} else if(args[0].equals("buyagain") || args[0].equals("ba")) {
return plugin.com_buy.onCommand(sender, plugin.getCommand("buyagain"), label, ArrayManip.arraySub(args, 1));
}
}
// todo: display help
return true;
} | 9 |
private float[] calcOrbit(int i, int depth, int color) {
double xf, yf, a, b, aa, bb;
int iter = 0;
xf = smart_random_points[color][i][0];
yf = smart_random_points[color][i][1];
a = 2 * (xf - 0.5f);
b = 2 * (yf - 0.5f);
aa = a;
bb = b;
Complex z = new Complex(aa, bb);
Complex old = new Complex(z.re, z.im);
z = Newt(z, aa, bb, alg);
while (iter < depth && distance(old, z) > rootBoundry) {
old = new Complex(z.re, z.im);
z = Newt(z, aa, bb, alg);
if (mandelbrotAddition)
z = z.add(new Complex(aa / 2, bb / 2));
img_cache[iter][0] = z.re;
img_cache[iter][1] = z.im;
iter++;
}
float solutionColor;
if (iter != depth_red || (doInverse && runtotal > 25)) {
if (mandelbrotAddition) {
// get Color based on angle of z
z = Newt(z, aa, bb, alg);
double angle = Math.atan(z.im / z.re);
angle = angle + (Math.PI / 2);
angle = angle / Math.PI;
solutionColor = (float) (angle * 254.0);
} else {
float curroot = (float) addRoot(z);
solutionColor = ((curroot * 254) / roots.size());
}
} else {
solutionColor = 0;
}
float[] data = new float[2];
data[0] = iter;
data[1] = solutionColor;
return data;
} | 7 |
Pair toPair( HashMap<Arc,Pair> parents, HashMap<Arc,Pair> orphans )
throws MVDException
{
if ( versions.nextSetBit(0)==0)
throw new MVDException("Ooops! hint detected!");
Pair p = new Pair( versions, data );
if ( this.parent != null )
{
// we're a child - find our parent
Pair q = parents.get( parent );
if ( q != null )
{
q.addChild( p );
// if this is the last child of the parent remove it
if ( parent.numChildren() == q.numChildren() )
parents.remove( parent );
}
else // we're orphaned for now
orphans.put( this, p );
}
else if ( children != null )
{
// we're a parent
for ( int i=0;i<children.size();i++ )
{
Arc child = children.get( i );
Pair r = orphans.get( child );
if ( r != null )
{
p.addChild( r );
orphans.remove( child );
}
}
if ( p.numChildren() < this.numChildren() )
parents.put( this, p );
}
return p;
} | 8 |
public void testSafeMultiplyLongInt() {
assertEquals(0L, FieldUtils.safeMultiply(0L, 0));
assertEquals(1L, FieldUtils.safeMultiply(1L, 1));
assertEquals(3L, FieldUtils.safeMultiply(1L, 3));
assertEquals(3L, FieldUtils.safeMultiply(3L, 1));
assertEquals(6L, FieldUtils.safeMultiply(2L, 3));
assertEquals(-6L, FieldUtils.safeMultiply(2L, -3));
assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3));
assertEquals(6L, FieldUtils.safeMultiply(-2L, -3));
assertEquals(-1L * Integer.MIN_VALUE, FieldUtils.safeMultiply(-1L, Integer.MIN_VALUE));
assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1));
assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1));
assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1));
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MAX_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
} | 4 |
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
try {
// TODO add your handling code here:
saveMetaRecords();
}
catch (IOException ex) {
Logger.getLogger(VAuthor.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton2MouseClicked | 1 |
public boolean addRoom(String name){
if (chatRooms.get(name.toLowerCase())!=null) return false;
ChatServerChatRoom room = new ChatServerChatRoom(name, chatRooms.size());
chatRooms.put(name.toLowerCase(), room);
System.out.println("New room added: "+name);
return true;
} | 1 |
public synchronized void actionPerformed(ActionEvent e){
File[] filePath = new File[4];
filePath[0] = new File("./ExampleText/tree.txt");
filePath[1] = new File("./ExampleText/forest.txt");
filePath[2] = new File("./ExampleText/semilattice.txt");
filePath[3] = null;
for (int i = 0 ; i < fileRadio.length; i++){
if (fileRadio[i].isSelected()){
if(filePath[i]==null)
{
returnFilePath = null;
}
else
{
if(filePath[i].exists())
{
returnFilePath = filePath[i].toString();//make test時の場合
}
else
{
String aString = filePath[i].toString();//app実行時の場合
String[] aStringArray = aString.split("/");
returnFilePath = "./" + aStringArray[aStringArray.length-1];
}
}
}
if (animetionRadio[0].isSelected()){
returnAnimetion = true;
}
}
notifyAll();//wait解除
System.out.println("ファイルパス:"+returnFilePath);
} | 5 |
public static List<Integer> getKNearestMovies(int k, int index)
{
SparseVector base = colMatrix.get(index);
List<Integer> nearestIndices = new ArrayList<Integer>();
List<Double> nearestScores = new ArrayList<Double>();
for (int i=0; i<colMatrix.size(); i++){
if (i == index) continue;
double score = colMatrix.get(i).distanceFrom(base);
if (nearestIndices.size()==0){
nearestIndices.add(i);
nearestScores.add(score);
}else if (nearestIndices.size()<k){
for (int j=0; j<nearestIndices.size(); j++){
if (score < nearestScores.get(j)){
nearestScores.add(j, score);
nearestIndices.add(j, i);
break;
}
}
}else{
for (int j=0; j<nearestIndices.size(); j++){
if (score < nearestScores.get(j)){
nearestScores.add(j, score);
nearestIndices.add(j, i);
nearestScores.remove(nearestIndices.size()-1);
nearestIndices.remove(nearestIndices.size()-1);
break;
}
}
}
}
return nearestIndices;
} | 8 |
public static void walkOldStyle(File file) {
System.out.println(file.getPath());
if (file.isFile()) {
return; // leaf element
}
File[] subs = file.listFiles(); // directory
if (subs == null) {
return;
}
for (File subDir : subs) { // go deeper
walkOldStyle(subDir.getAbsoluteFile());
}
} | 3 |
public static double chiVal(double [][] matrix, boolean useYates) {
int df, nrows, ncols, row, col;
double[] rtotal, ctotal;
double expect = 0, chival = 0, n = 0;
boolean yates = true;
nrows = matrix.length;
ncols = matrix[0].length;
rtotal = new double [nrows];
ctotal = new double [ncols];
for (row = 0; row < nrows; row++) {
for (col = 0; col < ncols; col++) {
rtotal[row] += matrix[row][col];
ctotal[col] += matrix[row][col];
n += matrix[row][col];
}
}
df = (nrows - 1)*(ncols - 1);
if ((df > 1) || (!useYates)) {
yates = false;
} else if (df <= 0) {
return 0;
}
chival = 0.0;
for (row = 0; row < nrows; row++) {
if (Utils.gr(rtotal[row], 0)) {
for (col = 0; col < ncols; col++) {
if (Utils.gr(ctotal[col], 0)) {
expect = (ctotal[col] * rtotal[row]) / n;
chival += chiCell (matrix[row][col], expect, yates);
}
}
}
}
return chival;
} | 9 |
public void run() {
while(isRefreshing) {
if(!OptionsManager.getInstance().isRefresh()) {
isRefreshing = false;
refreshView();
}
long timePassed = (new Date()).getTime() - lastRefresh.getTime();
fps = (timePassed==0)?0:(1000/timePassed);
refreshView();
lastRefresh = new Date();
try {
Thread.sleep(OptionsManager.getInstance().getRefreshDelay());
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
} | 4 |
public int[] twoSum(int[] numbers, int target) {
int[] numbers2 = Arrays.copyOf(numbers, numbers.length);
Arrays.sort(numbers2);
int start = 0;
int end = numbers2.length - 1;
while (start < end) {
int sum = numbers2[start] + numbers2[end];
if (sum == target) {
break;
} else if (sum < target) {
start++;
} else {
end--;
}
}
int index1 = -1, index2 = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == numbers2[start] && index1 == -1) {
index1 = i + 1;
} else if (numbers[i] == numbers2[end]) {
index2 = i + 1;
}
}
int[] indexes = new int[2];
indexes[1] = Math.max(index1, index2);
indexes[0] = Math.min(index1, index2);
return indexes;
} | 7 |
protected int widestDim(double[][] nodeRanges, double[][] universe) {
final int classIdx = m_Instances.classIndex();
double widest = 0.0;
int w = -1;
if (m_NormalizeDimWidths) {
for (int i = 0; i < nodeRanges.length; i++) {
double newWidest = nodeRanges[i][m_DistanceFunction.R_WIDTH] /
universe[i][m_DistanceFunction.R_WIDTH];
if (newWidest > widest) {
if(i == classIdx) continue;
widest = newWidest;
w = i;
}
}
}
else {
for (int i = 0; i < nodeRanges.length; i++) {
if (nodeRanges[i][m_DistanceFunction.R_WIDTH] > widest) {
if(i == classIdx) continue;
widest = nodeRanges[i][m_DistanceFunction.R_WIDTH];
w = i;
}
}
}
return w;
} | 7 |
public void updatePosition() {
if (xPos < xDestination)
xPos += 1;
else if (xPos > xDestination)
xPos -= 1;
if (yPos < yDestination)
yPos += 1;
else if (yPos > yDestination)
yPos -= 1;
if (xPos == xDestination && yPos == yDestination) {
if (command == Command.WaitingArea) {
agent.msgAnimationFinishedGoToWaitingArea();
}
if (command == Command.GoToSeat)
agent.msgAnimationFinishedGoToSeat();
else if (command == Command.LeaveRestaurant) {
agent.msgAnimationFinishedLeaveRestaurant();
//agent.print("about to call gui.setCustomerEnabled(agent);");
isHungry = false;
// gui.setCustomerEnabled(agent);
}
command = Command.noCommand;
}
} | 9 |
public Matrix solve (Matrix B) {
if (B.getRowDimension() != n) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!isspd) {
throw new RuntimeException("Matrix is not symmetric positive definite.");
}
// Copy right hand side.
double[][] X = B.getArrayCopy();
int nx = B.getColumnDimension();
// Solve L*Y = B;
for (int k = 0; k < n; k++) {
for (int j = 0; j < nx; j++) {
for (int i = 0; i < k ; i++) {
X[k][j] -= X[i][j]*L[k][i];
}
X[k][j] /= L[k][k];
}
}
// Solve L'*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
for (int i = k+1; i < n ; i++) {
X[k][j] -= X[i][j]*L[i][k];
}
X[k][j] /= L[k][k];
}
}
return new Matrix(X,n,nx);
} | 8 |
public static Instances clusterInstances(Instances data) {
XMeans xmeans = new XMeans();
Remove filter = new Remove();
Instances dataClusterer = null;
if (data == null) {
throw new NullPointerException("Data is null at clusteredInstances method");
}
//Get the attributes from the data for creating the sampled_data object
ArrayList<Attribute> attrList = new ArrayList<Attribute>();
Enumeration attributes = data.enumerateAttributes();
while (attributes.hasMoreElements()) {
attrList.add((Attribute) attributes.nextElement());
}
Instances sampled_data = new Instances(data.relationName(), attrList, 0);
data.setClassIndex(data.numAttributes() - 1);
sampled_data.setClassIndex(data.numAttributes() - 1);
filter.setAttributeIndices("" + (data.classIndex() + 1));
//int numberOfEnsembles = model.ensembleSizeOption.getValue();
data.remove(0);//In Wavelet Stream of MOA always the first element comes without class
try {
filter.setInputFormat(data);
dataClusterer = Filter.useFilter(data, filter);
String[] options = new String[4];
options[0] = "-L"; // max. iterations
options[1] = Integer.toString(noOfClassesInPool - 1);
if (noOfClassesInPool > 2) {
options[1] = Integer.toString(noOfClassesInPool - 1);
xmeans.setMinNumClusters(noOfClassesInPool - 1);
} else {
options[1] = Integer.toString(noOfClassesInPool);
xmeans.setMinNumClusters(noOfClassesInPool);
}
xmeans.setMaxNumClusters(data.numClasses() + 1);
System.out.println("No of classes in the pool: " + noOfClassesInPool);
xmeans.setUseKDTree(true);
//xmeans.setOptions(options);
xmeans.buildClusterer(dataClusterer);
System.out.println("Xmeans\n:" + xmeans);
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("Assignments\n: " + assignments);
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(xmeans);
try {
eval.evaluateClusterer(data);
int classesToClustersMap[] = eval.getClassesToClusters();
//check the classes to cluster map
int clusterNo = 0;
for (int i = 0; i < data.size(); i++) {
clusterNo = xmeans.clusterInstance(dataClusterer.get(i));
//Check if the class value of instance and class value of cluster matches
if ((int) data.get(i).classValue() == classesToClustersMap[clusterNo]) {
sampled_data.add(data.get(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ((Instances) sampled_data);
} | 7 |
protected void interrupted() {
end();
} | 0 |
@Override
public void tick()
{
xo = x;
yo = y;
zo = z;
yd -= 0.04F;
move(xd, yd, zd);
xd *= 0.98F;
yd *= 0.98F;
zd *= 0.98F;
if(onGround)
{
xd *= 0.7F;
zd *= 0.7F;
yd *= -0.5F;
}
if(!defused)
{
if(life-- > 0)
{
SmokeParticle smokeParticle = new SmokeParticle(level, x, y + 0.6F, z);
level.particleEngine.spawnParticle(smokeParticle);
} else {
remove();
Random random = new Random();
float radius = 4.0F;
level.explode(null, x, y, z, radius);
for(int i = 0; i < 100; i++)
{
float unknown0 = (float)random.nextGaussian() * radius / 4.0F;
float unknown1 = (float)random.nextGaussian() * radius / 4.0F;
float unknown2 = (float)random.nextGaussian() * radius / 4.0F;
float unknown3 = MathHelper.sqrt(unknown0 * unknown0 + unknown1 * unknown1 + unknown2 * unknown2);
float unknown4 = unknown0 / unknown3 / unknown3;
float unknown5 = unknown1 / unknown3 / unknown3;
unknown3 = unknown2 / unknown3 / unknown3;
TerrainParticle terrainParticle = new TerrainParticle(level, x + unknown0, y + unknown1, z + unknown2, unknown4, unknown5, unknown3, Block.TNT);
level.particleEngine.spawnParticle(terrainParticle);
}
}
}
} | 4 |
public int queueLengthIter(){
Patient temp = this;
int count = 0;
while (temp != null){
temp = temp.nextPatient;
count++;
}
return count;
} | 1 |
@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String[] args) {
if (!Commands.isPlayer(sender)) return false;
if (args.length != 1) return false;
Player p = (Player) sender;
ConfigurationSection cs = ChannelsConfig.getChannels().getConfigurationSection("channels");
if (!cs.contains(args[0])) {
Messenger.tell(p, Msg.CUSTOM_CHANNELS_NULL);
return false;
}
// We are going to use sendMessage() instead of custom tell() to avoid spamming the prefix.
p.sendMessage(ChatColor.DARK_PURPLE + "-----------------------------------------");
p.sendMessage("Channel Name: " + ChatColor.YELLOW + args[0]);
joinStatus(p, args[0]);
p.sendMessage(ChatColor.DARK_PURPLE + "-----------------------------------------");
return true;
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.