method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
1e34b07c-ecb3-4dc0-87c1-89637e8e51a3 | 8 | public boolean removeLastOccurrence(Object o) {
checkNotNull(o);
for (;;) {
Node<E> s = trailer;
for (;;) {
Node<E> n = s.back();
if (s.isDeleted() || (n != null && n.successor() != s))
break; // restart if pred link is suspect.
if (n == null)
return false;
if (o.equals(n.element)) {
if (n.delete())
return true;
else
break; // restart if interference
}
s = n;
}
}
} |
d25f532b-08f1-4e28-9a8d-c9bc384cd0ca | 5 | public static Solucao VizinhoOneFlip(Solucao inicio){
for(Coluna col : inicio.getColunas()){
for(Integer colx : inicio.getLinhasX().keySet()){
if(col.getNome()!=inicio.getLinhasX().get(colx).getNome()){
Solucao testarsolucao = new Solucao(inicio);
removerLinhas(col, testarsolucao);
cobrirLinhas(col, testarsolucao);
ArrayList colunas = testarsolucao.getColunas();
colunas.remove(col);
testarsolucao.setColunas(colunas);
if(cobreTodas(inicio.getLinhasX().get(colx), testarsolucao)){
ArrayList novascolunas = testarsolucao.getColunas();
novascolunas.add(inicio.getLinhasX().get(colx));
testarsolucao.setColunas(novascolunas);
testarsolucao.setCustototal(testarsolucao.getCustototal()-col.getCusto()+inicio.getLinhasX().get(colx).getCusto());
String newstring = MOAVNS.transformaSolucao(testarsolucao);
//System.out.println(newstring);
if(!(MOAVNS.solucoes.contains(newstring))){
return testarsolucao;
}
else{
//System.out.println("repetido");
}
}
}
}
}
return inicio;
} |
cbd29b52-e5ed-4795-a597-7acc59740bb4 | 6 | private static String getValue(JSONTokener x) throws JSONException {
char c;
do {
c = x.next();
} while (c == ' ' || c == '\t');
switch (c) {
case 0:
return null;
case '"':
case '\'':
return x.nextString(c);
case ',':
x.back();
return "";
default:
x.back();
return x.nextTo(',');
}
} |
55a7af3b-70ac-4feb-a43e-b31af66a761f | 4 | public void setMap(String stageName)
{
if (stageName.equals("yoshi's house"))
{
map = new YoshiHouseStart(marioWorld);
}
if (stageName.equals("yoshi's house end"))
{
map = new YoshiHouseEnd(marioWorld);
}
if (stageName.equals("Waterfall World"))
{
map = new WaterFallStart(marioWorld);
}
if (stageName.equals("Goomba's garden"))
{
map = new GoombaGardenStart(marioWorld);
}
resetMap = true;
} |
4124768d-bee7-4857-ad1e-bcd93a905178 | 0 | public ExportSelectionFileMenuItem(FileProtocol protocol) {
setProtocol(protocol);
addActionListener(this);
} |
4d7afd4d-5379-4925-a5de-db414ecac27f | 8 | final public void PairExp() throws ParseException {/*@bgen(jjtree) PairExp */
SimpleNode jjtn000 = (SimpleNode)SimpleNode.jjtCreate(this, JJTPAIREXP);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
jj_consume_token(LEFTB);
Expression();
jj_consume_token(COMMA);
Expression();
jj_consume_token(RIGHTB);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
} |
176fefaf-d685-40d3-b6df-879f397cf359 | 2 | @Test
public void testCount() throws Exception
{
PersistenceManager persist = new PersistenceManager(driver, database, login, password);
persist.dropTable(Object.class);
ConnectionWrapper cw = persist.getConnectionWrapper();
// add a large number of entries
for (int x = 0; x < 200; x++)
{
SimplestObject so = new SimplestObject();
if(x>50)
{
so.setFoo((double) x);
}
persist.saveObject(cw, so);
}
cw.commitAndDiscard();
// make sure the right number of objects are returned
long count = persist.getCount(new SimplestObject());
assertEquals(200L, count);
// select half of the objects
SimplestObject selectObject = new SimplestObject();
selectObject.setFoo(99.0);
Greater g = new Greater(selectObject);
count = persist.getCount(SimplestObject.class, g);
assertEquals(100L, count);
Number n = persist.calculateAggregate(SimplestObject.class, new Count("getFoo"),new All());
assertEquals(149l,n);
persist.close();
} |
fc50b79b-9730-4555-abda-d5ea130a4b63 | 7 | @Override
public <N, T> QualifiedValue<T> getFirstQualifiedValue(TKey<N, T> key, Enum<?>... qualifiers) {
QualifiedValue<T> result = null;
List<QualifiedValue<?>> values = fields.get(key);
if (values != null && values.size() > 0) {
for (QualifiedValue<?> value : values) {
if (checkQualifier(value, qualifiers)) {
result = (QualifiedValue<T>) value;
break;
}
}
}
return result;
} |
7562dac8-f09e-4d7f-80ad-b1080064dd2d | 1 | private void endWritingTxt() {
try {
fw.close();
} catch (Exception e)
{
e.printStackTrace();
}
} |
f3b7e5e9-82bd-4630-9ba7-a70e1fafa730 | 5 | public boolean eliminarProceso(Proceso p) {
int prioridad = p.getPrioridadDinamica();
boolean elimino = this.listas[prioridad].remove(p);
if (elimino) {
this.numProcesos--;
if (this.numProcesos == 0) {
this.menorPrioridadNoVacia = 140;
} else {
if (this.listas[prioridad].size() == 0) {
for (int i = prioridad + 1; i < listas.length; i++) {
if (this.listas[i].size() != 0) {
this.menorPrioridadNoVacia = i;
break;
}
}
}
}
}
return elimino;
} |
4f6201ef-4da7-447e-bdb8-4c461369be09 | 4 | public ItemSet getSelectedItemSet() throws Exception {
if (this.cache==null) {
Iterator<HypertopicMap.Viewpoint.Topic> t =
this.selectedTopics.iterator();
if (t.hasNext()) {
HypertopicMap.Viewpoint.Topic topic = t.next();
this.cache = new ItemSet(topic);
while (t.hasNext()) {
topic = t.next();
this.cache.retainAll(
new ItemSet(topic)
);
}
} else {
this.cache = new ItemSet();
for (HypertopicMap.Corpus c : this.openedCorpora) {
this.cache.addAll(
new ItemSet(c)
);
}
}
}
return this.cache;
} |
bd57dd58-fabc-438f-bc33-7e34f1a64a22 | 1 | public void toXML (XMLWriter xmlWriter, int indent, boolean relative)
throws IOException {
xmlWriter.printXMLStartTag(byteVectorXMLTag, indent, relative, true);
xmlWriter.printXMLStartTag(lengthXMLTag, indentLength, true, false);
xmlWriter.print(Integer.toString(bytes.length));
xmlWriter.printXMLEndTag(lengthXMLTag);
for (int i = 0; i < bytes.length; i++) {
xmlWriter.printXMLStartTag(byteXMLTag, 0, true, false);
xmlWriter.print(Byte.toString(bytes[i]));
xmlWriter.printXMLEndTag(byteXMLTag);
}
xmlWriter.printXMLEndTag(byteVectorXMLTag, -indentLength, true);
} |
4212a497-b71f-4710-b75e-9b14a3266257 | 9 | public String longestPalindrome(String s) {
int n = s.length();
int maxLength = 0;
String maxString = "";
for (int i = 0; i < n; i++) {
int j = 0;
while (i - j >= 0 && i + j < n
&& s.charAt(i - j) == s.charAt(i + j)) {
if (j * 2 + 1 > maxLength) {
maxLength = j * 2 + 1;
maxString = s.substring(i - j, i + j + 1);
}
j++;
}
j = 0;
while (i - j >= 0 && i + 1 + j < n
&& s.charAt(i - j) == s.charAt(i + 1 + j)) {
if ((j + 1) * 2 > maxLength) {
maxLength = (j + 1) * 2;
maxString = s.substring(i - j, i + j + 2);
}
j++;
}
}
return maxString;
} |
6c728cec-4449-40e3-a998-634aeff5b33d | 4 | public boolean inRadius(int x, int y) {
int dx = (int) Math.abs(x - getWorldPosition().x);
int dy = (int) Math.abs(y - getWorldPosition().y);
if (dx > RADIUS || dy > RADIUS) return false;
if (dx + dy <= RADIUS
|| Math.pow(dx, 2) + Math.pow(dy, 2) <= Math.pow(RADIUS, 2)) return true;
return false;
} |
e3031e00-0a80-44dc-ac33-7d319fa9d2be | 4 | public DictionarySource() {
this.dictionaryWords = new LinkedList<>();
this.dictionaryWords.add("jetblue"); // supplementing dictionary for passing testing.
try (
InputStream dictStream = this.getClass().getResourceAsStream("american-english.txt");
BufferedReader dictReader = new BufferedReader(new InputStreamReader(dictStream));) {
String word;
while (true) {
word = dictReader.readLine();
if (word == null) {
break;
}
if (!word.isEmpty()) {
this.dictionaryWords.add(word.toLowerCase()); // making the dictionary all lower case for faster comparisons.
}
}
} catch (IOException ex) {
Logger.getLogger(DictionarySource.class.getName()).log(Level.SEVERE, null, ex);
}
} |
1a959edf-8fa1-4812-b017-7e73fa4de51d | 0 | @Override
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
} |
518cc2d4-a749-4568-a322-4dabd8fc8ac5 | 3 | public void paint(Graphics g){//Does all the paintings
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
if(inGame){
for(int i=0;i<grasList.size();i++){
Gras gras;
gras = (Gras) grasList.get(i);
Image image = imageLoader.getImageGras();
g2d.drawImage(image, gras.getxPos(), gras.getyPos(), 64, 64, this);
}
for(int i=0;i<stoneList.size();i++){
Stone stone;
stone = (Stone) stoneList.get(i);
Image image = imageLoader.getImageStone();
g2d.drawImage(image, stone.getxPos(), stone.getyPos(), 64, 64, this);
}
//draw Character
g2d.drawImage(imageLoader.getImageCharacter(character.getImageLine(), character.getImageRow()), WIDTH/2-64, HEIGHT/2-64, 128, 128, this);
//draw Character-Colliderbox
g2d.setColor(Color.RED);
g2d.drawRect(WIDTH/2-32+12, HEIGHT/2-32+24, 64-24, 64+6);
}
} |
d3ae0fbb-d8ee-48aa-9262-9f4c2ecf507a | 6 | protected T fetchContainingInterval(U queryPoint) {
Node<U, T> node = (Node<U, T>) binarySearchTree.getRoot();
while (node != null) {
if (node.getValue().contains(queryPoint)) {
return node.getValue();
}
Node<U, T> leftChild = node.getLeft();
node = node.getRight();
if (leftChild != null) {
int cmp = leftChild.getSubtreeSpanHigh().compareTo(queryPoint);
if (cmp > 0 || cmp == 0 && leftChild.isClosedOnSubtreeSpanHigh()) {
node = leftChild;
}
}
}
return null;
} |
ddaf1ff9-dcf8-44cf-9e56-c3375561185d | 2 | public static List<Laureate> filterByLongName(List<Laureate> inputList, List<String> ListOfTerms) {
List<Laureate> outputList = new ArrayList<Laureate>();
// parse input, keep what matchs the terms.
for (Laureate Awinner : inputList) {
if (ListOfTerms.contains(Awinner.getLongName())) {
outputList.add(Awinner);
}
}
return outputList;
} |
b092bb8d-ef42-4ba3-b90b-4801411edf10 | 5 | protected CachedEntry findSub(String key)
{
if(!key.startsWith(getKey()))
return null;
if(children != null)
{
for (int x = children.size() - 1; x >= 0; x--)
{
CachedEntry tmp = (CachedEntry) children.get(x);
if(key.startsWith(tmp.getKey()))
{
return tmp.findSub(key);
}
}
}
if(!getKey().startsWith(key))
return null;
return this;
} |
5bc15eb9-0355-424e-97aa-371e649a028b | 4 | public static String getFullPinName(String name, byte[] subBus) {
StringBuffer result = new StringBuffer(name);
if (subBus != null
&& !name.equals(CompositeGateClass.TRUE_NODE_INFO.name)
&& !name.equals(CompositeGateClass.FALSE_NODE_INFO.name)) {
result.append("[");
result.append(subBus[0]);
if (subBus[0] != subBus[1])
result.append(".." + subBus[1]);
result.append("]");
}
return result.toString();
} |
d8510d82-847b-4c18-8888-30b6de93b7bf | 7 | @Test
public void testCommon()
throws Exception
{
byte[] expectedZero = concat(new byte[1] /* magic placeholder */,
fragment(0, new byte[] { 0 }), new byte[] { -0x80, 0, 0, 0, 0, 1 });
byte[] expectedCommon = new byte[] { COMMON_MAGIC, 0, 0, 12, -0x80, 0, 0, 0, 0, 1 };
for (byte[] withOwnData : new byte[][] { ONE_TO_THIRTEEN, ZERO_TO_TWELVE })
{
for (int i = 0; i < 2; i++)
{
InputStream in1 = new ByteArrayInputStream(0 == i ? withOwnData : ONE_TO_TWELVE);
InputStream in2 = new ByteArrayInputStream(0 == i ? ONE_TO_TWELVE : withOwnData);
if (0 == i)
{
expectedZero[0] = REVERSE_MAGIC;
if (0 == withOwnData[0])
{
expectedCommon[1] = 1; // reverse offset in common sequence
expectedZero[1] = 0; // fragment offset in forward sequence
expectedZero[3] = 0; // value in forward sequence
}
else
{
expectedCommon[1] = 0; // reverse offset in common sequence
expectedZero[1] = 12; // fragment offset in forward sequence
expectedZero[3] = 13; // value in forward sequence
}
expectedCommon[2] = 0; // forward offset in common sequence
compare(in1, in2, expectedZero, 1L, EMPTY_FORWARD, 0L, expectedCommon);
}
else
{
expectedZero[0] = FORWARD_MAGIC;
expectedCommon[1] = 0; // reverse offset in common sequence
if (0 == withOwnData[0])
{
expectedCommon[2] = 1; // forward offset in common sequence
expectedZero[1] = 0; // fragment offset in forward sequence
expectedZero[3] = 0; // value in reverse sequence
}
else
{
expectedCommon[2] = 0; // forward offset in common sequence
expectedZero[1] = 12; // fragment offset in forward sequence
expectedZero[3] = 13; // value in reverse sequence
}
compare(in1, in2, EMPTY_REVERSE, 0L, expectedZero, 1L, expectedCommon);
}
resetDeltas();
}
}
} |
943925db-730b-453f-814d-510615ed836f | 7 | public static int[] primeList2(int maximum) {
boolean[] list = new boolean[maximum + 1];
int primes = 0;
for (int i = 2; i <= maximum; i++) {
list[i] = true;
}
list[0] = false;
list[1] = false;
double wurzel = Math.sqrt(maximum);
for (int i = 0; i <= maximum; i++) {
if (list[i] != false) {
primes++;
if (i <= wurzel) {
for (int j = i * 2; j <= maximum; j += i) {
list[j] = false;
}
}
}
}
int[] primelist = new int[primes];
int c = 0;
for (int i = 0; i <= maximum; i++) {
if (list[i]) {
primelist[c] = i;
c++;
}
}
return primelist;
} |
2615ccf1-f9c4-4545-92c8-4ae6c65bd26c | 5 | public void startGame() {
int round = 1;
boolean gameover = false;
while (!gameover) {
System.out.println("Runda " + round++);
for (int i = 0; i < playersCount && !gameover; i++) {
char randomLetter = buildRandomLetter();
players[i].addLetter(randomLetter);
System.out.println("Jucatorul " + (i + 1)
+ " a primit cartea: " + randomLetter + ": "
+ players[i].getWord());
if (players[i].isWinner(wordLength)) {
System.out
.println("==================== GAME OVER ========================");
System.out.println("Jucatorul " + (i + 1)
+ " a castigat. Cuvantul format: "
+ players[i].getWinningWord());
try {
System.out.println("Ratia: " + players[i].ratio());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gameover = true;
}
}
}
} |
62e9abba-01f3-4602-87a3-3b6108ae4dc1 | 7 | private void test(String testPath) throws IOException {
int hit = 0;
int total = 0;
BufferedReader scanner = null;
try {
scanner = new BufferedReader(new FileReader(new File(testPath))); //new Scanner(new File(testPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String path = null;
while ((path = scanner.readLine()) != null){
total += 1;
//String path = scanner.nextLine();
int result = 0;
try {
result = bayse(path);
} catch (IOException e) {
e.printStackTrace();
}
if(Pattern.matches("con.*", path) && result == 1){
hit++;
}else if(Pattern.matches("lib.*", path) && result == 0) {
hit++;
}
}
System.out.printf("Accuracy: %.04f", (hit * 1.0) / (total * 1.0));
} |
2752bc76-9d0a-491a-a2e7-96c05b03cca9 | 1 | @Override
public void windowClosing(java.awt.event.WindowEvent event) {
Object object = event.getSource();
if (object == MonitorConsole.this) {
System.exit(0);
}
} |
d32a4087-ba7f-44fd-b6a8-39577e681653 | 1 | private void deleteFile_fileManagerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteFile_fileManagerButtonActionPerformed
try {
selectedDevice.getFileSystem().delete(directoryLabel_fileManagerLabel.getText() + jList1.getSelectedValue());
} catch (IOException | DeleteFailedException ex) {
logger.log(Level.ERROR, "An error occurred while deleting a file (" + jList1.getSelectedValue() + ") on device " + selectedDevice.getSerial() + "\n"
+ "The error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
}
}//GEN-LAST:event_deleteFile_fileManagerButtonActionPerformed |
035699b6-337e-4fc3-b876-a66915f41e57 | 7 | @Override
public boolean equals(Object obj)
{
if (obj != null && obj instanceof MarketOrder)
{
MarketOrder other = (MarketOrder) obj;
if (other.response.equals(this.response) && other.account.equals(this.account))
{
for (Entry<OrderField, String> ent : map.entrySet())
{
if (!other.hasField(ent.getKey()) && !other.getField(ent.getKey()).equals(ent.getValue()))
{
return false;
}
}
return true;
}
}
return false;
} |
f60faa19-7011-4f32-8410-c83514692ee6 | 8 | private void deleteCase5(RBNode n) {
if (n == n.parent.left &&
nodeColor(n.sibling()) == NodeColor.BLACK &&
nodeColor(n.sibling().left) == NodeColor.RED &&
nodeColor(n.sibling().right) == NodeColor.BLACK)
{
n.sibling().color = NodeColor.RED;
n.sibling().left.color = NodeColor.BLACK;
rotateRight(n.sibling());
}
else if (n == n.parent.right &&
nodeColor(n.sibling()) == NodeColor.BLACK &&
nodeColor(n.sibling().right) == NodeColor.RED &&
nodeColor(n.sibling().left) == NodeColor.BLACK)
{
n.sibling().color = NodeColor.RED;
n.sibling().right.color = NodeColor.BLACK;
rotateLeft(n.sibling());
}
deleteCase6(n);
} |
3fe4fe70-16d0-43df-babe-995d64323dfe | 6 | private boolean transmit() {
FileInputStream fis = null;
try {
byte[] data = new byte[1024];
fis = new FileInputStream(file);
byte[] buf = new byte[512];
int i = 1;
while (fis.read(buf) != -1) {
if (!transmitPacket(buf, i)) {
return false;
}
i++;
}
if (fis.available() >= 0) {
data = new byte[fis.available()];
fis.read(data);
if (!transmitPacket(data, i)) {
return false;
}
fis.close();
return true;
}
} catch (FileNotFoundException ex) {
System.out.println("Fichier non trouvé");
fireErrorOccured("Fichier non trouvé");
} catch (IOException ex) {
System.out.println("Echec lecture du fichier");
fireErrorOccured("Echec lecture du fichier");
}
return false;
} |
f3af229d-41d6-4dbf-b292-7b23e0bceccf | 2 | protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
} |
c22c1335-9c97-4708-9cdd-d3ee41fc34ae | 6 | public void setConnectedState(final ConnectionState state) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
switch (state) {
case CONNECTED:
mntmConnect.setEnabled(false);
mntmDisconnect.setEnabled(true);
mntmDownloadData.setEnabled(true);
mntmEraseLogger.setEnabled(true);
mntmSettings.setEnabled(true);
mnSerialPort.setEnabled(false);
mntmUploadSelectionerases.setEnabled(true);
// os specific function
if (controller.os != OS.OTHER)
mntmFlashFirmware.setEnabled(true);
break;
case DISCONNECTED:
mntmConnect.setEnabled(true);
mntmDisconnect.setEnabled(false);
mntmDownloadData.setEnabled(false);
mntmEraseLogger.setEnabled(false);
mntmSettings.setEnabled(false);
mnSerialPort.setEnabled(true);
mntmUploadSelectionerases.setEnabled(false);
// os specific function
if (controller.os != OS.OTHER)
mntmFlashFirmware.setEnabled(true);
break;
case BUSY:
mntmConnect.setEnabled(false);
mntmDisconnect.setEnabled(false);
mntmDownloadData.setEnabled(false);
mntmEraseLogger.setEnabled(false);
mntmSettings.setEnabled(false);
mnSerialPort.setEnabled(false);
mntmUploadSelectionerases.setEnabled(false);
// os specific function
if (controller.os != OS.OTHER)
mntmFlashFirmware.setEnabled(false);
break;
}
}
});
} |
ee49caed-43f7-4dba-9200-ec325ea28ca5 | 3 | public String getName(String IP){
try {
resultSet = statement.executeQuery("SELECT name, status FROM "+Table+" WHERE IP ='"+IP+"'");
while(resultSet.next()){
System.out.println(resultSet.getString("name"));
if(resultSet.getString("status").equals("alive"))
break;
}
return resultSet.getString("name");
} catch (SQLException ex) {
return null;
}
} |
925f08ff-61f9-4abd-b333-72a16b2ac7e3 | 0 | @Override
public Integer save(T entity) throws DaoException {
waitCompete();
Integer id = getIdForNewEntity();
entity.setId(id);
getEntities().put(id, entity);
return id;
} |
ccad3fb6-a98b-44d2-8158-aa29e53829f6 | 0 | @Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
setEnabled(false);
addActionListener(this);
Outliner.documents.addDocumentRepositoryListener(this);
} |
e9bf4657-7a13-4cf0-a59a-9a5b8a65c3a9 | 1 | public static void nofailAssertTrue(boolean testExpression,
String message) {
if (!testExpression) {
System.out.println("Test expression not true\n" + message);
}
} |
5f86341b-4557-44ee-9fb6-6e774ba1dea6 | 3 | public void setSlotNumber(Tray tray) {
int slotNumber = -1;
List<Integer> numbers = new ArrayList<Integer>();
for (Tray t : this.trays) {
numbers.add(t.getSlotNumber());
}
Collections.sort(numbers);
for (Integer num : numbers) {
if (num > slotNumber + 1) {
tray.setSlotNumber(slotNumber + 1);
return;
}
slotNumber = num;
}
tray.setSlotNumber(slotNumber + 1);
} |
f0cc6d0f-59a1-472f-a469-e78e5f31e209 | 7 | @Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0 :
return Integer.class;
case 1 :
return String.class;
case 2 :
return String.class;
case 3 :
return String.class;
case 4 :
return Integer.class;
case 5 :
return String.class;
default:
return Object.class;
}
} |
60412eca-b181-45fa-a500-6100001ba78b | 0 | @Override
public String getMessageTextAsHTML() {
String msg = "";
msg += "<font color="+Constants.NOTIFICATION_COLOR+">";
msg += oldName + " " + settings.getLanguage().getLabel("text_rename") + " " + newName;
msg += "</font>";
return msg;
} |
4e82eb16-cf87-4f07-b464-c1bfe84d3520 | 9 | public void displayView()
{
myMainView = new JFrame();
myMainView.setSize(1150, 700);
myMainView.setTitle("Queue Simulation");
myMainView.setDefaultCloseOperation(EXIT_ON_CLOSE);
myMainView.setResizable(false);
myContainer = myMainView.getContentPane();
myUserInputView = new JFrame();
myUserInputView.setSize(400, 450);
myUserInputView.setTitle("Enter Queue Simulation Input");
myUserInputView.setDefaultCloseOperation(EXIT_ON_CLOSE);
myUserInputView.setVisible(false);
myUserInputView.setLayout(null);
myUserInputView.setResizable(false);
Container inputContainer = myUserInputView.getContentPane();
myQueuePanels = new SingleQueuePanel[5];
JLabel numberCustomersLabel = new JLabel("Enter the number of customers: ");
final JTextArea numberCustomersInput = new JTextArea("# customers");
numberCustomersLabel.setBounds(20, 20, 250, 25);
inputContainer.add(numberCustomersLabel);
inputContainer.add(numberCustomersInput);
numberCustomersInput.setBounds(230, 20, 100, 25);
JLabel numberQueuesLabel = new JLabel("Enter the number of queues: ");
String[] numberQueues = {"1", "2", "3", "4", "5"};
final JComboBox<String> numberQueuesList = new JComboBox<String>(numberQueues);
numberQueuesList.setBounds(210, 100, 100, 25);
numberQueuesLabel.setBounds(20, 100, 190, 25);
inputContainer.add(numberQueuesList);
inputContainer.add(numberQueuesLabel);
JLabel cashierServiceTimeLabel = new JLabel("Enter max time for cashier to serve: ");
final JTextArea cashierServiceTimeInput = new JTextArea("Time (ms)");
cashierServiceTimeLabel.setBounds(20, 180, 250, 25);
inputContainer.add(cashierServiceTimeLabel);
inputContainer.add(cashierServiceTimeInput);
cashierServiceTimeInput.setBounds(260, 180, 100, 25);
JLabel generationTimeLabel = new JLabel("Enter customer generation time: ");
final JTextArea generationTimeInput = new JTextArea("Time (ms)");
generationTimeLabel.setBounds(20, 280, 350, 25);
inputContainer.add(generationTimeLabel);
inputContainer.add(generationTimeInput);
generationTimeInput.setBounds(240, 280, 100, 25);
JButton startButton = new JButton("Start Simulation");
startButton.setBounds(130, 400, 150, 25);
inputContainer.add(startButton);
startButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
myUserInputView.setVisible(false);
try
{
int size = numberQueuesList.getSelectedIndex();
int custTime = Integer.parseInt(generationTimeInput.getText());
int cashTime = Integer.parseInt(cashierServiceTimeInput.getText());
int customers = Integer.parseInt(numberCustomersInput.getText());
for(int i = 5 ; i > (size + 1); i--)
{
myQueuePanels[i - 1].hideCashier();
}
myController.setQueueManager(size, custTime , cashTime , customers);
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog(null, "The simulation can not be started. Please double check \n"
+ "that you have entered only numerical values, thank-you.");
}
}
});
myCenterPanel = new JPanel();
myGridLayout = new GridLayout(0, 5);
myCenterPanel.setLayout(myGridLayout);
myContainer.add(myCenterPanel, BorderLayout.CENTER);
SimulationPanel bottomPanel = new SimulationPanel();
myContainer.add(bottomPanel, BorderLayout.SOUTH);
TitledBorder border;
border = BorderFactory.createTitledBorder("Quick Stats");
border.setTitleJustification(TitledBorder.CENTER);
border.setTitleColor(Color.black);
bottomPanel.setBorder(border);
myCashierInfoTextArea = new JTextArea();
myCashierInfoTextArea.setSize(50, 50);
myCashierInfoTextArea.setEditable(false);
myCashierInfoTextArea.setBackground(Color.black);
myCashierInfoTextArea.setForeground(Color.green);
myCashierInfoTextArea.setBorder(new LineBorder(Color.WHITE));
bottomPanel.add(myCashierInfoTextArea);
for(int i = 0; i < myQueuePanels.length; i++)
{
myQueuePanels[i] = new SingleQueuePanel();
myCenterPanel.add(myQueuePanels[i]);
myQueuePanels[i].start();
final int t = i;
myQueuePanels[i].getCashier().addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
switch(t)
{
case 0: displayCashierResults(0); break;
case 1: displayCashierResults(1); break;
case 2: displayCashierResults(2); break;
case 3: displayCashierResults(3); break;
case 4: displayCashierResults(4); break;
default: break;
}
}
});
}
myGeneralLineTextArea = new JTextArea();
myGeneralLineTextArea.setSize(50, 50);
myGeneralLineTextArea.setEditable(false);
myGeneralLineTextArea.setBackground(Color.black);
myGeneralLineTextArea.setForeground(Color.green);
myGeneralLineTextArea.setBorder(new LineBorder(Color.WHITE));
bottomPanel.add(myGeneralLineTextArea);
/*
* set custom fonts here
*/
try
{
Font myfont = Font.createFont(Font.TRUETYPE_FONT, new File("Resources/digital-7.ttf"));
myGeneralLineTextArea.setFont(myfont.deriveFont(18f));
myGeneralLineTextArea.setText("General Line Information");
myCashierInfoTextArea.setFont(myfont.deriveFont(18f));
border.setTitleFont(myfont.deriveFont(18f));
myCashierInfoTextArea.setText("Click On Cashier For Information");
inputContainer.setFont(myfont.deriveFont(35f));
numberCustomersLabel.setFont(myfont.deriveFont(15f));
numberQueuesLabel.setFont(myfont.deriveFont(15f));
cashierServiceTimeLabel.setFont(myfont.deriveFont(15f));
generationTimeLabel.setFont(myfont.deriveFont(15f));
startButton.setFont(myfont.deriveFont(15f));
}
catch (IOException|FontFormatException e)
{
e.getCause();
}
JButton runAll = new JButton();
runAll.setOpaque(false);
runAll.setBorderPainted(false);
runAll.setIcon(new ImageIcon("Resources/launch2.jpeg"));
bottomPanel.add(runAll);
runAll.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
myUserInputView.setVisible(true);
}
});
this.pack();
myMainView.setVisible(true);
} |
d03f5c2d-38f8-48c3-ab9a-1f9ca71980d7 | 7 | int clear(){
vb.clear();
vd.clear();
os.clear();
if(vi!=null&&links!=0){
for(int i=0; i<links; i++){
vi[i].clear();
vc[i].clear();
}
vi=null;
vc=null;
}
if(dataoffsets!=null)
dataoffsets=null;
if(pcmlengths!=null)
pcmlengths=null;
if(serialnos!=null)
serialnos=null;
if(offsets!=null)
offsets=null;
oy.clear();
return (0);
} |
26e104da-d680-4abc-b32d-d81853f14637 | 9 | private void checkForActivity() throws MqttException {
final String methodName = "checkForActivity";
if(this.isMyControll && connected && this.keepAlive > 0) { //
pingOutstanding = true;
lastPing = System.currentTimeMillis();;
MqttToken token = new MqttToken(clientComms.getClient().getClientId());
tokenStore.saveToken(token, pingCommand);
pendingFlows.insertElementAt(pingCommand, 0);
this.isMyControll=false;
return;
}
if (connected && this.keepAlive > 0) {
long time = System.currentTimeMillis();
if (!pingOutstanding) {
// Is a ping required?
if (time - lastOutboundActivity >= this.keepAlive ||
time - lastInboundActivity >= this.keepAlive) {
//@TRACE 620=ping needed. keepAlive={0} lastOutboundActivity={1} lastInboundActivity={2}
log.fine(className,methodName,"620", new Object[]{new Long(this.keepAlive),new Long(lastOutboundActivity),new Long(lastInboundActivity)});
pingOutstanding = true;
lastPing = time;
MqttToken token = new MqttToken(clientComms.getClient().getClientId());
tokenStore.saveToken(token, pingCommand);
pendingFlows.insertElementAt(pingCommand, 0);
}
} else if (time - lastPing >= this.keepAlive) {
// A ping is outstanding but no packet has been received in KA so connection is deemed broken
//@TRACE 619=Timed out as no activity, keepAlive={0} lastOutboundActivity={1} lastInboundActivity={2}
log.severe(className,methodName,"619", new Object[]{new Long(this.keepAlive),new Long(lastOutboundActivity),new Long(lastInboundActivity)});
// A ping has already been sent. At this point, assume that the
// broker has hung and the TCP layer hasn't noticed.
throw ExceptionHelper.createMqttException(MqttException.REASON_CODE_CLIENT_TIMEOUT);
}
}
} |
d4b32e6f-5511-484e-93fb-45bded86015c | 6 | @Override
public double unsafe_get(int row, int col) {
if( row == 0 ) {
if( col == 0 ) {
return a11;
} else if( col == 1 ) {
return a12;
}
} else if( row == 1 ) {
if( col == 0 ) {
return a21;
} else if( col == 1 ) {
return a22;
}
}
throw new IllegalArgumentException("Row and/or column out of range. "+row+" "+col);
} |
2ad5a80f-afce-47da-9a9e-b134bf95e363 | 7 | @EventHandler
public void killObj(EntityDeathEvent ev)
{
LivingEntity ent = ev.getEntity();
if(ent.getKiller() == null)return;
Player player = ent.getKiller();
PlayerQuestLog log = qm.getQuestLog(player.getName());
for(Quest q:log.getAssigned())
{
QuestData qd = log.getProgress(q);
for(Objective o:qd.getAssignedObjectives())
{
if(o.getType() != ObjectiveType.KILL)continue;
String prog = qd.getProgress(o.getID());
String targ = o.getTarget();
if(!ObjectiveType.KILL.isSimilarType(targ, prog))continue;
if(!ObjectiveType.KILL.getEntityType(targ).equals(ent.getType().name()))continue;
int p = ObjectiveType.KILL.getKills(prog) + 1;
int t = ObjectiveType.KILL.getKills(targ);
if(o.isVisible())player.sendMessage(ChatColor.GREEN + o.getName() + " (" + p + "/" + t + ")");
qd.setProgress(o.getID(), p + " " + ent.getType().name());
}
}
} |
c5329ae2-b9a7-4a2f-9120-3c7b546b4d13 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=false;
if(target.getStartRoom()==null)
{
int levelDiff=target.phyStats().level()-(mob.phyStats().level()+(2*getXLEVELLevel(mob)));
if(levelDiff<0)
levelDiff=0;
success=proficiencyCheck(mob,-(levelDiff*5),auto);
}
else
success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MASK_MOVE|somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> point(s) at <T-NAMESELF> and utter(s) a dismissive spell!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(msg.value()<=0)
{
if(target.getStartRoom()==null)
target.destroy();
else
{
mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> vanish(es) in dismissal!"));
target.getStartRoom().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> appear(s)!"));
target.getStartRoom().bringMobHere(target,false);
CMLib.commands().postLook(target,true);
}
mob.location().recoverRoomStats();
}
}
}
else
maliciousFizzle(mob,target,L("<S-NAME> point(s) at <T-NAMESELF> and utter(s) a dismissive but fizzled spell!"));
// return whether it worked
return success;
} |
c822d7ab-7909-4006-b720-e476690d31a2 | 9 | public static void main(String[] args) {
if (apiKey.isEmpty() || geckoOMeterWidgetKey.isEmpty() || lineChartWidgetKey.isEmpty()) {
System.out.println("Please add API and widget keys to the code example");
return;
}
GeckoboardTemplate template = new GeckoboardTemplate();
template.setApiKey(apiKey);
RestTemplate restOperations = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
MediaType textHtmlMediaType = new MediaType("text", "html");
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(textHtmlMediaType);
jsonMessageConverter.setSupportedMediaTypes(mediaTypes);
messageConverters.add(jsonMessageConverter);
restOperations.setMessageConverters(messageConverters);
template.setRestOperations(restOperations);
try {
template.pushToGeckOMeterWidget(geckoOMeterWidgetKey, 1, 20, "", 0, "");
System.out.println("Successfully pushed stats to Geck-O-Meter widget");
} catch (UnableToPushToWidgetException e) {
System.out.println(e.getMessage());
}
try {
List<Number> values = new LinkedList<Number>();
for (int i = 0; i < 10; i++)
values.add(i);
for (int i = 9; i > 0; i--)
values.add(i);
List<String> axysx = new LinkedList<String>();
axysx.add("00:00");
axysx.add("06:00");
axysx.add("12:00");
axysx.add("18:00");
axysx.add("00:00");
List<String> axysy = new LinkedList<String>();
axysy.add("Min");
axysx.add("Max");
template.pushToLineChartWidget(lineChartWidgetKey, values, axysx, axysy);
System.out.println("Successfully pushed stats to Line Chart widget");
} catch (UnableToPushToWidgetException e) {
System.out.println(e.getMessage());
}
} |
7a949b6d-3b03-4d54-8723-d27ad8c2ae7e | 4 | public boolean blockIsNotSafe(World world, double x, double y, double z) {
if (world.getBlockAt((int) Math.floor(x), (int) Math.floor(y - 1.0D),
(int) Math.floor(z)).getType() == Material.LAVA)
return true;
if (world.getBlockAt((int) Math.floor(x), (int) Math.floor(y - 1.0D),
(int) Math.floor(z)).getType() == Material.FIRE)
return true;
if ((world.getBlockAt((int) Math.floor(x), (int) Math.floor(y),
(int) Math.floor(z)).getType() != Material.AIR)
|| (world.getBlockAt((int) Math.floor(x),
(int) Math.floor(y + 1.0D), (int) Math.floor(z))
.getType() != Material.AIR)) {
return true;
}
return blockIsAboveAir(world, x, y, z);
} |
c0f09161-479e-424c-8b26-025e5d777761 | 5 | public boolean dialogueModelsCached(int gender) {
int head = maleDialogue;
int hat = maleHat;
if (gender == 1) {
head = femaleDialogue;
hat = femaleHat;
}
if (head == -1) {
return true;
}
boolean flag = true;
if (!Model.isCached(head)) {
flag = false;
}
if (hat != -1 && !Model.isCached(hat)) {
flag = false;
}
return flag;
} |
473d06a8-b3a0-4159-bb30-2a6b07394934 | 8 | public String toString(){
StringBuffer sb = new StringBuffer();
switch(type){
case TYPE_VALUE:
sb.append("VALUE(").append(value).append(")");
break;
case TYPE_LEFT_BRACE:
sb.append("LEFT BRACE({)");
break;
case TYPE_RIGHT_BRACE:
sb.append("RIGHT BRACE(})");
break;
case TYPE_LEFT_SQUARE:
sb.append("LEFT SQUARE([)");
break;
case TYPE_RIGHT_SQUARE:
sb.append("RIGHT SQUARE(])");
break;
case TYPE_COMMA:
sb.append("COMMA(,)");
break;
case TYPE_COLON:
sb.append("COLON(:)");
break;
case TYPE_EOF:
sb.append("END OF FILE");
break;
}
return sb.toString();
} |
565d587c-bf26-4f00-ab80-798b9c2e6f64 | 1 | public void addWarnMessage(String message) {
Document docs = textArea.getDocument();
SimpleAttributeSet attrSet = new SimpleAttributeSet();
StyleConstants.setForeground(attrSet, Color.ORANGE);
try {
docs.insertString(docs.getLength(), "\r\n" + lineNumber++ + ":【警告】"
+ message, attrSet);
} catch (BadLocationException e) {
e.printStackTrace();
}
textArea.setCaretPosition(docs.getLength());
} |
7b28ffa8-5fe3-4b14-b564-5c80beb6feeb | 5 | public void render(int xScroll, int yScroll, Renderer screen) {
screen.setOffset(xScroll, yScroll);
int x0, y0, x1, y1;
x0 = xScroll >> 4;
x1 = (xScroll + screen.width + 16) >> 4; //change to Sprite.SIZE in the future
y0 = yScroll >> 4;
y1 = (yScroll + screen.height + 16) >> 4; //change to Sprite.SIZE in the future
for (int y = y0; y < y1; y++) {
for (int x = x0; x < x1; x++) {
getTile(x, y).render(x, y, screen); //just for random level gen
}
}
for (int i = 0; i < entities.size(); i++) {
entities.get(i).render(screen);
}
for (int i = 0; i < projectiles.size(); i++) {
projectiles.get(i).render(screen);
}
for (int i = 0; i < players.size(); i++) {
players.get(i).render(screen);
}
} |
91e56ab9-6b1f-48fa-8845-e44e779fc7a2 | 5 | private void handleMouseMoveAt(int xCoord, int yCoord) {
final int tileSizeInPixels = ModelManager.getInstance().getTileSizeInPixels();
final int oldSelectedX = selectedX;
final int oldSelectedY = selectedY;
if (coordinateBounds(xCoord, yCoord)) {
selectedX = getTileXByAbsolutePixelX(xCoord, tileSizeInPixels);
selectedY = getTileYByAbsolutePixelY(yCoord, tileSizeInPixels);
if (oldSelectedX != selectedX || oldSelectedY != selectedY) {
repaintTile(selectedX, selectedY);
repaintTile(oldSelectedX, oldSelectedY);
}
}
else {
selectedX = -1;
selectedY = -1;
if (oldSelectedX != selectedX || oldSelectedY != selectedY)
repaintTile(oldSelectedX, oldSelectedY);
}
} |
11301768-c656-4a8f-a27a-f8d7a0e6795c | 0 | public Bid(String amount, Account Buyer) {
amountInt = amount;
buyerInt = Buyer;
} |
5bfab84e-fc64-47eb-a846-54e17d1f5e98 | 0 | public StrungDocumentInfo(
String someString,
DocumentInfo someDocInfo
){
docInfo = someDocInfo;
string = someString;
} |
c7143486-e091-43ba-9259-fb54be2be2d2 | 4 | public void tableWrite(Prop p, StringBuilder sb1, StringBuilder sb2)
throws IOException {
switch (p) {
case single_Head:
sb1.append("<div id=\"wrap\"><div id=\"contents\"><h2>")
.append(nameArray[1].split("_\\(")[0])
.append(" 出演リスト</h2>");
sb2.append(
"<table border=\"1\" cellspacing=\"0\"><tr><th class\"genre\">ジャンル</th><th class\"year\">年</th><th>シリーズ名</th>")
.append("<th class\"title\">タイトル</th><th class\"name\"><a target=\"_blank\" href=\"http://ja.wikipedia.org/wiki/")
.append(nameArray[1]).append("\">")
.append(nameArray[1].split("_\\(")[0])
.append("</a></th></tr>");
break;
case double_Head:
sb1.append("<div id=\"wrap\"><div id=\"contents\"><h2>")
.append(nameArray[1].split("_\\(")[0]).append("&")
.append(nameArray[2].split("_\\(")[0])
.append(" 共演リスト</h2>");
sb2.append(
"<table border=\"1\" cellspacing=\"0\"><tr><th class=\"genre\">ジャンル</th><th class=\"year\">年</th>")
.append("<th class=\"as\">商品</th><th class=\"title\"colspan=\"2\">共演タイトル</th><th class\"name\">")
.append("<a target=\"_blank\" href=\"http://ja.wikipedia.org/wiki/")
.append(nameArray[1])
.append("\">")
.append(nameArray[1].split("_\\(")[0])
.append("</a></th><th class\"name\"><a target=\"_blank\" href=\"http://ja.wikipedia.org/wiki/")
.append(nameArray[2]).append("\">")
.append(nameArray[2].split("_\\(")[0])
.append("</a></th></tr>");
break;
case Middle:
sb2.append("<tr><th class\"genre\">種別</th>")
.append("<th class\"year\"></th><th class=\"as\">商品</th><th class\"title\">部分一致タイトル1 / ジャンル / 年</th>")
.append("<th class\"title\">部分一致タイトル2 / ジャンル / 年</th><th class\"name\"><a href=\"http://ja.wikipedia.org/wiki/")
.append(nameArray[1])
.append("\">")
.append(nameArray[1].split("_\\(")[0])
.append("</a></th><th class\"name\"><a target=\"_blank\" href=\"http://ja.wikipedia.org/wiki/")
.append(nameArray[2]).append("\">")
.append(nameArray[2].split("_\\(")[0])
.append("</a></th></tr>");
break;
case foot:
sb2.append("</table></div>");
break;
}
} |
18758d82-4038-4d9f-a1fe-3a16b2350f32 | 3 | private void TimeLeft(Player player) {
if (_currentPhase.equals(Phase.Registration)) {
if (_registeredPlayers.size() < 2) {
_initialRegistrationDate = new Date();
player.sendMessage("You need more then 1 player before the countdown will start");
}
long secondsRemains = secondsLeft(_initialRegistrationDate,
_registrationLength);
player.sendMessage(String
.format("There are '%d' remaining seconds till the next phase Begins",
secondsRemains));
} else if (_currentPhase.equals(Phase.Fighting)) {
long secondsRemains = secondsLeft(_initialFightDate, _fightLength);
player.sendMessage(String
.format("There are '%d' remain seconds till the end of the Hunger Games",
secondsRemains));
}
} |
ce7dae86-6970-4668-a73f-5b3881f8561e | 3 | private static boolean isWhitespace(Token t) {
if (t.isCharacter()) {
String data = t.asCharacter().getData();
// todo: this checks more than spec - "\t", "\n", "\f", "\r", " "
for (int i = 0; i < data.length(); i++) {
char c = data.charAt(i);
if (!StringUtil.isWhitespace(c))
return false;
}
return true;
}
return false;
} |
f92e9899-b12e-46fe-9ec8-08934b0b97e2 | 7 | private boolean isDragOk( final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt )
{ boolean ok = false;
// Get data flavors being dragged
java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors();
// See if any of the flavors are a file list
int i = 0;
while( !ok && i < flavors.length )
{
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
// Is the flavor a file list?
final DataFlavor curFlavor = flavors[i];
if( curFlavor.equals( java.awt.datatransfer.DataFlavor.javaFileListFlavor ) ||
curFlavor.isRepresentationClassReader()){
ok = true;
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
i++;
} // end while: through flavors
// If logging is enabled, show data flavors
if( out != null )
{ if( flavors.length == 0 )
log( out, "FileDrop: no data flavors." );
for( i = 0; i < flavors.length; i++ )
log( out, flavors[i].toString() );
} // end if: logging enabled
return ok;
} // end isDragOk |
f0959101-1bdc-47bf-ac86-58f565cadd40 | 5 | public final void update(Level level, int x, int y, int z, Random rand) {
if(rand.nextInt(4) == 0) {
if(!level.isLit(x, y, z)) {
level.setTile(x, y, z, Block.DIRT.id);
} else {
for(int var9 = 0; var9 < 4; ++var9) {
int var6 = x + rand.nextInt(3) - 1;
int var7 = y + rand.nextInt(5) - 3;
int var8 = z + rand.nextInt(3) - 1;
if(level.getTile(var6, var7, var8) == Block.DIRT.id && level.isLit(var6, var7, var8)) {
level.setTile(var6, var7, var8, Block.GRASS.id);
}
}
}
}
} |
03899935-e1e9-478b-b523-cf162889b00f | 2 | public final TLParser.elseIfStat_return elseIfStat() throws RecognitionException {
TLParser.elseIfStat_return retval = new TLParser.elseIfStat_return();
retval.start = input.LT(1);
Object root_0 = null;
Token Else67=null;
Token If68=null;
Token Do70=null;
TLParser.expression_return expression69 = null;
TLParser.block_return block71 = null;
Object Else67_tree=null;
Object If68_tree=null;
Object Do70_tree=null;
RewriteRuleTokenStream stream_Do=new RewriteRuleTokenStream(adaptor,"token Do");
RewriteRuleTokenStream stream_Else=new RewriteRuleTokenStream(adaptor,"token Else");
RewriteRuleTokenStream stream_If=new RewriteRuleTokenStream(adaptor,"token If");
RewriteRuleSubtreeStream stream_expression=new RewriteRuleSubtreeStream(adaptor,"rule expression");
RewriteRuleSubtreeStream stream_block=new RewriteRuleSubtreeStream(adaptor,"rule block");
try {
// src/grammar/TL.g:102:3: ( Else If expression Do block -> ^( EXP expression block ) )
// src/grammar/TL.g:102:6: Else If expression Do block
{
Else67=(Token)match(input,Else,FOLLOW_Else_in_elseIfStat668);
stream_Else.add(Else67);
If68=(Token)match(input,If,FOLLOW_If_in_elseIfStat670);
stream_If.add(If68);
pushFollow(FOLLOW_expression_in_elseIfStat672);
expression69=expression();
state._fsp--;
stream_expression.add(expression69.getTree());
Do70=(Token)match(input,Do,FOLLOW_Do_in_elseIfStat674);
stream_Do.add(Do70);
pushFollow(FOLLOW_block_in_elseIfStat676);
block71=block();
state._fsp--;
stream_block.add(block71.getTree());
// AST REWRITE
// elements: block, expression
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (Object)adaptor.nil();
// 102:34: -> ^( EXP expression block )
{
// src/grammar/TL.g:102:37: ^( EXP expression block )
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(EXP, "EXP"), root_1);
adaptor.addChild(root_1, stream_expression.nextTree());
adaptor.addChild(root_1, stream_block.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} |
32d9352e-7081-45cb-84a4-2761876ba428 | 3 | public final SymbolraetselASTParser.arith_return arith() throws RecognitionException {
SymbolraetselASTParser.arith_return retval = new SymbolraetselASTParser.arith_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token set2=null;
CommonTree set2_tree=null;
try {
// C:\\Users\\Florian\\Dropbox\\Git\\CI_WiSe2013-2014\\CI_Aufgabe3\\teil1\\symbolraetsel_AST_Normalisiert\\SymbolraetselAST.g:37:6: ( PLUS | MINUS )
// C:\\Users\\Florian\\Dropbox\\Git\\CI_WiSe2013-2014\\CI_Aufgabe3\\teil1\\symbolraetsel_AST_Normalisiert\\SymbolraetselAST.g:
{
root_0 = (CommonTree)adaptor.nil();
set2=(Token)input.LT(1);
if ( (input.LA(1)>=PLUS && input.LA(1)<=MINUS) ) {
input.consume();
adaptor.addChild(root_0, (CommonTree)adaptor.create(set2));
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} |
49133c57-f155-4f87-aa3a-9ca2c59e5eb1 | 2 | public boolean move(int dx, int dy) {
Cell destination = this.landlord.getGridPanel().getGrid()[this.x + dx][this.y
+ dy];
if (destination instanceof Fence) {
this.destroy(dx, dy);
return true;
}
this.x = landlord.getX() + dx;
this.y = landlord.getY() + dy;
destination.occupy((Mob<? extends Mob>) this);
this.landlord.occupy(null);
this.landlord = landlord.getGridPanel().getCell(this.x, this.y);
return true;
} |
c2550379-89ea-410e-bd92-b2a7b48bad88 | 8 | protected Class determineClass(String name) throws Exception {
Class result;
if (name.equals(Boolean.TYPE.getName()))
result = Boolean.TYPE;
else
if (name.equals(Byte.TYPE.getName()))
result = Byte.TYPE;
else
if (name.equals(Character.TYPE.getName()))
result = Character.TYPE;
else
if (name.equals(Double.TYPE.getName()))
result = Double.TYPE;
else
if (name.equals(Float.TYPE.getName()))
result = Float.TYPE;
else
if (name.equals(Integer.TYPE.getName()))
result = Integer.TYPE;
else
if (name.equals(Long.TYPE.getName()))
result = Long.TYPE;
else
if (name.equals(Short.TYPE.getName()))
result = Short.TYPE;
else
result = Class.forName(name);
return result;
} |
df25aa67-6b52-4df0-af5f-d3066a6e7ab2 | 8 | private void joinTokens(final CobolToken token) {
boolean codeToken = false;
CobolToken prevToken = null;
CobolType type = CobolType.UNDEFINED;
// Skips last (continuation), and comments and other non-code tokens.
int index = tokens.size() - 2;
while (index >= 0 && !codeToken) {
prevToken = tokens.get(index);
type = prevToken.getType();
if (type == CobolType.COMMENT || type == CobolType.NEW_PAGE || type == CobolType.SPECIAL_LINE) {
index--;
} else {
codeToken = true;
}
}
if (codeToken && type == token.getType()) {
// Delete last token (of type CobolType.CONTINUATION);
tokens.remove(tokens.size() - 1);
// Join two tokens.
int row = prevToken.getRow();
int col = prevToken.getCol();
String text = prevToken.getText();
String text2= token.getText();
if (type == CobolType.STRING) {
// Delete the initial quote/semiquote.
text2 = text2.substring(1);
}
CobolToken joinedToken = new CobolToken(row, col, text + text2, type);
tokens.set(index, joinedToken);
}
else {
// Source code is bad; just append the token.
tokens.add(token);
}
} |
8b52cc65-9ffa-43b5-9f59-652f6f42f2f8 | 2 | public static String checkFontSize(JTextPane pane)
{
AttributeSet attributes = pane.getInputAttributes();
if (attributes.isDefined(StyleConstants.FontSize))
{
return attributes.getAttribute(StyleConstants.FontSize).toString();
}
if (attributes.isDefined(CSS.Attribute.FONT_SIZE))
{
return attributes.getAttribute(CSS.Attribute.FONT_SIZE).toString();
}
return String.valueOf(pane.getFont().getSize());
} |
40f5075c-5198-411e-90c0-d7b495b175e3 | 4 | @Override
public String validateIntruction() {
if(getOperand(0) == null || getOperand(1) == null){
return "Has no operand";
}
if(this.position == null){
return "Choose position";
}
if(getNextUnit() == null){
return "Choose next unit";
}
return null;
} |
5fa5a445-7a8b-4f4a-8264-a07968c4e7e1 | 4 | public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
} |
ca486735-e357-48c8-be7d-67184937654d | 1 | public DataOut deleteData(int index){
if(listDataOut != null)
return listDataOut.remove(index);
else return null;
} |
b3d35e2b-0f66-4294-b3f5-ca7b8a67bf1b | 2 | public static MarketClockField getFieldFromAbbreviation(String a)
{
for (MarketClockField field : MarketClockField.values())
{
if (field.toString().equals(a))
{
return field;
}
}
return null;
} |
673a6d44-da9b-4aaf-ba7d-88da4ea3eca1 | 7 | private void initChildrens(ICPBrasilCertificate cert) {
if ((cert.getBasicConstraints() != null && !cert.getBasicConstraints().isCA()) || cert.getBasicConstraints() == null) {
return;
}
ICPBrasilCACertificate ca = (ICPBrasilCACertificate) cert;
try {
for (ICPBrasilCertificate c : ca.getChildren()) {
this.add(new CertificateTreeNode(c));
}
}
catch (SQLException ex) {
Logger.getLogger(CertificateTreeNode.class.getName()).log(Level.SEVERE, null, ex);
}
catch (CertificateException ex) {
Logger.getLogger(CertificateTreeNode.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(CertificateTreeNode.class.getName()).log(Level.SEVERE, null, ex);
}
} |
6255cec7-521e-4be5-9d87-f7c8aeefa654 | 4 | @Override
public Product readObject() throws IOException {
Product readObject = null ;
if(!connectionInStatus){
startInputConnection();
}
if(connectionInStatus){
try{
readObject = (Product)is.readObject();
}catch(EOFException ex){
return null;
} catch(ClassNotFoundException|IOException e ) {
e.printStackTrace();
}
}
return readObject;
} |
c95d7128-c9b0-4495-a6da-0f8d913d12cb | 3 | private static void generateNumber(int[] lotto) {
for (int i = 0; i < lotto.length; i++) {
lotto[i] = (int) (Math.random() * 45 + 1);
for (int j = 0; j < i; j++) {
if (lotto[i] == lotto[j]) {
i--;
break;
}
}
}
} |
c34dbba2-e0a1-40a8-856b-34542551ce0d | 4 | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PairNode pairNode = (PairNode) o;
return !(element != null ? !element.equals(pairNode.element) : pairNode.element != null);
} |
0c1cc192-7a53-4a88-85c8-006ea4da59d5 | 4 | public void setForecast(String name, int forecast) throws IOException {
if (!order.isCurrentPlayer(pm.getPlayerWithName(name))) {
pm.sendErrorPacket(name, "It is not your turn!", ErrorReason.NOT_YOUR_TURN);
return;
}
if (stats.allForecastsMade()) {
pm.sendErrorPacket(name, "All forecasts are already made!", ErrorReason.ALL_FORECASTS_MADE);
return;
}
if (forecast > stats.getCurrentRoundNo()) {
pm.sendErrorPacket(name, String.format("You can not make more than %d tricks this round!", stats.getCurrentRoundNo()), ErrorReason.TOO_MANY_FORECASTS);
return;
}
LOG.debug(String.format("%s tries to make %d tricks!", name, forecast));
log.addLine(String.format("%s tries to make %d tricks!", name, forecast));
PlayerInterface p = pm.getPlayerWithName(name);
stats.setForecast(p, stats.getCurrentRoundNo(), forecast);
order.advanceCurrentPlayer();
data.setActivePlayer(order.getCurrentPlayer());
if (stats.allForecastsMade()) {
LOG.info("All forecasts are made! Clearing table and setting new State...");
data.clearCardsOnTable();
data.setState(GameState.PLAYING);
}
pm.updateClients(data);
} |
810274d3-f5b4-4312-b194-9743e9109bae | 7 | public void menuSelected(MenuEvent arg0) {
// System.out.println("Selected menu items " + arg0);
for (Iterator i = menuItemHolder.iterator(); i.hasNext(); ) {
StructuredMenuItemHolder holder = (StructuredMenuItemHolder) i
.next();
Action action = holder.getAction();
boolean isEnabled = false;
JMenuItem menuItem = holder.getMenuItem();
if (holder.getEnabledListener() != null) {
try {
isEnabled = holder.getEnabledListener().isEnabled(
menuItem, action);
} catch (Exception e) {
Resources.getInstance().logException(e);
}
action.setEnabled(isEnabled);
// menuItem.setEnabled(isEnabled);
}
isEnabled = menuItem.isEnabled();
if (isEnabled && holder.getSelectionListener() != null) {
boolean selected = false;
try {
selected = holder.getSelectionListener().isSelected(
menuItem, action);
} catch (Exception e) {
Resources.getInstance().logException(e);
}
if (menuItem instanceof JCheckBoxMenuItem) {
JCheckBoxMenuItem checkItem = (JCheckBoxMenuItem) menuItem;
checkItem.setSelected(selected);
} else {
// Do icon change if not a check box menu!
setSelected(menuItem, selected);
}
}
}
} |
21b0dcba-a67c-4d89-b8e8-46d93bbc25e4 | 7 | private boolean displayPlayAgain(String message, boolean win) {
int reply = JOptionPane.showConfirmDialog(null, message, message,
JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
resetTimer();
Player playerOne;
Player playerTwo;
if (m_playerOneType.equals("Computer: Easy")) {
playerOne = new ConnectFourEasyComputerPlayer(
getGame()
.getPlayerName(
Game.PLAYER_ONE),
getPlayerOnePieceColour());
} else if (m_playerOneType.equals("Computer: Hard")) {
playerOne = new ConnectFourHardComputerPlayer(
getGame()
.getPlayerName(
Game.PLAYER_ONE),
getPlayerOnePieceColour());
} else {
playerOne = new HumanPlayer(
getGame()
.getPlayerName(
Game.PLAYER_ONE),
getPlayerOnePieceColour());
}
if (m_playerTwoType.equals("Computer: Easy")) {
playerTwo = new ConnectFourEasyComputerPlayer(
getGame()
.getPlayerName(
Game.PLAYER_TWO),
getPlayerTwoPieceColour());
} else if (m_playerTwoType.equals("Computer: Hard")) {
playerTwo = new ConnectFourHardComputerPlayer(
getGame()
.getPlayerName(
Game.PLAYER_TWO),
getPlayerTwoPieceColour());
} else {
playerTwo = new HumanPlayer(
getGame()
.getPlayerName(
Game.PLAYER_TWO),
getPlayerTwoPieceColour());
}
ConnectFourGame newGame = new ConnectFourGame(
playerOne, playerTwo);
setGame(newGame);
if(win && (getGame().getPlayerTurn() % TOTAL_PLAYERS
== PLAYER_ONE)) {
newGame.incrementTurn();
}
m_panel.updatePieces(getGame().getPieces());
m_panel.setCurrentPiece(new ConnectFourPiece(
getPlayerOnePieceColour()));
m_panel.refreshDisplay();
}
return reply == JOptionPane.YES_OPTION;
} |
6f9fda88-b626-4471-9864-481bec2eab58 | 1 | public Patron getPatron(int cardNumber) throws SQLException {
openPatronsDatabase();
PreparedStatement statement = patronsConnection.prepareStatement(
"SELECT * FROM Patrons WHERE CardNumber = ?");
statement.setInt(1, cardNumber);
ResultSet resultSet = statement.executeQuery();
Patron result;
if (resultSet.next()) {
result = new Patron(resultSet.getInt(1), resultSet.getString(2));
} else {
result = null;
}
resultSet.close();
statement.close();
closePatronsDatabase();
return result;
} |
31cc4a35-fed8-448f-8662-4c59676e2076 | 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(Environmental.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Environmental.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Environmental.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Environmental.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 Environmental().setVisible(true);
}
});
} |
60dc1908-32b0-46e2-adb6-77e5a5200468 | 3 | public static void encryptChallenge(byte[] challenge, String passwd) {
byte[] key = new byte[8];
for (int i = 0; i < 8 && i < passwd.length(); i++) {
key[i] = (byte)passwd.charAt(i);
}
DesCipher des = new DesCipher(key);
for (int j = 0; j < CHALLENGE_SIZE; j += 8)
des.encrypt(challenge, j, challenge, j);
} |
2948bde1-1530-4e1b-9c79-db441a3aff6f | 2 | private void checkValue()
{
if (mvalue > mmax)
mvalue = mmax;
if (mvalue < mmin)
mvalue = mmin;
} |
9403b955-124c-44c7-a017-0751b80ea592 | 3 | public static void find(String s, int i) {
// 保存上一次的字符串
String temp = s;
//判断是否符合要求
if (s.length() == n) {
count++;
System.out.print(s + " ");
if (count % 10 == 0)
System.out.println();
return;
}
//从寻找点开始循环,风之境地
for (int k =i; k < str.length(); k++) {
s = temp;
s += str.charAt(k);
find(s, k);
}
} |
7c52825a-0c33-41ed-9e61-589b219e02fe | 1 | public ArgSet fetchList() throws InputMismatchException {
if(!hasListArg()) {
throw new InputMismatchException("There are no list arguments to fetch from.");
} else {
String s = pop();
return new ArgSet(s.substring(1, s.length() - 1));
}
} |
d91cab25-f1c0-4ab6-bc05-55c9024d1927 | 6 | public static void assign_position(Vector<AlignmentTriplet> triplets) {
for (AlignmentTriplet triplet : triplets) {
FlaggableCharacterString stream = triplet.getInputstream();
int pos = 0;
for (int i = 0; i < stream.size(); i++) {
FlaggableCharacter c = stream.charAt(i);
if (c.isFlagged()) {
c.setPosition(0);
pos = 0;
} else {
if (c.getSymbol() == '<' && pos > 0) {
pos--;
}
c.setPosition(pos);
if (new IsLetterCondition().applies(c)) {
pos++;
}
}
}
}
} |
3eb1f14a-7041-4812-acec-dba965d17ca3 | 2 | private boolean validWordLength(String[] words, String word, int length)
throws IOException {
String firstWord = words[0].trim().toLowerCase();
if (firstWord.equals(word)) {
if (words.length == length) {
return true;
} else {
throw new IOException("begin need " + length + " arguments");
}
} else {
return false;
}
} |
ec6c9ad2-0d72-4462-bf3d-9f5bffe5df8b | 2 | @Override
public boolean getUserMatchesPassword(String username, String password) {
boolean userMatchesPassword = false;
// Find an user record in the entity bean User, passing a primary key of
// username.
User user = emgr.find(entity.User.class, username);
// Determine whether the user exists and matches the password
if (user != null && user.getPassword().equals(password)) {
userMatchesPassword = true;
}
return userMatchesPassword;
} |
74b34375-a26f-49ef-b126-1f3161f4fcde | 8 | @Override
public void run() {
do {
// Keep working on tasks
if(null != rateGuaranteedJob)
task = taskScheduler.nextTask(rateGuaranteedJob);
else
task = taskScheduler.nextTask();
if(null == task) {
addExclusiveJob(null);
}
if(task != null && !task.isComplete()) {
percentComplete = 0;
long size = task.getTaskWorkLoad();
try {
for(int i=1;i<=size;i++) {
Thread.sleep(1000);
percentComplete = 100 * i/(size);
}
task.setComplete();
}catch(InterruptedException ix) {
System.out.println(ix);
}
}
try {
Thread.sleep(200);
}catch(InterruptedException ix) {
ix.printStackTrace();
}
}while(true);
} |
58a86f4c-a703-4a91-86d2-e3035411a41e | 0 | @Override
public void mouseDragged(MouseEvent e) {
unprocessedEvents.add(e);
mouse = e.getPoint();
} |
3d92cb94-5039-49d5-99ea-1ea0f67518d1 | 7 | void prune(File[] files) {
int size = 0;
for(File file : files) {
if(file.isFile() && !file.getName().equals("FAT")) {
size += file.length();
}
}
int cnt = 0;
int limit = Globals.getCacheLimit();
while(size > limit && cnt < files.length) {
File current = files[cnt++];
if(current.isFile() && !current.getName().equals("FAT")) {
size -= current.length();
current.delete();
}
}
fileUse.set(size);
updateGUIDisk();
} |
9976f29b-f8a5-44e1-86d2-cb06bb0ad85d | 0 | public byte[] getPlainValue() {
return plainValue;
} |
7ccbc3b7-4581-40c9-9c2e-049c958b251e | 3 | static private String unicodeEncode(String word) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < word.length(); ++i) {
char ch = word.charAt(i);
if (ch >= '\u0080') {
String st = Integer.toHexString(0x10000 + (int) ch);
while (st.length() < 4) st = "0" + st;
buf.append("\\u").append(st.subSequence(1, 5));
} else {
buf.append(ch);
}
}
return buf.toString();
} |
a7ebe63b-4a1e-4030-8c66-5ac81296dc7a | 7 | public String format(long logid, Map<String, ValueGenerator> generators, Map<String, String> staticParams) {
StringBuffer sb = new StringBuffer();
for (String token: tokens) {
if (isPlaceholder(token)) {
String key = token.substring(2, token.length() - 2);
String param = null;
if (key.contains(":")) {
param = key.substring(key.indexOf(":") + 1);
key = key.substring(0, key.indexOf(":"));
}
ValueGenerator valueGenerator = generators != null ? generators.get(key) : null;
if (valueGenerator != null)
sb.append(valueGenerator.nextValue(logid, format, Collections.unmodifiableCollection(tokens), param));
else if (staticParams != null && staticParams.containsKey(key))
sb.append(staticParams.get(key));
else
sb.append(token);
} else {
sb.append(token);
}
}
return sb.toString();
} |
02465d33-ed2e-4c76-ab33-988e4fbf35bb | 7 | public int read(int width) throws IOException {
if (width == 0) {
return 0;
}
if (width < 0 || width > 32) {
throw new IOException("Bad read width.");
}
int result = 0;
while (width > 0) {
if (this.available == 0) {
this.unread = this.in.read();
if (this.unread < 0) {
throw new IOException("Attempt to read past end.");
}
this.available = 8;
}
int take = width;
if (take > this.available) {
take = this.available;
}
result |= ((this.unread >>> (this.available - take)) &
((1 << take) - 1)) << (width - take);
this.nrBits += take;
this.available -= take;
width -= take;
}
return result;
} |
a446cf7e-a8db-4791-8877-7870ad421cbd | 6 | public void addWorkshopToSchedule(Workshop w){
Workshop workshop = w;
for(int i = 0; i < data.length; i++){
if(data[i][0].equals(workshop.getTime())){
if(day == 1 && workshop.getDate().equals(conference.getStartDate())){
data[i][1] = w.getTitle();
}else if(day == 2 && workshop.getDate().equals(conference.getEndDate())){
data[i][1] = w.getTitle();
}
}
}
} |
bb1dc139-e161-483e-95a0-544f79e8077f | 6 | public final void setQuestion(Question question) {
String answerString = "";
ArrayList<String> order = new ArrayList<>();
order.add(question.getCorrectAnswer());
order.add(question.getOtherAnswers()[0]);
order.add(question.getOtherAnswers()[1]);
order.add(question.getOtherAnswers()[2]);
Collections.shuffle(order);
currentCorrectAnswer = order.indexOf(question.getCorrectAnswer());
currentQuestion = question;
for (int i = 0; i < 4; i++) {
String character = "";
switch (i) {
case 0:
character = "A) ";
break;
case 1:
character = "B) ";
break;
case 2:
character = "C) ";
break;
case 3:
character = "D) ";
break;
}
answerString += "<h1>" + character + order.get(i) + "</h1>";
}
panel.setBackground(Color.BLACK);
mainPanel.setText("<html><center>"
+ "<h2>Please choose the best response to the following question. </h2>"
+ "<p>" + question.getQuestion() + "</p>"
+ "</center><br>" + answerString + "</html>");
if(prefs.usingTimer()){
timer.startAndControlClock(timerLabel, prefs.getTimerDuration() + 1);
}
} |
71fb7c61-916d-4fac-a18e-6caf6d047f5b | 0 | public String getClientID() {
return clientID;
} |
778f124b-dc1c-4e83-8ba6-7ac8be81006b | 8 | public void itemStateChanged(ItemEvent e) {
if (e.getSource() == comboLaser1 || e.getSource() == comboLaser2){
if(("" + comboLaser1.getSelectedItem()).compareTo("Wavelength L1") != 0 && ("" + comboLaser2.getSelectedItem()).compareTo("Wavelength L2") != 0){
System.out.println("" + comboLaser1.getSelectedItem());
double[] firstValue;
double[] secondValue;
firstValue = FileManager.readValues(("" + comboLaser1.getSelectedItem()).replaceFirst(" nm", ".ml1"), 1);
secondValue = FileManager.readValues(("" + comboLaser2.getSelectedItem()).replaceFirst(" nm", ".ml2"), 2);
for(int l = 0; l < 11; l++){
calibrationLaser1[l] = firstValue[l];
calibrationLaser2[l] = secondValue[l];
}
calculation.setCurve(firstValue, secondValue);
labelTotalPower.setText("Puissance totale actuelle : " + calculation.computePower(sliderLaser1.getValue(), sliderLaser2.getValue()) + " mW");
if (calculation.computePower(valueSliderLaser1,valueSliderLaser2) > 250 && calculation.computePower(valueSliderLaser1,valueSliderLaser2) < 300){
labelIcon.setIcon(new ImageIcon(getClass().getResource("/images/danger.png" )));
labelIcon.setVisible(true);
}
else if (calculation.computePower(valueSliderLaser1,valueSliderLaser2) >= 300){
labelIcon.setIcon(new ImageIcon(getClass().getResource("/images/erreur.png" )));
labelIcon.setVisible(true);
}
else{
labelIcon.setVisible(false);
}
calibrationMemorised = true;
sliderLaser1.setVisible(true);
sliderLaser2.setVisible(true);
labelSliderLaser1.setVisible(true);
labelSliderLaser2.setVisible(true);
labelPointNumber.setVisible(true);
buttonAdd.setVisible(true);
buttonRemove.setVisible(true);
buttonRemoveAll.setVisible(true);
updateConsole();
}
else{
calibrationMemorised = false;
sliderLaser1.setVisible(false);
sliderLaser2.setVisible(false);
labelSliderLaser1.setVisible(false);
labelSliderLaser2.setVisible(false);
labelPointNumber.setVisible(false);
buttonAdd.setVisible(false);
buttonRemove.setVisible(false);
buttonRemoveAll.setVisible(false);
buttonLaunch.setVisible(false);
}
}
updateBackup();
} |
0b2b9602-3aeb-46f2-9d9e-9184c6b95469 | 6 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Answer)) return false;
Answer answer = (Answer) o;
if (isCorrect != null ? !isCorrect.equals(answer.isCorrect) : answer.isCorrect != null) return false;
if (text != null ? !text.equals(answer.text) : answer.text != null) return false;
return true;
} |
43da328c-31c9-47ad-9f2c-036b93ac89e8 | 2 | private static void printWords(Map<String, List<GridPosition>> foundWords) {
Set<String> words = foundWords.keySet();
for ( String word : words) {
List<GridPosition> path = foundWords.get(word);
StringBuilder sb = new StringBuilder();
for ( GridPosition position : path){
sb.append(position.toString());
}
System.out.println("Found Word: " + word + " : " + sb.toString());
}
} |
3d5de7c2-d008-44ed-8407-3951d3856e09 | 2 | @Override
public Cible postCible(Cible c) throws JSONException, BadResponseException {
Representation r = new JsonRepresentation(c.toJSON());
r = serv.postResource("intervention/" + interId + "/cible", c.getUniqueID(), r);
Cible cible = null;
try {
cible = new Cible(new JsonRepresentation(r).getJsonObject());
} catch (InvalidJSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cible;
} |
a14296d8-6c00-44a9-9a9c-070a238c18d6 | 4 | public void start()
{
worker = new Thread()
{
// necessary to count frames per secound
long fpsCounter = 0;
long timeCounter = 0;
@Override
public void run()
{
while (!this.isInterrupted())
{
long t = System.currentTimeMillis();
pModel.getPhysicsEngine2D().calculateNextFrame( deltaTime / 1000d );
// real time that the calculation needed
long diffTime = System.currentTimeMillis() - t;
DebugMonitor.getInstance().updateMessage("calc", "" + diffTime);
finishedCallback.done();
// calculation time + repaint time (repaint will now use
// another thread, so it does not matter anymore here)
diffTime = System.currentTimeMillis() - t;
try
{
// don't waste cpu power, so sleep rest of the time
Thread.sleep(diffTime < deltaTime ? deltaTime - diffTime : 0);
}
catch (InterruptedException e)
{
// may occur, but should not be a problem, we just ignore it
//e.printStackTrace();
// finally we need to set the interrupt flag again, because
// it was rejected by the exception
this.interrupt();
}
fpsCounter++;
if (System.currentTimeMillis() >= timeCounter)
{
timeCounter = System.currentTimeMillis() + 1000;
DebugMonitor.getInstance().updateMessage("FPS", "" + fpsCounter);
fpsCounter = 0;
}
DebugMonitor.getInstance().updateMessage("all", "" + (System.currentTimeMillis() - t));
}
DebugMonitor.getInstance().updateMessage("FPS", "0");
}
};
worker.start();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.