method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
4191463e-a608-4b0f-a1f0-bf788b83df06
| 4
|
public boolean updateScore(int player1Score, int player2Score) {
boolean test = false;
if (test || m_test) {
System.out.println("GameWindow :: updateScore() BEGIN");
}
getDrawing().setPlayer1Score(player1Score);
getDrawing().setPlayer2Score(player2Score);
if (test || m_test) {
System.out.println("GameWindow :: updateScore() END");
}
return true;
}
|
1b42c069-f139-4b49-b900-7d0e0e008a9a
| 5
|
public boolean pageSetup(PrintProxy proxy) {
if (useNativeDialogs()) {
PageFormat format = mJob.pageDialog(createPageFormat());
if (format != null) {
adjustSettingsToPageFormat(format);
proxy.adjustToPageSetupChanges();
return true;
}
} else {
PageSetupPanel panel = new PageSetupPanel(getPrintService(), mSet);
if (WindowUtils.showOptionDialog(UIUtilities.getComponentForDialog(proxy), panel, PAGE_SETUP_TITLE, false, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
try {
PrintService service = panel.accept(mSet);
if (service != null) {
mJob.setPrintService(service);
}
proxy.adjustToPageSetupChanges();
return true;
} catch (PrinterException exception) {
WindowUtils.showError(UIUtilities.getComponentForDialog(proxy), UNABLE_TO_SWITCH_PRINTERS);
}
}
}
return false;
}
|
e1ec3913-f213-4918-b2d6-7cdb68a63fe4
| 9
|
public Object[] exec(ImagePlus imp1, String new_name, boolean whiteParticles, boolean connect4) {
// 0 - Check validity of parameters
if (null == imp1) return null;
int width = imp1.getWidth();
int height = imp1.getHeight();
int size = width * height;
ImageProcessor ip3;
ImagePlus imp3;
int x, y, offset, pointer, labelColour=1;
int foreground = 255;//, background = 0;
IJ.showStatus("Labelling...");
// 1 - Perform the magic
imp3 = new ImagePlus(new_name,imp1.getProcessor().duplicate());
ip3 = imp3.getProcessor();
if (!whiteParticles)
ip3.invert();
ImageConverter ic = new ImageConverter(imp3);
ic.convertToGray32();
ip3 = imp3.getProcessor();
ip3.multiply(-1);
float[] pixel =(float []) ip3.getPixels();
FloodFiller ff = new FloodFiller(ip3);
if (connect4){
for(y=0; y<height; y++) {
offset=y*width;
for(x=0; x<width; x++){
pointer = offset + x;
if ( pixel[pointer] == -foreground) {
ip3.setColor(labelColour++);
ff.fill(x, y);
}
}
}
}
else { //8
for(y=0; y<height; y++) {
offset=y*width;
for(x=0; x<width; x++){
pointer = offset + x;
if ( pixel[pointer] == -foreground) {
ip3.setColor(labelColour++);
ff.fill8(x, y);
}
}
}
}
imp3.updateAndDraw();
labelColour --;
// 2 - Return the new name and the image
return new Object[]{new_name, imp3, labelColour};
}
|
aff20682-c16f-4598-9c3b-8ed938e7dd01
| 4
|
void Louer() {
// Début de la location
int idCarte = Integer.parseInt(JOptionPane.showInputDialog("Numéro carte abonnée ?"));
Utilisateur user = null;
for (Utilisateur s : ConfigGlobale.utilisateurs) {
if(s.getFk_id_carte()==idCarte){
user = s;
break;
}
}
if(user != null && user.getFk_id_velo()==-1){
LabelCarte.setForeground(Color.green);
ctrlLV.locationVelo(user);
LabelRecupVelo.setForeground(Color.green);
LabelRemerciement.setForeground(Color.green);
} else {
LabelCarte.setForeground(Color.red);
}
}
|
e481079c-0be6-435f-aa72-e88a081d7bd1
| 4
|
public void randomStart()
{
start = rand.nextInt(2);
switch(start)
{
case 0: direction = 6;
break;
case 1: direction = 5;
break;
case 2: direction = 5;
break;
case 3: direction = 6;
break;
}
}
|
3ef655a3-8158-4bd3-bc3c-00b17540686b
| 0
|
public int getQuantityOfHurdles() {
return hurdleList.size();
}
|
c10389a0-d23c-48f9-95ce-f95b956502a6
| 9
|
public void handlePacket(int id, PacketReader read, ClientConnection client) {
try {
if (id == 2) {
int sub = read.readInt();
if(sub == 0){
}else if(sub == 1){
RaspIDE.newSnippet(read.readString());
}else if(sub == 2){
String name = read.readString();
RaspIDE.getSnippet(name).setCode(read.readString());
PacketWriter pac = new PacketWriter(2);
pac.writeInt(2);
pac.writeString(name);
pac.writeString(RaspIDE.getSnippet(name).getCode());
RaspIDE.network.sendPacketToAll(pac);
}else if(sub == 3){
RaspIDE.getSnippet(read.readString()).run();
}else if(sub == 4){
}
} else if (id == 3) {
int sub = read.readInt();
if(sub == 2){
RaspIDE.stopCode();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
a01c9c72-cd36-404e-b987-5984addaccae
| 9
|
protected List<PingData> read(InputStream in) {
List<PingData> retval=null;
try {
while(true) {
try {
String name_str=Util.readToken(in);
String uuid_str=Util.readToken(in);
String addr_str=Util.readToken(in);
String coord_str=Util.readToken(in);
if(name_str == null || uuid_str == null || addr_str == null || coord_str == null)
break;
UUID uuid=null;
try {
long tmp=Long.valueOf(uuid_str);
uuid=new UUID(0, tmp);
}
catch(Throwable t) {
uuid=UUID.fromString(uuid_str);
}
PhysicalAddress phys_addr=new IpAddress(addr_str);
boolean is_coordinator=coord_str.trim().equals("T") || coord_str.trim().equals("t");
if(retval == null)
retval=new ArrayList<>();
retval.add(new PingData(uuid, true, name_str, phys_addr).coord(is_coordinator));
}
catch(Throwable t) {
log.error(Util.getMessage("FailedReadingLineOfInputStream"), t);
}
}
return retval;
}
finally {
Util.close(in);
}
}
|
91403e55-2e07-4d56-9372-7ec8bde70791
| 5
|
public void insertBelow(String filter) {
gui.addToHistory(filter);
if (filter != null && !filter.trim().equals("")) {
JList list =
(JList) filterLists.elementAt(currentFilterIndex);
int i = list.getSelectedIndex();
DefaultListModel model =
(DefaultListModel) list.getModel();
int size = model.getSize();
StringTokenizer tokenizer =
new StringTokenizer(filter, "|");
while (tokenizer.hasMoreTokens()) {
if (i < 0 || size - 1 == i) {
model.addElement(tokenizer.nextToken().trim());
} else {
model.add(++i, tokenizer.nextToken().trim());
}
}
}
}
|
e85917e6-71c7-425f-8c0b-3b0e2ef62592
| 6
|
public void checkAttackCollision(Character c){
Ellipse2D.Double attackArea = null;
if(c.getDirection() == "up"){
attackArea = new Ellipse2D.Double(
c.getX(),
c.getY() - c.getWidth()/2,
c.getWidth(),
c.getHeight());
}else if(c.getDirection() == "down"){
attackArea = new Ellipse2D.Double(
c.getX(),
c.getY() + c.getWidth()/2 ,
c.getWidth(),
c.getHeight());
}else if(c.getDirection() == "left"){
attackArea = new Ellipse2D.Double(
c.getX() - c.getWidth()/2,
c.getY(),
c.getWidth(),
c.getHeight());
}else{
attackArea = new Ellipse2D.Double(
c.getX() + c.getWidth()/2 ,
c.getY(),
c.getWidth(),
c.getHeight());
}
for(Character target : characters){
if(attackArea.intersects(target.getBounds()) && target.isAttackable() ){
target.setHealth( target.getHealth()-player.getDamage());
pushCharacter(player,target, 5);
System.out.println("Target health: " + target.getHealth() );
}
}
}
|
b9c1ee17-6ec2-4db6-accb-c25247d9f1f2
| 6
|
public void close(){
System.out.println("inner close");
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
is = null;
}
if(os != null){
try {
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
os = null;
}
if(client != null){
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client = null;
}
}
|
1574cdff-2dc9-481a-8ee9-e05e0f946343
| 1
|
public String toString()
{
if (nome != null)
return nome.toString();
return id + "";
}
|
9be63dd4-8c09-48d5-8f26-259e92b4a668
| 7
|
public void changeGameState() {
if (this.isGameEndConditionReached()) {
if (this.gameState == Game.GAME_STATE_BLACK) {
this.gameState = Game.GAME_STATE_END_BLACK_WON;
} else if (this.gameState == Game.GAME_STATE_WHITE) {
this.gameState = Game.GAME_STATE_END_WHITE_WON;
}
return;
}
switch (this.gameState) {
case GAME_STATE_BLACK:
this.gameState = GAME_STATE_WHITE;
break;
case GAME_STATE_WHITE:
this.gameState = GAME_STATE_BLACK;
break;
case GAME_STATE_END_WHITE_WON:
case GAME_STATE_END_BLACK_WON:
break;
default:
throw new IllegalStateException("Unknown game state: " + this.gameState);
}
}
|
74cd66d5-c782-4199-a393-1f26e3451eb9
| 6
|
@Override
public void performOperation(String name, ArgParser args) {
//We support only three args, add, remove, and list
loadProperties();
if (args.hasOption("-add")) {
String prop = args.getStringArg("-add");
if (! prop.contains("=")) {
System.err.println("Please supply a property in the form key=value");
}
else {
String[] toks = prop.split("=");
properties.put(toks[0].trim(), toks[1].trim());
System.err.println("Added property " + toks[0] + " = " + toks[1]);
}
}
if (args.hasOption("-remove")) {
String prop = args.getStringArg("-remove");
if (properties.containsKey(prop)) {
properties.remove(prop);
System.err.println("Removed property " + prop);
}
else {
System.err.println("Property " + prop + " not found");
}
}
if (args.hasOption("-list")) {
System.out.println("Properties contains " + properties.size() + " pairs");
for(String key : properties.keySet()) {
System.out.println(key + " = " + properties.get(key));
}
}
writeProperties();
}
|
cca5d449-adec-4d51-9082-7f8c60c3de03
| 5
|
private void listMemberMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMemberMouseClicked
try
{
try
{
int select = listMember.getSelectedIndex();
listMember.setSelectedIndex(select);
String tempFirst = arrayFirstName.get(select);
String tempLast = arrayLastName.get(select);
String tempMid = arrayMidName.get(select);
//System.out.println("MemberID: "+lastname + " : " + select);
String tempQuery = "select loanid,grantdt,billingdt,loanamt,interestrt,interestamt,status,balance from cashloan where memberid = (select memberid from member where firstname = '"+ tempFirst +"' and lastname = '"+tempLast+"' and midinit = '"+tempMid+"')";
Statement stmt = null;
this.connect();
conn = this.getConnection();
try
{
stmt = conn.createStatement();
}
catch(SQLException e)
{
e.printStackTrace();
}
ResultSet rs;
try
{
rs = stmt.executeQuery(tempQuery);
try
{
tableUtils.updateTableModelData((DefaultTableModel) listLoan.getModel(), rs, 8);
}
catch (Exception ex)
{
Logger.getLogger(ViewMember.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
this.disconnect();
}
}
catch(Exception e)
{
DefaultTableModel model = (DefaultTableModel) listLoan.getModel();
model.removeRow(model.getRowCount()-1);
}
}
catch(Exception o)
{
}
// TODO add your handling code here:
}//GEN-LAST:event_listMemberMouseClicked
|
e2b8f020-4911-4eef-b72a-31a92830d0b0
| 7
|
public static List<QParameter> getQueryParameters(String queryString) {
if (queryString.startsWith("?")) {
queryString = queryString.substring(1);
}
List<QParameter> result = new ArrayList<QParameter>();
if (queryString != null && !queryString.equals("")) {
String[] p = queryString.split("&");
for (String s : p) {
if (s != null && !s.equals("")) {
if (s.indexOf('=') > -1) {
String[] temp = s.split("=");
result.add(new QParameter(temp[0], temp[1]));
}
}
}
}
return result;
}
|
7285c258-3087-46c8-ad9b-d86ef5b211f7
| 7
|
public static synchronized void setCodec( String extension,
Class iCodecClass )
throws SoundSystemException
{
if( extension == null )
throw new SoundSystemException( "Parameter 'extension' null in " +
"method 'setCodec'.",
SoundSystemException.NULL_PARAMETER );
if( iCodecClass == null )
throw new SoundSystemException( "Parameter 'iCodecClass' null in " +
"method 'setCodec'.",
SoundSystemException.NULL_PARAMETER );
if( !ICodec.class.isAssignableFrom( iCodecClass ) )
throw new SoundSystemException( "The specified class does " +
"not implement interface 'ICodec' in method 'setCodec'",
SoundSystemException.CLASS_TYPE_MISMATCH );
if( codecs == null )
codecs = new LinkedList<Codec>();
ListIterator<Codec> i = codecs.listIterator();
Codec codec;
while( i.hasNext() )
{
codec = i.next();
if( extension.matches( codec.extensionRegX ) )
i.remove();
}
codecs.add( new Codec( extension, iCodecClass ) );
// Let SoundSystem know if this is a MIDI codec, so it won't use
// javax.sound.midi anymore:
if( extension.matches( EXTENSION_MIDI ) )
midiCodec = true;
}
|
afed5d52-715a-4d27-8174-531d3d51a739
| 5
|
@SuppressWarnings("unchecked")
private IRandomAccessor2<T> createRandomAccessor(Object source)
{
if(source instanceof List<?>)
{
return new ListRandomAccessor((List<T>)source);
}
else if (source.getClass().isArray())
{
return new ArrayRandomAccessor((T[])source);
}
else if(source instanceof ArrayIterable<?>)
{
return new ArrayRandomAccessor(((ArrayIterable<T>)source).getSource());
}
throw new UnsupportedOperationException();
}
|
df0a4c49-8f70-4eb1-9f73-2137024f974e
| 3
|
private void relax(EdgeWeightedDigraph G, Vertex v)
{
for (WeightedDirectedEdge e : G.adj(v.label))
{
Vertex w = vertex[e.to()];
if (w.distTo > v.distTo + e.weight())
{
w.distTo = v.distTo + e.weight();
w.edgeTo = e;
if (!w.onQ)
{
queue.addFirst(w);
w.onQ = true;
}
}
}
}
|
11d48a75-3ebb-41f7-9526-47ab26001793
| 4
|
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9)) {
buf.append((char) ('0' + halfbyte));
} else {
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
|
63b20f27-6c0a-4504-b9e8-b828cdf4edc2
| 3
|
public static byte[] mix(Voice[] voices, int bufferSize) {
byte[] mixedOutput = new byte[bufferSize];
for (int i = 0; i < voices.length; i++) {
if (voices[i].isInUse()) {
byte[] voiceFrame = voices[i].getNextFrame(bufferSize);
for (int j = 0; j < bufferSize; j++) {
mixedOutput[j] += (voiceFrame[j]) / voices.length;
}
}
}
return mixedOutput;
}
|
9552695d-b86d-46f1-9e77-33182826d2e3
| 2
|
private void doViewAlLFS(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pageNum = StringUtil.toString(request.getParameter("pageNum"));
if("".equals(pageNum)) {
pageNum = "1";
}
try {
Pager<LianXiWoMen> pager = manager.getCurrentPageFSs(pageNum);
request.setAttribute("pager",pager);
request.getRequestDispatcher("/admin/lianxiwomen/lianxifangshiList.jsp").forward(request,response);
return;
} catch (SQLException e) {
logger.error("查找所有联系方式失败",e);
request.setAttribute("errorMsg","查找所有联系方式失败");
request.getRequestDispatcher("/admin/error.jsp").forward(request, response);
return;
}
}
|
0ad3ffa6-ad1b-4a91-97bc-6fb6b28b4405
| 0
|
protected int getPort() {
return port;
}
|
ee8fdd43-026e-4b2e-a75c-f6d2855ac2d2
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Menu().setVisible(true);
}
});
}
|
7a601c0b-834f-4dc7-8718-bc4ef1c3c2bc
| 5
|
@Override
void removeNode(final Node node)
{
if (this.isInGroundTruth())
{
assert this.getNodeCount() > 1;
int gtIndexOfRemovedNode = node.getGtClIndex();
// remove from pseudo cluster
this.graph.getPseudoCluster().removeNode(node);
/*
* Remove node from adjacency list.
* The last node will take its place.
*/
final Node lastNode = adjacencyList.getLastNode();
/*
* Remove all adjacencies of the last node from the *Fisher-Yates shuffle*
* This is a prerequisite of using the #fastResize method of the shuffle!
*/
final Iterator<Edge> intraClIterOfLast =
adjacencyList.intraClusterIterator(lastNode);
while (intraClIterOfLast.hasNext())
{
final Edge edge = intraClIterOfLast.next();
final long localID = this.getLocalID(edge);
assert this.shuffle.contains(localID);
this.shuffle.delete(localID);
}
this.adjacencyList.removeNode(node);
// the last node has taken the place of the removed node
assert BooleanUtils.implies(!lastNode.equals(node),
lastNode.getGtClIndex() == gtIndexOfRemovedNode);
assert BooleanUtils.implies(lastNode.equals(node),
lastNode.getGtClIndex() == node.getGtClIndex());
/*
* Update Fisher-Yates shuffle:
* Insert adjacencies of the former last node
* as adjacencies corresponding to the new position it takes!
*/
if (!node.equals(lastNode))
{
final Iterator<Edge> updatedEdgesIterator =
adjacencyList.intraClusterIterator(lastNode);
while (updatedEdgesIterator.hasNext())
{
final Edge edge = updatedEdgesIterator.next();
final long localID = this.getLocalID(edge);
assert !this.shuffle.contains(localID);
this.shuffle.select(localID);
}
}
this.shuffle.fastResize(Edge.maxEdgeCount(this.getNodeCount()));
updateTreeWeights();
}
else if (this.isInReferenceClustering())
{
this.adjacencyList.removeNode(node);
}
}
|
56798a14-1408-4bc4-8dc9-e78fd0e9a1d4
| 9
|
static void checkFrameValue(final Object value) {
if (value == Opcodes.TOP || value == Opcodes.INTEGER
|| value == Opcodes.FLOAT || value == Opcodes.LONG
|| value == Opcodes.DOUBLE || value == Opcodes.NULL
|| value == Opcodes.UNINITIALIZED_THIS)
{
return;
}
if (value instanceof String) {
checkInternalName((String) value, "Invalid stack frame value");
return;
}
if (!(value instanceof Label)) {
throw new IllegalArgumentException("Invalid stack frame value: "
+ value);
}
}
|
6e335250-90f3-4b70-adbe-991a4b537607
| 4
|
private void cpu2() {
switch (this.getGeneratoreRouting().getNextRoute()) {
case IO:
if (this.getIo().isFree()) {
this.getIo().setFree(false);
this.getIo().setJob(this.getCpu2().getJob());
this.getCpu2().setJob(null);
this.getCpu2().setFree(true);
double tmp = this.getIo().getGeneratore().getNext3Erlang();
this.getIo().getJob().setTempoProcessamento(tmp);
this.getCalendar().setTempoIO(this.getClock() + this.getIo().getJob().getTempoProcessamento());
// System.out.println("\tCPU2 " + this.getCalendar().getTempoIO());
} else {
Job j = this.getCpu2().getJob();
double tmp = this.getIo().getGeneratore().getNext3Erlang();
// System.out.println(tmp);
j.setTempoProcessamento(tmp);
this.getCpu2().setJob(null);
this.getCpu2().setFree(true);
}
break;
case OUT:
this.getCpu2().setFree(true);
this.getCpu2().getJob().setTempoUscita(this.getClock());
this.getTempiUscita().add(this.getCpu2().getJob().getTempoJob());
this.getCpu2().setJob(null);
break;
}
if (this.getCpu2().getQ().size() > 0) {
this.getCpu2().setJob(this.getJobFromQ());
this.getCpu2().setFree(false);
this.getCalendar().setTempoCPU2(this.getClock() + this.getCpu2().getJob().getTempoProcessamento());
} else {
this.getCalendar().setTempoCPU2(Double.MAX_VALUE);
this.getCpu2().setFree(true);
this.getCpu2().setJob(null);
}
}
|
1dab8216-2c8a-4df9-b0fb-95d25ee3b2f6
| 3
|
public void actionPerformed(ActionEvent ev)
{
try
{
FonteFinanciamento objt = classeView();
if (obj == null)
{
long x = new FonteFinanciamentoDAO().inserir(objt);
objt.setId(x);
JOptionPane.showMessageDialog(null,
"Os dados foram inseridos com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
if (tabela != null)
tabela.adc(objt);
else
autocp.adicionar(objt);
}
else
{
new FonteFinanciamentoDAO().atualizar(objt);
JOptionPane.showMessageDialog(null,
"Os dados foram atualizados com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
tabela.edt(objt);
}
view.dispose();
}
catch (Exception e)
{
JOptionPane
.showMessageDialog(
null,
"Verifique se os campos estão preenchidos corretamente ou se estão repetidos",
"Alerta", JOptionPane.WARNING_MESSAGE);
}
}
|
3160f08f-67c8-45e5-8b37-776330940c6a
| 6
|
public static Node merge(Node l, Node r) {
Node p1 = l;
Node p2 = r;
Node newHead = new Node(100);
Node pNew = newHead;
while (p1 != null || p2 != null) {
if (p1 == null) {
pNew.next = new Node(p2.val);
p2 = p2.next;
pNew = pNew.next;
} else if (p2 == null) {
pNew.next = new Node(p1.val);
p1 = p1.next;
pNew = pNew.next;
} else {
if (p1.val < p2.val) {
pNew.next = new Node(p1.val);
p1 = p1.next;
pNew = pNew.next;
} else if (p1.val == p2.val) {
pNew.next = new Node(p1.val);
pNew.next.next = new Node(p1.val);
pNew = pNew.next.next;
p1 = p1.next;
p2 = p2.next;
} else {
pNew.next = new Node(p2.val);
p2 = p2.next;
pNew = pNew.next;
}
}
}
return newHead.next;
}
|
fc7a269e-041c-426f-8fae-8852e76a4542
| 0
|
public void addVisitor(Element element) {
elements.add(element);
}
|
46e45b92-b417-4796-b45d-e6fedf4b1904
| 9
|
private void installNodeDefault() throws InstallationException {
try {
final String longNodeFilename =
this.config.getPlatform().getLongNodeFilename(this.nodeVersion, false);
String downloadUrl = this.nodeDownloadRoot
+ this.config.getPlatform().getNodeDownloadFilename(this.nodeVersion, false);
String classifier = this.config.getPlatform().getNodeClassifier();
File tmpDirectory = getTempDirectory();
CacheDescriptor cacheDescriptor = new CacheDescriptor("node", this.nodeVersion, classifier,
this.config.getPlatform().getArchiveExtension());
File archive = this.config.getCacheResolver().resolve(cacheDescriptor);
downloadFileIfMissing(downloadUrl, archive, this.userName, this.password);
extractFile(archive, tmpDirectory);
// Search for the node binary
File nodeBinary =
new File(tmpDirectory, longNodeFilename + File.separator + "bin" + File.separator + "node");
if (!nodeBinary.exists()) {
throw new FileNotFoundException(
"Could not find the downloaded Node.js binary in " + nodeBinary);
} else {
File destinationDirectory = getInstallDirectory();
File destination = new File(destinationDirectory, "node");
this.logger.info("Copying node binary from {} to {}", nodeBinary, destination);
if (!nodeBinary.renameTo(destination)) {
throw new InstallationException("Could not install Node: Was not allowed to rename "
+ nodeBinary + " to " + destination);
}
if (!destination.setExecutable(true, false)) {
throw new InstallationException(
"Could not install Node: Was not allowed to make " + destination + " executable.");
}
if (npmProvided()) {
File tmpNodeModulesDir = new File(tmpDirectory,
longNodeFilename + File.separator + "lib" + File.separator + "node_modules");
File nodeModulesDirectory = new File(destinationDirectory, "node_modules");
File npmDirectory = new File(nodeModulesDirectory, "npm");
FileUtils.copyDirectory(tmpNodeModulesDir, nodeModulesDirectory);
this.logger.info("Extracting NPM");
// create a copy of the npm scripts next to the node executable
for (String script : Arrays.asList("npm", "npm.cmd")) {
File scriptFile = new File(npmDirectory, "bin" + File.separator + script);
if (scriptFile.exists()) {
scriptFile.setExecutable(true);
}
}
}
deleteTempDirectory(tmpDirectory);
this.logger.info("Installed node locally.");
}
} catch (IOException e) {
throw new InstallationException("Could not install Node", e);
} catch (DownloadException e) {
throw new InstallationException("Could not download Node.js", e);
} catch (ArchiveExtractionException e) {
throw new InstallationException("Could not extract the Node archive", e);
}
}
|
d8af48de-b46c-4360-9c87-7ca3cc493361
| 9
|
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
List<Integer> leaves = new ArrayList<Integer>();
if (n <= 0) return leaves;
if (n == 1) {
leaves.add(0);
return leaves;
}
List<Set<Integer>> adj = new ArrayList<Set<Integer>>(n);
for (int i = 0; i < n; i++) adj.add(new HashSet<Integer>());
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
adj.get(edge[1]).add(edge[0]);
}
for (int i = 0; i < n; i++) {
if (adj.get(i).size() == 1) leaves.add(i);
}
while (n > 2) {
n -= leaves.size();
List<Integer> newLeaves = new ArrayList<Integer>();
for (int i : leaves) {
int j = adj.get(i).iterator().next();
adj.get(j).remove(i);
if (adj.get(j).size() == 1) newLeaves.add(j);
}
leaves = newLeaves;
}
return leaves;
}
|
c2a8d24f-1528-41d7-b667-eca2a9beb6b1
| 8
|
private int helper(int m, int n, int[][] men, int[][] grid) {
if (n <= 0 || m <= 0) {
return 0;
}
if (m == 1 && n == 1) {
return grid[0][0];
}
men[0][0] = grid[0][0];
for (int i = 1; i < m; i++) {
men[i][0] = men[i - 1][0] + grid[i][0];
}
for (int j = 1; j < n; j++) {
men[0][j] = men[0][j - 1] + grid[0][j];
}
/**
* for loop will be better than recursive
*/
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
men[i][j] = Math.min(men[i - 1][j], men[i][j - 1]) + grid[i][j];
}
}
// if (men[m - 1][n - 1] != 0) {
// return men[m - 1][n - 1];
// } else {
// men[m - 1][n - 1] = Math.min(helper(m - 1, n, men, grid), helper(m, n - 1, men, grid)) + grid[m - 1][n - 1];
// }
return men[m - 1][n - 1];
}
|
2c94b9d7-5e13-45b2-93de-b306f4a1e5ff
| 2
|
private static void init() {
// Initialize any uninitialized globals.
command = new String();
stillPlaying = true;
// Set up the location instances of the Locale class.
FirstFloor loc0 = new FirstFloor(0);
loc0.setName("Living Room (Shop)");
loc0.setDesc("You are greeted by Colonel Mustard. He tells you there has been a murder in this house and you will be paid 10 gold for each room you explore. He hands you a map and a camera. \n" +
"He can show you items you may consider buying. Type 'buy' or 'b' to see what items you can buy from Colonel Mustard. \n" +
"You can go north, east or west from here");
loc0.setNorth(4);
loc0.setSouth(0);
loc0.setEast(2);
loc0.setWest(1);
FirstFloor loc1 = new FirstFloor(1);
loc1.setName("Kitchen");
loc1.setDesc("The kitchen seems unscathed until the maid, Mrs. White, tells you to check the sink. In the sink you notice a knife covered in blood. \n" +
"You can go east from here");
loc1.setNorth(1);
loc1.setSouth(1);
loc1.setEast(0);
loc1.setWest(1);
FirstFloor loc2 = new FirstFloor(2); // Locale(2);
loc2.setName("Library");
loc2.setDesc("A man named Professor Plum shows you an opened book. The book is titled 'How to Hide a Body for Dummies'. Prof. Plum tells you someone was reading it before the murder. \n" +
"You can go north or west from here");
loc2.setNorth(3);
loc2.setSouth(2);
loc2.setEast(2);
loc2.setWest(0);
FirstFloor loc3 = new FirstFloor(3);
loc3.setName("Lounge");
loc3.setDesc("Miss Scarlet and Mrs. Peacock are smoking in the lounge. They offer to tell you what they saw. \n" +
"You can go north or south from here");
loc3.setNorth(7);
loc3.setSouth(2);
loc3.setEast(3);
loc3.setWest(3);
SecondFloor loc4 = new SecondFloor(4);
loc4.setName("Hall");
loc4.setDesc("There is a knocked over table and a picture on the wall of the home owner. \n" +
"You can go north, south, east or west from here");
loc4.setNorth(6);
loc4.setSouth(0);
loc4.setEast(7);
loc4.setWest(5);
SecondFloor loc5 = new SecondFloor(5);
loc5.setName("Bathroom");
loc5.setDesc("There is a dead body in bathtub. The body belongs to the home owner. \n" +
"You can go east from here");
loc5.setNorth(5);
loc5.setSouth(5);
loc5.setEast(4);
loc5.setWest(5);
SecondFloor loc6 = new SecondFloor(6);
loc6.setName("Master Bed");
loc6.setDesc("It looks as if a tornado has gone through the room. You notice the safe is open and empty. \n" +
"You can go south from here");
loc6.setNorth(6);
loc6.setSouth(4);
loc6.setEast(6);
loc6.setWest(6);
SecondFloor loc7 = new SecondFloor(7);
loc7.setName("Guest Bed");
loc7.setDesc("There is a briefcase full of money and you also notice a secret pathway leading south. \n" +
"You can go south or west from here.");
loc7.setNorth(7);
loc7.setSouth(3);
loc7.setEast(7);
loc7.setWest(4);
// Set up the location array.
locations = new Locale[8];
locations[0] = loc0; // "Living Room";
locations[1] = loc1; // "Kitchen";
locations[2] = loc2; // "Library";
locations[3] = loc3; // "Lounge";
locations[4] = loc4; // "Hall";
locations[5] = loc5; // "Bathroom";
locations[6] = loc6; // "Master Bed";
locations[7] = loc7; // "Guest Bed";
//Instances for items
Items item0 = new Items(0);
item0.setName("A photo of the bloody knife");
item0.setDesc("You took a photo of the bloody knife in the sink.");
Items item1 = new Items(1);
item1.setName("A photo of 'How to Hide a Body for Dummies'");
item1.setDesc("You took a photo of the opened book.");
Items item2 = new Items(2);
item2.setName("Audio recording of the Witness' Story");
item2.setDesc("You record Mrs. Peacock and Miss Scarlet claim that they saw a green man frantically leave the house.");
Items item3 = new Items(3);
item3.setName("Picture of house owner");
item3.setDesc("You take the picture that is a portrait of a middle aged man, the house owner.");
Items item4 = new Items(4);
item4.setName("Photo of the victim's body");
item4.setDesc("You take a photo of the victim. It's the house owner who is dead in the bathtub.");
Items item5 = new Items(5);
item5.setName("A photo of the opened safe");
item5.setDesc("The safe in the owner's room was broken into and is now empty. You took a photo of it.");
Items item6 = new Items(6);
item6.setName("A photo of the briefcase full of money");
item6.setDesc("There was a briefcase full of money on the guest bed. You took a photo of it.");
//Item array
interaction = new Items[10];
interaction[0] = item0;
interaction[1] = item1;
interaction[2] = item2;
interaction[3] = item3;
interaction[4] = item4;
interaction[5] = item5;
interaction[6] = item6;
Items nottaken0 = new Items(0);
nottaken0.setName("empty slot");
nottaken0.setDesc("");
Items nottaken1 = new Items(1);
nottaken1.setName("empty slot");
nottaken1.setDesc("");
Items nottaken2 = new Items(2);
nottaken2.setName("empty slot");
nottaken2.setDesc("");
Items nottaken3 = new Items(3);
nottaken3.setName("empty slot");
nottaken3.setDesc("");
Items nottaken4 = new Items(4);
nottaken4.setName("empty slot");
nottaken4.setDesc("");
Items nottaken5 = new Items(5);
nottaken5.setName("empty slot");
nottaken5.setDesc("");
Items nottaken6 = new Items(6);
nottaken6.setName("empty slot");
nottaken6.setDesc("");
taken = new Items[10];
taken[0] = nottaken0;
taken[1] = nottaken1;
taken[2] = nottaken2;
taken[3] = nottaken3;
taken[4] = nottaken4;
taken[5] = nottaken5;
taken[6] = nottaken6;
if (DEBUGGING) {
System.out.println("All game locations:");
for (int i = 0; i < locations.length; ++i) {
System.out.println(i + ":" + locations[i].toString());
}
}
}
|
633802ef-7a13-47ae-b511-dfd15f9162ba
| 1
|
static ClassType make(String s, int b, int e,
TypeArgument[] targs, ClassType parent) {
if (parent == null)
return new ClassType(s, b, e, targs);
else
return new NestedClassType(s, b, e, targs, parent);
}
|
aa1f5fa2-6ed5-4120-8595-e593dfe83434
| 7
|
private var_type eval_exp10() throws StopException, SyntaxError {
var_type result;
var_type partial_value;
String op;
result = eval_exp11();
op = token.value;
while( op.equals("<") || op.equals("<=") || op.equals(">") || op.equals(">=") ){
token = lexer.get_token();
partial_value = eval_exp11();
boolean constant = result.constant && partial_value.constant;
if(checkOnly && !constant){
result = result.getReturnTypeFromBinaryOp(op, partial_value);
}
else{
result = result.relationalOperator(partial_value, op);
}
op = token.value;
}
return result;
}
|
2ee73d64-0347-480f-875b-2268db2544cb
| 6
|
public void readFirst(){
synchronized (lock1) {
String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("E:/Intern/Java/workspace/Translator/src/translator/first.txt"));
while (!((sCurrentLine = br.readLine()).equals(""))) {
//System.out.println(sCurrentLine);
keyPairs =sCurrentLine.split(",");
if(isReadOver==false){
tbl.put(keyPairs[0], keyPairs[1]);
//System.out.println(tbl.get(keyPairs[0]));
}else{
Thread.sleep(10);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
c69181aa-645e-450b-a6ef-b786550935d3
| 1
|
public void visit_fcmpg(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
}
|
0044a8f5-3574-49b0-815b-12aaaca7143b
| 8
|
protected void testsWithoutClass(boolean weighted,
boolean multiInstance) {
boolean PNom = canPredict(true, false, false, false, false, multiInstance, NO_CLASS)[0];
boolean PNum = canPredict(false, true, false, false, false, multiInstance, NO_CLASS)[0];
boolean PStr = canPredict(false, false, true, false, false, multiInstance, NO_CLASS)[0];
boolean PDat = canPredict(false, false, false, true, false, multiInstance, NO_CLASS)[0];
boolean PRel;
if (!multiInstance)
PRel = canPredict(false, false, false, false, true, multiInstance, NO_CLASS)[0];
else
PRel = false;
if (PNom || PNum || PStr || PDat || PRel) {
if (weighted)
instanceWeights(PNom, PNum, PStr, PDat, PRel, multiInstance, NO_CLASS);
canHandleZeroTraining(PNom, PNum, PStr, PDat, PRel, multiInstance, NO_CLASS);
boolean handleMissingPredictors = canHandleMissing(PNom, PNum, PStr, PDat, PRel,
multiInstance, NO_CLASS,
true, false, 20)[0];
if (handleMissingPredictors)
canHandleMissing(PNom, PNum, PStr, PDat, PRel, multiInstance, NO_CLASS, true, false, 100);
correctBuildInitialisation(PNom, PNum, PStr, PDat, PRel, multiInstance, NO_CLASS);
datasetIntegrity(PNom, PNum, PStr, PDat, PRel, multiInstance, NO_CLASS,
handleMissingPredictors, false);
}
}
|
bf6dbb66-c28d-4542-9971-79057056757b
| 8
|
private void prepareItems(Composite parent) {
Composite composite = createDefaultComposite(parent);
/*
* ---------------- server name
*/
Label serverLabel = new Label(composite, SWT.NONE);
serverLabel.setText(SERVERNAME_TITLE);
serverText = new Text(composite, SWT.SINGLE | SWT.BORDER);
// creo il layout in cui inserire la casella di testo
GridData gd = new GridData();
gd.widthHint = convertWidthInCharsToPixels(40);
serverText.setLayoutData(gd);
try {
String serverValue = ((IResource) getElement()).getPersistentProperty(new QualifiedName("", IProperty.SERVERNAME)); //$NON-NLS-1$
serverText.setText((serverValue != null) ? serverValue : ""); //$NON-NLS-1$
} catch (CoreException e) {
serverText.setText(""); //$NON-NLS-1$
}
/*
* ---------------- nome utente
*/
Label userLabel = new Label(composite, SWT.NONE);
userLabel.setText(USERNAME_TITLE);
userText = new Text(composite, SWT.SINGLE | SWT.BORDER);
userText.setLayoutData(gd);
try {
String userValue = ((IResource) getElement()).getPersistentProperty(new QualifiedName("", IProperty.USERNAME)); //$NON-NLS-1$
userText.setText((userValue != null) ? userValue : ""); //$NON-NLS-1$
} catch (CoreException e) {
userText.setText(""); //$NON-NLS-1$
}
/*
* ---------------- percorso remoto
*/
Label remotePathLabel = new Label(composite, SWT.NONE);
remotePathLabel.setText(REMOTEPATH_TITLE);
remotepathText= new Text(composite, SWT.SINGLE | SWT.BORDER);
remotepathText.setLayoutData(gd);
try {
String serverPathValue = ((IResource) getElement()).getPersistentProperty(new QualifiedName("", IProperty.REMOTEPATH)); //$NON-NLS-1$
remotepathText.setText((serverPathValue != null) ? serverPathValue : ""); //$NON-NLS-1$
} catch (CoreException e) {
remotepathText.setText(""); //$NON-NLS-1$
}
/*
* ---------------- esclusioni del progetto
*/
GridData gd_multi = new GridData();
gd_multi.widthHint = convertWidthInCharsToPixels(40);
gd_multi.heightHint = convertWidthInCharsToPixels(15);
Label excludeLabel = new Label(composite, SWT.NONE);
excludeLabel.setText(EXCLUDE_TITLE);
excludeText= new Text(composite, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);
excludeText.setLayoutData(gd_multi);
try {
String excludeValue = ((IResource) getElement()).getPersistentProperty(new QualifiedName("", IProperty.EXCLUDE)); //$NON-NLS-1$
excludeText.setText((excludeValue != null) ? excludeValue : ""); //$NON-NLS-1$
} catch (CoreException e) {
excludeText.setText(""); //$NON-NLS-1$
}
}
|
53ec637c-70dd-4fc5-bbc3-002198b6b78b
| 8
|
* @param artist2
* @throws IOException
*/
public void checkPair(String artist1, String artist2){
String concat12 = artist1.concat(artist2);
String concat21 = artist2.concat(artist1);
Pair found;
if(this.pairMap.containsKey(concat12)){
found = this.pairMap.get(concat12);
if(found.occurences<50){
found.occurences++;
}else{
if(!result.containsKey(found)){
result.put(found, found);
try {
writer.write(found.getArtist1() + "," + found.getArtist2());
writer.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return;
}
if(this.pairMap.containsKey(concat21)){
found = this.pairMap.get(concat21);
if(found.occurences<50){
found.occurences++;
}else{
if(!result.containsKey(found)){
result.put(found, found);
try {
writer.write(found.getArtist1() + "," + found.getArtist2());
writer.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return;
}
found = new Pair(artist1, artist2);
this.pairMap.put(concat12, found);
}
|
1d7bb366-24d6-4292-9c4c-bd975b1f94e4
| 5
|
private int stripMultipartHeaders(ByteBuffer b, int offset) {
int i;
for (i=offset; i<b.limit(); i++) {
if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') {
break;
}
}
return i + 1;
}
|
6d397a01-82fd-4413-9b09-52a0ac26f4eb
| 1
|
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
sumNumbersRec(root, 0);
return this.res;
}
|
41e30931-5995-454b-88f8-7f88852765a0
| 4
|
public String getTypeName(){
switch(_type){
case 0: return "DivX Standard";
case 1: return "DivX Standard";
case 4: return "H.264 Mobile";
case 5: return "H.264 Standard";
default : return "No Type Set";
}
}
|
512fcc87-191f-423b-98c1-14133fdd557c
| 0
|
public void setEncryptionKey(KeyInfoType value) {
this.encryptionKey = value;
}
|
7a563ec7-e64f-45a0-9cd1-94ddc363a24c
| 3
|
@Override
public void bind ( SocketAddress endpoint, int backlog ) throws IOException {
if ( isClosed() )
throw new SocketException("Socket is closed");
if ( isBound() )
throw new SocketException("Already bound");
if ( ! ( endpoint instanceof AFUNIXSocketAddress ) ) {
throw new IOException("Can only bind to endpoints of type " + AFUNIXSocketAddress.class.getName());
}
this.impl.bind(backlog, endpoint);
this.boundEndpoint = (AFUNIXSocketAddress) endpoint;
}
|
d185870a-d314-4ed9-b988-2ed75012348d
| 0
|
public void addQuizDataObjectArray(QuizDataObject [] tqDBArray)
{
getGraphPanel().setQuizListFromArray(tqDBArray);
}
|
16597a50-b57d-4a00-a226-a5f47892abbe
| 6
|
public TreeMap<Double,Object> kNN(DatasetObject objectQuery, int k) {
TreeMap res=null;
res=new TreeMap();
for(int i=0; i<dataset.size()&&getDataset().getObject(i)!=null;i++)
{
double dist=distance(objectQuery,getDataset().getObject(i));
Integer o=Integer.valueOf(i);
if(res.size()<k){
while(o!=null)
{
o=(Integer)res.put(dist,o);
dist+=0.0001;
}
}
else if(dist<(Double)res.lastKey())
{
while(o!=null)
{
o=(Integer)res.put(dist,o);
dist+=0.0001;
}
res.remove(res.lastKey());
}
}
return res;
}
|
4db213a2-9041-4382-b115-cb8da45f15b7
| 9
|
private boolean putsKingInCheck(Board board, Location intendedLocation) {
boolean inCheck = false;
for(Piece p : board.getAllPieces()) {
if (p.getColor() != this.getColor() && !p.isCheckable()) {
for (Move m : p.getMoves(board)) {
Piece endPiece = board.getPiece(m.getEnd());
if (endPiece != null) {
if ((endPiece.isCheckable()) && (endPiece.getColor() != p.getColor()) || (m.getEnd().equals(intendedLocation))) {
inCheck = true;
}
} else if((m.getEnd().equals(intendedLocation))) {
inCheck = true;
}
}
}
}
return inCheck;
}
|
6e8b8604-ce4f-446c-aeb1-7ee8d918613e
| 9
|
@Override
public void populate( World world, Random random, Chunk chunk )
{
//if (true) return;
if (gen1 == null)
{
int numOctaves = 2;
gen1 = new SimplexOctaveGenerator(world, numOctaves);
gen1.setScale(1/128.0);
}
//float density = minDensity + ((float)((gen1.noise(chunk.getZ() * 16 + 8192, -chunk.getX() * 16 - 8192, 0.2, 0.7) + 1.0) * 0.5) * (maxDensity - minDensity));
double density = minDensity + ((float)((gen1.noise(chunk.getZ() * 16 + 8192, -chunk.getX() * 16 - 8192, 0.2, 0.7) + 1.0) * 0.5) * (maxDensity - minDensity));
if (density <= 0.0)
{
return; // Skip this chunk.
}
int realZ = chunk.getZ() * 16;
for (int z = 0; z < 16; ++z, ++realZ)
{
int realX = chunk.getX() * 16;
for (int x = 0; x < 16; ++x, ++realX)
{
float rf = random.nextFloat();
// Do a random-check with the density parameter to see if we should place a tree here.
//if (rf <= density)
if (rf <= density)
{
Block highestBlock = world.getHighestBlockAt(realX, realZ);
// If the block is a free block...
if (highestBlock.getType() == Material.AIR ||
highestBlock.getType() == Material.SNOW)
{
Block highestBlockBelow = highestBlock.getRelative(BlockFace.DOWN);
// ...and we have grass below us.
if (highestBlockBelow.getType() == Material.GRASS)
{
world.generateTree( highestBlock.getLocation(),
random.nextFloat() < redwoodVsTallredwoodDistribution ? TreeType.REDWOOD : TreeType.TALL_REDWOOD);
//placeTreeIfPossibleRandom(world, random, chunk, realX, highestBlock.getY(), realZ);
}
}
}
}
}
}
|
cbc58c96-2aea-4a72-ad4d-3ca55eef3ea6
| 0
|
public void setIsLayer(boolean isLayer) {
this.isLayer = isLayer;
}
|
83e42334-60c9-45db-8f1f-4ff7383d7a66
| 5
|
private int distanceToBase() {
Integer distance = null;
for (Unit base : self.getUnits()) {
if (base.getType() == UnitType.Terran_Command_Center) {
int dist = resource.getDistance(base);
if (distance == null || dist < distance) {
distance = dist;
}
}
}
if (distance != null) {
return distance;
}
// We don't have any bases. Uh oh.
System.out.println("I SURE HOPE OUR BASES ARE ALL GONE");
return 0;
}
|
d20f22d8-9275-4dfe-8d87-0b6c0fb6534f
| 7
|
@org.junit.Test
public void testPut()
{
BiHashMap< Integer, String > map = new BiHashMap< Integer, String >();
Integer key = null;
String value = null;
// Add entry to map and ensure its existence
value = map.put( 1, "One" );
assertTrue( "01. Old value is null.", value == null );
assertTrue( "02. Map contains key.", map.containsKey( 1 ) );
assertTrue( "03. Map contains value.", map.containsValue( "One" ) );
value = map.get( 1 );
key = map.inverse().get( "One" );
assertTrue( "04. Correct value for key.", value != null && value.equals( "One" ) );
assertTrue( "05. Correct key for value.", key != null && key.equals( 1 ) );
// Add overriding entry to map and test again
value = map.put( 1, "Two" );
assertTrue( "06. Old value returned.", value != null && value.equals( "One" ) );
assertTrue( "07. Map contains key.", map.containsKey( 1 ) );
assertTrue( "08. Map contains value.", map.containsValue( "Two" ) );
assertTrue( "09. Map doesn't contain value.", !( map.containsValue( "One" ) ) );
value = map.get( 1 );
key = map.inverse().get( "Two" );
assertTrue( "10. Correct value for key.", value != null && value.equals( "Two" ) );
assertTrue( "11. Correct key for value.", key != null && key.equals( 1 ) );
// Add overriding entry to map and test again
value = map.put( 2, "Two" );
assertTrue( "12. Old value is null.", value == null );
assertTrue( "13. Map contains key.", map.containsKey( 2 ) );
assertTrue( "14. Map contains value.", map.containsValue( "Two" ) );
assertTrue( "15. Map doesn't contain key.", !( map.containsKey( 1 ) ) );
value = map.get( 2 );
key = map.inverse().get( "Two" );
assertTrue( "16. Correct value for key.", value != null && value.equals( "Two" ) );
assertTrue( "17. Correct key for value.", key != null && key.equals( 2 ) );
}
|
ca432930-f3df-455e-bf7d-c3d4745605f9
| 1
|
public void visitLookupSwitchInsn(
final Label dflt,
final int[] keys,
final Label[] labels)
{
mv.visitLookupSwitchInsn(dflt, keys, labels);
if (constructor) {
popValue();
addBranches(dflt, labels);
}
}
|
b834e31a-4891-4f6c-9003-7681c98fa3f7
| 9
|
public NPC[] getSpawns()
{
int npcs[] = new int[6];
int index = 0;
int id = stage;
for(int i = 6; i >= 1; i--)
{
int threshold = (1 << i) - 1;
if(id >= threshold)
{
for(int j = 0; j <= id / threshold; j++)
{
npcs[index++] = BASE_NPCS[i - 1] + (i == 6 ? 0 : RANDOM.nextInt(2));
id -= threshold;
}
}
}
FightCaveNPC enemies[] = new FightCaveNPC[index];
for(int i = 0; i < enemies.length; i++)
{
int random = Misc.random(3);
switch(random)
{
case 0: // '\0'
enemies[i] = new FightCaveNPC(npcs[i], new WorldTile(2399 - Misc.random(3), 5086 - Misc.random(3), 0));
break;
case 1: // '\001'
enemies[i] = new FightCaveNPC(npcs[i], new WorldTile(2399 + Misc.random(3), 5086 + Misc.random(3), 0));
break;
case 2: // '\002'
enemies[i] = new FightCaveNPC(npcs[i], new WorldTile(2399 - Misc.random(3), 5086 + Misc.random(3), 0));
break;
case 3: // '\003'
enemies[i] = new FightCaveNPC(npcs[i], new WorldTile(2399 + Misc.random(3), 5086 - Misc.random(3), 0));
break;
}
}
return enemies;
}
|
63aabfc0-60c2-46f9-adc6-03770c4d7896
| 0
|
public void request()
{
System.out.println("From Real Subject !");
}
|
3cdd3061-67c4-4149-86b7-229f3195db99
| 0
|
public String getSaveFileFormat() {
return (String) saveFormatComboBox.getSelectedItem();
}
|
60516e00-c847-41c4-917d-361e9c3d88d3
| 2
|
@Override
public void update(long deltaMs) {
if(!spawned) {
GameSector s = Application.get().getLogic().getGame().getSector(sector);
if(s.free()) {
s.spawnEnemy(resource);
spawned = true;
}
}
}
|
fc026a65-68f5-421c-934c-9b477316606b
| 4
|
public void testCreateWanted() {
for (HTML.Tag t : HTMLParser.getWantedSimpleTags()) {
HTMLComponent comp = HTMLComponentFactory.create(t, null);
Class<?> cl = HTMLComponentFactory.classForTagType(t);
assertSame(comp.getClass(), cl);
}
for (HTML.Tag t : HTMLParser.getWantedComplexTags()) {
HTMLComponent comp = HTMLComponentFactory.create(t, null);
Class<?> cl = HTMLComponentFactory.classForTagType(t);
assertSame(comp.getClass(), cl);
}
}
|
45c84ea9-555e-498b-860a-8ef03d9e030d
| 6
|
public static boolean checkPositionInside(Element element, int x, int y) {
// ignore x / left-right values for x == -1
if (x != -1) {
// check if the mouse pointer is within the width of the target
int left = DomUtil.getRelativeX(x, element);
int offsetWidth = element.getOffsetWidth();
if ((left <= 0) || (left >= offsetWidth)) {
return false;
}
}
// ignore y / top-bottom values for y == -1
if (y != -1) {
// check if the mouse pointer is within the height of the target
int top = DomUtil.getRelativeY(y, element);
int offsetHeight = element.getOffsetHeight();
if ((top <= 0) || (top >= offsetHeight)) {
return false;
}
}
return true;
}
|
82f80649-3fbf-44d9-b46a-ff86dc3c956d
| 1
|
public void visitLineNumber(final int line, final Label start) {
buf.setLength(0);
buf.append(tab2).append("LINENUMBER ").append(line).append(' ');
appendLabel(start);
buf.append('\n');
text.add(buf.toString());
if (mv != null) {
mv.visitLineNumber(line, start);
}
}
|
d07542c4-9d9f-4900-bf42-203bbd1136bd
| 3
|
public GUIInventoryWindow(int id, String name, Inventory inventory, int WorldX, int WorldY, int across) {
super(id, name);
linksTo = inventory;
this.WorldX = WorldX;
this.WorldY = WorldY;
this.Width = (across * 34) + 4;
this.Height = ((linksTo.getInventorySize() / across) * 34) + 8;
int j = 0;
int k = 0;
for (int i = 0; i < linksTo.getInventorySize(); i++){
if (i % across == 0 && i != 0){
k = 0;
j++;
}
addSlot(new GUISlot((k * 34) + 2, (j * 34) + 4, i, linksTo));
k++;
}
}
|
bec62ef2-0918-419e-8667-e3f6ffbbffa1
| 3
|
public static void zip(String filepath){
try
{
File inFolder=new File(filepath);
File outFolder=new File("Reports.zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
BufferedInputStream in = null;
byte[] data = new byte[1000];
String files[] = inFolder.list();
for (int i=0; i<files.length; i++)
{
in = new BufferedInputStream(new FileInputStream
(inFolder.getPath() + "/" + files[i]), 1000);
out.putNextEntry(new ZipEntry(files[i]));
int count;
while((count = in.read(data,0,1000)) != -1)
{
out.write(data, 0, count);
}
out.closeEntry();
}
out.flush();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
|
24db2ff3-ae37-498e-a784-c5adbe5dbd07
| 8
|
public void setDay(int day){
buttonArray.get(1).getDay().doClick();
if(buttonArray.size()-1 < day){
for(int x = 0; x < day+1; x++){
while(timer.isRunning()){} //This will delay the method until timer has ran out
if(!buttonArray.containsKey(x)){
this.createNewDay();
}
}
} else if(buttonArray.size()-1 > day){
for(int x = buttonArray.size(); x > day+1; x--){
while(timer.isRunning()){} //This will delay the method until timer has ran out
if(!buttonArray.containsKey(x)){
this.removeDays();
}
}
}
}
|
f3737209-edf1-4cc1-b3cd-fb64395323fd
| 4
|
@Override
public void setStackInSlot(int slot, ItemStack stack) {
if(inventory[slot] == null)
inventory[slot] = stack;
else if (stack == null && inventory[slot] != null)
inventory[slot] = null;
else if(inventory[slot].getItem().equals(stack.getItem()))
inventory[slot].stackSize += stack.stackSize;
else
System.out.println("something tried to replace the existing item" + inventory[slot].getItem().getUIN() +
" by "+ stack.getItem().getUIN() );
}
|
d3d6e442-7f54-496c-a14e-065823291b85
| 4
|
public LevelReader(World world, File path) {
try {
Document document = new SAXBuilder().build(path);
Element rootNode = document.getRootElement();
List blocks = rootNode.getChildren("block");
List flags = rootNode.getChildren("flag");
//Blokken
for (int i = 0; i < blocks.size(); i++) {
Element el = (Element) blocks.get(i);
int x = Integer.valueOf(el.getAttributeValue("x")).intValue();
int y = Integer.valueOf(el.getAttributeValue("y")).intValue();
int width = Integer.valueOf(el.getAttributeValue("width")).intValue();
int height = Integer.valueOf(el.getAttributeValue("height")).intValue();
boolean visible = Boolean.valueOf(el.getAttributeValue("visible")).booleanValue();
world.addBlock(x, y, width, height, visible);
}
//Vlaggen
for (int i = 0; i < flags.size(); i++) {
Element el = (Element) flags.get(i);
int x = Integer.valueOf(el.getAttributeValue("x")).intValue();
int y = Integer.valueOf(el.getAttributeValue("y")).intValue();
boolean visible = Boolean.valueOf(el.getAttributeValue("visible")).booleanValue();
world.addFlag(x, y, visible);
}
} catch (IOException ioexep) {
System.out.println("IO @ Parser");
} catch (JDOMException jdomexep) {
System.out.println("JDOM @ Parser");
}
}
|
881b0db3-e873-45f9-8518-7e3652d72277
| 6
|
@SuppressWarnings("deprecation")
@Override
public void updateContent(IDocument myDocument, List<String> myWordList) {
//Start analysis here...
if(myDocument==null){
new_analyse.setEnabled(true);
return;
}
profileInformation = connector.getProfileInformation(userID);
AnalyzeTaskInformation task = new AnalyzeTaskInformation();
task.setDocument(myDocument);
task.setProfile(profileInformation);
task.setWordList(myWordList);
WaitingDialog waiter = new WaitingDialog();
waiter.showWaiting();
Worker myWorker = new Worker(analyzer, task);
Thread job = new Thread(myWorker);
job.start();
while(job.isAlive() && waiter.isVisible()){
try {
Thread.currentThread().sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
waiter.dispose();
if(job.isAlive()){
job.stop();
new_analyse.setEnabled(true);
return;
}
IResultSet set = myWorker.getResult();
if(set == null){
new_analyse.setEnabled(true);
return;
}
connector.saveResultSet(userID, set);
refreshTextList();
buildReport(set);
new_analyse.setEnabled(true);
}
|
b9837621-1093-4907-9cd8-652026103936
| 3
|
public ArrayList<FormEvent> resultQuery(String sql){
ArrayList<FormEvent> dbList = new ArrayList<FormEvent>();
try {
rs = stm.executeQuery(sql);
try {
while(rs.next()){
FormEvent item = new FormEvent(this);
item.setId(rs.getInt("idTrabajador"));
item.setEmpTipo(rs.getInt("tipoEmpleado_Id"));
item.setName(rs.getString("nombre"));
item.setOccupation(rs.getInt("ocupacion_Id"));
item.setEdad(rs.getInt("edad"));
item.setNacionId(rs.getInt("nacionalidad_Id"));
item.setGender(rs.getString("genero"));
dbList.add(item);
}
rs.close();
} catch (SQLException i) {
// TODO Auto-generated catch block
i.printStackTrace();
}
return dbList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return dbList;
}
}
|
726a0296-2694-462e-ae02-62ff1df478de
| 1
|
@Override
public String getStringProp(String key, String value) {
String result = (String) get(key);
if (null == result)
result = value;
return result;
}
|
8c46d33c-46a1-42a3-bedd-069a58adcb58
| 0
|
public LLParseController(LLParsePane pane) {
this.pane = pane;
productions = pane.grammar.getProductions();
}
|
666e7ab1-7c04-44b7-8cc9-fb27cf8a6b63
| 0
|
public ArrayList<String> getRivit() {
return rivit;
}
|
51208ee6-aca2-4207-af18-9446697b3abb
| 8
|
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-undo")) showUndo = true;
if (args[i].startsWith("-goToMultiplayer")) multi = true;
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
window = new Window(WIDTH, HEIGHT);
window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setTitle(getTitle());
window.setName("A game by Rory Claasen");
try {
window.setIconImage(ImageIO.read(Bootstrap.class.getClassLoader().getResourceAsStream("icon.png")));
} catch (IOException e) {
e.printStackTrace();
}
window.setVisible(true);
}
});
}
|
7fb52cf9-0e6f-4c16-b6ec-efa8485b0703
| 5
|
private static int[] getFirstK(double[] sum, int k) {
Map<Integer, Double> m = new TreeMap<Integer, Double>();
for (int i = 0; i < sum.length; i++) {
m.put(i, sum[i]);
}
List<Map.Entry<Integer, Double>> mappingList = null;
mappingList = new ArrayList<Map.Entry<Integer, Double>>(m.entrySet());
Collections.sort(mappingList,
new Comparator<Map.Entry<Integer, Double>>() {
public int compare(Map.Entry<Integer, Double> mapping1,
Map.Entry<Integer, Double> mapping2) {
return mapping1.getValue().compareTo(
mapping2.getValue());
}
});
Map<Integer, Double> newMap = new HashMap<Integer, Double>();
int count = 0;
for (Map.Entry<Integer, Double> mapping : mappingList) {
newMap.put(mapping.getKey(), mapping.getValue());
count++;
if (count == k) {
break;
}
}
int array[] = new int[k];
Iterator<Integer> iterator = newMap.keySet().iterator();
while (iterator.hasNext() && k > 0) {
array[k - 1] = (int) iterator.next();
k--;
}
return array;
}
|
b94ca5fe-e193-4298-8f58-7b964ab4e692
| 3
|
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
}
|
7d35f9b4-b053-46dc-86fd-bf7ce3311c02
| 2
|
public ArrayList<Trajet> getTrajetsWithPassager(Membre m){
ArrayList<Trajet> res = new ArrayList<Trajet>();
for(Trajet t : listeTrajets){
if(t.hasMembreAsPassager(m)){
res.add(t);
}
}
return res;
}
|
0d17212d-a081-4caf-a0cd-bdc4bdac96d7
| 2
|
public QuickFind(List<ConnectedPair> list) {
numbers = new int[list.size()];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (ConnectedPair pair : list) {
connect(pair.getFirst(), pair.getSecond());
}
}
|
8f72ff79-3750-4131-94d7-caa9461f048f
| 9
|
public void updateWith(Instruction currentExecuting)
{
if (inst.workingOperands.size()>1 && inst.instructionType==0)
{
for (int i=1; i<inst.operands.size(); i++)
{
String s = inst.operands.get(i);
if (s.equals(currentExecuting.destinationRegister))
{
// Need to circulate the result
inst.workingOperands.set(i,currentExecuting.result + "");
validBits[i-1] = true;
}
}
}
else if (inst.workingOperands.size()>1 && inst.instructionType!=0)
{
int k = 0;
for (int i=0; i<inst.operands.size(); i++)
{
String s = inst.operands.get(i);
if (s.equals(currentExecuting.destinationRegister))
{
if(k>2) System.err.println("Error updating a reservation station entry containing a non type 0 instruction");
// Need to circulate the result
inst.workingOperands.set(i,currentExecuting.result + "");
validBits[k] = true;
k++;
}
}
}
updateValidBits();
}
|
63cc3911-921b-498d-913f-533e58bd9480
| 4
|
private List<List<Integer>> getAllChains(int currentVertex)
{
List<List<Integer>> chains = new ArrayList<List<Integer>>();
if(countConnections(currentVertex) > 2 || isEdgeNode(currentVertex))
{
for(int neighbor = gameBoard.first(currentVertex); neighbor < gameBoard.vcount(); neighbor = gameBoard.next(currentVertex, neighbor))
{
if(countConnections(neighbor) == 2)
{
chains.add(getCurrentChain(neighbor));
}
}
}
return chains;
}
|
500cea70-b1eb-42d0-9f57-37a1e0e2d2ed
| 2
|
public Iterator<T> iterator() {
return new Iterator<T>() {
MyList<T> next = first;
MyList<T> node = null;
@Override
public boolean hasNext() {
return (node != last);
}
@Override
public T next() {
if (next == null)
throw new NoSuchElementException();
node = next;
if (node == last)
next = null;
next = node.right;
return node.value;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
|
dfe890c8-716b-4e9f-9efd-4a55b434b0f7
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Pedidos.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 Pedidos().setVisible(true);
}
});
}
|
3aa8c572-0b0d-4e54-b9c4-ba77ab5894d7
| 1
|
public void setReachable() {
if (!reachable) {
reachable = true;
setSingleReachable();
}
}
|
0bcd36b0-19a0-485b-84c3-74f79802bdfe
| 3
|
public void run ()
{
boolean fini = false;
try
{
// recevoir requete
String maLigne;
String ligne = maLigne = reader.readLine();
//Consommer l'entête du browser
while (!ligne.equals(""))
{
ligne = reader.readLine();
}
//envoi page
TraitementRequete(maLigne);
}
catch(IOException ioe)
{
//Rien a faire
}
finally
{
ServeurWeb.NbrConnexion--;
System.out.println("Fermeture de session " + NumSession);
try
{
reader.close();
client.close();
}
catch(IOException ioe) { }
}
}
|
98b866fd-c94c-45be-b421-635e19d1e86d
| 6
|
@Override
public FileBlob getBlob(String name) throws FileNotFoundException {
if( !name.startsWith(HEAD_URN_PREFIX) ) {
throw new FileNotFoundException(getClass().getName()+" only finds "+HEAD_URN_PREFIX+"s! Not '"+name+"'.");
}
name = name.substring(HEAD_URN_PREFIX.length());
if( name.startsWith("//") ) {
throw new FileNotFoundException(getClass().getName()+" doesn't support heads from specific repositories.");
}
if( name.startsWith("/") ) name = name.substring(1);
if( name.endsWith("/latest") ) {
return findLatest(name.substring(0, name.length()-"/latest".length()));
}
for( File headRoot : headRoots ) {
FileBlob f = new FileBlob(headRoot, name);
if( f.exists() ) return f;
}
throw new FileNotFoundException("Couldn't find head '"+name+"'");
}
|
947b3d15-bf8d-4352-9cdd-97d7bb5db102
| 2
|
private Tree programPro(){
Tree element = null;
Tree program = null;
if((element = elementPro())!=null){
if((program = programPro())!=null){
return new Program(element, program);
}
return element;
}
return null;
}
|
758d4af4-3c82-4e7a-80df-b78594fce40d
| 7
|
String consumeHexSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
pos++;
else
break;
}
return new String(input, start, pos - start);
}
|
44c21891-bf97-4c47-89cc-3629be4663ad
| 3
|
public boolean collisionHead(Obstacle[][] obs,int i, int j, int k) {
if (i < 0)
return false;
boolean collide = obs[i][j].CollisionBot(); // box at his head
while (k<width){ // try all boxes on Stubi's head line
collide |= obs[i][++j].CollisionBot();
k += Obstacle.getWidth();
}
if (collide) {
y = (i+1)*Obstacle.getHeight(); // Put Stubi back in his N box if collision
}
return collide;
}
|
f5e42948-0035-486e-9d59-d135a41ce177
| 3
|
private List<MessageSwitch> parseSwitches(final ConfigurationSection switches, final String path) {
if (switches == null) return Collections.emptyList();
final ConfigurationSection section = switches.getConfigurationSection(path);
if (section == null) return Collections.emptyList();
final List<MessageSwitch> result = new ArrayList<MessageSwitch>();
for (final String name : section.getKeys(false)) {
final ConfigurationSection entry = section.getConfigurationSection(name);
final MessageSwitch ms = new MessageSwitch(entry.getString("permission"), entry.getString("true"), entry.getString("false"));
result.add(ms);
}
return result;
}
|
4c8ed297-87de-4a26-aa65-77e387bf3720
| 3
|
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Activity activity;
if (rowIndex < activities.size()) {
// Get the Activity from the indicated row.
activity = activities.get(rowIndex);
// Get the appropriate field from the columnIndex
if (columnIndex == columnNames.indexOf("Name")) {
return activity.getName();
} else if (columnIndex == columnNames.indexOf("Description")) {
return activity.getDescription();
} else {
return null;
}
}
return null;
}
|
aa0f40a7-2b75-423a-9dae-b4ee726dae27
| 5
|
public void dayTransition() {
if (dayTime == true) {
darkness = darkness - .03f;
if (darkness < 0) {darkness = 0;}
}
else {
darkness = darkness + .03f;
if (darkness > .95f) {darkness = .95f;}
}
timeOfDay = timeOfDay + daySpeed;
if (timeOfDay > 40) {timeOfDay = 40; daySpeed = -daySpeed; dayTrans = false;darkness = 0;}
if (timeOfDay < 10) {timeOfDay = 10; daySpeed = -daySpeed; dayTrans = false;darkness = .95f;}
}
|
e4ea5555-eba4-401f-b92d-eaf021fdceaa
| 2
|
void crawler (String URL){
try {
URL my_url = new URL("http://www.vimalkumarpatel.blogspot.com/");
BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
String strTemp = "";
while(null != (strTemp = br.readLine())){
System.out.println(strTemp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
ebcc3e87-3c98-4b55-8c99-b3ed2b6c29d6
| 4
|
public Message poll(EnumMessageType type) {
switch(type) {
case PROCESS:
return hasMessageToProcess() ? MessageDispatchManager.inboundMessageMap.get(getName()).poll() : null;
case SEND:
return hasMessageToSend() ? MessageDispatchManager.outboundMessageMap.get(getName()).poll() : null;
}
return null;
}
|
b0cff0e4-4790-417e-bd13-9863590525e4
| 6
|
public boolean removeAll(Collection<?> c){
if(c.isEmpty() || c == null)
return false;
boolean modStatus = false;
for(int i = 0; i < size; i++){
if(c.contains(elements[i])){
remove(i);
i--;
modStatus = true;
}
}
return (modStatus)? true : false;
}
|
88e4b5d1-3ca5-4beb-a9ad-6ccb4582e467
| 8
|
private void replaceState(State state, State replacement) {
if (states.remove(state)) {
if (this.xorJoinState.containsValue(state)) {
Set<XorJoin> keys = xorJoinState.keySet();
for (XorJoin key : keys) {
if (xorJoinState.get(key).equals(state)) {
xorJoinState.put(key, replacement);
}
}
}
Set<Transition> transitionsCopy = new HashSet<Transition>(transitions);
for (Transition t : transitionsCopy) {
Transition newTrans = t.replaceState(state, replacement);
transitions.remove(t);
transitions.add(newTrans);
ActivityNode correspNode = null;
for (ActivityNode node : correspondences.keySet()) {
if (correspondences.get(node).equals(t)) {
correspNode = node;
break;
}
}
if (correspNode != null) {
correspondences.put(correspNode, newTrans);
}
}
}
}
|
8dbde6a1-d729-4738-9da2-f74206730723
| 4
|
Tuple<Markers, Markers> createMarkers(Chromosome chr, int numMarkers) {
Markers markers = new Markers();
Markers markersCollapsed = new Markers();
int start = 0, startPrev = -1, end = 0, gap = 0;
Marker m = null, mcol = null;
for (int i = 0; i < numMarkers; i++) {
// Interval size
int size = rand.nextInt(maxLen) + minLen;
end = start + size;
if (startPrev < 0) startPrev = start;
// Create marker
m = new Marker(chr, start, end, 1, "");
markers.add(m);
// Next interval
gap = rand.nextInt(maxGap);
mcol = new Marker(chr, startPrev, end, 1, "");
if (gap <= minGap) {
gap = 1;
} else {
markersCollapsed.add(mcol);
mcol = null;
startPrev = -1;
}
start = end + gap;
}
if (mcol != null) markersCollapsed.add(mcol);
return new Tuple<Markers, Markers>(markers, markersCollapsed);
}
|
8c503475-efcb-446a-b6c6-7d3ef0f34c81
| 9
|
public static void checkOverlap(OrderedList<Alignment> rankAlign, double overlapThresh)
{
int i=0, j=0, k=0;
NodeOrdList<Alignment> aux=rankAlign.getMax();
HashSet<String> nodiOverlap=new HashSet<String>();
while(aux!=null)
{
Vector<String>[] mapping=aux.getInfo().getMapping();
double[] overlapping=new double[mapping.length];
for(i=0;i<overlapping.length;i++)
overlapping[i]=0.0;
for(i=0;i<mapping.length;i++)
{
for(j=0;j<mapping[i].size();j++)
{
if(nodiOverlap.contains(mapping[i].get(j)))
overlapping[i]++;
}
}
double avg=0.0;
for(i=0;i<overlapping.length;i++)
{
overlapping[i]=overlapping[i]/mapping[0].size();
avg+=overlapping[i];
}
avg=avg/overlapping.length;
if(avg<=overlapThresh)
{
for(i=0;i<mapping.length;i++)
{
for(j=0;j<mapping[i].size();j++)
nodiOverlap.add(mapping[i].get(j));
}
}
else
rankAlign.delete(aux.getInfo());
aux=aux.getNext();
}
}
|
b6df609d-4ac0-43aa-9e17-82e3371dae80
| 6
|
@Command(aliases = { "info" }, desc = "Gibt Informationen zu Votes von dir oder einen anderen Spieler aus", usage = "[spielername]", max = 1)
@CommandPermissions("nextvote.info")
public final void info(final CommandContext args, final CommandSender sender) throws CommandException {
String playerName = sender.getName();
if (args.argsLength() > 0) {
playerName = args.getString(0);
}
OfflinePlayer oPlayer = Utils.offlinePlayerWithMessage(playerName, sender.getName());
if (oPlayer != null) {
List<VoteHistory> votes = plugin.getDatabase().find(VoteHistory.class).where().eq("minecraft_user", playerName).findList();
if (votes.size() == 0) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', String.format("&6%s&f hat noch nie gevotet", playerName)));
return;
}
double econ = 0;
int items = 0;
String econName = NextVote.getEconomy().currencyNamePlural();
for (VoteHistory vote : votes) {
if (vote.hasEcon()) {
econ += vote.getEconAmmount();
}
if (vote.hasItem()) {
items += vote.getAmmount();
}
}
sender.sendMessage(Utils.colorFormat("============= &6 %s &f =============", playerName));
sender.sendMessage(Utils.colorFormat("Votes: &6 %d", votes.size()));
sender.sendMessage(Utils.colorFormat("%s: &6 %.2f", econName, econ));
sender.sendMessage(Utils.colorFormat("Items: &6 %d", items));
}
}
|
10694352-26de-4aff-a870-d59a9baaff2d
| 9
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
try{
Connection adaugareMembriConn = null;
ResultSet adaugareMembriResult = null;
Statement adaugareMembriStatement = null;
PreparedStatement adaugareMembriPStatement = null;
String adaugareMembriQuery = "insert into membri_proiect (idMembru,idProiect,functie) values (?, ?, ?)";
String idProiectQuery = "select idProiect from proiect where denumire='"+session.getAttribute("denumireProiect")+"'";
try{
adaugareMembriConn=ConnectionManager.getConnection();
adaugareMembriStatement=adaugareMembriConn.createStatement();
adaugareMembriResult=adaugareMembriStatement.executeQuery(idProiectQuery);
String idProiect = null;
if(adaugareMembriResult.next()){
idProiect = adaugareMembriResult.getString("idProiect");
}
adaugareMembriPStatement=adaugareMembriConn.prepareStatement(adaugareMembriQuery);
adaugareMembriPStatement.setInt(1,Integer.parseInt(request.getParameter("ListaMembri")));
adaugareMembriPStatement.setInt(2,Integer.parseInt(idProiect));
adaugareMembriPStatement.setString(3,request.getParameter("Functie"));
adaugareMembriPStatement.executeUpdate();
}catch(Exception ex){System.out.println("Error getting idProiect/inserting Membri: "+ex);}
finally{
if(adaugareMembriResult!=null){
try{
adaugareMembriResult.close();
}catch(Exception e){}
adaugareMembriResult=null;
}
if(adaugareMembriStatement!=null){
try{
adaugareMembriStatement.close();
}catch(Exception e){}
adaugareMembriStatement=null;
}
if(adaugareMembriConn!=null){
try{
adaugareMembriConn.close();
}catch(Exception e){}
adaugareMembriConn=null;
}
}
String referer = request.getHeader("Referer");
response.sendRedirect(referer);
}catch(Throwable theException){System.out.println("Exception is"+theException);}
}
|
ef134830-3fb9-42f8-b124-943ac826e46b
| 5
|
* @param mt the microtheory from which to delete the matched assertions
*
* @throws IOException if a communications error occurs
* @throws UnknownHostException if the Cyc server cannot be found
* @throws CycApiException if the Cyc server returns an error
*/
public void unassertMatchingAssertionsWithoutTranscript(CycFort predicate,
Object arg1,
CycObject mt)
throws UnknownHostException, IOException,
CycApiException {
CycList assertions = getAllAssertionsInMt(mt);
Iterator iter = assertions.iterator();
while (iter.hasNext()) {
CycAssertion assertion = (CycAssertion) iter.next();
CycList sentence = assertion.getFormula();
if (sentence.size() < 2) {
continue;
}
if (!(arg1.equals(sentence.second()))) {
continue;
}
if ((predicate != null) && (!(predicate.equals(sentence.first())))) {
continue;
}
String command = "(cyc-unassert " + assertion.stringApiValue()
+ makeELMt(mt).stringApiValue() + "))";
converseVoid(command);
}
}
|
9f97ac0f-cd3b-4f35-b4a9-a1e002059a2d
| 1
|
@Override
public void enterState(int id, Transition leave, Transition enter) {
if (gui != null) {
gui.setRootPane(emptyRootWidget);
}
super.enterState(id, leave, enter);
}
|
a65da040-494d-4531-935d-fbfb27328a9c
| 2
|
public void actionPerformed(ActionEvent event)
{
//DB STUFF
try {
if (sendAuthentication())
{
//dispose current panel
dispose();
//You logged in as the manager
ManagerMainMenu menu = new ManagerMainMenu();
menu.setVisible(true);
}
else
{
//Your username or password was wrong
ManagerIncorrectLogin badLogin = new ManagerIncorrectLogin();
badLogin.setVisible(true);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
usernameFld.setText("");
passwordFld.setText("");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.