method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
95efa1c1-ea2a-484e-9d92-a02d3434d58b | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final List<Ability> offensiveAffects=CMLib.flags().flaggedAffects(target,Ability.FLAG_PARALYZING|Ability.FLAG_UNHOLY);
if((success)&&(offensiveAffects.size()>0))
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A visible glow surrounds <T-NAME>."):L("^S<S-NAME> @x1 for <T-NAMESELF> to be able to move.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
}
}
else
beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} |
d5235ed3-c268-4f6d-aac4-5f4f0e3d3b34 | 9 | public boolean setField(int x, int y, char player) {
if (x > 4 || x < 1 || y > 4 || y < 1) {
return false;
} else {
for (int i = 1; i < field.length + 1; i++) {
for (int j = 1; j < field[i - 1].length + 1; j++) {
if (((i == y) && (j == x) && field[i - 1][j - 1] == '+')) {
field[i - 1][j - 1] = player;
return true;
}
}
}
return false;
}
} |
87bb736a-6a6a-4287-ad3b-60f2fa155b29 | 1 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
return getBumoncode() == ((Bumon) obj).getBumoncode();
} |
b8bde2e8-1d10-46c8-9c66-9dd5c288576c | 8 | protected Boolean tryCheckVLine5(boolean update) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
int count = (gemArray[i][j]);
if (j + 4 <= 5) {
if (count == gemArray[i][j + 1] && count == gemArray[i][j + 2] && count == gemArray[i][j + 3] && count == gemArray[i][j + 4]) {
if (update) {
gemArray[i][j] = randInt(1, 6);
gemArray[i][j + 1] = randInt(1, 6);
gemArray[i][j + 2] = randInt(1, 6);
gemArray[i][j + 3] = randInt(1, 6);
gemArray[i][j + 4] = randInt(1, 6);
doAction(count, 2);
}
return true;
}
}
}
}
return false;
} |
ede9a41a-8390-4f49-b943-274e69a32088 | 1 | public boolean equals(Pair o) {
return o.x == x && o.y == y;
} |
0ad63cc8-ea6f-4d40-afb9-eccfa1108e3c | 7 | public static void setMatrix(int[][] matrix){
boolean[] row = new boolean[matrix.length];
boolean[] column = new boolean[matrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length;j++){
if(matrix[i][j] == 0){
row[i] = true;
column[j] = true;
}
}
}
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length;j++){
if(row[i] || column[j]){
matrix[i][j] = 0;
}
}
}
} |
89e002d1-eb0c-477d-b921-81bf487acd15 | 4 | public void MakeMove(int r1, int c1, int r2, int c2)
{
this.cell[r2][c2] = this.cell[r1][c1];
this.cell[r1][c1] = CellEntry.empty;
// Promote To King
if(this.cell[r2][c2].equals(CellEntry.white) && r2==rows-1){
this.cell[r2][c2] = CellEntry.whiteKing;
}
else if(this.cell[r2][c2].equals(CellEntry.black) && r2==0){
this.cell[r2][c2] = CellEntry.blackKing;
}
} |
83c54dc4-b1db-4870-8575-6a321fb564b7 | 5 | private boolean executarCommand(Operation op, Object object){
int updatedRows = -1;
switch(op){
case INSERIR:
updatedRows = inserir(object);
break;
case ATUALIZAR:
updatedRows = salvar(object);
break;
case EXCLUIR:
updatedRows = excluir(object);
break;
default:
throw new AssertionError(op.name());
}
if(updatedRows > 0){
//Atualizar items da tela
tela.setCollection(listItems());
}
else if(updatedRows <= 0){
JOptionPane.showMessageDialog(null, "Um erro inesperado ocorreu!", "", JOptionPane.ERROR_MESSAGE);
}
return (updatedRows > 0);
} |
4ac19287-5bb4-474c-b0b8-aeb23dc2e8c9 | 8 | @Override
public boolean evaluate(Work w) {
int i;
int j;
int limit;
int prime;
int number_of_primesX = 0;
int number_of_41primesX = 1;
int number_of_43primesX = 0;
System.out.println("Thread " + lc_omp.omp_get_thread_num() + ": " + w.start + " - " + w.end);
for (i = w.start; i <= w.end; i += 2) {
limit = (int) Math.sqrt((float) i) + 1;
prime = 1;
j = 3;
while (prime != 0 && (j <= limit)) {
if (i % j == 0)
prime = 0;
j += 2;
}
if (prime != 0) {
if (print_primes != 0)
System.out.printf("%d ", i);
number_of_primesX++;
if (i % 4 == 1)
number_of_41primesX++;
if (i % 4 == 3)
number_of_43primesX++;
}
}
synchronized (lc_omp.critical()) {
number_of_primes += number_of_primesX;
number_of_41primes += number_of_41primesX;
number_of_43primes += number_of_43primesX;
}
return true;
} |
77248432-1a24-4c73-b175-11fe5f0fea28 | 8 | public Object calculate(GraphModel g) {
SubGraph sg = new SubGraph();
int limit=r2.nextInt(g.getEdgesCount());
Vector<Integer> vi = new Vector<Integer>();
HashMap<Vertex,Vertex> vv= new HashMap<Vertex, Vertex>();
for(int i=0;i<g.getVerticesCount();i++) {
vi.add(i);
}
Vertex[] varr = g.getVertexArray();
Vertex[] rvarr = (Vertex[]) rotate(varr,r.nextInt(g.getVerticesCount()-2));
for(Vertex v1 : rvarr) {
if(vv.size() > limit) break;
for(Vertex v2 : g.directNeighbors(v1)) {
if(vi.contains(v1.getId()) && vi.contains(v2.getId())) {
vv.put(v1,v2);
vi.remove(vi.indexOf(v1.getId()));
vi.remove(vi.indexOf(v2.getId()));
break;
}
}
}
for(Vertex v : vv.keySet()) {
sg.vertices.add(v);
sg.vertices.add(vv.get(v));
}
for(Vertex v : vv.keySet()) {
sg.edges.add(g.getEdge(v,vv.get(v)));
}
Vector ret = new Vector();
ret.add("Number of Matching:" + sg.edges.size());
ret.add(sg);
return ret;
} |
f397d12d-a7a5-41f3-8080-26b2074efcc5 | 6 | private void quickSortDate(int low, int high) {
int i = low;
int j = high;
java.util.Date pivot = tabledata.get(low + (high - low) / 2).getOrder().getFullDate();
while (i <= j) {
while (tabledata.get(i).getOrder().getFullDate().before(pivot)) {
i++;
}
while (tabledata.get(j).getOrder().getFullDate().after(pivot)) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if (low < j) {
quickSortDate(low, j);
}
if (i < high) {
quickSortDate(i, high);
}
} |
b1716ad7-0a85-44ab-ac9e-ecaabbfc4e3e | 3 | public void rebuild() {
for (int x = 0; x < sizeX; x++) {
for (int y = 0; y < sizeY; y++) {
for (int z = 0; z < sizeZ; z++) {
vertices.add(new Vertex(new Vector3f(x, y, z + BLOCKSIZE)));
vertices.add(new Vertex(new Vector3f(x + BLOCKSIZE, y, z + BLOCKSIZE)));
vertices.add(new Vertex(new Vector3f(0, y + BLOCKSIZE, z + BLOCKSIZE)));
vertices.add(new Vertex(new Vector3f(x + BLOCKSIZE, y + BLOCKSIZE, z + BLOCKSIZE)));
vertices.add(new Vertex(new Vector3f(x, y, z)));
vertices.add(new Vertex(new Vector3f(x + BLOCKSIZE, y, z)));
vertices.add(new Vertex(new Vector3f(x, y + BLOCKSIZE, z)));
vertices.add(new Vertex(new Vector3f(x + BLOCKSIZE, y + BLOCKSIZE, z)));
// indices.add(0);
// indices.add(1);
// indices.add(2);
// indices.add(3);
// indices.add(7);
// indices.add(1);
// indices.add(5);
// indices.add(4);
// indices.add(7);
// indices.add(6);
// indices.add(2);
// indices.add(4);
// indices.add(0);
// indices.add(1);
}
}
}
chunkMesh = new Mesh(toVertexArray(vertices), Util.toIntArray(toIntegerArray(indices)));
// chunkMesh.setDrawType(GL_TRIANGLE_STRIP);
} |
06f48f52-e8c8-4757-819d-10612ad7308c | 7 | @Override
public void stateChanged(ChangeEvent args) {
if(args != null && args instanceof GetDatabySubjectPanelChangeEvent) {
try {
Document doc = this.getRequest().getDocument();
this.updateRequest(doc);
} catch (Exception e) {
// TODO: log this.
}
}
super.stateChanged(args);
try {
String trxId = this.getRequest().getTransactionId();
String old = this.trxIdTextField.getText();
if(old != null && trxId != null && !old.equals(trxId)) {
this.trxIdTextField.setText(trxId);
}
} catch(Exception e) {
// Do nothing.
}
} |
8ad41d82-87d2-49e4-8bee-ee984b9e4f7e | 1 | public void run(){
try {
//SqlSession session = RequestDataSessionManager.getRequestSession();
//DataMapper mapper = session.getMapper(DataMapper.class);
JDBCConn();
//session.commit();
} catch (SQLException ex) {
Logger.getLogger(testDB.class.getName()).log(Level.SEVERE, null, ex);
}
} |
cef8502a-6fa0-4734-95f0-e99aa2bea234 | 1 | private void populateWorld() {
for (int i = 0; i < this.size * CREATURES_ON_SQUARE; i++) {
Random random = new Random();
this.creatures.add(new Creature(square[0], random.nextInt(100), random.nextInt(100)));
System.out.println(this.creatures.get(i).toString());
}
} |
091096a3-4aaf-4969-b51b-0f88a8e6295a | 6 | public void directionForce(final int x){
if(pointChargePosX >= particleXpos && pointChargePosY < particleYpos){
electroForce.setEndX((particleYpos+(particleCharge()*230))/slopeLine);
electroForce.setEndY(((slopeLine*particleXpos)-(particleCharge()*230)));
}
if(pointChargePosX < particleXpos && pointChargePosY <= particleYpos){
electroForce.setEndX(((particleYpos-(particleCharge()*230))/slopeLine));
electroForce.setEndY(((slopeLine*particleXpos) - (particleCharge()*230)));
}
if(pointChargePosX <= particleXpos && pointChargePosY > particleYpos){
electroForce.setEndX(((particleYpos-(particleCharge()*230))/slopeLine));
electroForce.setEndY(((slopeLine*particleXpos) +(particleCharge()*230)));
}
electroForce.setEndX(((particleYpos+(particleCharge()*230))/slopeLine));
electroForce.setEndY(((slopeLine*particleXpos) +(particleCharge()*230)));
} |
a61e74fb-4071-49be-9844-96c36a934634 | 7 | private float[] getComputedWindow() {
int ix=(blockFlag?4:0)+(previousWindowFlag?2:0)+(nextWindowFlag?1:0);
float[] w=windows[ix];
if(w==null) {
w=new float[n];
for(int i=0;i<leftN;i++){
float x=(float)((i+.5)/leftN*Math.PI/2.);
x=(float)Math.sin(x);
x*=x;
x*=(float)Math.PI/2.;
x=(float)Math.sin(x);
w[i+leftWindowStart]=x;
}
for(int i=leftWindowEnd; i<rightWindowStart; w[i++]=1.0f);
for(int i=0;i<rightN;i++){
float x=(float)((rightN-i-.5)/rightN*Math.PI/2.);
x=(float)Math.sin(x);
x*=x;
x*=(float)Math.PI/2.;
x=(float)Math.sin(x);
w[i+rightWindowStart]=x;
}
windows[ix]=w;
}
return w;
} |
637fdd0e-df00-44c3-b7b1-ca187310f02e | 1 | @Override
public void KeyDown(int key, char c) {
// TODO Auto-generated method stub
if(key == Input.KEY_F2) {
GameInfo.SHOW_DEBUG_INFO = !GameInfo.SHOW_DEBUG_INFO;
}
} |
aa3ea274-6e8f-4a51-b77a-7b4fcaaccf5b | 8 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if((affected==null)
||(!(affected instanceof MOB))
||(((MOB)affected).amDead())
||(((MOB)affected).amFollowing()==null)
||(((MOB)affected).amFollowing().amDead())
||((hasFought)&&(!((MOB)affected).isInCombat())))
{
unInvoke();
return false;
}
else
if(!hasFought)
hasFought=((MOB)affected).isInCombat();
return super.tick(ticking,tickID);
} |
2aa12ad6-1234-4d97-8db4-dfc7840cf9b1 | 3 | private void populate()
{
if (isPopulated == false) {
for (int y = 0; y < gridSize; y++) {
for (int x = 0; x < gridSize; x++) {
squares[x][y] = new Square(this, x, y);
}
}
isPopulated = true;
}
} |
b754058e-d4ec-4f6e-93b3-2a7e1faaa124 | 9 | private void jButtonGuardarNovoFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarNovoFornecedorActionPerformed
// BOTAO GUARDAR NOVO FORNECEDOR -> JANELA NOVO FORNECEDOR
String nome = jTextFieldNomeFornecedor.getText();
String morada = jTextFieldMoradaFornecedor.getText();
String codPostal = jTextFieldCodPostalFornecedor.getText();
String localidade = jTextFieldLocalidadeFornecedor.getText();
String contacto = jTextFieldContactoFornecedor.getText();
String email = jTextFieldEmailFornecedor.getText();
String nif = jTextFieldNIFFornecedor.getText();
String tipoProduto = jTextFieldTipoProdutoFornecedor.getText();
if (nome.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Nome !");
} else if (morada.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira a Morada !");
} else if (codPostal.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Codigo Postal !");
} else if (localidade.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira a Localidade !");
} else if (contacto.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Contacto !");
} else if (nif.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o NIF !");
}else if(!nif.equals("")){
if( validarNif(nif))
System.out.println("valido");
else{
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "NIF INVALIDO!");
System.out.println("Invalisdo");
}
}else if (tipoProduto.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Tipo de Produto !");
} else {
InserirNovoFornecedor();
LimpaNovoFornecedor();
jDialogNovoFornecedor.setVisible(false);
}
} |
9d4c19ed-d48e-4dc3-81e6-a7a527b1006e | 7 | private void method289(InteractiveObject interactiveObject) {
for (int x = interactiveObject.x; x <= interactiveObject.anInt524; x++) {
for (int y = interactiveObject.y; y <= interactiveObject.anInt526; y++) {
GroundTile groundTile = groundTiles[interactiveObject.z][x][y];
if (groundTile != null) {
for (int i = 0; i < groundTile.anInt1317; i++) {
if (groundTile.interactiveObjects[i] != interactiveObject) {
continue;
}
groundTile.anInt1317--;
for (int j = i; j < groundTile.anInt1317; j++) {
groundTile.interactiveObjects[j] = groundTile.interactiveObjects[j + 1];
groundTile.anIntArray1319[j] = groundTile.anIntArray1319[j + 1];
}
groundTile.interactiveObjects[groundTile.anInt1317] = null;
break;
}
groundTile.anInt1320 = 0;
for (int i = 0; i < groundTile.anInt1317; i++) {
groundTile.anInt1320 |= groundTile.anIntArray1319[i];
}
}
}
}
} |
96ef5d6e-571f-4eeb-8c4e-a7193a31fb9d | 5 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (bgToOamPriority ? 1231 : 1237);
result = prime * result + (flipHorizontally ? 1231 : 1237);
result = prime * result + (flipVertically ? 1231 : 1237);
result = prime * result + ((palette == null) ? 0 : palette.hashCode());
result = prime * result + ((tile == null) ? 0 : tile.hashCode());
return result;
} |
54eb78e4-5512-440c-a20e-8aa36a3fee6d | 6 | private int method465(Model model, int i)
{
int j = -1;
int k = model.anIntArray1627[i];
int l = model.anIntArray1628[i];
int i1 = model.anIntArray1629[i];
for(int j1 = 0; j1 < anInt1626; j1++)
{
if(k != anIntArray1627[j1] || l != anIntArray1628[j1] || i1 != anIntArray1629[j1])
continue;
j = j1;
break;
}
if(j == -1)
{
anIntArray1627[anInt1626] = k;
anIntArray1628[anInt1626] = l;
anIntArray1629[anInt1626] = i1;
if(model.anIntArray1655 != null)
anIntArray1655[anInt1626] = model.anIntArray1655[i];
j = anInt1626++;
}
return j;
} |
b72a9236-4157-40b9-a238-48391b62d42a | 7 | public Edge addPhraseStructureEdge(PhraseStructureNode parent, PhraseStructureNode child) throws MaltChainedException {
if (parent == null || child == null) {
throw new MaltChainedException("Parent or child node is missing in sentence "+getSentenceID());
} else if (parent.getBelongsToGraph() != this || child.getBelongsToGraph() != this) {
throw new MaltChainedException("Parent or child node is not a member of the graph in sentence "+getSentenceID());
} else if (parent == child) {
throw new MaltChainedException("It is not allowed to add a phrase structure edge connecting the same node in sentence "+getSentenceID());
} else if (parent instanceof NonTerminalNode && !child.isRoot()) {
Edge e = edgePool.checkOut();
e.setBelongsToGraph(this);
e.setEdge((Node)parent, (Node)child, Edge.PHRASE_STRUCTURE_EDGE);
graphEdges.add(e);
return e;
} else {
throw new MaltChainedException("Parent or child node is not of correct node type.");
}
} |
3ddfd241-d62c-49ba-9354-9f4dbbe84ce5 | 8 | public static Adventurer setupPlayer(){
Adventurer player;
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("New player! What will be your adventurer's name?");
String name = s.nextLine();
System.out.println("\nWelcome, " + name + "! Choose a class:\nA : Warrior\nB : Wizard\nC : Rogue\nD : Martial Artist");
String choice = s.nextLine();
while(! choice.equalsIgnoreCase("A") && ! choice.equalsIgnoreCase("B") && ! choice.equalsIgnoreCase("C") && !choice.equalsIgnoreCase("D")){ // if they enter something invalid
System.out.println("Invalid response received. Please try again.");
choice = s.nextLine();
}
if(choice.equals("A")){
player = new Warrior(name);
System.out.println("You chose Warrior!");
}else if(choice.equals("B")){
player = new Wizard(name);
if(name.equals("Harry")){
System.out.println("Yer a Wizard, " + name + "!");
}else{
System.out.println("You chose Wizard!");
}
}else if(choice.equals("C")){
player = new Rogue(name);
System.out.println("You chose Rogue!");
}else{
player = new MartialArtist(name);
System.out.println("You chose Martial Artist!");
}
pause(2);
setupStats(player);
return player;
} |
6e68032c-638b-4bf9-8ecf-402bf1dd0dea | 3 | void star2() {
int rows = 5;
for (int i = rows -1; i >= 0; i--){
for (int j = 0; j < i; j++){
System.out.print(" ");
}
for (int j = (rows - i) * 2 - 1; j > 0; j--){
System.out.print("*");
}
System.out.println();
}
} |
03b75e19-5f6f-4792-829a-dff7137529b8 | 2 | public void recall()
{
if(isReadOnly()) return;
try { fdbf.seek( recordpos() ); } catch (IOException e) {}
writeChars(0,1," "); deleted = false;
} |
f9bdad9e-2d08-40cc-9937-01f9673eb25d | 3 | public String addFile( String filename, String alt_filename, String mimetype, METSMetadata md ) throws Exception {
// read in the file
File fileobj = new File( filename );
InputStream is = new FileInputStream(fileobj);
long length = fileobj.length();
byte[] arr = new byte[ (int) length ];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < arr.length
&& (numRead=is.read(arr, offset, arr.length-offset)) >= 0) {
offset += numRead;
}
is.close();
// change the filename to remove any path.
filename = fileobj.getName();
// replace the physical filename with an alternative, if specified
if( alt_filename != null ) {
filename = alt_filename;
}
MessageDigest md5 = MessageDigest.getInstance( "MD5" );
md5.update( arr );
String digest = dumpBytes( md5.digest() ) ;
String fileid = filename;
String dmdid = "DMD-" + fileid+"-" + dmd_idx;
dmd_idx++;
Element file = (Element) doc.createElement( "file" );
file.setAttribute( "ID", fileid );
file.setAttribute( "DMDID" , dmdid );
file.setAttribute( "CHECKSUMTYPE", "MD5" );
file.setAttribute( "CHECKSUM", digest );
file.setAttribute( "MIMETYPE", mimetype );
Element flocate = (Element) doc.createElement( "FLocat" );
flocate.setAttribute( "LOCTYPE", "URL" );
flocate.setAttribute( "xlink:type", "simple" );
flocate.setAttribute( "xlink:href", filename );
file.appendChild( flocate );
filegrp.appendChild( file );
// DMD object
Element xmlData = addMetadata( dmdid );
dmd_hash.put ( dmdid, xmlData );
// structmap
{
Element e1 = (Element) doc.createElement( "div" );
e1.setAttribute( "ID", dmdid + "-struct" );
Element e2 = (Element) doc.createElement( "fptr" );
e2.setAttribute( "FILEID", fileid );
e1.appendChild( e2 );
structmap.appendChild( e1 );
}
set_md( xmlData, md );
// write data to zipfile
ZipEntry ze = new ZipEntry( filename );
zout.putNextEntry( ze );
zout.write( arr, 0, arr.length );
return dmdid;
} |
24646c99-072c-4ce7-9ec3-b33af9b951cb | 7 | public <V> Adapter.Setter<V> makeSetter(String methodName, Class<V> _class) {
try {
T version = (T) start.get().newVersion;
final Method method = version.getClass().getMethod(methodName, _class);
return new Adapter.Setter<V>() {
public void call(V value) {
try {
Transaction me = Thread.getTransaction();
Locator oldLocator = start.get();
T version = (T) oldLocator.fastPath(me);
if (version != null) {
method.invoke(version, value);
return;
}
ContentionManager manager = Thread.getContentionManager();
Locator newLocator = new Locator(me, (Copyable)factory.create());
version = (T) newLocator.newVersion;
while (true) {
oldLocator.writePath(me, manager, newLocator);
if (!me.isActive()) {
throw new AbortedException();
}
method.invoke(version, value);
if (Adapter.this.start.compareAndSet(oldLocator, newLocator)) {
return;
}
oldLocator = Adapter.this.start.get();
}
} catch (IllegalAccessException e) {
throw new PanicException(e);
} catch (InvocationTargetException e) {
throw new PanicException(e);
}
}};
} catch (NoSuchMethodException e) {
throw new PanicException(e);
}
} |
57064c68-5103-4dfd-b5ee-1eeb4ad18dae | 4 | public static void read(String fileName) {
System.out.println("read start");
SAXBuilder builder = new SAXBuilder();
try {
Document document = builder.build(fileName);
Element root = document.getRootElement();
List<?> list = root.getChildren();
for (int i = 0; i < list.size(); i++) {
Element teacher = (Element) list.get(i);
System.out.println(teacher.getAttributeValue("name") + "->"
+ teacher.getText());
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("read end");
} |
58d46ce3-f00f-4313-845c-246a5859fbdc | 7 | public final void updateMode()
{
// WE'LL NEED THESE GUYS
Poseur singleton = Poseur.getPoseur();
PoseurStateManager state = singleton.getStateManager();
PoseurState mode = state.getMode();
PoseurFileManager fileManager = singleton.getFileManager();
// IN THIS MODE THE USER IS DRAGGING THE MOUSE TO
// COMPLETE THE DRAWING OF A SINGLE SHAPE
if (mode == PoseurState.COMPLETE_SHAPE_STATE)
{
// THIS USES THE CROSSHAIR
selectCursor(Cursor.CROSSHAIR_CURSOR);
}
// IN THIS MODE THE USER IS ABOUT TO START DRAGGING
// THE MOUSE TO CREATE A SHAPE
else if (mode == PoseurState.CREATE_SHAPE_STATE)
{
// THIS USES THE CROSSHAIR
selectCursor(Cursor.CROSSHAIR_CURSOR);
// TURN THE APPROPRIATE CONTROLS ON/OFF
setEnabledEditControls(false);
selectionButton.setEnabled(true);
}
// IN THIS STATE THE USER HAS SELECTED A SHAPE
// ON THE CANVAS AND IS DRAGGING IT
else if (mode == PoseurState.DRAG_SHAPE_STATE)
{
// THIS USES THE MOVE
selectCursor(Cursor.MOVE_CURSOR);
}
// IN THIS STATE THE USER IS ABLE TO CLICK ON
// A SHAPE TO SELECT IT. THIS IS THE MOST COMMON
// STATE AND IS THE DEFAULT AT THE START OF THE APP
else if (mode == PoseurState.SELECT_SHAPE_STATE)
{
// THIS USES THE ARROW CURSOR
selectCursor(Cursor.DEFAULT_CURSOR);
// THERE IS NO SHAPE SELECTED, SO WE CAN'T
// USE THE EDIT CONTROLS
enableSaveAsAndExport();
setEnabledEditControls(false);
selectionButton.setEnabled(false);
setEnabledColorControls(true);
setEnabledShapeControls(true);
setEnabledZoomControls(true);
}
// IN THIS STATE A SHAPE HAS BEEN SELECTED AND SO WE
// MAY EDIT IT, LIKE CHANGE IT'S COLORS OR TRANSPARENCY
else if (mode == PoseurState.SHAPE_SELECTED_STATE)
{
// THIS USES THE ARROW CURSOR
selectCursor(Cursor.DEFAULT_CURSOR);
// THE EDIT CONTROLS CAN NOW BE USED
setEnabledEditControls(true);
}
// THIS IS THE STATE WHEN THE Poseur APP FIRST
// STARTS. THERE IS NO Pose YET, SO MOST CONTROLS
// ARE DISABLED
else if (mode == PoseurState.STARTUP_STATE)
{
// THIS USES THE ARROW CURSOR
selectCursor(Cursor.DEFAULT_CURSOR);
// NOTHING IS SELECTED SO WE CAN'T EDIT YET
enableStartupFileControls();
setEnabledEditControls(false);
selectionButton.setEnabled(false);
setEnabledColorControls(false);
toggleOutlineColorButton();
setEnabledZoomControls(false);
setEnabledShapeControls(false);
}
saveButton.setEnabled(!fileManager.isSaved());
// AND UPDATE THE SLIDER
PoseurShape selectedShape = state.getSelectedShape();
if (selectedShape != null)
{
// UPDATE THE SLIDER ACCORDING TO THE SELECTED
// SHAPE'S ALPHA (TRANSPARENCY) VALUE, IF THERE
// EVEN IS A SELECTED SHAPE
transparencySlider.setValue(selectedShape.getAlpha());
}
// REDRAW EVERYTHING
zoomableCanvas.repaint();
this.repaint();
} |
e13dfd67-ad4f-4d3d-9d13-0ff1153b9380 | 2 | private void buildTree(Document doc, Element root) {
doc.setXmlStandalone(true);
doc.setStrictErrorChecking(true);
doc.setXmlVersion("1.0");
Element subRoot;
Element e;
subRoot = createElement(doc, "Towns", null);
for(Town i: towns){
String[] args = {"name","id"};
e = createXmlObj(doc,"town", args,i.getName(),i.getId().toString());
//e.setAttribute("id", i.getId().toString());
subRoot.appendChild(e);
}
root.appendChild(subRoot);
subRoot = createElement(doc, "Airports", null);
for(Airport i: aports){
String[] args = {"airportId","locationId","name"};
e = createXmlObj(doc,"Airport", args,i.getAirportId().toString(),i.getLocationId().toString(),i.getAirportName());
//e.setAttribute("airportId", i.getAirportId().toString());
subRoot.appendChild(e);
}
root.appendChild(subRoot);
} |
97b4f35f-61a5-489a-9d05-bd37c422f7bb | 1 | public static void addIntegers(List<? super Integer> list){
list.add(new Integer(50));
} |
2a031d71-ae27-4582-a852-bfa703729cea | 2 | public static void main(String[] args) {
/* program to print the pattern
*
**
***
****
*/
for (int i=0;i<=5;i++)
{
for (int j=0;j<=i;j++)
System.out.print("*");
System.out.println("");
}
} |
58fd8ec8-107a-4a6f-a5a7-f0145543acd1 | 9 | @Test
public void testGitHubSignIn()
{
// I *could* put my actual name and password here, but for obvious security reasons,
// the only use case where I would would be if I had a test account, not a real one.
page.clickOnSignInButton();
SignInPage signInPage = PageFactory.initElements(webDriver, SignInPage.class);
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement loginField = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("login_field")));
Assert.assertEquals(loginField, signInPage.login_field);
signInPage.enterUserName(username);
signInPage.enterPassword(password);
signInPage.signIn();
webDriver.navigate().to(webDriver.getCurrentUrl() + username);
GithubUserPage userPage = PageFactory.initElements(webDriver, GithubUserPage.class);
userPage.clickRepositoryTab(); // Show Click on tab showing repositories
wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("repolist")));
GithubRepositoryPage repos = PageFactory.initElements(webDriver, GithubRepositoryPage.class);
Assert.assertTrue(repos != null);
List<WebElement> repoItems = repos.div_repolist.get(0).findElements(By.cssSelector("li"));
List<Repo> myRepos = new ArrayList<Repo>(10);
Repo r = null;
for ( WebElement we : repoItems )
{
r = new Repo("", "", 0);
List<WebElement> repostats = we.findElements(By.cssSelector("ul[class='repo-stats']"));
if ( repostats.size() > 0 )
{
for ( WebElement rs : repostats)
{
r.language = rs.getText();
}
}
repostats = we.findElements(By.cssSelector("h3[class='repolist-name']"));
if ( repostats.size() > 0 )
{
for ( WebElement rs : repostats)
{
r.reponame = rs.getText();
}
}
repostats = we.findElements(By.cssSelector("h3[class='repolist-name']"));
if ( repostats.size() > 0 )
{
for ( WebElement rs : repostats)
{
r.url = String.format("%s/%s/%s", GITHUB, username, r.reponame);
}
}
if (r.reponame != "")
myRepos.add(r);
}
for ( Repo reps : myRepos )
{
System.out.println(reps);
}
} |
b5bce000-985e-423e-9a59-d9cdd7880641 | 9 | private Space[] getNeighbors(){
Space[] ret=new Space[4];
for (int i=0; i<ret.length;i++){
if (i==0){
if (!(_r==0)){
ret[i]=maze[_r-1][_c];
}
}
if (i==1){
if (!(_c==maze[0].length-1)){
ret[i]=maze[_r][_c+1];
}
}
if (i==2){
if (!(_r==maze.length-1)){
ret[i]=maze[_r+1][_c];
}
}
if (i==3){
if (!(_c==0)){
ret[i]=maze[_r][_c-1];
}
}
}
return ret;
} |
bf64fa48-84cc-460a-9072-30ccdd375f64 | 3 | public void testQuery(String query, int numCols)
{
// try the following
try {
// open the connection to the database
Connection connection =
DriverManager.getConnection(this.urlStr);
// create a statement
Statement statement = connection.createStatement();
// execute the query
ResultSet rs = statement.executeQuery(query);
// print out the results
while (rs.next())
{
for (int i = 1; i <= numCols; i++)
{
System.out.print(rs.getString(i) + ", ");
}
System.out.println();
}
// close everything
rs.close();
statement.close();
connection.close();
} catch (SQLException ex) {
SimpleOutput.showError("Trouble with the database " +
urlStr);
ex.printStackTrace();
}
} |
68ebe9b5-e154-49ca-b8ec-ffc794aeca5f | 6 | public static int countBacklinksOnRelation(Stella_Object self, Keyword kind, Surrogate relation) {
{ BacklinksIndex index = Logic.getBacklinksIndex(self);
Cons equivalents = (Stella_Object.isaP(self, Logic.SGT_LOGIC_LOGIC_OBJECT) ? ((LogicObject)(self)).variableValueInverse() : Stella.NIL);
int count = 0;
if (index == null) {
return (Stella.NULL_INTEGER);
}
count = Logic.selectPropositions(Cons.cons(Logic.KWD_RELATION, Cons.cons(((Stella.NIL == null) ? Stella.NIL : Stella.NIL), Cons.cons(relation, Cons.cons(self, Stella.NIL))))).estimatedLength();
if ((count == 0) &&
(!(NamedDescription.allDirectSubrelations(Logic.surrogateToDescription(relation), false) == Stella.NIL))) {
count = 1;
}
{ Stella_Object equiv = null;
Cons iter000 = equivalents;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
equiv = iter000.value;
count = count + Logic.countBacklinksOnRelation(equiv, kind, relation);
}
}
return (count);
}
} |
c860b3b5-3088-4919-95ae-a3007d2317fa | 3 | private ResTable_Entry readEntryTable(byte[] data, int offset) throws IOException {
// The exact type of entry depends on the size
int size = readUInt16(data, offset);
offset += 2;
ResTable_Entry entry;
if (size == 0x8)
entry = new ResTable_Entry();
else if (size == 0x10)
entry = new ResTable_Map_Entry();
else
throw new RuntimeException("Unknown entry type");
entry.size = size;
int flags = readUInt16(data, offset);
offset += 2;
entry.flagsComplex = (flags & FLAG_COMPLEX) == FLAG_COMPLEX;
entry.flagsPublic = (flags & FLAG_PUBLIC) == FLAG_PUBLIC;
entry.key = readUInt32(data, offset);
offset += 4;
if (entry instanceof ResTable_Map_Entry) {
ResTable_Map_Entry mapEntry = (ResTable_Map_Entry) entry;
mapEntry.parent = readUInt32(data, offset);
offset += 4;
mapEntry.count = readUInt32(data, offset);
offset += 4;
}
return entry;
} |
f04761fe-2aee-43e7-9498-124a8c09b70a | 9 | private static Holder runATrial(MetaboliteClass metabolite, String phyla, OtuWrapper wrapper, List<String> keys,
boolean scramble)
throws Exception
{
int otuIndex = wrapper.getIndexForOtuName(phyla);
HashMap<Integer, List<Double>> metaboliteMap = WriteTrialsForSVMLight.getMetabolites(metabolite, scramble);
int halfPoint = keys.size() / 2;
File trainingSetFile = new File(ConfigReader.getMicrboesVsMetabolitesDir() + File.separator +
"trainingSet.txt");
deleteOrThrow(trainingSetFile);
BufferedWriter writer = new BufferedWriter(new FileWriter(
trainingSetFile));
for( int x=0; x < halfPoint; x++)
{
int sampleIndex = wrapper.getIndexForSampleName(keys.get(x));
writer.write( wrapper.getDataPointsNormalizedThenLogged().get(sampleIndex).get(otuIndex)+ " " );
List<Double> list = metaboliteMap.get( Integer.parseInt(keys.get(x).replace("sample", "")));
for( int y=0; y < list.size(); y++ )
{
boolean skip = false;
if( metabolite.equals(MetaboliteClass.METADATA) && Math.abs( list.get(y) + 1 ) < 0.0001)
skip =true;
if( ! skip)
writer.write( (y+1) + ":" + list.get(y) + " " );
else
System.out.println("SKIP!!!!!!!!");
}
writer.write("\n");
}
writer.flush(); writer.close();
File regressModel = new File(ConfigReader.getMicrboesVsMetabolitesDir() + File.separator +
"regressionModel");
deleteOrThrow(regressModel);
// train with svm_learn.exe -z r trainingSet.txt regressModel
String[] args = new String[5];
args[0] = ConfigReader.getSvmDir() + File.separator + "svm_learn.exe";
args[1] = "-z";
args[2] = "r";
args[3] = trainingSetFile.getAbsolutePath();
args[4] = regressModel.getAbsolutePath();
new ProcessWrapper(args);
File setToClassify = new File(
ConfigReader.getMicrboesVsMetabolitesDir() + File.separator +
"setToClassify.txt" );
deleteOrThrow(setToClassify);
writer = new BufferedWriter(new FileWriter(setToClassify));
for( int x=halfPoint; x < keys.size(); x++ )
{
writer.write(keys.get(x) + " " );
List<Double> list = metaboliteMap.get(Integer.parseInt(keys.get(x).replace("sample", "")));
for( int y=0; y < list.size(); y++ )
writer.write( (y+1) + ":" + list.get(y) + " " );
writer.write("\n");
}
writer.flush(); writer.close();
File svmOut = new File(ConfigReader.getMicrboesVsMetabolitesDir() + File.separator +
"svmOut.txt");
deleteOrThrow(svmOut);
// classify with svm_classify setToClassify.txt regressModel svmOut.txt
args = new String[4];
args[0] = ConfigReader.getSvmDir() + File.separator + "svm_classify.exe";
args[1] = setToClassify.getAbsolutePath();
args[2] = regressModel.getAbsolutePath();
args[3] = svmOut.getAbsolutePath();
new ProcessWrapper(args);
BufferedReader svmOutReader = new BufferedReader(new FileReader(svmOut));
BufferedReader classifiedReader = new BufferedReader(new FileReader(setToClassify));
List<Double> predicted = new ArrayList<Double>();
List<Double> actual = new ArrayList<Double>();
for(String s= classifiedReader.readLine(); s != null; s = classifiedReader.readLine())
{
StringTokenizer sToken = new StringTokenizer(s);
String sample = sToken.nextToken();
int sampleID = wrapper.getIndexForSampleName(sample);
actual.add(wrapper.getDataPointsNormalizedThenLogged().get(sampleID).get(otuIndex));
predicted.add(Double.parseDouble(svmOutReader.readLine()));
}
if( svmOutReader.readLine() != null)
throw new Exception("No");
classifiedReader.close();
svmOutReader.close();
Holder h= new Holder();
h.actual= actual;
h.predicted = predicted;
return h;
} |
33421dc8-cf41-4261-843c-133f9ae9d2b3 | 8 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt();
if ( (n % 2) == 0 ) {
System.out.println("2^? mod " + n + " = 1");
continue;
}
long s = 1;
boolean b = false;
for( int i = 1;i <n;i++) {
if ( (i * 2 % n) == 1) {
b = true;
break;
}
}
if ( !b ) {
System.out.println("2^? mod " + n + " = 1");
continue;
}
b = false;
int i = 0;
while(true) {
i++;
s = s * 2 % n;
if ( s == 1) {
System.out.println("2^" + i + " mod " + n + " = 1");
b = true;
break;
}
}
if ( b) continue;
System.out.println("2^? mod " + n + " = 1");
}
} |
315c19f9-f8d1-4644-9092-7938a1394d15 | 8 | private void insertClusterSequence ( ClusterSequence cs, float offSet) {
//
int scoreIndex=0;
float clusterTime;
for ( int i=0; i < cs.getClusterNumber() ; i++ ) {
clusterTime=cs.getTimeAtStep(i)+offSet;
System.out.println(clusterTime+"eccolo");
for (int j=scoreIndex; j < score.getClusterNumber() ; j++ ) {
// ERRORE CONTROLLARE
if ( clusterTime == score.getTimeAtStep(j) ) {
// add notes to existing cluster
//aggiunger elemnti al cluster esistente, per ora forza bruta
// score.
score.addToCluster(cs.getCluster(i),j);
scoreIndex=j;
break;
}
else if ( j==score.getClusterNumber()-1 ) {
// it creates a new cluster in the internal sequence
score.insertCluster(cs.getCluster(i),j+1,clusterTime);
scoreIndex=j;
break;
}
else if (( j==0 )&&(clusterTime<score.getTimeAtStep(0))) {
// it creates a new cluster in the internal sequence
score.insertCluster(cs.getCluster(i),0,clusterTime);
scoreIndex=j;
break;
}
else if (( clusterTime > score.getTimeAtStep(j) )&&( clusterTime < score.getTimeAtStep(j+1) )) {
// it creates a new cluster in the internal sequence
score.insertCluster(cs.getCluster(i),j+1,clusterTime);
scoreIndex=j;
break;
}
}
}
} |
5890a102-bdc7-4683-b4d8-f728c7959a10 | 1 | public final double getTotalBeforeDiscount() {
double total = 0.0;
for (LineItem item : lineItems) {
total += item.getProductAmount();
}
return total;
} |
e4309cf5-0503-4aae-acae-5354275b7f2c | 9 | private void sort()
{
for(File f : rootDir.listFiles())
{
if(f.isDirectory() && !f.equals(outputDir))
{
for(File f1 : f.listFiles())
{
if(f1.isDirectory())
continue;
String[] split = f1.getName().split("\\.");
if(split.length > 1 && split[1].equalsIgnoreCase(extension))
{
move(f1);
}
}
continue;
}
String[] split = f.getName().split("\\.");
if(split.length > 1 && split[1].equalsIgnoreCase(extension))
{
move(f);
}
}
} |
cfc06e0d-5bf6-42ed-9c68-65d6428278fe | 2 | private void bNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNewActionPerformed
TextEnterDialog dg = new TextEnterDialog(this, true);
dg.setLocationRelativeTo(this);
dg.setVisible(true);
if (dg.getReturnStatus() == TextEnterDialog.RET_ADD) {
mapShapes(false);
} else if (dg.getReturnStatus() == TextEnterDialog.RET_REPLACE) {
mapShapes(true);
}
}//GEN-LAST:event_bNewActionPerformed |
03b0da86-d6d6-4450-91ea-28f893a49150 | 0 | @Override
public String getDef() {
return convertToString(def);
} |
d258dd80-913f-41c1-ae58-f3f287fdc644 | 2 | public void render()
{
for(GuiButton button : buttons)
{
button.render(g);
}
for(Particle p : particles)
{
p.render();
}
renderText(new Font("Arial", Font.BOLD, 18), Color.white, Game.WIDTH - 120, 15, "Frames: " + Game.getFPS());
renderText(new Font("Arial", Font.BOLD, 18), Color.white, Game.WIDTH - 120, 36, "Ticks: " + Game.getTPS());
g.dispose();
} |
51c38b58-316f-4c34-9ae0-f9a54e5f0e86 | 1 | public Vector toVector() {
Vector<E> vec = new Vector<E>(array.length);
for (int i = 0; i < array.length; i++) {
vec.addElement(array[i]);
}
return vec;
} |
3f241e45-7330-4fff-89a7-47d5821faff7 | 8 | public boolean matches(InventoryCrafting par1InventoryCrafting)
{
ArrayList var2 = new ArrayList(this.recipeItems);
for (int var3 = 0; var3 < 3; ++var3)
{
for (int var4 = 0; var4 < 3; ++var4)
{
ItemStack var5 = par1InventoryCrafting.getStackInRowAndColumn(var4, var3);
if (var5 != null)
{
boolean var6 = false;
Iterator var7 = var2.iterator();
while (var7.hasNext())
{
ItemStack var8 = (ItemStack)var7.next();
if (var5.itemID == var8.itemID && (var8.getItemDamage() == -1 || var5.getItemDamage() == var8.getItemDamage()))
{
var6 = true;
var2.remove(var8);
break;
}
}
if (!var6)
{
return false;
}
}
}
}
return var2.isEmpty();
} |
7fd2c37f-a914-4e5a-b6b3-5c21ca7dcdc3 | 9 | public synchronized void run() {
int temps;
this.grille.setScore(this.grille.getScore() + 1); // des qu'une piece est placée sur le plateau, on augmente le score de 1
// tant que la partie n'est pas finie
while (!this.isFin()) {
// est ce qu'on triche ???
if (this.cheat != 0) {
this.setPieceSuivante(new Piece(cheat));
}
// on ajoute la piece à la grille
this.grille.ajoute_piece(this.getPieceCourante());
// est ce qu'on est en pause ??
if (this.mettreEnPause) {
try {
this.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Partie.class.getName()).log(Level.SEVERE, null, ex);
}
}
// si la piece peut descendre d'un coup (cette methode supprime la piece de la grille sans la remettre)
if (!(this.grille.bloquer_bas(this.pieceCourante))) {
try {
// on rajoute donc la piece et on la décale
this.grille.ajoute_piece(this.getPieceCourante());
this.grille.decale_bas(this.getPieceCourante());
// definition level avec level max
if (this.grille.getLevel() < 19) {
temps = 1000 - 50 * this.grille.getLevel();
} else {
temps = 100;
}
// on fait patienter le thread
Thread.currentThread().sleep(temps);
} catch (InterruptedException ex) {
Logger.getLogger(Partie.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
// si la piece ne peut pas descendre alors on teste la fin de partie
if (!this.grille.fin_partie()) {
// si c'est pas la fin, le score augmente, on rajoute la piece, et on teste si des lignes ont été faites
this.grille.setScore(this.grille.getScore() + 1);
this.grille.ajoute_piece(this.getPieceCourante());
this.grille.efface_ligne(this.getPieceCourante());
this.setPieceCourante(this.getPieceSuivante());
if (this.cheat != 0) {
this.setPieceSuivante(new Piece(cheat));
} else {
this.setPieceSuivante(new Piece());
}
} else {
// si c'est la fin de la partie, on arrete tout !
this.setFin(true);
this.setPieceCourante(null);
Thread.currentThread().stop();
}
}
}
} |
baf5c3ed-da51-4f65-9163-121ad1948f69 | 3 | private boolean isInnerElement(TreeItem sourceTreeItem, Object investigationItem) {
boolean isInnerElement = false;
assert sourceTreeItem != null;
if (investigationItem == null) {
return false;
}
if (sourceTreeItem == investigationItem) {
return true;
}
for (TreeItem childItem : sourceTreeItem.getItems()) {
isInnerElement |= isInnerElement(childItem, investigationItem);
}
return isInnerElement;
} |
9d3f1f2b-b928-4e63-bdb3-60054a989ad3 | 6 | public static void binarySearch(int[] arr, int data) {
if (arr.length < 1) {
System.out.println("null?");
return;
}
if (arr.length == 1) {
if (data == arr[0]) {
System.out.println("success.\t" + data + " -> arr[0]");
return;
} else {
System.out.println("not in.");
return;
}
}
int left = 0;
int right = arr.length;
while (left <= right) {
int mid = (left + right) >> 2;
if (data == arr[mid]) {
System.out.println("success.\r" + data + " -> arr[" + mid + "]");
return;
}
if (data < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
System.out.println("not in.");
return;
} |
9395e1e4-73ad-43d6-8531-f76dfb93a113 | 6 | private void cherche_Base(){
ArrayList<Cellule> autour = curent.env.getenv(curent);
for (int i =0 ; i<autour.size() ; i++){
if (autour.get(i).objet != null){
if((autour.get(i).objet instanceof Forum)){
Forum b =(Forum ) autour.get(i).objet;
if (this.al != b.al && !b.perdu){
if (!this.al.forum_ennemi.contains(autour.get(i))){
this.al.forum_ennemi.add(autour.get(i));
}
}
}
}
}
} |
917f8b5f-6ed1-4862-9db5-6e8c7ed5c492 | 2 | public void stop(){
if(running){
running = false;
try {
serverSocket.close();
} catch (IOException e) {
LOG.error("stop process server error", e);
System.exit(-1);
}
}
} |
704c98b3-dfa0-4826-8588-cf0e8eb03ee7 | 8 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ReverseLookupList)) {
return false;
}
final ReverseLookupList<?> other = (ReverseLookupList<?>) obj;
if (decorated == null) {
if (other.decorated != null) {
return false;
}
} else if (!decorated.equals(other.decorated)) {
return false;
}
return true;
} |
90cdf4b9-d660-4d0b-ab66-d92d16953cad | 0 | public void setStation(Station value) {
this._station = value;
} |
3f5408f4-82c1-41c8-aa88-27a0b6e336e3 | 2 | public void InsertarDocumento(ArrayList datos)
{
// Cambiamos todos los datos, que se puedan cambiar, a minúsculas
for(int i = 0 ; i < datos.size() ; i++)
{
try{datos.set(i, datos.get(i).toString().toLowerCase());}
catch(Exception e){}
}
biblioteca.insertarRegistros("documento", datos);
} |
6390631b-c1a9-4a55-8778-e83b3b7d0337 | 0 | public void setX(double x) {
this.x = x;
} |
7903d87e-ae51-4928-bafc-913d247171aa | 6 | public void run() {
ServerSocket serversocket = null;
Socket s;
InputStreamReader input;
BufferedReader b;
PrintWriter p;
String message = null;
boolean done = false;
try {
serversocket = new ServerSocket(Utils.FAULTMNGR_PORT, 1); /* backlog is 1 */
serversocket.setSoTimeout(0);
} catch (IOException e) {
System.err.println("Error: failed to launch FaultManager.");
System.err.println(e.getMessage());
System.exit(1);
}
while (! done) {
s = null;
try {
s = serversocket.accept();
} catch (IOException e) {
System.err.println("Error: failed to accept connection from FaultInjector.");
System.err.println(e.getMessage());
System.exit(1);
}
try {
input = new InputStreamReader(s.getInputStream());
b = new BufferedReader(input);
p = new PrintWriter(s.getOutputStream());
while ((message = b.readLine()) != null) {
/* Handle FaultInjector's command */
if (! parse(message)) {
p.println("E.g. usage: P1<|>ON; P2<|>OFF; etc.");
p.flush();
continue;
}
/* Search registry */
Record record = r.find(key);
/* Update process status */
record.beFaulty(value);
r.update(record);
p.println("OK");
p.flush();
}
/* Null message. */
p.close();
b.close();
s.close();
} catch (IOException e) {
System.err.println("Error: failed to read/write at FaultManager.");
System.err.println(e.getMessage());
System.exit(1);
}
}
} |
50302a06-445a-4bc1-affd-eaf69cfe8434 | 3 | public void handleClick(int button) {
switch (button) {
case 1:
state = State.OBSTACLE;
break;
case 2:
state = State.START;
break;
case 3:
state = State.END;
break;
default:
break;
}
} |
8e255cf1-1f42-4fec-999e-cd4b01f6a5f1 | 7 | public Ast.AstSchemaExpression parse_SchemaExpression(SpecObject specObject, String property)
{
int at = m_current;
if (!ok())
{
return null;
}
int tat;
if (next(TozeTokenizer.TOKEN_ALL))
{
Ast.AstForAllS node = m_ast.new AstForAllS();
node.m_schemaText = parse_SchemaText(specObject, property);
next(TozeTokenizer.TOKEN_DOT);
node.m_schemaExpression = parse_SchemaExpression(specObject, property);
if (ok())
{
return node;
}
}
reset(at);
if (next(TozeTokenizer.TOKEN_EXI))
{
Ast.AstThereExistsS node = m_ast.new AstThereExistsS();
node.m_schemaText = parse_SchemaText(specObject, property);
next(TozeTokenizer.TOKEN_DOT);
node.m_schemaExpression = parse_SchemaExpression(specObject, property);
if (ok())
{
return node;
}
}
reset(at);
if (next(TozeTokenizer.TOKEN_EXIONE))
{
Ast.AstThereExistsS node = m_ast.new AstThereExistsS();
node.m_schemaText = parse_SchemaText(specObject, property);
next(TozeTokenizer.TOKEN_DOT);
node.m_schemaExpression = parse_SchemaExpression(specObject, property);
if (ok())
{
return node;
}
}
Ast.AstSchemaExpression node = parse_rrSchemaExpression1(specObject, property);
return node;
} |
0f440654-f08a-4779-a09c-3231e0dd39d3 | 0 | public String getMessage() {
return " a";
} |
38af37dd-93f4-41d8-8f5b-c79bb0037f81 | 2 | private static void loadAllTheCardImagesFromFileNames(String[] cardImageFileNames, MediaTracker tracker) {
String curDir = System.getProperty("user.dir");
Image pic;
for (int i=0; i < cardImageFileNames.length; i++) {
pic = Toolkit.getDefaultToolkit().getImage(curDir + "/classic_cards/" + cardImageFileNames[i]);
tracker.addImage(pic, i);
}
try {
tracker.waitForAll();
imagesHaveBeenLoaded = true;
} catch(java.lang.InterruptedException e) {
}
} |
f74b8d9c-526a-4ab1-970f-65d20f22bfa7 | 2 | public int getPlayersPatronXP(String playerName) {
int patronsXP = 0;
String SQL = "SELECT `XP` " + " FROM " + tblAllegiance + " WHERE `player` LIKE ?";
Connection con = getSQLConnection();
try {
PreparedStatement statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
ResultSet result = statement.executeQuery();
while (result.next()) {
patronsXP = result.getInt(1);
}
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return patronsXP;
} |
270fbde6-6939-484f-9a78-b86e1bfc46a8 | 3 | private static void insertionSort(int[] num) {
int j;
int key;
int i;
for (j = 1; j < num.length; j++) {
key = num[ j ];
for(i = j - 1; (i >= 0) && (num[ i ] >= key); i--) {
num[ i+1 ] = num[ i ];
}
iSwaps++;
num[ i+1 ] = key;
}
} |
2e43bbe7-205e-4748-9214-618ba992f259 | 7 | public Node findLoopStart(Node head) {
Node fast = head;
Node slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
break;
}
}
if (fast != slow)
return null;
slow = head;
while (slow != null && fast != null) {
if (slow == fast)
break;
slow = slow.next;
fast = fast.next;
}
return slow;
} |
7aa35d92-4832-43d7-98bc-ec02a034c99a | 2 | public void addCard(Card card, boolean position) {
if (position == TOP) {
cardPile.addFirst(card);
}
else {
cardPile.addLast(card);
}
if (component != null) {
component.updateTopCard();
}
} |
f9b488a0-b7c8-4573-be08-2b8e92bafd8b | 0 | public int getId() {
return id;
} |
4e553521-6108-466f-b865-172e1082ec68 | 7 | public static boolean isVersionGreaterThan(String isThis, String greaterThanThis){
int A[] = parseVersion(isThis);
int B[] = parseVersion(greaterThanThis);
if(A[0] > B[0]){
return true;
}
if(A[0] == B[0]){
if(A[1] > B[1]){
return true;
}
if(A[1] == B[1]){
if(A[2] > B[2]){
return true;
}
if(A[2] == B[2]){
if(A[3] > B[3]){
return true;
}
return false;
}
return false;
}
return false;
}
return false;
} |
6b372859-2f8a-4c57-9f14-3a54ebfc26a7 | 0 | public LRParseTableAction(GrammarEnvironment environment) {
super("Build SLR(1) Parse Table", null);
this.environment = environment;
this.frame = Universe.frameForEnvironment(environment);
} |
8aa54e70-8e8d-4fd2-9cba-728b9257d522 | 3 | public static boolean isValidationKeyPressed(){
return (keyState[SPACE] && !prevKeyState[SPACE]) || (keyState[ENTER] && !prevKeyState[ENTER]);
} |
1e9ab658-57b1-49d7-9502-7e08bfaf6f5f | 9 | @Override
public final void connect() throws CommunicationError, ConnectionException {
synchronized(_lock) {
if(_isConnected) {
throw new RuntimeException("Verbindung zum Datenverteiler besteht bereits.");
}
if(_dataModelConnection != null) {
_dataModelConnection.connect();
_dataModel = _dataModelConnection.getDataModel();
((DafDataModel)this._dataModel).setPublicConnection(this);
}
if(_reinitializeOnConnect) {
if(_dataModel instanceof DafDataModel && _dataModelConnection == null) {
createDataModel();
}
_closeHandler.reset();
_cacheManager = null;
_configurationManager = null;
_subscriptionManager = null;
if(_implicitUnsubscriber != null) {
try {
_implicitUnsubscriber.interrupt();
_implicitUnsubscriber.join();
}
catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
_implicitSubscriptionDataReceived = new Object();
_implicitSubscriptions = new Hashtable<BaseSubscriptionInfo, ImplicitSubscriptionNote>();
_implicitUnsubscriber = null;
_streamedRequestManager = null;
_defaultData = new HashMap<AttributeGroup, Data>();
_readyMessageSender = null;
}
_reinitializeOnConnect = true;
if(_highLevelCommunication != null) {
_highLevelCommunication.terminate(false, "Verbindung soll erneut aufgebaut werden");
}
_highLevelCommunication = new ClientHighLevelCommunication(_clientDavParameters, _closeHandler);
_highLevelCommunication.setConnectionListener(
new DavConnectionListener() {
@Override
public void connectionClosed(ClientDavInterface nullConnection) {
notifyConnectionClosed();
}
}
);
_isConnected = true;
_isLoggedIn = false;
if(_implicitUnsubscriber == null) {
_implicitUnsubscriber = new ImplicitUnsubscriber();
_implicitUnsubscriber.start();
}
}
} |
e706ce79-e053-424e-b475-5dadecb1f635 | 1 | public AuctionOntology() {
super(ONTOLOGY_NAME, BasicOntology.getInstance());
try {
//Add Concepts
ConceptSchema cs = new ConceptSchema(GOOD);
add(cs, Good.class);
cs.add(GOOD_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.MANDATORY);
cs.add(GOOD_PRICE, (PrimitiveSchema) getSchema(BasicOntology.INTEGER), ObjectSchema.MANDATORY);
//Add AgentActions
AgentActionSchema as;
add(as = new AgentActionSchema(PARTICIPATE), Participate.class);
as.add(PARTICIPATE_MESSAGE, (PrimitiveSchema) getSchema(BasicOntology.BOOLEAN), ObjectSchema.MANDATORY);
add(as = new AgentActionSchema(ADD_GOOD), AddGood.class);
as.add(ADD_GOOD_PRICE, (PrimitiveSchema) getSchema(BasicOntology.INTEGER), ObjectSchema.MANDATORY);
as.add(ADD_GOOD_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.MANDATORY);
add(as = new AgentActionSchema(INCREASE_PRICE), IncreasePrice.class);
as.add(INCREASE_PRICE_AMOUNT, (PrimitiveSchema) getSchema(BasicOntology.INTEGER), ObjectSchema.MANDATORY);
add(as = new AgentActionSchema(ACCEPT_PRICE), AcceptPrice.class);
as.add(ACCEPT_PRICE_DECISION, (PrimitiveSchema) getSchema(BasicOntology.BOOLEAN), ObjectSchema.MANDATORY);
add(as = new AgentActionSchema(DROPOUT), Dropout.class);
as.add(DROPOUT_BIDDERS, (PrimitiveSchema) getSchema(BasicOntology.INTEGER), ObjectSchema.MANDATORY);
as.add(DROPOUT_REMAINING, (PrimitiveSchema) getSchema(BasicOntology.INTEGER), ObjectSchema.MANDATORY);
} catch (OntologyException e) {
e.printStackTrace();
}
} |
af34f88e-2615-4d94-a6d5-5527ef5a73a0 | 1 | @Override
protected Element getSpecificDataXML() {
Element e = new Element("Album");
if (coverUrl != null) e.setAttribute("coverUrl", coverUrl.toString());
// if (moreInfo != null) e.setAttribute("moreInfo", moreInfo);
return e;
} |
b167f927-b955-479b-88b2-52d385cad38f | 9 | private Point[] chooseRandomCentres(int k, int n, int d, Point points[]) {
//array to store the choosen centres
Point[] centres = new Point[k];
//choose the first centre (each point has the same probability of being choosen)
int i = 0;
int next = 0;
int j = 0;
do { //only choose from the n-i points not already choosen
next = this.clustererRandom.nextInt(n - 1);
//check if the choosen point is not a dummy
} while (points[next].weight < 1);
//set j to next unchoosen point
j = next;
//copy the choosen point to the array
centres[i] = points[j].clone();
//set the current centre for all points to the choosen centre
for (i = 0; i < n; i++) {
points[i].centreIndex = 0;
points[i].curCost = points[i].costOfPointToCenter(centres[0]);
}
//choose centre 1 to k-1 with the kMeans++ distribution
for (i = 1; i < k; i++) {
double cost = 0.0;
for (j = 0; j < n; j++) {
cost += points[j].curCost;
}
double random = 0;
double sum = 0.0;
int pos = -1;
do {
random = this.clustererRandom.nextDouble();//genrand_real3();
sum = 0.0;
pos = -1;
for (j = 0; j < n; j++) {
sum = sum + points[j].curCost;
if (random <= sum / cost) {
pos = j;
break;
}
}
} while (points[pos].weight < 1);
//copy the choosen centre
centres[i] = points[pos].clone();
//check which points are closest to the new centre
for (j = 0; j < n; j++) {
double newCost = points[j].costOfPointToCenter(centres[i]);
if (points[j].curCost > newCost) {
points[j].curCost = newCost;
points[j].centreIndex = i;
}
}
}
/*printf("random centres: \n");
for(i = 0; i < k; i++){
//printf("%d: (",i);
int l = 0;
for(l = 0; l < centres[i].dimension; l++){
printf("%f,",centres[i].coordinates[l] / centres[i].weight);
}
printf(")\n");
}*/
return centres;
} |
38be3061-6d37-466a-9553-337024da936c | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final List<Ability> offensiveAffects=returnOffensiveAffects(target);
if((success)&&(offensiveAffects.size()>0))
{
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_OK_VISUAL,null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
if((!CMLib.flags().isStillAffectedBy(target,offensiveAffects,false))&&(target.location()!=null))
target.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> feel(s) much better."));
}
}
// return whether it worked
return success;
} |
aea6de7b-fd37-4429-aff3-55e5617a8f8d | 4 | public static double Distance2Objects (ABObject o1, ABObject o2)
{
List<Point2D> pointsO1 = MathFunctions.getObjectContourPoints(o1);
List<Point2D> pointsO2 = MathFunctions.getObjectContourPoints(o2);
double error_distance = 2.0;
double min_distance = 999.0;
for (int i = 0; i < pointsO1.size(); i++)
{
Point2D p1 = pointsO1.get(i);
for (int j = 0; j < pointsO2.size(); j++)
{
Point2D p2 = pointsO2.get(j);
double distance = Distance2Points(p1, p2);
//System.out.println("Distance between " + p1 + ", " + p2 + " = " + distance);
if (distance < error_distance)
{
/*System.out.println("Distance between " + "(" + p1.x + ", " + p1.y + ")" +
"(" + p2.x + ", " + p2.y + ")" +
" = " + distance);*/
if (distance < min_distance)
min_distance = distance;
}
}
}
return min_distance;
} |
85edaece-ec8e-4767-9a41-f7e9915b984e | 6 | private void parseType() throws SyntaxError {
switch(currentToken.kind) {
case Token.BOOLEAN:
case Token.VOID:
acceptIt();
break;
case Token.IDENTIFIER:
parseIdentifier();
if(currentToken.kind == Token.LBRACKET) {
acceptIt();
accept(Token.RBRACKET);
}
break;
case Token.INT:
acceptIt();
if(currentToken.kind == Token.LBRACKET) {
acceptIt();
accept(Token.RBRACKET);
}
break;
default:
syntacticError("\"%\" cannot start a type", currentToken.spelling);
break;
}
} |
b47e8d38-343d-4fe2-b047-7cd7c4f44da9 | 3 | private static void selectionSort(Items[] items) {
for (int pass = 0; pass < items.length-1; pass++) {
// System.out.println(pass + "-" + items[pass]);
int indexOfTarget = pass;
int indexOfSmallest = indexOfTarget;
for (int j = indexOfTarget+1; j < items.length; j++) {
if (items[j].getItemName().compareToIgnoreCase(items[indexOfSmallest].getItemName()) < 0) {
indexOfSmallest = j;
}
}
Items temp = items[indexOfTarget];
items[indexOfTarget] = items[indexOfSmallest];
items[indexOfSmallest] = temp;
}
} |
9490332a-4a1c-4524-b857-c3bfe90cd60d | 3 | public void validate(){
if ( personBean.getFirstName().length() == 0 ){
addFieldError( "personBean.firstName", "First name is required." );
}
if ( personBean.getEmail().length() == 0 ){
addFieldError( "personBean.email", "Email is required." );
}
if ( personBean.getAge() < 18 ){
addFieldError( "personBean.age", "Age is required and must be 18 or older" );
}
} |
b19c65cc-03b3-47d4-a656-e9aef38df798 | 9 | @SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
NameValuePair other = (NameValuePair) obj;
if (k == null) {
if (other.k != null) return false;
} else if (!k.equals(other.k)) return false;
if (v == null) {
if (other.v != null) return false;
} else if (!v.equals(other.v)) return false;
return true;
} |
311367b7-8326-40f9-8233-b5273c338d31 | 9 | public void draw(UShape shape) {
// System.err.println("inter=" + shape.getClass());
if (shape instanceof Ftile) {
final Ftile tile = (Ftile) shape;
final Set<Swimlane> swinlanes = tile.getSwimlanes();
final boolean contained = swinlanes.contains(swimlane);
if (contained) {
tile.drawU(this);
// drawGoto();
}
} else if (shape instanceof Connection) {
final Connection connection = (Connection) shape;
final Ftile tile1 = connection.getFtile1();
final Ftile tile2 = connection.getFtile2();
final boolean contained1 = tile1 == null || tile1.getSwimlaneOut() == null
|| tile1.getSwimlaneOut() == swimlane;
final boolean contained2 = tile2 == null || tile2.getSwimlaneIn() == null
|| tile2.getSwimlaneIn() == swimlane;
if (contained1 && contained2) {
connection.drawU(this);
}
} else {
getUg().draw(shape);
// System.err.println("Drawing " + shape);
}
} |
19746056-b0a6-4331-9a0d-0ab60626a846 | 6 | @Override
protected void idle() {
boolean moved=false;
switch(facing) {
case UP: moved=move(x, y-1); break;
case DOWN: moved=move(x, y+1); break;
case LEFT: moved=move(x-1, y); break;
case RIGHT: moved=move(x+1, y); break;
}
Random r = new Random();
if(!moved || r.nextInt(8) == 0)
facing = r.nextInt(4);
} |
2d450092-2df6-4d8d-82be-4f350cbffe59 | 1 | public final Instruction getPrevByAddr() {
if (prevByAddr.opcode == opc_impdep1)
return null;
return prevByAddr;
} |
974eae42-ed3b-41be-922a-2f827f2e979b | 8 | private static void recursiveParse(Corpus corpus, Element element, boolean includeTokensWithNonAToZ) {
NodeList nodeList = element.getChildNodes();
for (int i=0; i<nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element el = (Element) node;
switch (el.getNodeName()) {
case "Article":
corpus.startArticle();
recursiveParse(corpus, el, includeTokensWithNonAToZ);
break;
case "sentence":
corpus.startSentence();
recursiveParse(corpus, el, includeTokensWithNonAToZ);
break;
case "cons":
corpus.openConstituent(el.getAttribute("cat"));
recursiveParse(corpus, el, includeTokensWithNonAToZ);
corpus.closeConstituent();
break;
case "tok":
String text = el.getTextContent();
if (includeTokensWithNonAToZ || text.matches("[A-Za-z]+")) {
corpus.addToken(el.getTextContent(), el.getAttribute("cat"));
}
break;
default:
recursiveParse(corpus, el, includeTokensWithNonAToZ);
}
}
}
} |
81bdb228-a90b-4714-9a79-cb7c155bb9fd | 0 | public long getSequence() {
return this._sequence;
} |
4fb1fa46-624b-4cc9-91db-1c01b4ac7713 | 9 | public static void main(String[] args)
{
int index = 0;
URL url = Driver.class.getResource("kap1.txt");
In input = new In(url);
TwoThreeTree<String, Value> tree = new TwoThreeTree<String, Value>();
Value v = null;
while (!input.isEmpty())
{
String line = input.readLine().trim();
String[] words = line.split(" ");
for (String word : words)
{
if (word.equals(""))
{
continue;
}
v = tree.get(word);
if(v != null)
{
v.count++;
}
else
{
v = new Value(++index);
}
word = word.replaceAll("[,.;:'-()]", ""); //remove some special characters
tree.put(word.toLowerCase(), v); //make it case insensitive
System.out.println(word);
//Run the program and scan the words
//First strip away extra characters from each word
//Then add the word into the search tree
}
}
System.out.println(" ");
System.out.println("size=" + tree.size());
System.out.println("density=" + tree.density());
System.out.println("depth=" + tree.depth());
System.out.println("howMuchMore=" + tree.howMuchMore());
java.util.Iterator<String> it = tree.new Iterator().iterator();
System.out.println(" ");
System.out.println("Printing the 10 words with most occurances using iterator");
Stack<Value> stack = new Stack<Value>();
while (it.hasNext())
{
String k = it.next();
// System.out.println(k + ":" + tree.get(k));
stack.push(tree.get(k));
}
//Since the values (<id, occurrence>) is not sorted, so we need to sort them before popping
Collections.sort(stack);
for (int i = 0; i < 10; ++i)
{
System.out.println("[" + i + "]" + ":" + stack.pop());
}
TwoThreeTree<Value, String> inverseTree = new TwoThreeTree<Value, String>();
it = tree.new Iterator().iterator();
//Loop all keys and reverse the key-value pair
while (it.hasNext())
{
String key = it.next();
Value value = tree.get(key);
inverseTree.put(value, key);
}
//create an iterator for the inverseTree
java.util.Iterator<Value> inverseIt = inverseTree.new Iterator().iterator();
Stack<String> stackForInverseTree = new Stack<String>();
while (inverseIt.hasNext())
{
Value reversedKey = inverseIt.next();
stackForInverseTree.push(inverseTree.get(reversedKey)); //Push the words in the stack. It is ordered by the number of occurences
// System.out.println(reversedKey + ":" + inverseTree.get(reversedKey));
}
System.out.println("Printing the 10 words with most occurances reversed tree");
for (int i = 0; i < 10; ++i)
{
System.out.println("[" + i + "]" + ":" + stackForInverseTree.pop());
}
} |
7d3ae6de-493f-4eb3-b505-5495674396b2 | 3 | private static int skipUTF8Char(byte b){
if((byte)(b&0x80)==0) return 1;
if((byte)(b&0xe0)==(byte)0xc0) return 2;
if((byte)(b&0xf0)==(byte)0xe0) return 3;
return 1;
} |
8e8cc203-241a-46b1-ac9d-27aa1d1029ec | 3 | @Test
public void coloursWhenShapeRotates() {
BoardGui board = new BoardGui(30, 10);
board.addNewShape(new LShape());
board.getBoard().rotateShapeAntiClockwise();
int[][] cells = board.getBoard().mapper.getShape().getLayoutArray();
for (int row = 0; row < cells.length; row++) {
for (int col = 0; col < cells[0].length; col++) {
if (cells[row][col] == 0) {
assertFalse("cell populated when should be empty", board.getBoard().getCell(Board.START_ROW + row, Board.START_COL + col).isPopulated());
assertEquals("unpopulated cell not empty colour", Board.DEFAULT_EMPTY_COLOUR, cellGuiAt(row + Board.START_ROW, col + Board.START_COL, board).getColour());
} else {
assertTrue("cell empty when should be populated", board.getBoard().getCell(Board.START_ROW + row, Board.START_COL + col).isPopulated());
assertEquals("populated cell not correct shape colour",
board.getBoard().mapper.getShape().getColour(),
cellGuiAt(row + Board.START_ROW, col + Board.START_COL, board).getColour());
}
}
}
} |
adb48982-c03a-41fc-85d6-fe47b4947343 | 5 | public static void main(String[] args)
{
BaseSetting bs = new BaseSetting();
Wording w = new Wording("Je suis un énoncé", new Object[10]);
if (w != null) {System.out.println("WORDING NOT NULL");}
// INSERTION WORDING
w.insert(bs);
if (w != null) {System.out.println("WORDING NOT NULL");}
w = null;
if (w == null) {System.out.println("WORDING NULL");}
w = Wording.findById(1, bs);
if (w != null) {System.out.println("WORDING NULL");}
if (bs != null) {System.out.println("BS OK");}
ArrayList<Question> alq = new ArrayList<>();
QuestionCalculation qc1 = new QuestionCalculation("Qui suis-je ?",1);
ArrayList<Integer> ali1 = new ArrayList<>();
ali1.add(6);
ali1.add(9);
qc1.setOperands(ali1);
ArrayList<Character> alc1 = new ArrayList<>();
alc1.add('-');
qc1.setOperators(alc1);
qc1.setLength(0);
QuestionCalculation qc2 = new QuestionCalculation("Où est Brian ?",1);
ArrayList<Integer> ali2 = new ArrayList<>();
ali2.add(6);
ali2.add(6);
ali2.add(6);
qc2.setOperands(ali2);
ArrayList<Character> alc2 = new ArrayList<>();
alc2.add('/');
alc2.add('/');
qc2.setOperators(alc2);
qc2.setLength(0);
// INSERTION QUESTIONS
qc1.insert(bs);
qc2.insert(bs);
System.out.println("INSERT QC OK");
alq.add(qc1);
alq.add(qc2);
Exercise e1 = new Exercise("Titre1", w, alq, "Exercice de calculs", 1, true);
Exercise e2 = new Exercise("Titre2", w, alq, "Exercice de calculs", 1, true);
Exercise e3 = new Exercise("Titre3", w, alq, "Exercice de calculs", 1, true);
Exercise e4 = new Exercise("Titre4", w, alq, "Exercice de calculs", 1, true);
// INSERTION EXERCISE
e1.insert(bs);
e2.insert(bs);
e3.insert(bs);
e4.insert(bs);
System.out.println("INSERT E OK");
ArrayList<Exercise> ale = Exercise.findAll(bs);
ArrayList<Question> alquest = e1.findById_AllQuestions(1, bs);
System.out.println(">>> "+alquest+" <<<");
} |
791c0181-2063-485a-8334-919c5bf42c1e | 0 | static void tune(Instrument instrument) {
instrument.play(Note.C_SHARP);
} |
515ba9c0-0192-4702-b48a-02fdc2590944 | 8 | @SuppressWarnings("unchecked")
private ClassNode newConcreteTrait(final TraitInfo info) {
final Type interfaceType = Type.getType(info.getInterfase());
final Type superType = Type.getType(info.getImplementation());
final String implName = superType.getInternalName();
final ClassNode cn = new ClassNode();
final List<Method> toImplement = info.getToImplement();
final Map<Class<?>, Class<?>> parentTraits = info.getParentTraits();
cn.version = Opcodes.V1_6;
cn.access = Opcodes.ACC_PUBLIC;
cn.name = implName + "Concrete";
cn.superName = implName;
newParamConstructor(cn, types(toImplement.size(), interfaceType));
// add trait fields, one for each possible method overload
for (int i = 0; i < toImplement.size(); i++) {
cn.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "overload" + i, interfaceType.getDescriptor(), null, null));
}
{
int i = 0;
for (final Method method : toImplement) {
final FieldInfo fi = new FieldInfo("overload" + i, interfaceType.getInternalName(), interfaceType.getDescriptor());
cn.methods.add(newAdapterMethod(cn.name, method, fi));
i++;
}
}
// add fields for parent classes
{
int i = 0;
for (final Entry<Class<?>, Class<?>> parent : parentTraits.entrySet()) {
final Type parentInterfaceType = Type.getType(parent.getKey());
final String fieldName = "parent" + i;
cn.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, fieldName, parentInterfaceType.getDescriptor(), null, null));
final FieldInfo fi = new FieldInfo(fieldName, parentInterfaceType.getInternalName(), parentInterfaceType.getDescriptor());
for (final Method method : parent.getValue().getDeclaredMethods()) {
cn.methods.add(newAdapterMethod(cn.name, method, fi));
}
i++;
}
}
return cn;
} |
61953cea-90ef-436d-9df4-a469d3ee8373 | 8 | public PlayerNumber winner() {
// @@@ quit function use
if (someoneQuit) {
return onePlayerLeft;
}
if (containsInt(moves1, 2) && containsInt(moves1, 5)
&& (movesLeft() != 0)) {
return FIRST_PLAYER;
}
if (containsInt(moves2, 2) && containsInt(moves2, 5)
&& (movesLeft() != 0)) {
return SECOND_PLAYER;
}
if (movesLeft() > 0) {
return GAME_NOT_OVER;
}
return DRAW;
} |
899a7f9e-2749-4e7c-8c4e-d0e8189e55ed | 8 | private void jBtnSubmitModActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnSubmitModActionPerformed
DateFormat df = new SimpleDateFormat("M/d/yy", Locale.ENGLISH);
DateFormat tf = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
CourseSection section;
ArrayList<MeetingDay> days = new ArrayList();
// Create CourseSection object
section = new CourseSection();
section.course_number = jCmbCourseNum.getSelectedItem().toString();
section.section_number = Integer.parseInt(jtxtSectionNumber.getText());
section.available = true;
section.capacity = Integer.parseInt(jFmtCapacity.getText());
section.seats_available = section.capacity;
section.status = "Open";
section.term = jCmbTerm.getSelectedItem().toString();
section.student_count = 0;
section.type = jCmbType.getSelectedItem().toString();
try
{
section.start_date = new Date(df.parse(dateChooserStart.getText()).getTime());
section.last_date = new Date(df.parse(dateChooserEnd.getText()).getTime());
}
catch (ParseException ex)
{
System.out.println(ex);
}
// Build meeting day list
int totalRows = jTblMeetingDays.getRowCount();
MeetingDay day = new MeetingDay();
jTblMeetingDays.clearSelection();
for (int row = 0; row < totalRows; row++) {
if (jTblMeetingDays.getValueAt(row, 0) != null &&
jTblMeetingDays.getValueAt(row, 1) != null &&
jTblMeetingDays.getValueAt(row, 2) != null &&
jTblMeetingDays.getValueAt(row, 3) != null)
{
// Create MeetingDay object
try {
day.start_time = new Time(tf.parse(jTblMeetingDays.getValueAt(row, 0).toString()).getTime());
day.end_time = new Time(tf.parse(jTblMeetingDays.getValueAt(row, 1).toString()).getTime());
} catch (ParseException ex) {
System.out.println(ex);
}
day.room_number = jTblMeetingDays.getValueAt(row, 2).toString();
day.day = jTblMeetingDays.getValueAt(row, 3).toString();
// Save MeetingDay to MeetingDay list
days.add(day);
day = new MeetingDay();
}
}
GUIController.coursesections.addCourseSection(section, days);
JOptionPane.showMessageDialog(null, "Course has been created");
try {
GUIController.courseListingCard.jTblResults.setModel(GUIController.buildTable());
} catch (SQLException ex) {
System.out.println(ex);
}
GUIController.switchTo("COURSE LISTING");
}//GEN-LAST:event_jBtnSubmitModActionPerformed |
a4579b3d-e4d5-4e6a-a1a1-6b68f3ec710b | 3 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
fillBox(1000);
while ((line = in.readLine()) != null && line.length() != 0) {
int nCase = Integer.parseInt(line.trim());
for (int i = 0; i < nCase; i++) {
int n = Integer.parseInt(in.readLine().trim());
out.append(box[n] + "\n");
}
}
System.out.print(out);
} |
bfd0bc71-5400-40d5-b9bb-2c523b8efe64 | 5 | public void register(HttpServletRequest request, HttpServletResponse response) {
try{
//request.setCharacterEncoding("UTF-8");
//response.setCharacterEncoding("UTF-8");
//JSPȡûϢ
String name = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8");
String pass =request.getParameter("password");
String realName =new String(request.getParameter("realname").getBytes("ISO-8859-1"),"UTF-8");
String sex = new String(request.getParameter("gender").getBytes("ISO-8859-1"),"UTF-8");
String ag = "0";
int age;
if(request.getParameter("age")==null){
age = 0;
}else{
age = Integer.parseInt(request.getParameter("age"));
}
String email = new String(request.getParameter("email").getBytes("ISO-8859-1"),"UTF-8");
String phone = request.getParameter("connectnumber");
String address = new String(request.getParameter("address").getBytes("ISO-8859-1"),"UTF-8");
//ϵͳлע
Calendar cal = Calendar.getInstance();
Date registerDate = new Date(cal.get(Calendar.YEAR) - 1900, cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
//ǿûΪû
int role = 1;
int id = 0;
//ûϢװUSER
User user = new User(id,name,pass,sex,age,role,realName,phone,email,address,registerDate);
//UserDAOʵ
UserDAO ud = new UserDAO();
//жûǷ
if((ud.querryUseName(name))==null){
ud.insertUser(user);
response.sendRedirect("/BookShop/userView/registSuccess.jsp");
}else{
String alert ="ûѴ";
if(pass == null){
alert = "벻Ϊ";
request.setAttribute("alert", alert);
}
//û,ûʾ,FORWARDעҳ
request.setAttribute("alert", alert);
request.getRequestDispatcher("../userView/register.jsp").forward(request, response);
}
}catch(IOException e){
e.printStackTrace();
}catch(ServletException se){
se.printStackTrace();
}
} |
e96f44f6-62a0-4c8f-ac7d-190dd61890a9 | 7 | public void caseAVariableOccursFixedOrVariable(AVariableOccursFixedOrVariable node)
{
inAVariableOccursFixedOrVariable(node);
if(node.getDataName() != null)
{
node.getDataName().apply(this);
}
if(node.getOn() != null)
{
node.getOn().apply(this);
}
if(node.getDepending() != null)
{
node.getDepending().apply(this);
}
if(node.getTimes() != null)
{
node.getTimes().apply(this);
}
if(node.getNumber() != null)
{
node.getNumber().apply(this);
}
if(node.getOccursTo() != null)
{
node.getOccursTo().apply(this);
}
if(node.getOccurs() != null)
{
node.getOccurs().apply(this);
}
outAVariableOccursFixedOrVariable(node);
} |
516e9b36-3404-4240-9a04-b86150a31820 | 3 | public void buildXmlDocument() throws Exception {
System.out.println(entryList);
System.out.println(file);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = (Element) doc.createElement("journal");
doc.appendChild(root);
for (ScriptureReference entry : entryList) {
Element jEntry = doc.createElement("entry"); //makes and element
root.appendChild(jEntry); //attaches it to the root
// set attribute to entry element
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Attr attr = doc.createAttribute("date");
attr.setValue(sdf.format(entry.getEntryDate().getTime()));
jEntry.setAttributeNode(attr);
for (Scripture s : entry.getScriptures()) {
// create scripter elements
Element script = doc.createElement("scripture");
jEntry.appendChild(script);
attr = doc.createAttribute("book");
attr.setValue(s.getBook());
script.setAttributeNode(attr);
attr = doc.createAttribute("chapter");
attr.setValue(Integer.toString(s.getChapter()));
script.setAttributeNode(attr);
attr = doc.createAttribute("startverse");
attr.setValue(Integer.toString(s.getStartVerse()));
script.setAttributeNode(attr);
attr = doc.createAttribute("endverse");
attr.setValue(Integer.toString(s.getEndVerse()));
script.setAttributeNode(attr);
}
for (String t : entry.getTopics()) {
// create topic elements
Element topic = doc.createElement("topic");
topic.appendChild(doc.createTextNode(t));
jEntry.appendChild(topic);
}
// add the content to the file
Element content = doc.createElement("content");
content.appendChild(doc.createTextNode(entry.getContent()));
jEntry.appendChild(content);
}
saveDocument(doc);
} |
a5b04c7d-3bd6-4851-a600-63753654223a | 4 | public static void main(String[] args) {
NKeyMap<String, String> map = new NKeyHashMap<String, String>();
for(int i = 0; i < 3; i++){
Double longitude = Math.random();
String latitude = ""+Math.random();
String height = ""+Math.random();
String value = "I am multi key value longitude: '" + longitude +
"' latitude: '" + latitude + "' and height: '" + height + "' with value: '" +
System.currentTimeMillis() + "'";
map.put(value, ""+longitude, latitude, height);
}
for( String value : map.values()){
System.out.println(value);
}
for(Set<String> keys : map.keySet()){
System.out.println("-------------- NEXT PAIR -------------");
for(String key : keys){
System.out.println("And my keys are " + key);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.