method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
61081453-9c48-4924-b2f2-5a66a417d5fd
| 7
|
public boolean tryOpen(Matrix matrix) {
LinkedList<Node> neighbours = matrix.allNeighbours(x, y);
for (Node neighbour : neighbours) {
if (neighbour instanceof Door) {
if (((Door)neighbour).isOpen()) {
((Door)neighbour).close();
if (inventory.containsValue(((Door)neighbour).getKey())) {
((Door)neighbour).close();
}
return true;
}
if (!((Door)neighbour).isOpen()) {
if (!((Door)neighbour).isUnlocked()) {
if (inventory.containsValue(((Door)neighbour).getKey())) {
((Door)neighbour).unlock();
((Door)neighbour).open();
removeItem((((Door)neighbour).getKey()).getName());
return true;
}
return false;
}
((Door)neighbour).open();
return true;
}
}
}
return false;
}
|
a20b07cc-3564-4db5-b5c6-ef1aeb262616
| 7
|
public boolean getFile(String branch, String path, File file)
{
boolean b = true;
Utils.logger.log(Level.INFO, "Getting file from github " + path + " to " + file.getAbsolutePath());
InputStream is = null;
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try
{
URL url = new URL(APIBASE + "repos/" + OWNER + "/" + REPO + "/git/blobs/" + getFileSha(path, getLastBranchCommitSHA(branch)));
Map<String, String> headers = new HashMap<>();
headers.put(AUTHORIZATION_TYPE_KEY, AUTHORIZATION_TYPE);
is = URLHandler.getAsBinary(url, headers);
rbc = Channels.newChannel(is);
fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
catch(Exception e)
{
Utils.logger.log(Level.SEVERE, "Error writing file from github!", e);
b = false;
}
try
{
if(fos != null)
{
fos.close();
}
}
catch(Exception ignored)
{
}
try
{
if(rbc != null)
{
rbc.close();
}
}
catch(Exception ignored)
{
}
try
{
if(is != null)
{
is.close();
}
}
catch(Exception ignored)
{
}
return b;
}
|
ae7fdc4a-3a0d-4877-8978-613b93c52f6b
| 2
|
private void createSearchList() {
searchList.clear();
for ( Column column : columns ) {
if ( column.isSearchId() ) {
searchList.add( column.getFldName() );
hasSearch = true;
}
}
}
|
9e40c644-e1f5-4691-b653-11c1ba2f8671
| 2
|
static public Integer clampPriority(Integer priority) {
if (priority.intValue() > MAX_PRIORITY.intValue()) {
priority = MAX_PRIORITY;
} else if (priority.intValue() < MIN_PRIORITY.intValue()) {
priority = MIN_PRIORITY;
}
return priority;
}
|
06763cb8-67ec-4d9d-87f0-2216c940d54e
| 9
|
private void createVitalSignjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createVitalSignjButtonActionPerformed
// TODO add your handling code here:
boolean isInputValid = true;
if(this.respiratoryRatejTextField.getText().trim().compareTo("") == 0 &&
!isInteger(this.respiratoryRatejTextField.getText().trim()))
isInputValid = false;
if(this.heartRatejTextField.getText().trim().compareTo("") == 0 &&
!isInteger(this.heartRatejTextField.getText().trim()))
isInputValid = false;
if(this.systolicBloodPressurejTextField.getText().trim().compareTo("") == 0 &&
!isInteger(this.systolicBloodPressurejTextField.getText().trim()))
isInputValid = false;
if(this.weightjTextField.getText().trim().compareTo("") == 0 &&
!isInteger(this.weightjTextField.getText().trim()))
isInputValid = false;
if(!isInputValid){
JOptionPane.showMessageDialog(null, "Please enter valid value!");
return;
}
int respiratoryRate=Integer.parseInt(respiratoryRatejTextField.getText());
int heartRate=Integer.parseInt(heartRatejTextField.getText());
int systolicBloodPressure=Integer.parseInt(systolicBloodPressurejTextField.getText());
int weight=Integer.parseInt(weightjTextField.getText());
String time=timejTextField.getText();
VitalSign vs = new VitalSign(respiratoryRate,heartRate,systolicBloodPressure,weight,time);
vs.diagnose(patient.getAge());
patient.getVitalSignHistory().addVitalSign(vs);
}//GEN-LAST:event_createVitalSignjButtonActionPerformed
|
96599372-d808-4fe7-aa11-7b5c42f0d86c
| 2
|
public void showPersonalPostsToFile(FileWriter f) throws IOException {
for (TimedPosts post : posts) {
long elapsedTimeInSec = (endTime - post.getTime()) / 1000000000;
endTime += 1000000000;
if (elapsedTimeInSec < 60) {
int elapsedTime = (int) elapsedTimeInSec;
f.write(post.getPost() + "(" + elapsedTime
+ " seconds ago)\n");
} else {
int elapsedTime = (int) (elapsedTimeInSec / 60);
f.write(post.getPost() + "(" + elapsedTime
+ " minutes ago)\n");
}
}
}
|
04e7d5e2-05e3-4940-ad31-b1f78e680916
| 9
|
public static ArrayList<String> walk(String ip, String comunidade, String objeto) throws IOException {
System.out.println("\nSNMP Walk");
System.out.println("Objeto: " + objeto);
System.out.println("Comunidade: " + comunidade);
// Inicia sessaso SNMP
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// Configura o endereco
Address endereco = new UdpAddress(ip + "/" + porta);
// Configura target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(comunidade));
target.setAddress(endereco);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
// Armazena OID atual para saber quando finalizar comando WALK
String oidAtual = objeto;
ArrayList<String> retorno = new ArrayList<String>();
// Termina as requisicoes quando o proximo objeto
// nao pertencer a sub-arvore do objeto inicial
while(oidAtual.contains(objeto)) {
// Cria PDU (SNMP Protocol Data Unit)
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(oidAtual)));
pdu.setType(PDU.GETNEXT);
// Envia PDU
ResponseEvent responseEvent = snmp.send(pdu, target);
if(responseEvent != null) {
// Extrai a resposta PDU (pode ser null se ocorreu timeout)
PDU responsePDU = responseEvent.getResponse();
if(responsePDU != null) {
int errorStatus = responsePDU.getErrorStatus();
int errorIndex = responsePDU.getErrorIndex();
String errorStatusText = responsePDU.getErrorStatusText();
if (errorStatus == PDU.noError) {
Vector <VariableBinding> tmpv = (Vector <VariableBinding>) responsePDU.getVariableBindings();
if(tmpv != null) {
for(int k=0; k <tmpv.size();k++) {
VariableBinding vb = (VariableBinding) tmpv.get(k);
if (vb.isException()) {
String errorstring = vb.getVariable().getSyntaxString();
System.out.println("Error:"+errorstring);
return retorno;
}
else {
//System.out.println("Tipo do Objeto: " + vb.getVariable().getSyntaxString());
oidAtual = vb.getOid().toString();
// Termina as requisicoes quando saimos da sub-arvore do objeto inicial
if(!oidAtual.contains(objeto))
break;
Variable var = vb.getVariable();
OctetString oct = new OctetString(var.toString());
String sVar = oct.toString();
//System.out.println(oidAtual + " = " + sVar);
retorno.add(oidAtual + " = " + sVar);
}
}
}
}
else {
System.out.println("Erro: WALK Request Falhou");
System.out.println("Status do Erro = " + errorStatus);
System.out.println("Index do Erro = " + errorIndex);
System.out.println(errorStatusText);
}
}
else {
System.out.println("Resultado vazio");
throw new NullPointerException("Null Response");
}
}
else {
throw new RuntimeException("WALK Request Timed Out");
}
}
snmp.close();
for(String s : retorno)
System.out.println(s);
return retorno;
}
|
de13196e-8643-464d-a9b7-e1c9d0dbbae4
| 8
|
private DataCacheEntry fetchLine(int address) {
int tag = address / (lineSize * (numberOfLines / associativity));
int set = (address / lineSize) % (numberOfLines / associativity);
int offset = address % lineSize;
int index = 0, oldest = 0;
DataCacheEntry entry = null;
for (int i = 0; i < associativity; i++) {
entry = cache.get(set * associativity + i);
if (entry == null) {
index = i;
break;
}
if (entry.getTag() == tag) {
hits++;
return entry;
}
if (i == 0 || oldest > entry.getAge()) {
index = i;
oldest = entry.getAge();
}
}
entry = cache.get(set * associativity + index);
if (onHit == WritePolicy.WRITE_BACK && entry != null && entry.isDirty())
nextLevel.setData(entry.getDataAddress(), entry.getData());
byte[] data = nextLevel.getData(address - offset, lineSize);
entry = new DataCacheEntry(tag, data, address - offset, accesses);
cache.put(set * associativity + index, entry);
return entry;
}
|
21cc301c-44d5-47d8-a501-668bb5f6b0ff
| 5
|
private void calculateDesiredVelocity() {
float distanceToTarget = Maths.getDistance(this.getX(), this.getY(), this.targetX, this.targetY);
double angleDifference = Maths.angleDifference(Math.toDegrees(angle), Math.toDegrees(desiredAngle));
if(!halting && distanceToTarget > 1) {
// First case handles cases where movement point is very close to ai so the angle must be spot on so it doesn't loop around the target
if(distanceToTarget < 120 && angleDifference > 45 + distanceToTarget){
this.desiredVelocity = 0;
}
else if(distanceToTarget > ((velocity * velocity) / (float)(2 * maxAccel)))
this.desiredVelocity = maxVelocity;
else
this.desiredVelocity = 0;
}
else {
this.desiredVelocity = 0;
}
}
|
5382e825-64b7-480b-91a6-444c11d82d75
| 3
|
public boolean intersects(GameObj obj){
return (pos_x + width >= obj.pos_x
&& pos_y + height >= obj.pos_y
&& obj.pos_x + obj.width >= pos_x
&& obj.pos_y + obj.height >= pos_y);
}
|
74e469ad-e6dd-46f0-81c3-04116f4e0ff2
| 3
|
public Token getNextToken(){
//mat.usePattern(space).find();
Token curToken = new Token();
curToken.type = TokType.UNKNOWN;
curToken.value = "";
for(int i=0;i<patterns.length-1;i++){
if(mat.usePattern(patterns[i].pat).find()){
curToken.value = mat.group();
curToken.type = patterns[i];
curPosition = mat.end();
return curToken;
}
}
mat.region(curPosition, mat.regionEnd());
//mat.usePattern(space).find();
if(mat.usePattern(unknown).find()){
curToken.value = mat.group();
curToken.type = TokType.UNKNOWN;
}
return curToken;
}
|
e653324d-e465-4d0e-97ae-7b253ce622bf
| 2
|
public void init()
{
glMatrixMode(GL_PROJECTION);
glOrtho(-4, 4, -4, 4, 20, -40);
//gluPerspective(70f, 800f/600f, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, Display.getWidth(), Display.getHeight());
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
texture = Texture.loadWindow(100);
System.out.println("Loaded window with " + 10);
Util.checkGLError();
HashMap<FloatBuffer, Integer> houses = HouseGenerator.generateHouses(globalWidth2*globalHeight2);
//FloatBuffer vertices = (FloatBuffer) houses.keySet().toArray()[0];
//vertCount = houses.get(vertices);
FloatBuffer[] verticeses = houses.keySet().toArray(new FloatBuffer[houses.keySet().size()]);
vertCounts = new int[verticeses.length];
for (int i = 0; i < verticeses.length; i++)
{
vertCounts[i] = houses.get(verticeses[i]);
}
FloatBuffer verticesTex = BufferUtils.createFloatBuffer(3*4*6);
verticesTex.put(new float[]
{
0, 0, 0,
5, 0, 0,
5, 20, 0,
0, 20, 0,
0, 0, 0,
5, 0, 0,
5, 20, 0,
0, 20, 0,
0, 0, 0,
5, 0, 0,
5, 20, 0,
0, 20, 0,
0, 0, 0,
5, 0, 0,
5, 20, 0,
0, 20, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0
});
verticesTex.rewind();
//vboVertexID = glGenBuffers();
//glBindBuffer(GL_ARRAY_BUFFER, vboVertexID);
//glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
//glBindBuffer(GL_ARRAY_BUFFER, 0);
vboTexID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vboTexID);
glBufferData(GL_ARRAY_BUFFER, verticesTex, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
vboVertexIDs = new int[verticeses.length];
for (int i = 0; i < verticeses.length; i++)
{
vboVertexIDs[i] = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vboVertexIDs[i]);
glBufferData(GL_ARRAY_BUFFER, verticeses[i], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
glRotatef(-20, 1, 0, 0);
glRotatef(-45, 0, 1, 0);
//glRotatef(00, 0, 1, 0);
//glRotatef(-20, 1, 0, 0);
//glRotatef(20, 0, 0, 1);
//glRotatef(-00, 1, 0, 1);
//glTranslatef(1*HouseGenerator.widthS*vboVertexIDs.length*0.5f, 0f, 0f);
//glTranslatef(0, -2, 0);
glTranslatef(-1*HouseGenerator.tWidth*globalWidth2*1f, 0f, -1*HouseGenerator.tDepth*globalHeight2*1f);
}
|
8f0b72ed-9853-4544-9c05-f802a099dd6f
| 6
|
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
|
d6fa6291-49cb-43b9-91f9-34f76ace5890
| 9
|
public Data gen() {
int ano = 1960 + g.nextInt(40);
int mes = g.nextInt(12);
int dia = 1;
if (mes == 2 && ano % 400 == 0) {
dia = 1 + g.nextInt(27);
} else if (mes == 2 && ano % 4 == 0 && ano % 100 != 0) {
dia = 1 + g.nextInt(28);
} else if (mes == 4 || mes == 6 || mes == 9 || mes == 11) {
dia = 1 + g.nextInt(30);
} else {
dia = 1 + g.nextInt(31);
}
return new Data(dia,mes,ano);
}
|
18030fd1-0994-4a47-9c08-14cf96c1ada3
| 1
|
public synchronized void editar(int i)
{
try
{
new InstituicaoSubmissaoView(this, list.get(i));
}
catch (Exception e)
{
}
}
|
94a53feb-052f-41f3-afd2-4084a8c198a8
| 5
|
public final String getUrl() {
if (url == null) {
return null;
}
String returnUrl = url;
returnUrl += isUseExtraParams() ? "&cver=html5&ratebypass=yes&c=WEB&alr=yes&keepalive=yes" : "";
returnUrl += String.format("&range=%s-%s", String.valueOf(startRange), String.valueOf(endRange));
returnUrl += isSignatureRequired() && signature != null ? String.format("&signature=%s", signature) : "";
returnUrl += isUseMimeType() ? String.format("&mime=%s", mimeType) : "";
return returnUrl;
}
|
48e2f355-0dfe-44f9-9519-3df4a13d942c
| 5
|
public static JsonElement parse(JsonReader reader) throws JsonParseException {
boolean isEmpty = true;
try {
reader.peek();
isEmpty = false;
return TypeAdapters.JSON_ELEMENT.read(reader);
} catch (EOFException e) {
/*
* For compatibility with JSON 1.5 and earlier, we return a JsonNull for
* empty documents instead of throwing.
*/
if (isEmpty) {
return JsonNull.INSTANCE;
}
// The stream ended prematurely so it is likely a syntax error.
throw new JsonSyntaxException(e);
} catch (MalformedJsonException e) {
throw new JsonSyntaxException(e);
} catch (IOException e) {
throw new JsonIOException(e);
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
|
74782a68-a400-4ebf-a70d-a70c3b76f45d
| 9
|
static String[] toStringArray(MatVar mv, boolean transpose) {
if (mv.type() == MatVar.TEXT) {
MatText mt = (MatText) mv;
int[] dims = mv.getDim();
String[] out = new String[dims[transpose ? 1 : 0]];
for (int i = 0; i < dims[transpose ? 1 : 0]; i++) {
char[] chars = new char[dims[transpose ? 0 : 1]];
for (int j = 0; j < dims[transpose ? 0 : 1]; j++) {
chars[j] = mt.getChar(transpose ? j : i, transpose ? i : j);
}
out[i] = new String(chars).trim();
}
return out;
}
return new String[0];
}
|
71f7efaf-805f-445d-a0f4-7d44f56840d9
| 6
|
private void writeObject(List<Byte> ret, TypedObject val) throws EncodingException, NotImplementedException
{
if (val.type == null || val.type.equals(""))
{
ret.add((byte)0x0B); // Dynamic class
ret.add((byte)0x01); // No class name
for (String key : val.keySet())
{
writeString(ret, key);
encode(ret, val.get(key));
}
ret.add((byte)0x01); // End of dynamic
}
else if (val.type.equals("flex.messaging.io.ArrayCollection"))
{
ret.add((byte)0x07); // Externalizable
writeString(ret, val.type);
encode(ret, val.get("array"));
}
else
{
writeInt(ret, (val.size() << 4) | 3); // Inline + member count
writeString(ret, val.type);
List<String> keyOrder = new ArrayList<String>();
for (String key : val.keySet())
{
writeString(ret, key);
keyOrder.add(key);
}
for (String key : keyOrder)
encode(ret, val.get(key));
}
}
|
8c48d14e-075b-426f-9c5e-e032e89bcc4b
| 5
|
private Thread createAliveThread()
{
return new Thread()
{
public void run()
{
while(true)
{
try{
if (aliveNotificator != null) {
aliveNotificator.iamAlive(rmiObjectName);
System.out.println("Sende alive");
}
sleep(2000);
}
catch (ConnectException e)
{
System.out.println("Monitor nicht erreicht");
}
catch(InterruptedException e)
{
System.out.println("AliveThread stoppt");
break;
} catch (RemoteException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
};
}
|
bd3be8ab-8e1a-4b6c-8641-58abd999fbad
| 8
|
private boolean isCollision(Entity e1, Entity e2) {
// Hvis objektene er det samme, return false.
if (e1 == e2) {
return false;
}
// Er objektene vesener og er de i livet enda?
if (e1 instanceof Creature && !((Creature) e1).isAlive()) {
return false;
}
if (e2 instanceof Creature && !(((Creature) e2).isAlive())) {
return false;
}
// Henter inn lokasjonene og grensene basert p� lokasjon i x-y-rom.
int e1x = Math.round(e1.getX() + map.getOffsetX());
int e1y = Math.round(e1.getY());
int e2x = Math.round(e2.getX());
int e2y = Math.round(e2.getY());
// Sjekker om grensene overlapper.
return (e1x < e2x + e2.getWidth() && e2x < e1x + e1.getWidth() - 5 && e1y < e2y + e2.getHeight() && e2y < e1y
+ e1.getHeight() - 8);
}
|
2afe7c33-6aff-4939-b76a-f11e3cc8a9ad
| 0
|
public void setAihao(String aihao) {
this.aihao = aihao;
}
|
751f7de5-4410-4d33-8f8e-7c5e6789e955
| 9
|
private static void bindByField(Object pojo, CommandLine cli, Field field) throws Exception
{
CLIOptionBinding cliBinding = field
.getAnnotation(CLIOptionBinding.class);
char shortOpt = cliBinding.shortOption();
String longOpt = cliBinding.longOption();
if (cliBinding.values()) {
if (field.getType().isArray()) {
field.set(pojo, cli.getArgs());
} else if (cli.getArgs().length > 0) {
field.set(
pojo,
getTypedvalue(field.getType(),
cli.getArgs()[0],
cliBinding.format()));
}
} else if (shortOpt != 0 && cli.hasOption(shortOpt)) {
String val = (cli.getOptionValue(shortOpt) == null) ? "true"
: cli.getOptionValue(shortOpt);
field.set(
pojo,
getTypedvalue(field.getType(), val,
cliBinding.format()));
} else if (!longOpt.isEmpty() && cli.hasOption(longOpt)) {
String val = (cli.getOptionValue(longOpt) == null) ? "true"
: cli.getOptionValue(longOpt);
field.set(
pojo,
getTypedvalue(field.getType(), val,
cliBinding.format()));
}
}
|
374dfbdd-fc2d-4633-afae-7263fcac5cbc
| 3
|
private static void printGridletList(GridletList list, String name,
boolean detail)
{
int size = list.size();
Gridlet gridlet = null;
String indent = " ";
System.out.println();
System.out.println("============= OUTPUT for " + name + " ==========");
System.out.println("Gridlet ID" + indent + "STATUS" + indent +
"Resource ID" + indent + "Cost");
// a loop to print the overall result
int i = 0;
for (i = 0; i < size; i++)
{
gridlet = (Gridlet) list.get(i);
System.out.print(indent + gridlet.getGridletID() + indent
+ indent);
System.out.print( gridlet.getGridletStatusString() );
System.out.println( indent + indent + gridlet.getResourceID() +
indent + indent + gridlet.getProcessingCost() );
}
if (detail == true)
{
// a loop to print each Gridlet's history
for (i = 0; i < size; i++)
{
gridlet = (Gridlet) list.get(i);
System.out.println( gridlet.getGridletHistory() );
System.out.print("Gridlet #" + gridlet.getGridletID() );
System.out.println(", length = " + gridlet.getGridletLength()
+ ", finished so far = " +
gridlet.getGridletFinishedSoFar() );
System.out.println("======================================\n");
}
}
}
|
7e8be42b-a799-4e1e-94f8-d5bc20c3674a
| 7
|
private Holiday getHoliday(Element element)
{
String className = null;
if (className == null)
className = element.getAttributeValue("class");
if (className == null)
{
className = "nz.co.senanque.madura.datetime.holidays."+element.getName();
}
Holiday ret;
try
{
Class<?> holidayClass = Class.forName(className);
ret = (Holiday)holidayClass.newInstance();
}
catch (Exception e)
{
throw new HolidayCalendarFactoryException(e);
}
@SuppressWarnings("unchecked")
List<Attribute> attributes = element.getAttributes();
for (Attribute attribute: attributes)
{
String name = attribute.getName();
if ("class".equals(name)) continue;
try
{
BeanUtils.setProperty(ret,name,attribute.getValue());
}
catch (Exception e)
{
e.printStackTrace();
}
}
return ret;
}
|
269bd39b-9c59-4095-b4b0-34dd7d281be2
| 1
|
int daysOfYear(int year) {
if (isLeepYear(year)) {
return 366;
}
return 365;
}
|
eefed605-b1d6-4e47-beae-0c7a13beb7c8
| 2
|
@SuppressWarnings("unchecked")
@Override
public String displayQuestion(int position) {
ArrayList<String> questionList = (ArrayList<String>) question;
String questionStr = questionList.get(0);
StringBuilder sb = new StringBuilder();
sb.append("<span class=\"dominant_text\">" + position + ".</span>\n");
sb.append("<span class=\"quiz_title\">\n");
sb.append("<span class=\"dominant_text\">Matching Question (" + score + " points):</span><br /><br />\n");
sb.append(questionStr + "\n");
sb.append("</span><br /><br />\n");
sb.append("<div>\n");
for (int i = 1; i < questionList.size()/2+1; i++) {
sb.append("<p>\n");
sb.append(questionList.get(i) + " \n");
sb.append("<select name=\"user_answer" + position + "_" + i + "\">\n");
for (int j = questionList.size()/2+1; j < questionList.size(); j++) {
sb.append("<option value=\"" + questionList.get(j) + "\">" + questionList.get(j) + "</option>\n");
}
sb.append("</select></p><br /><br />\n");
}
sb.append("</div\n");
return sb.toString();
}
|
c9faf376-d42b-42c1-a065-a2a416405008
| 1
|
@Test
public void testDisconnectOnce() throws Exception {
final Properties config = new Properties();
final int min_uptime = 20;
final int max_uptime = 2000;
config.setProperty("min_uptime", "" + min_uptime);
config.setProperty("max_uptime", "" + max_uptime);
final long started = System.currentTimeMillis();
final MockConnectionProcessor proc = new MockConnectionProcessor();
final Filter f = new DisconnectFilter(proc, config);
while ((System.currentTimeMillis() - started) < max_uptime) {
Assert.assertEquals(10, f.filter(10));
Thread.sleep(max_uptime - min_uptime);
}
Assert.assertEquals(1, proc.disconnect_count);
}
|
dbbdf762-c808-4db7-96f1-7b5835d52785
| 3
|
static double[][] multiply(double[][] A, double[][] B){
double[][] AB = new double[A.length][B[0].length];
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B[i].length; j++){
for(int k = 0; k < B.length ; k++){
AB[i][j] += A[i][k]*B[k][j];
}
}
}
return AB;
}
|
91b7ec85-aa86-43f1-9fb6-e0b225a64d90
| 6
|
public List<StudentObj> getStudentBySubmitted(String classname, int objId, int topicId) {
List<StudentObj> items = new LinkedList<StudentObj>();
String sql = "select Student.classname, Student.rollNo, fullname, email from Student inner join Result on Student.rollNo = Result.rollNo inner join Assignment on Result.asm_id = Assignment.asm_id "
+ "inner join Topic on Assignment.topic_id = Topic.topic_id inner join Objective on Topic.obj_id = Objective.obj_id "
+ "where Objective.obj_id = ? and Topic.topic_id=? ";
if(!classname.equals(ALL)){
sql += "and Student.classname = ? ";
}
sql += "order by Student.classname";
try {
connect();
PreparedStatement pre = con.prepareStatement(sql);
pre.setInt(1, objId);
pre.setInt(2, topicId);
if(!classname.equals(ALL)){
pre.setString(3, classname);
}
try {
ResultSet rs = pre.executeQuery();
if (rs != null) {
while (rs.next()) {
StudentObj item = new StudentObj();
item.setClassname(rs.getString("classname"));
item.setRollNo(rs.getString("rollNo"));
item.setFullName(rs.getString("fullname"));
item.setEmail(rs.getString("email"));
items.add(item);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
close();
} catch (Exception e) {
e.printStackTrace();
}
return items;
}
|
646dbd48-149a-421f-8f66-0e57e36c9413
| 2
|
@Override
protected boolean next() {
switch(state()) {
case size_ready:
return size_ready ();
case message_ready:
return message_ready ();
default:
return false;
}
}
|
5cec8ca4-a8ae-4e00-a812-da4a3bfa7134
| 6
|
@EventHandler
public void WitchRegeneration(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getWitchConfig().getDouble("Witch.Regeneration.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getWitchConfig().getBoolean("Witch.Regeneration.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getWitchConfig().getInt("Witch.Regeneration.Time"), plugin.getWitchConfig().getInt("Witch.Regeneration.Power")));
}
}
|
7e372058-80b0-40fe-86cc-4deaed3d4fc6
| 3
|
private void close() {
try {
out.close();
} catch(Exception e) {}
try {
in.close();
} catch(Exception e) {}
try {
socket.close();
} catch(Exception e) {}
System.out.println("Thread closed.");
}
|
ff8d999d-6989-4fba-a383-042e5fb57016
| 8
|
public ArrayList<Integer> getAvailableRooms(String startTime, String endTime, int capacity){
ArrayList<Integer> availableRooms = new ArrayList<>();
ArrayList<Meeting> meetings = meetings().getMeetings();
for(Room room : rooms().getRooms()){
if(room.getRoomNumber() == -1) continue;
if(room.getCapacity() < capacity) continue;
availableRooms.add(room.getRoomNumber());
}
for(Meeting meeting : meetings){
int room = meeting.getRoom();
if(room == -1) continue;
if(!availableRooms.contains(room)) continue;
if(!(LocalDateTime.parse(meeting.getEndtime()).isBefore(LocalDateTime.parse(startTime)) && LocalDateTime.parse(meeting.getStarttime()).isAfter(LocalDateTime.parse(endTime)))) continue;
availableRooms.remove(room);
}
return availableRooms;
}
|
c7a27b8f-2b54-4e91-b1f0-03556195ad36
| 9
|
@Override
public Party getEnemyParty(int level)
{
Party party = new Party();
Random gen = new Random();
if(level == 1)
{
if(gen.nextInt(2) == 0)
party.add(new Goblin());
else
party.add(new Rat());
}
else if(level == 2)
{
if(gen.nextInt(2) == 0)
party.add(new Orc());
else
party.add(new Zombie());
}
else if(level == 3)
{
party.add(new Spider());
}
else if(level == 5)
{
party.add(new Ogre());
}
else if(level == 7)
{
party.add(new Gargoyle());
}
else if(level == 15)
{
party.add(new Dragon());
}
else
{
do{
int enemy = gen.nextInt(level)+1;
party.addAll(getEnemyParty(enemy));
level = level - enemy;
}while(level != 0);
}
return party;
}
|
019cfc73-168c-4e4c-9a1f-31067c288056
| 0
|
public byte[] getInfoHash() {
return this.info_hash;
}
|
9049e893-1c7a-475a-b432-d6c0ca797f8d
| 5
|
@Test
public void testInitRandom() {
try {
System.out.println("initRandom");
int numberOfGenerators = 5;
int numberOfLoadsForGenerator = 3;
int R = 2;
double xmean = 0.2;
double delta = 0.2;
PowerGrid instance = new PowerGrid(numberOfGenerators, numberOfLoadsForGenerator, R, xmean, delta);
System.out.println("Instance created:\n" + instance.toStringFile());
for (Generator g : instance.getGenerators()) {
assertEquals(g.howManyLoads(), R + numberOfLoadsForGenerator);
}
} catch (InitializatedException ex) {
ex.printStackTrace();
} catch (UnInitializatedException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (NoMoreGeneratorsException ex) {
System.out.println("No more generators, sorry!");
}
}
|
53358e53-5663-4083-a1e0-265d99582786
| 2
|
private <T> T[] copyElements(T[] a) {
if (head < tail) {
System.arraycopy(elements, head, a, 0, size());
} else if (head > tail) {
int headPortionLen = elements.length - head;
System.arraycopy(elements, head, a, 0, headPortionLen);
System.arraycopy(elements, 0, a, headPortionLen, tail);
}
return a;
}
|
d642ab00-903b-4614-998a-b1c2f3538f6e
| 9
|
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
}
|
42e5c6ec-5700-4c9f-aa5f-2e902c237fc2
| 5
|
public void prepare( Map<String,BasicType> optionalReturnSettings )
throws MalformedRequestException,
UnsupportedVersionException,
UnsupportedMethodException,
UnknownMethodException,
ConfigurationException,
MissingResourceException,
AuthorizationException,
HeaderFormatException,
DataFormatException,
UnsupportedFormatException,
ParametrizedHTTPException,
SecurityException,
IOException {
// The current implemenation of tiny server only supports HTTP-GET, -POST and -OPTIONS.
String httpMethod = this.checkValidHTTPMethod();
if( this.getRequestHeaders().isGETRequest()
|| this.getRequestHeaders().isPOSTRequest()
|| this.getRequestHeaders().isHEADRequest() ) {
this.prepareGETorPOSTorHEAD( optionalReturnSettings );
} else if( this.getRequestHeaders().isOPTIONSRequest() ) {
this.prepareOPTIONS( optionalReturnSettings );
} else if( this.getRequestHeaders().isTRACERequest() ) {
// Note that TRACE is not secure.
// http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf
this.prepareTRACE( optionalReturnSettings );
} else {
throw new UnsupportedMethodException( httpMethod, "Unsupported HTTP method ('" + httpMethod + "')" );
}
}
|
530815a7-bbb2-4f81-ba6b-88085aa95718
| 9
|
public void run() {
Socket incomingSocket = null;
while(true) {
try {
incomingSocket = serverSocket.accept();
System.out.println("Parsing msg..");
Message msg = Utility.parseMessage(incomingSocket);
msg.readMessage();
switch(msg.getType()) {
case GET:
//send peer response
//send the file to requesting host
File rfcFile = new File(Utility.getRFCFilename(msg.getRFCNumber()));
ResponseRFCMessage response = null;
if(!rfcFile.exists()) {
response = new ResponseRFCMessage(Utility.RESPONSE_TYPE.NOT_FOUND);
} else {
response = new ResponseRFCMessage(Utility.RESPONSE_TYPE.OK);
}
StringBuffer buf = new StringBuffer();
buf.append(0 + Message.EOL);
response.setResponseContent(buf);
response.sendServerResponse(incomingSocket);
System.out.println("Sent response for GET...");
if(rfcFile.exists()) {
System.out.println("Sending file...");
Utility.send_file(incomingSocket, msg.getRFCNumber());
System.out.println("Sending file...DONE");
}
incomingSocket.close();
break;
case ADD:
case LOOKUP:
case LIST:
break;
case RESPONSE: //response from server
System.out.println("Response from server...");
synchronized (Peer.waitObject) {
Peer.waitObject.notify();
}
}
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
|
256d8fd9-a121-413d-b019-8e1fc2f9cb00
| 0
|
@Before
public void setUp() {
view = new DialogWindowView("title");
view.addPropertyChangeListener(this);
controller.addView(view);
propertyChangeSupport.addPropertyChangeListener(controller);
}
|
1374b574-5bd2-4e83-a397-86d4c0d8fa30
| 7
|
private Content getInheritedTagletOutput(boolean isNonTypeParams, Doc holder,
TagletWriter writer, Object[] formalParameters,
Set<String> alreadyDocumented) {
Content result = writer.getOutputInstance();
if ((! alreadyDocumented.contains(null)) &&
holder instanceof MethodDoc) {
for (int i = 0; i < formalParameters.length; i++) {
if (alreadyDocumented.contains(String.valueOf(i))) {
continue;
}
//This parameter does not have any @param documentation.
//Try to inherit it.
DocFinder.Output inheritedDoc =
DocFinder.search(new DocFinder.Input((MethodDoc) holder, this,
String.valueOf(i), ! isNonTypeParams));
if (inheritedDoc.inlineTags != null &&
inheritedDoc.inlineTags.length > 0) {
result.addContent(
processParamTag(isNonTypeParams, writer,
(ParamTag) inheritedDoc.holderTag,
isNonTypeParams ?
((Parameter) formalParameters[i]).name():
((TypeVariable) formalParameters[i]).typeName(),
alreadyDocumented.size() == 0));
}
alreadyDocumented.add(String.valueOf(i));
}
}
return result;
}
|
8c49844a-3a69-4d65-873a-d8e1f036a1d9
| 5
|
static final void method1119(boolean bool) {
anInt8381++;
try {
Method method
= (aClass8389 != null ? aClass8389
: (aClass8389 = method1121("java.lang.Runtime")))
.getMethod("availableProcessors", new Class[0]);
if (bool != false)
method1118(false, false, null, -35);
if (method != null) {
try {
Runtime runtime = Runtime.getRuntime();
Integer integer = (Integer) method.invoke(runtime, null);
Class348_Sub40_Sub29.anInt9372 = integer.intValue();
} catch (Throwable throwable) {
/* empty */
}
}
} catch (Exception exception) {
/* empty */
}
}
|
a8cba7d1-529b-495d-80e2-02fcf589e758
| 5
|
public boolean equals(Packet p) {
if((end-start) != (p.end - p.start)) {
return false;
}
if(p.mask != mask || p.timeStamp != timeStamp) {
return false;
}
int length = end-start;
for(int cnt=0;cnt<length;cnt++) {
if(buffer[(start+cnt)&mask] != p.buffer[(p.start+cnt)&mask]) {
System.out.println("Mismatch at position " + cnt);
return false;
}
}
return true;
}
|
ace216e8-63dc-4d77-a149-a0749d1fa3c0
| 6
|
public static void drawNetwork(Network network, Renderer renderer)
{
ArrayList<Layer> layers = network.getLayers();
int maxWidth = 0;
/**
* Calculate the maximum width of the layers.
* This will later be used to center all layers that are smaller than the widest one
*/
for(Layer layer : layers)
{
maxWidth = Math.max(maxWidth, layer.getSize() * 50);
}
/**
* Draw the input layer + input connections
*/
ArrayList<Neuron> neurons = layers.get(0).getNeurons();
for(int i = 0; i <= neurons.size() - 1; i++)
{
int x = i * (maxWidth / neurons.size()) + (maxWidth / (2 * neurons.size())) + 25;
renderer.addDrawable(new DrawableNeuron(neurons.get(i), new Circle(x, 50, 10)));
renderer.addDrawable(new DrawableConnection(neurons.get(i).getInputs().get(0), new Line(x, 20, x, 40)));
}
/**
* Draw the hidden layers + connections to previous input layers + the output layer
*/
for(int i = 1; i <= layers.size() - 1; i++)
{
neurons = layers.get(i).getNeurons();
for(int j = 0; j <= neurons.size() - 1; j++)
{
int x = j * (maxWidth / neurons.size()) + (maxWidth / (2 * neurons.size())) + 25;
renderer.addDrawable(new DrawableNeuron(neurons.get(j), new Circle(x, i * 50 + 50, 10)));
ArrayList<Connection> connections = neurons.get(j).getInputs();
for(int k = 0; k <= connections.size() - 1; k++)
{
int otherX = k * (maxWidth / layers.get(i - 1).getSize()) + (maxWidth / (2 * layers.get(i - 1).getSize())) + 25;
renderer.addDrawable(new DrawableConnection(connections.get(k), new Line(otherX, (i - 1) * 50 + 60, x, i * 50 + 40)));
}
}
}
/**
* Draw the output connections
*/
neurons = layers.get(layers.size() - 1).getNeurons();
for(int i = 0; i <= neurons.size() - 1; i++)
{
int x = i * (maxWidth / neurons.size()) + (maxWidth / (2 * neurons.size())) + 25;
renderer.addDrawable(new DrawableConnection(neurons.get(i).getOutputs().get(0), new Line(x, (layers.size() - 1) * 50 + 60 , x, (layers.size() - 1) * 50 + 80)));
}
}
|
7374b689-2b57-46bf-b0a4-ac60af3df2ea
| 0
|
public void addCode(ByteCode code) {
bytecodes.add(code);
}
|
1c9a251b-7a26-4816-8623-c85d99e3ae3e
| 9
|
public void incrementTime(int amount){
//increase elapsed time by one
elapsed_time += amount;
Process temp;
//increase wait time for each process in ready queue
Iterator<Process> it = readyQueue.iterator();
while(it.hasNext()){
temp=it.next();
if(cpuList.indexOf(temp) == -1){
temp.waitTime++;
temp.turnaroundTime++;
}
}
//re-add any processes that are ready to go into ready queue
for(int j=0; j < waitingTimeList.size(); ++j){
temp=waitingTimeList.get(j);
if(temp.pType == "CPU-bound process"){
temp.blockTime--;
if(temp.blockTime == 0){
waitingTimeList.remove(temp);
waitCompletion(temp);
}
}
else{
temp.responseTime--;
if(temp.responseTime == 0){
waitingTimeList.remove(temp);
waitCompletion(temp);
}
}
}
//edit remaining time in current burst and handle completions if any occur
for(int i = 0; i < cpuList.size(); ++i){
temp = cpuList.get(i);
temp.remBurstTime--;
temp.turnaroundTime++;
temp.timeWithCpu++;
if(temp.remBurstTime == 0){
// System.out.println("Removing "+temp.processID+" from cpuList");
temp.endTime=elapsed_time;
burstCompletion(temp);
cpuList.remove(temp);
}
else if(temp.timeWithCpu >= t_slice) {
temp.timeWithCpu = 0;
sliceCompletion(temp);
cpuList.remove(temp);
}
}
}
|
6b30bdeb-fa40-481b-a6ed-d394f8623acb
| 9
|
synchronized void updateMap(int intLocX, int intLocY)
{
DuskObject objStore;
LivingThing thnStore;
int i=0, i2=0, i3;
if (intLocX-viewrange<0) i = -1*(intLocX-viewrange);
if (intLocY-viewrange<0) i2 = -1*(intLocY-viewrange);
for (;i<mapsize;i++)
{
if (intLocX+i-viewrange<MapColumns)
{
for (i3=i2;i3<mapsize;i3++)
{
if (intLocY+i3-viewrange<MapRows)
{
objStore = objEntities[intLocX+i-viewrange][intLocY+i3-viewrange];
while (objStore != null)
{
if (objStore.isLivingThing())
{
thnStore = (LivingThing)objStore;
if (thnStore.isPlayer())
thnStore.updateMap();
}
objStore = objStore.objNext;
}
}
}
}
}
}
|
1574a842-e1b2-4c2b-ac3b-bdc71f40669b
| 2
|
public String getCollectionName(Object[] args) {
if (collectionIndex == -1) {
return globalCollectionName;
}
Object arg = args[collectionIndex];
if (arg == null) {
return globalCollectionName;
} else {
return arg.toString();
}
}
|
f48a3385-d13f-4c3c-ae71-497c286992fe
| 5
|
@Override
public void drawShape(Graphics graphics) {
int thick = super.getThick();
int radius;
// x and y are the coordinates for the centre of the circle
int x, y;
// xn and yn is the first point the user clicked
// xm and ym is the second point the user clicked
int xn, yn, xm, ym;
xn = super.getXi();
yn = super.getYi();
xm = super.getXo();
ym = super.getYo();
graphics.setColor(super.getColor());
int dx = xm - xn;
int dy = ym - yn;
// Scenario for slope less than 1.
if (Math.abs(dx) > Math.abs(dy)) {
if (xn > xm) {
int tempX = xn;
xn = xm;
xm = tempX;
int tempY = yn;
yn = ym;
ym = tempY;
} else {
xn = super.getXi();
yn = super.getYi();
xm = super.getXo();
ym = super.getYo();
}
x = ((xm - xn) / 2) + xn;
if (yn > ym) {
y = ((yn - ym) / 2) + ym;
} else {
y = ((ym - yn) / 2) + yn;
}
radius = (xm - xn) / 2;
// Scenario for slope is greater or equal to 1.
} else {
if (yn > ym) {
int tempX = xn;
xn = xm;
xm = tempX;
int tempY = yn;
yn = ym;
ym = tempY;
} else {
xn = super.getXi();
yn = super.getYi();
xm = super.getXo();
ym = super.getYo();
}
y = ((ym - yn) / 2) + yn;
if (xn > xm) {
x = ((xn - xm) / 2) + xm;
radius = (xn - xm) / 2;
} else {
x = ((xm - xn) / 2) + xn;
radius = (xm - xn) / 2;
}
}
// Calls the drawCircle method to draw the circle in each loop.
this.drawCircle(x, y, radius, graphics);
}
|
8c15b9ae-cfd3-4f9d-bd67-43f55bb58fbc
| 6
|
final boolean method2847(int i, Class348_Sub43 class348_sub43) {
try {
anInt8948++;
int i_37_ = 47 / ((i - -62) / 36);
if (((Class348_Sub43) class348_sub43).aClass348_Sub16_Sub5_7081
== null) {
if ((((Class348_Sub43) class348_sub43).anInt7087 ^ 0xffffffff)
<= -1) {
class348_sub43.removeNode();
if ((((Class348_Sub43) class348_sub43).anInt7088
^ 0xffffffff) < -1
&& (class348_sub43
== (aClass348_Sub43ArrayArray8915
[((Class348_Sub43) class348_sub43).anInt7067]
[(((Class348_Sub43) class348_sub43)
.anInt7088)])))
aClass348_Sub43ArrayArray8915
[((Class348_Sub43) class348_sub43).anInt7067]
[((Class348_Sub43) class348_sub43).anInt7088]
= null;
}
return true;
}
return false;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("ma.W(" + i + ','
+ (class348_sub43 != null
? "{...}" : "null")
+ ')'));
}
}
|
d1dec875-3ae0-4276-9816-2be638f75e47
| 4
|
public boolean execute(CommandSender par1Sender, Command par2Command,
String par3Args, String[] par4Args) {
if (par1Sender instanceof Player) {
String message;
Player player = (Player) par1Sender;
if (par4Args.length < 1)
message = i18n._("genericreason_afk" + (AFKWorker.isPlayerAFK(player) ? "" : "_returned"));
else
message = par4Args[0];
message = Util.maskedStringReplace(message, new String[][] {
{ "%player", player.getDisplayName() }
});
if (AFKWorker.isPlayerAFK(player))
AFKWorker.setAFK(player, AFKReason.DECIDED, message);
else
AFKWorker.setOnline(player, AFKReason.DECIDED, message);
}
return true;
}
|
b01b3845-72e6-40a5-b1e9-c7534faead3f
| 7
|
@Override
public void createSomeObjects() {
this.addUser(new User("worker", "password", GroupType.WORKER));
this.addUser(new User("Gumby", "MyBrainHurts", GroupType.WORKER));
this.addUser(new User("manager", "password", GroupType.MANAGER));
ProductType pt = new ProductType("Skumbananer"), pt2 = new ProductType(
"P-Taerter");
Stock semi = new Stock("Semi products - main room", StockType.SEMI,
100, 16, 10), cores = new Stock("Cores machine",
StockType.MACHINE, 9, 16, 3), coat = new Stock(
"Coating machine", StockType.MACHINE, 16, 16, 4), done = new Stock(
"Finished", StockType.FINISHED, 64, 16, 8);
SubProcess sp = null;
pt.addSubProcess(sp = new SubProcess(0, "Core Production", 2, 4, 6));
sp.addStock(cores);
pt.addSubProcess(sp = new SubProcess(1, "Core Drying", 2, 4, 6));
sp.addStock(semi);
pt.addSubProcess(sp = new SubProcess(2, "Coating", 2, 4, 6));
sp.addStock(coat);
pt.addSubProcess(sp = new SubProcess(3, "Drying", 2, 4, 6));
sp.addStock(semi);
pt.addSubProcess(sp = new SubProcess(4, "Second Coating", 2, 4, 6));
sp.addStock(coat);
pt.addSubProcess(sp = new SubProcess(5, "Last Drying", 2, 4, 6));
sp.addStock(done);
pt2.addSubProcess(sp = new SubProcess(0, "Core Production", 2, 4, 6));
sp.addStock(cores);
pt2.addSubProcess(sp = new SubProcess(1, "Core Drying", 2, 4, 6));
sp.addStock(semi);
pt2.addSubProcess(sp = new SubProcess(2, "Coating", 2, 4, 6));
sp.addStock(coat);
pt2.addSubProcess(sp = new SubProcess(3, "Drying", 2, 4, 6));
sp.addStock(semi);
pt2.addSubProcess(sp = new SubProcess(4, "Second Coating", 2, 4, 6));
sp.addStock(coat);
pt2.addSubProcess(sp = new SubProcess(5, "Last Drying", 2, 4, 6));
sp.addStock(done);
sp = pt.getSubProcesses().get(0);
for (int i = 0; i < 5; i++) {
StorageUnit su = new StorageUnit(cores, i);
int cap = (int) Math.ceil(Math.max(.75, Math.random())
* cores.getMaxTraysPerStorageUnit());
for (int j = 0; j < cap; j++) {
Tray tray = new Tray(su, pt, 0);
State s = new State(tray, new Date(System.currentTimeMillis()));
s.setSubProcess(sp);
tray.addState(s);
su.addTray(tray);
this.addTray(tray);
}
cores.addStorageUnit(su);
}
sp = pt2.getSubProcesses().get(0);
for (int i = 5; i < 9; i++) {
StorageUnit su = new StorageUnit(cores, i);
int cap = (int) Math.ceil(Math.max(.75, Math.random())
* cores.getMaxTraysPerStorageUnit());
for (int j = 0; j < cap; j++) {
Tray tray = new Tray(su, pt2, 0);
State s = new State(tray, new Date(System.currentTimeMillis()));
s.setSubProcess(sp);
tray.addState(s);
su.addTray(tray);
this.addTray(tray);
}
cores.addStorageUnit(su);
}
for (int i = 0; i < done.getCapacity(); i++) {
done.addStorageUnit(new StorageUnit(done, i));
}
for (int i = 0; i < semi.getCapacity(); i++) {
semi.addStorageUnit(new StorageUnit(semi, i));
}
for (int i = 0; i < coat.getCapacity(); i++) {
coat.addStorageUnit(new StorageUnit(coat, i));
}
this.addProductType(pt);
this.addProductType(pt2);
this.addStock(done);
this.addStock(semi);
this.addStock(cores);
this.addStock(coat);
}
|
f6c91e71-8782-4e61-83fa-fb65fcff9cd8
| 6
|
public void updateBookType(String typeName, BookType bt) {
Connection conn = null;
Statement st = null;
//Do nothing if category is not properly instantiated
if(bt == null || bt.getTypeName() == null)
return;
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
st=conn.createStatement();
st.executeUpdate("UPDATE bookType SET maxReservation = " + bt.getMaxReservation() + " WHERE typeName = '" + typeName + "'");
st.executeUpdate("UPDATE bookType SET overdueFee = " + bt.getOverdueFee() + " WHERE typeName = '" + typeName + "'");
st.executeUpdate("UPDATE bookType SET typeName = '" + bt.getTypeName() + "' WHERE typeName = '" + typeName + "'");
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
try {
if(conn != null)
conn.close();
if(st != null)
st.close();
} catch (Exception e) { }
}
}
|
62dfafeb-448e-483f-9707-8cb065873257
| 7
|
public void run() {
if (isRunning) {
return;
}
autoRunEnabled = true;
Object selectedItem = commandCombo.getSelectedItem();
String commandLine = null;
if (selectedItem == null) {
return;
} else {
commandLine = selectedItem.toString();
}
isRunning = true;
runButton.setEnabled(false);
final String line = commandLine;
final String path = sourcePanel.getDirectory();
// Parse the command separator ';'
Thread runner = new Thread() {
public void run() {
StringTokenizer tokenizer = new StringTokenizer(line, ";");
while (tokenizer.hasMoreTokens()) {
FilterChain chain =
FilterChain.createFilterChain(
tokenizer.nextToken(),
sourcePanel,
destinationPanel);
chain.execute(line, path, gui);
while (isRunning) {
isRunning = chain.isRunning();
if (isRunning) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Just continue silently
}
}
}
}
isRunning = false;
runButton.setEnabled(true);
}};
runner.start();
addToHistory(commandLine);
if (autoClearCheckBox.isSelected()) {
clear();
}
}
|
21778376-0515-4c58-9fe6-868e0d18ffb2
| 5
|
public static Map getRandomMapExcluding(List<String> ex){
List<Map> notexcluded = new ArrayList<Map>();
for(Map m : maps){
boolean match = false;
String name = m.getName();
for(String s : ex){
if(name.equals(s)) match = true;
}if(match == false){
notexcluded.add(m);
}
}
if(notexcluded.size() != 0){
Random r = new Random();
int map = r.nextInt(notexcluded.size());
return notexcluded.get(map);
}else return getRandomMap();
}
|
5cec08e7-608d-4990-ba3f-97190ad0b06d
| 0
|
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
|
5ed64b50-2d15-4d42-816c-eb2650d6ebb2
| 2
|
private void addTab(JPanel tab, String tabImagePath, int tabWidth, int tabHeight, int width, int height) {
tab.setBounds(width-tabWidth,(height/2)-(tabHeight/2),tabWidth,tabHeight);
BufferedImage TabImage;
try{
if(tab.getComponentCount() == 0){
TabImage = ImageIO.read(new File(tabImagePath));
Image scaledUTab = TabImage.getScaledInstance(tabWidth, tabHeight, java.awt.Image.SCALE_SMOOTH);
JLabel uTabLabel = new JLabel(new ImageIcon(scaledUTab));
uTabLabel.setBounds(0, 0, tabWidth, tabHeight);
uTabLabel.setOpaque(false);
tab.add(uTabLabel);
}
}catch (IOException ex){
}
tab.setOpaque(false);
tab.setVisible(false);
}
|
3f8a5ca0-58e9-4b4c-b5e9-d3532da8ec0c
| 0
|
@Override
public void restoreCurrentToDefault() {cur = def;}
|
3e01ed67-2acc-4092-aa7c-622ca37f11da
| 8
|
public void updateGameSign() {
if (signLoc == null)
return;
if (EventHandle.callGameSignUpdateEvent(this, signLoc).isCancelled())
return;
Block block = null;
try {
block = plugin.getServer().getWorld(signLoc.getWorld().getName()).getBlockAt(signLoc);
} catch (NullPointerException e) {
EventHandle.callGameSignNotFoundEvent(this, signLoc);
signLoc = null;
return;
}
if (block.getState() instanceof Sign) {
Sign sign = (Sign) block.getState();
String l = sign.getLine(2);
int originalSize;
int originalMax;
try {
originalSize = Integer.parseInt(l.split("/")[0]);
originalMax = Integer.parseInt(l.split("/")[1]);
} catch (Exception e) {
return;
}
if (originalSize != playerlist.size()) {
sign.setLine(2, playerlist.size() + "/" + maxPlayers);
}
if (originalMax != playerlist.size()) {
sign.setLine(2, playerlist.size() + "/" + maxPlayers);
}
if (!sign.getLine(3).equalsIgnoreCase(getGameStage().toString())) {
sign.setLine(3, gamestage.toString());
}
sign.update();
} else {
EventHandle.callGameSignNotFoundEvent(this, signLoc);
signLoc = null;
return;
}
}
|
ccb920f7-d9d3-4f1e-be65-b4b277e9b09d
| 5
|
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (int p=0 ; p<listeGroupes.size() ; p++) {
Groupe groupe = listeGroupes.get(p);
// Liste des moyennes (par matières) pour ce groupe
float[] moyennesParMatieres = new float[20];
for (Integer numLigne : groupe.getItems()) {
// Affiche le numéro de l'étudiant
//s.append(numLigne);
for (int i=0 ; i< this.donnees.get(numLigne).size() ; i++) {
float f = this.donnees.get(numLigne).get(i);
//s.append(f).append("\t");
moyennesParMatieres[i] += f;
}
//s.append("\n");
}
// Termine le calcul des moyennes
s.append("Groupe ").append(p);
for (int i=0 ; i< moyennesParMatieres.length ; i++) {
String moy = String.valueOf(moyennesParMatieres[i] / groupe.getItems().size());
if (moy.length()>4) moy = moy.substring(0, 4);
s.append("\t").append(moy);
}
s.append(" ----------------------------------\n");
}
return s.toString();
}
|
00fc6dda-9346-43fe-bed2-cd4a073e017f
| 0
|
public MyTimer() {
setLayout(new GridLayout(3, 0, 0, 0));
JButton btnCountUp = new JButton("Count Up");
btnCountUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "MyTimerUp");
}
});
add(btnCountUp);
JButton btnCountDown = new JButton("Count Down");
btnCountDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "NotYet");
}
});
add(btnCountDown);
JButton btnBack = new JButton("Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainFrame.cardLayout.show(getParent(), "startScreen");
}
});
add(btnBack);
}
|
677a246f-c997-403b-b30e-6bab08d49835
| 4
|
public static void downloadfile(String DLURL, String DLDIR, String DLFILE) { //This downloads a mod given the url and the location/filename
String DLOC = DLDIR+DLFILE; //The dir to download to
new File(DLOC).getParentFile().mkdirs(); //Create parent dirs
System.out.println("URL: "+ DLURL);
System.out.println("FILE: "+ DLOC);
MIFU.modsDisplay.append(DLFILE+"\n");
MIFU.modsDisplay.setCaretPosition(MIFU.modsDisplay.getDocument().getLength());
try {
long startTime = System.currentTimeMillis();
System.out.println("Connecting..");
URL url = new URL(DLURL);
url.openConnection();
InputStream reader = url.openStream();
FileOutputStream writer = new FileOutputStream(DLOC);
byte[] buffer = new byte[153600];
int totalBytesRead = 0;
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
totalBytesRead += bytesRead;
}
long endTime = System.currentTimeMillis();
System.out.println("Downloaded: "+DLOC+ " " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).");
writer.close();
reader.close();
tries=0;
}catch (IOException e) {
e.printStackTrace();
MIFU.error.setText("Error downloading, Trying again...");
try {
Thread.sleep(5000);
MIFU.error.setText("");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tries++;
if(tries<3){
System.out.print("Trying to download again: "+tries);
downloadfile(DLURL,DLDIR,DLFILE);
}else{
System.out.println("Failed to download: "+DLOC);
MIFU.error.setText("Failed to download: "+DLOC);
}
}
}
|
7f842a4c-d667-488f-8e17-3a154defc422
| 0
|
protected void initialize() {
Robot.ledStrip.setColor(_red, _green, _blue);
}
|
461bfae7-009b-4714-9f65-4eb1d1bfe809
| 9
|
public static void main(String[] args) throws IOException {
String[] qps = {"22", "27", "32", "37"};
PsvdTest psvdTest = new PsvdTest(qps, args[0], args[1], args[2], args[3], args[4], args[5], args[6], new String("true"));
//make directories
psvdTest.makeDirectory("./common/bits");
psvdTest.makeDirectory("./common/yuv");
psvdTest.makeDirectory("./Cfg/h265");
psvdTest.makeDirectory("./Cfg/psvd");
psvdTest.makeDirectory("./Out/h265/log");
psvdTest.makeDirectory("./Out/h265/bits");
psvdTest.makeDirectory("./Out/h265/yuv");
psvdTest.makeDirectory("./Out/psvd/xml");
psvdTest.makeDirectory("./Out/psvd/log");
psvdTest.makeDirectory("./Out/psvd/bits");
psvdTest.makeDirectory("./Out/psvd/yuv");
psvdTest.makeDirectory("./Done");
// make cfg for h265 and psvd
psvdTest.mkCfg();
// prepare to make Xml
DomXmlDocument dxd = new DomXmlDocument();
// make encoder.xml
psvdTest.hmap.put("ResYuv", "common/yuv/"+psvdTest.seqName+"Residue.yuv");
dxd.createXmlFromTemplate("common/xml/encoder.xml", "./Out/psvd/xml/encoder.xml", psvdTest.hmap);
// encode
if (!(new File("./Done/encoder.done").exists())) {
PrintStream encoderOutLog = null;
try {
// redirect encoderOutLog
encoderOutLog = new PrintStream(new BufferedOutputStream(new FileOutputStream("Out/psvd/log/encoder.log")));
System.setOut(encoderOutLog);
// encode
Encoder.encode("Out/psvd/xml/encoder.xml");
DirMaker.createFile(new File("./Done/encoder.done"));
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
// close redirection
encoderOutLog.close();
System.setOut(System.out);
}
}
// File fileY = new File(psvdTest.seqName+psvdTest.diagBinFile+"Y.bin");
// File fileCb = new File(psvdTest.seqName+psvdTest.diagBinFile+"Cb.bin");
// File fileCr = new File(psvdTest.seqName+psvdTest.diagBinFile+"Cr.bin");
// long diagFileSize = fileY.length() + fileCb.length() + fileCb.length();
File diagDataFile = new File(psvdTest.seqName+psvdTest.diagDataFile);
long diagFileSize = diagDataFile.length();
// run h265 TAppEncoder.exe
for (String qp : qps) {
if (!(new File("./Done/h265Encoder"+qp+".done").exists())) {
Process h265EncoderProcess = runEXE("common/bin/TAppEncoder.exe -c common/cfg/encoder_randomaccess_main.cfg -c Cfg/h265/"+psvdTest.seqName+qp+".cfg");
// h265 TAppEncoder.exe log redirection
FileOutputStream h265Fos = new FileOutputStream("Out/h265/log/"+psvdTest.seqName+qp+".log");
ProcessStreamRedirect h265Redirect = new ProcessStreamRedirect(h265EncoderProcess.getInputStream(), "OUTPUT", h265Fos);
h265Redirect.start();
DirMaker.createFile(new File("./Done/h265Encoder"+qp+".done"));
}
}
for (String qp : qps) {
if (!(new File("./Done/psvdResidueEncoder"+qp+".done").exists())) {
// run psvd TAppEncoder.exe
System.setOut(null);
Process psvdEncoderProcess = runEXE("common/bin/TAppEncoder.exe -c common/cfg/encoder_randomaccess_main.cfg -c Cfg/psvd/"+psvdTest.seqName+"Residue"+qp+".cfg");
// psvd TAppEncoder.exe log redirection
FileOutputStream psvdFos = new FileOutputStream("Out/psvd/log/"+psvdTest.seqName+"Residue"+qp+".log");
ProcessStreamRedirect psvdRedirect = new ProcessStreamRedirect(psvdEncoderProcess.getInputStream(), "OUTPUT", psvdFos);
psvdRedirect.start();
try {
psvdEncoderProcess.waitFor();
DirMaker.createFile(new File("./Done/psvdResidueEncoder"+qp+".done"));
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
System.setOut(System.out);
}
// make decoder.xml
psvdTest.hmap.put("ResYuv", "Out/psvd/yuv/"+psvdTest.seqName+"Residue"+qp+"Rec.yuv");
psvdTest.hmap.put("DecYuv", "Out/psvd/yuv/"+psvdTest.seqName+""+qp+"Dec.yuv");
dxd.createXmlFromTemplate("common/xml/decoder.xml", "./Out/psvd/xml/decoder"+qp+".xml", psvdTest.hmap);
// decode
if (!(new File("./Done/decoder"+qp+".done").exists())) {
PrintStream decoderOutLog = null;
try {
// redirect decoderOutLog
decoderOutLog = new PrintStream(new BufferedOutputStream(new FileOutputStream("Out/psvd/log/decoder"+qp+".log")));
System.setOut(decoderOutLog);
// decode
Decoder.decode("Out/psvd/xml/decoder"+qp+".xml");
DirMaker.createFile(new File("./Done/decoder"+qp+".done"));
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
// close redirection
decoderOutLog.close();
System.setOut(System.out);
}
}
// make psnr.xml and calc psnr
File resFile = new File("Out/psvd/bits/"+psvdTest.seqName+"Residue"+qp+".bin");
long resFileSize = resFile.length();
psvdTest.hmap.put("TotalBytes", String.valueOf(diagFileSize+resFileSize));
dxd.createXmlFromTemplate("common/xml/psnr.xml", "./Out/psvd/xml/psnr"+qp+".xml", psvdTest.hmap);
// redirect decoderOutLog
PrintStream psnrOutLog = new PrintStream(new BufferedOutputStream(new FileOutputStream("Out/psvd/log/psnr"+qp+".log")));
System.setOut(psnrOutLog);
// calc psnr
PsnrCalculation.calcPsnr("Out/psvd/xml/psnr"+qp+".xml");
// close redirection
psnrOutLog.close();
System.setOut(System.out);
}
}
|
6740e8b7-79b9-4c5f-b838-2f911ba6ccf8
| 5
|
public static boolean isReservedLessThanOp(String candidate) {
int START_STATE = 0;
int TERMINAL_STATE = 1;
char next;
if (candidate.length()!=1){
return false;
}
int state = START_STATE;
for (int i = 0; i < candidate.length(); i++)
{
next = candidate.charAt(i);
switch (state)
{
case 0:
switch ( next )
{
case '<': state++; break;
default : state = -1;
}
break;
}
}
if ( state == TERMINAL_STATE )
return true;
else
return false;
}
|
6cd584ef-67e4-4dcc-9bc6-ba9d0bc2df1f
| 6
|
public void onPickupFromSlot(ItemStack par1ItemStack)
{
ModLoader.takenFromCrafting(this.thePlayer, par1ItemStack, this.craftMatrix);
ForgeHooks.onTakenFromCrafting(thePlayer, par1ItemStack, craftMatrix);
this.func_48434_c(par1ItemStack);
for (int var2 = 0; var2 < this.craftMatrix.getSizeInventory(); ++var2)
{
ItemStack var3 = this.craftMatrix.getStackInSlot(var2);
if (var3 != null)
{
this.craftMatrix.decrStackSize(var2, 1);
if (var3.getItem().hasContainerItem())
{
ItemStack var4 = new ItemStack(var3.getItem().getContainerItem());
if (!var3.getItem().doesContainerItemLeaveCraftingGrid(var3) || !this.thePlayer.inventory.addItemStackToInventory(var4))
{
if (this.craftMatrix.getStackInSlot(var2) == null)
{
this.craftMatrix.setInventorySlotContents(var2, var4);
}
else
{
this.thePlayer.dropPlayerItem(var4);
}
}
}
}
}
}
|
daa51778-4a11-4cae-91c4-b60f321b878e
| 9
|
public void handleInteraction(Automaton automaton,
AutomatonSimulator simulator, Configuration[] configs,
Object initialInput) {
JFrame frame = Universe.frameForEnvironment(environment);
// How many configurations have we had?
int numberGenerated = 0;
// When should the next warning be?
int warningGenerated = WARNING_STEP;
// How many have accepted?
int numberAccepted = 0;
while (configs.length > 0) {
numberGenerated += configs.length;
// Make sure we should continue.
if (numberGenerated >= warningGenerated) {
if (!confirmContinue(numberGenerated, frame))
return;
while (numberGenerated >= warningGenerated)
warningGenerated *= 2;
}
// Get the next batch of configurations.
ArrayList next = new ArrayList();
for (int i = 0; i < configs.length; i++) {
if (configs[i].isAccept()) {
numberAccepted++;
if (!reportConfiguration(configs[i], frame))
return;
} else {
next.addAll(simulator.stepConfiguration(configs[i]));
}
}
configs = (Configuration[]) next.toArray(new Configuration[0]);
}
if (numberAccepted == 0) {
JOptionPane.showMessageDialog(frame, "The input was rejected.");
return;
}
JOptionPane.showMessageDialog(frame, numberAccepted + " configuration"
+ (numberAccepted == 1 ? "" : "s")
+ " accepted, and\nother possibilities are exhausted.");
}
|
c8b7c707-426f-4e27-bf5e-1e6daa6e89fe
| 6
|
private void freeResources(Socket socket, InputStream in, OutputStream out) {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
|
ef404c0f-53e5-49fd-a04e-cfbe050fcad9
| 5
|
private void addButtonsListeners() {
btnAddPics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getSoundsPath(picsListModel);
}
});
btnAddSounds.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getPicturesPath(soundsListModel);
}
});
btnDelPics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (picsListModel.getSize() != 0)
{
imageInventoryList.remove(pics.getSelectedIndex());
String path = picsListModel.getElementAt(pics.getSelectedIndex());
deleteFile(path);
picsListModel.remove(pics.getSelectedIndex());
}
}
});
btnDelSounds.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (soundsListModel.getSize() != 0)
{
String path = soundsListModel.getElementAt(sounds.getSelectedIndex());
deleteFile(path);
soundInventoryList.remove(sounds.getSelectedIndex());
soundsListModel.remove(sounds.getSelectedIndex());
int size = listNarration.size();
listNarration = new ArrayList();
listNarration.add("Brak");
for(int i=1;i<size-1;i++)
{
listNarration.add(Integer.toString(i));
}
comboBoxNarration.removeAllItems();
comboBoxNarration.setModel(new DefaultComboBoxModel(listNarration.toArray()));
}
}
});
btnAddParagraph.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
paragraphInputDialog = new ParagraphInputDialog(paragraph);
paragraphInputDialog.addWindowListener(new WindowAdapter()
{
public void windowClosed(WindowEvent e) {
paragraph = paragraphInputDialog.getParagraph();
}
});
}
});
sounds.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = sounds.getSelectedIndex();
String selected = sounds.getSelectedValue();
createDialog(soundInventoryList, index);
}
}
});
pics.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = pics.getSelectedIndex();
String selected = pics.getSelectedValue();
createDialog(imageInventoryList, index);
}
}
});
}
|
ce488e1c-a75e-432c-9b26-4588e0a4fac0
| 0
|
public void addPeople(ArrayList<Villager> newPeople) {people.addAll(newPeople);}
|
c1830336-9558-4591-88f3-3ee5da92b7eb
| 0
|
@Override
public String toString() {
return "FUNCTION " + functionName + " " + startLineNumber + " "
+ endLineNumber;
}
|
76508097-9d34-4427-846d-a19c1c47c23d
| 9
|
public static void javaHelpOutputPrintStream(Stella_Object stream, Cons exps, boolean nativeWriterP, boolean endoflineP) {
if (stream == Stella.SYM_STELLA_JAVA_STANDARD_OUT) {
if ((Stella.string_getStellaClass("SYSTEM", false) != null) ||
Stella.inheritedClassNameConflictsP("SYSTEM")) {
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("java.lang.System.out");
}
else {
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("System.out");
}
}
else if (stream == Stella.SYM_STELLA_JAVA_STANDARD_ERROR) {
if ((Stella.string_getStellaClass("SYSTEM", false) != null) ||
Stella.inheritedClassNameConflictsP("SYSTEM")) {
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("java.lang.System.err");
}
else {
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("System.err");
}
}
else {
Stella_Object.javaOutputStatement(stream);
if (!nativeWriterP) {
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(".nativeWriter");
}
}
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(((endoflineP ? ".println(" : ".print(")));
Stella_Object.javaMaybeOutputStatementWithParentheses(exps.value);
{ Stella_Object e = null;
Cons iter000 = exps.rest;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
e = iter000.value;
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(" + ");
Stella_Object.javaMaybeOutputStatementWithParentheses(e);
}
}
((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(")");
}
|
fa3df9bd-afe8-4fe0-9fbd-3bf020046be5
| 0
|
public String getLocalhost() {
return localhost;
}
|
2ff46030-db6e-4273-97bc-c8006d88d207
| 9
|
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentLevel++;
currentElement = true;
currentValue = "";
String name = null;
if (localName != null && localName.length() != 0 && !elementsHandled.contains(localName)) {
name = localName;
}
else if (qName != null && qName.length() != 0 && !elementsHandled.contains(qName)) {
name = qName;
}
if(name != null)
{
if(currentObject == null)
{
String subclassName = Util.toUppercaseFirst(name);
currentObject = new XMLObject(packageName, subclassName, attributes);
}
else
{
String key = Util.getKey(name, currentLevel);
boolean isList = lists.containsKey(key) && lists.get(key);
currentObject.addField(name, attributes, isList);
}
}
}
|
2cca31a1-ae8d-49fc-ac67-e3981534025c
| 1
|
public void initAllCells() {
initCells();
initBorders();
initInsideFences();
initEnemies();
initPlayer(1);
if(p2) initPlayer(2);
}
|
4b5de6df-77e6-4620-afbb-b3703402c1fa
| 7
|
public HashMap<String, Multimap<String, Double>> call() throws Exception {
HashMap<String, Multimap<String, Double>> rt = new HashMap<String, Multimap<String, Double>>();
HypermodulesHeuristicAlgorithm ha = new HypermodulesHeuristicAlgorithm(this.stat, this.foregroundvariable, this.sampleValues, this.clinicalValues, this.network);
ha.initialize();
HashSet<String> allSeeds = new HashSet<String>();
for (int i=0; i<sampleValues.size(); i++){
if (!sampleValues.get(i)[1].equals("no_sample") && sampleValues.get(i)[1]!=null){
allSeeds.add(sampleValues.get(i)[0]);
}
}
HashSet<String> filteredSeeds = new HashSet<String>();
for (int i=0; i<network.size(); i++){
if (allSeeds.contains(network.get(i)[0])){
filteredSeeds.add(network.get(i)[0]);
}
if (allSeeds.contains(network.get(i)[1])){
filteredSeeds.add(network.get(i)[1]);
}
}
for (String runSeed : filteredSeeds){
Multimap<String, Double> oneResult = testSeed(ha, runSeed);
rt.put(runSeed, oneResult);
}
//System.out.println("finished running.");
return rt;
}
|
ab0441a4-8840-4c91-95e7-3087ee76e8cc
| 3
|
static double[][] multiply(double[][] A, double[][] B){
double[][] AB = new double[A.length][B[0].length];
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B[i].length; j++){
for(int k = 0; k < B.length ; k++){
AB[i][j] += A[i][k]*B[k][j];
}
}
}
return AB;
}
|
5da82cc1-43ac-40b3-a3aa-112cb5382992
| 1
|
private char[] charArrToUpperCase(char[] cArr) {
for (int i = 0; i < cArr.length; i++) {
cArr[i] = Character.toUpperCase(cArr[i]);
}
return cArr;
}
|
87a1a704-b89b-40f4-8cac-c031db5a749a
| 0
|
@Override
public void addPool(ITicketPool pool) {
throw new UnsupportedOperationException();
}
|
912c4741-e991-4091-9082-f0bd7507d25a
| 9
|
private static String[] tokenizeTransformation(String transformation)
throws NoSuchAlgorithmException {
if (transformation == null) {
throw new NoSuchAlgorithmException("No transformation given");
}
/*
* array containing the components of a Cipher transformation:
*
* index 0: algorithm component (e.g., DES)
* index 1: feedback component (e.g., CFB)
* index 2: padding component (e.g., PKCS5Padding)
*/
String[] parts = new String[3];
int count = 0;
StringTokenizer parser = new StringTokenizer(transformation, "/");
try {
while (parser.hasMoreTokens() && count < 3) {
parts[count++] = parser.nextToken().trim();
}
if (count == 0 || count == 2 || parser.hasMoreTokens()) {
throw new NoSuchAlgorithmException("Invalid transformation"
+ " format:" +
transformation);
}
} catch (NoSuchElementException e) {
throw new NoSuchAlgorithmException("Invalid transformation " +
"format:" + transformation);
}
if ((parts[0] == null) || (parts[0].length() == 0)) {
throw new NoSuchAlgorithmException("Invalid transformation:" +
"algorithm not specified-"
+ transformation);
}
return parts;
}
|
a6b52ec8-ff96-4642-a02b-24f53eaf69e3
| 7
|
public int[] getInts(int par1, int par2, int par3, int par4)
{
int ai[] = parent.getInts(par1 - 1, par2 - 1, par3 + 2, par4 + 2);
int ai1[] = IntCache.getIntCache(par3 * par4);
for (int i = 0; i < par4; i++)
{
for (int j = 0; j < par3; j++)
{
initChunkSeed(j + par1, i + par2);
int k = ai[j + 1 + (i + 1) * (par3 + 2)];
if (k == BiomeGenBase.swampland.biomeID && nextInt(6) == 0 || (k == BiomeGenBase.jungle.biomeID || k == BiomeGenBase.jungleHills.biomeID) && nextInt(8) == 0)
{
ai1[j + i * par3] = BiomeGenBase.river.biomeID;
}
else
{
ai1[j + i * par3] = k;
}
}
}
return ai1;
}
|
6cf564a5-fa39-4fc6-a014-27bbf618fbc0
| 9
|
public void addGateComponent(Component gateComponent) {
if (flowLayout) {
flowLayoutGatesPanel.add(gateComponent);
flowLayoutGatesPanel.revalidate();
flowLayoutGatesPanel.repaint();
}
else {
Component[] components = nullLayoutGatesPanel.getComponents();
for(int i=0; i<components.length; i++) {
Rectangle componentBounds = components[i].getBounds();
int x1 = (int)componentBounds.getX();
int y1 = (int)componentBounds.getY();
int x2 = (int)(componentBounds.getX() + componentBounds.getWidth() -1);
int y2 = (int)(componentBounds.getY() + componentBounds.getHeight() -1);
if(!(gateComponent.getY() > y2 || gateComponent.getX() > x2 ||
gateComponent.getY() + gateComponent.getHeight()-1 < y1 ||
gateComponent.getX() + gateComponent.getWidth()-1 < x1)) {
flowLayout = true;
if (currentAdditionalDisplay == null) {
nullLayoutGatesPanel.setVisible(false);
flowLayoutGatesPanel.setVisible(true);
}
for(i=0; i<components.length; i++)
flowLayoutGatesPanel.add(components[i]);
flowLayoutGatesPanel.add(gateComponent);
break;
}
}
if(!flowLayout) {
nullLayoutGatesPanel.add(gateComponent);
nullLayoutGatesPanel.revalidate();
nullLayoutGatesPanel.repaint();
}
}
}
|
d221401a-68ac-4279-9626-2447f91a5576
| 0
|
public String getDirFilterInclude() {
return this.dirFilterInclude;
}
|
32ecbc22-51d6-4755-9bd3-7a0b8cad4899
| 2
|
public BPTreeNodeItem getItem(int index){
if(getItemCount() > 0 && index < getItemCount())
return leafItems.get(index);
else
return null;
}
|
5d69e46b-629d-4d9e-a59e-b1255dcf7752
| 1
|
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces)
{
this.version = version;
this.access = access;
this.name = name;
this.signature = signature;
this.superName = superName;
if (interfaces != null) {
this.interfaces.addAll(Arrays.asList(interfaces));
}
}
|
118a9001-99ef-45f0-a8d4-0a59b342845e
| 9
|
* @param str the string to search for
* @param start the index to start at (0 is good)
* @return the index at which the search string was found in the string list, or -1
*/
private static int strIndex(final Vector<String> V, final String str, final int start)
{
if(str.indexOf(' ')<0)
return V.indexOf(str,start);
final List<String> V2=CMParms.parse(str);
if(V2.size()==0)
return -1;
int x=V.indexOf(V2.get(0),start);
boolean found=false;
while((x>=0)&&((x+V2.size())<=V.size())&&(!found))
{
found=true;
for(int v2=1;v2<V2.size();v2++)
{
if(!V.get(x+v2).equals(V2.get(v2)))
{
found=false;
break;
}
}
if(!found)
x=V.indexOf(V2.get(0),x+1);
}
if(found)
return x;
return -1;
}
|
a1bdfd2b-8366-467a-931b-3e00fb7167d7
| 3
|
public static int bin(int[] a, int from, int to,
int key) {
int left = from;
int right = to - 1;
while (left <= right) {
int mid = (left + right) >>> 1;
int mid1 = a[mid];
if (mid1 < key) {
left = mid + 1;
} else if (mid1 > key) {
right = mid - 1;
} else {
return mid;
}
}
return -(left + 1);
}
|
316407c8-34ce-493f-af32-6760ca33903f
| 1
|
public void testProperty() {
LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40, GJ_UTC);
assertEquals(test.year(), test.property(DateTimeFieldType.year()));
assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear()));
assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth()));
assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek()));
assertEquals(test.dayOfYear(), test.property(DateTimeFieldType.dayOfYear()));
assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear()));
assertEquals(test.weekyear(), test.property(DateTimeFieldType.weekyear()));
assertEquals(test.yearOfCentury(), test.property(DateTimeFieldType.yearOfCentury()));
assertEquals(test.yearOfEra(), test.property(DateTimeFieldType.yearOfEra()));
assertEquals(test.centuryOfEra(), test.property(DateTimeFieldType.centuryOfEra()));
assertEquals(test.era(), test.property(DateTimeFieldType.era()));
assertEquals(test.hourOfDay(), test.property(DateTimeFieldType.hourOfDay()));
assertEquals(test.minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour()));
assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute()));
assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond()));
assertEquals(test.millisOfDay(), test.property(DateTimeFieldType.millisOfDay()));
try {
test.property(null);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals(test, test.property(DateTimeFieldType.minuteOfDay()).getLocalDateTime());
}
|
a7519015-b659-4134-8b24-b19e7daa4d26
| 8
|
public void disconnect() {
if (state == CONNECTED) {
try {
mConnection.getOutputStream().write(Messages.disconnect());
// last_action = System.currentTimeMillis();
} catch (IOException e) {
if (DEBUG)
PApplet.println("Ohno! Something went wrong... IO Error, failed to send DISCONNECT message.");
if (DEBUG)
e.printStackTrace();
}
try {
mConnection.close();
} catch (IOException e) {
if (DEBUG)
PApplet.println("Ohno! Something went wrong... IO Error, failed to close the connection.");
if (DEBUG)
e.printStackTrace();
}
mMonitoringThread.stop();
mKeepaliveThread.stop();
state = DISCONNECTED;
} else {
if (DEBUG)
PApplet.println("Ohno! Something went wrong... MQTT Error, you gots to be connected dude!");
}
}
|
148f0ff2-4284-4bda-a8ae-04006e6bae4e
| 2
|
public Type getHint() {
int hint = possTypes & hintTypes;
if (hint == 0)
hint = possTypes;
int i = 0;
while ((hint & 1) == 0) {
hint >>= 1;
i++;
}
return simpleTypes[i];
}
|
369ff0a6-56dc-4ec2-b53e-09be30dc5a76
| 6
|
public void unpackDat(File outFolder) throws IOException {
log.trace("Unpacking dat file " + datFile.getPath() + " into " + outFolder.getPath());
byte[] buffer = new byte[4096];
int bytesRead;
outFolder.mkdirs();
for (Map.Entry<String, InnerFileInfo> entry : innerFilesMap.entrySet()) {
String innerPath = entry.getKey();
InnerFileInfo info = entry.getValue();
log.trace("Unpacking: " + innerPath + " ("+ info.dataSize +"b)");
File outFile = new File(outFolder, innerPath);
outFile.getParentFile().mkdirs();
InputStream in = null;
FileOutputStream out = null;
try {
in = getInputStream(innerPath);
out = new FileOutputStream(outFile);
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} finally {
try {if (in != null) in.close();}
catch (IOException e) {}
try {if (out != null) out.close();}
catch (IOException e) {}
}
}
}
|
3b7078ac-ab6e-495d-8b4b-2d5ffb8765a0
| 8
|
public Vector getObjects(String prefix,int cidmask,boolean suspended_obj,
JGRectangle bbox) {
Vector objects_v = new Vector(50,100);
int nr_obj=0;
JGRectangle obj_bbox = tmprect1;
int firstidx=getFirstObjectIndex(prefix);
int lastidx=getLastObjectIndex(prefix);
for (int i=firstidx; i<lastidx; i++) {
JGObject obj = (JGObject)objects.values[i];
if (cidmask==0 || (obj.colid&cidmask)!=0) {
if (suspended_obj || !obj.is_suspended) {
if (bbox!=null) {
if (!obj.getBBox(obj_bbox)) continue;
if (bbox.intersects(obj_bbox)) {
objects_v.addElement(obj);
}
} else {
objects_v.addElement(obj);
}
}
}
}
return objects_v;
}
|
9662dadb-7df2-4431-805b-7b3cf2cd36d9
| 4
|
@Test
public void test_addition() {
int m = 2;
int n = 3;
Matrix m1 = new MatrixList(m, n);
Matrix m2 = new MatrixList(m, n);
Matrix m3 = new MatrixList(m, n);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
m1.insert(i, j, (double) (2 * i + j));
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
m2.insert(i, j, (double) (i * i * j * j));
}
// m1:
// [
// [3.0, 4.0, 5.0],
// [5.0, 6.0, 7.0]
// ]
// m2:
// [
// [1.0, 4.0, 9.0],
// [4.0, 16.0, 36.0]
// ]
// Erwartetes Ergebnis:
// [
// [4.0, 8.0, 14.0],
// [9.0, 22.0, 43.0]
// ]
m3.insert(1, 1, 4.0);
m3.insert(1, 2, 8.0);
m3.insert(1, 3, 14.0);
m3.insert(2, 1, 9.0);
m3.insert(2, 2, 22.0);
m3.insert(2, 3, 43.0);
assertEquals(m1.add(m2), m3);
}
|
de14ee1c-6140-4925-badc-e63cf34abdc0
| 3
|
public Tex draw(int h, long scale) {
TexIM ret = new TexIM(new Coord(hist.length, h));
Graphics g = ret.graphics();
for(int i = 0; i < hist.length; i++) {
Frame f = hist[i];
if(f == null)
continue;
long a = 0;
for(int o = 0; o < f.prt.length; o++) {
long c = a + f.prt[o];
g.setColor(cols[o]);
g.drawLine(i, (int)(h - (a / scale)), i, (int)(h - (c / scale)));
a = c;
}
}
ret.update();
return(ret);
}
|
b766c285-e9cd-4532-9c69-1151c643183e
| 4
|
void paintOpacity(CPRect srcRect, CPRect dstRect, byte[] brush, int w, int alpha) {
int[] opacityData = opacityBuffer.data;
int by = srcRect.top;
for (int j = dstRect.top; j < dstRect.bottom; j++, by++) {
int srcOffset = srcRect.left + by * w;
int dstOffset = dstRect.left + j * width;
for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++) {
int brushAlpha = (brush[srcOffset] & 0xff) * alpha;
if (brushAlpha != 0) {
int opacityAlpha = opacityData[dstOffset];
if (brushAlpha > opacityAlpha) {
opacityData[dstOffset] = brushAlpha;
}
}
}
}
}
|
227b010a-ef0b-48b2-a69e-22a51ca78efd
| 2
|
public int getScore(int player) {
int score = 0;
for (int piece : boardArray) if (piece == player) score++;
return score;
}
|
32196411-65ee-453a-bd36-6e40e3c48f53
| 7
|
void createColorAndFontGroup () {
/* Create the group. */
colorGroup = new Group(controlGroup, SWT.NONE);
colorGroup.setLayout (new GridLayout (2, true));
colorGroup.setLayoutData (new GridData (SWT.FILL, SWT.FILL, false, false));
colorGroup.setText (ControlExample.getResourceString ("Colors"));
colorAndFontTable = new Table(colorGroup, SWT.BORDER | SWT.V_SCROLL);
colorAndFontTable.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
TableItem item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Foreground_Color"));
colorAndFontTable.setSelection(0);
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Background_Color"));
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Font"));
Button changeButton = new Button (colorGroup, SWT.PUSH);
changeButton.setText(ControlExample.getResourceString("Change"));
changeButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
Button defaultsButton = new Button (colorGroup, SWT.PUSH);
defaultsButton.setText(ControlExample.getResourceString("Defaults"));
defaultsButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
/* Add listeners to set/reset colors and fonts. */
colorDialog = new ColorDialog (shell);
fontDialog = new FontDialog (shell);
colorAndFontTable.addSelectionListener(new SelectionAdapter() {
public void widgetDefaultSelected(SelectionEvent event) {
changeFontOrColor (colorAndFontTable.getSelectionIndex());
}
});
changeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
changeFontOrColor (colorAndFontTable.getSelectionIndex());
}
});
defaultsButton.addSelectionListener(new SelectionAdapter () {
public void widgetSelected (SelectionEvent e) {
resetColorsAndFonts ();
}
});
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
if (foregroundColor != null) foregroundColor.dispose();
if (backgroundColor != null) backgroundColor.dispose();
if (font != null) font.dispose();
foregroundColor = null;
backgroundColor = null;
font = null;
if (colorAndFontTable != null && !colorAndFontTable.isDisposed()) {
TableItem [] items = colorAndFontTable.getItems();
for (int i = 0; i < items.length; i++) {
Image image = items[i].getImage();
if (image != null) image.dispose();
}
}
}
});
}
|
8ba04b45-19f1-46a4-9a2b-9f9c0fb1b006
| 5
|
private boolean CharClass()
{
begin("CharClass");
if (!next('[')
&& !next("^[")
) return reject();
if (next(']')) return reject();
do if (!Char()) return reject();
while (!next(']'));
Space();
sem.CharClass();
return accept();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.