method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
ed236bba-9bb3-47c8-8f86-ed07f202982f
| 7
|
public static int discrete(double[] a) {
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0.0)
throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries not equal to one: " + sum);
// the for loop may not return a value when both r is (nearly) 1.0 and
// when the
// cumulative sum is less than 1.0 (as a result of floating-point
// roundoff error)
while (true) {
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum > r)
return i;
}
}
}
|
7e4092aa-50ec-4169-9d5f-ef958c50fd96
| 8
|
public static int countNeighbours(boolean [][] world, int col, int row){
int total = 0;
total = getCell(world, col-1, row-1) ? total + 1 : total;
total = getCell(world, col , row-1) ? total + 1 : total;
total = getCell(world, col+1, row-1) ? total + 1 : total;
total = getCell(world, col-1, row ) ? total + 1 : total;
total = getCell(world, col+1, row ) ? total + 1 : total;
total = getCell(world, col-1, row+1) ? total + 1 : total;
total = getCell(world, col , row+1) ? total + 1 : total;
total = getCell(world, col+1, row+1) ? total + 1 : total;
return total;
}
|
59387f9e-526a-4e99-9e57-60914fae6d6d
| 6
|
protected void validateBySelector(DataSetReport report, List<Tuple> actual) {
for (int i = 0; i < actual.size(); i++) {
Tuple tuple = actual.get(i);
// -- create a list of the validators which can be applied to the current tuple
List<TupleValidator> applicableValidators = new ArrayList<TupleValidator>();
for (TupleValidator validator : tupleValidators) {
if (validator.isApplicable(tuple)) applicableValidators.add(validator);
}
// -- if more then one validator is applicable, we will fail the record since it smells like a user error
if (applicableValidators.size() > 1) {
TupleReport tupleReport = new TupleReport("#" + i);
// -- construct the message
StringBuilder msg = new StringBuilder();
msg.append("Multiple validators are applicable for this tuple: \n");
for (TupleValidator v : applicableValidators)
msg.append("\t- ").append(v).append("\n");
tupleReport.setMessage(msg.toString());
report.add(tupleReport);
} else if (applicableValidators.isEmpty()) {
TupleReport tupleReport = new TupleReport("#" + i);
tupleReport.setMessage("No validator could be found for the current record");
report.add(tupleReport);
} else {
report.add(applicableValidators.get(0).validate("#" + i, tuple));
}
}
}
|
19998279-fee8-46d3-b8f6-b5e28161afad
| 0
|
public void setCbSecteur(JComboBox cbSecteur) {
this.jComboBoxSecteur = cbSecteur;
}
|
9fcdb11a-f746-45cb-8869-c5add3c89383
| 5
|
public void edit(Fornecedor fornecedor) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
fornecedor = em.merge(fornecedor);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
String id = fornecedor.getCpf();
if (findFornecedor(id) == null) {
throw new NonexistentEntityException("The fornecedor with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
|
b0491029-2798-4ffe-99dd-a80ebb314a5c
| 3
|
private boolean shouldBlock(HttpRequest req) {
String uri = req.getUri();
for (Pattern blockPattern : blackList) {
if (blockPattern != null && blockPattern.matcher(uri).matches()) {
return true;
}
}
return false;
}
|
a946bcf7-e93d-4ac0-94a6-cb91d2dde5a2
| 2
|
private void paintEscudos(Graphics2D g2d){
for(Escudo e: escudos)
if(e.isVivo()) e.paint(g2d);
}
|
23dd25a7-b234-4813-b55b-e7974670c2b0
| 0
|
public Liste() {
listeMetadonnees = new ArrayList<Metadonnee>();
}
|
da9d2b34-fb09-4616-9c98-6a1104798a21
| 8
|
private ArrayList buildPredicates() throws Exception {
ArrayList predicates = new ArrayList(); /* The result. */
Predicate predicate;
Attribute attr;
Enumeration attributes = m_instances.enumerateAttributes();
boolean individual = (m_parts != null); /* Individual-based learning ? */
/* Attributes. */
while (attributes.hasMoreElements()) {
attr = (Attribute) attributes.nextElement();
/* Identifiers do not appear in rules in individual-based learning. */
if (!(individual && attr.name().equals("id"))) {
predicate = buildPredicate(m_instances, attr, false);
predicates.add(predicate);
}
}
/* Class attribute. */
attr = m_instances.classAttribute();
/* Identifiers do not appear in rules. */
if (!(individual && attr.name().equals("id"))) {
predicate = buildPredicate(m_instances, attr, true);
predicates.add(predicate);
}
/* Attributes of the parts in individual-based learning. */
if (individual) {
attributes = m_parts.enumerateAttributes();
while (attributes.hasMoreElements()) {
attr = (Attribute) attributes.nextElement();
/* Identifiers do not appear in rules. */
if (!attr.name().equals("id")) {
predicate = buildPredicate(m_parts, attr, false);
predicates.add(predicate);
}
}
}
return predicates;
}
|
4b6d73e8-2a32-48be-92d5-2dea1e262891
| 5
|
public Brick14(int gameAreaStartX, int gameAreaStartY, int brickSize, int brickIndex, BufferedImage brickImage)
{
super(brickSize, brickIndex, brickImage);
switch(brickIndex)
{
case 1:
this.row = 0;
this.column = 8;
this.relativeRow = 0;
this.relativeColumn = 0;
break;
case 2:
row = 0;
column = 9;
this.relativeRow = 0;
this.relativeColumn = 1;
break;
case 3:
row = 1;
column = 8;
this.relativeRow = 1;
this.relativeColumn = 0;
break;
case 4:
row = 1;
column = 9;
this.relativeRow = 1;
this.relativeColumn = 1;
break;
case 5:
row = 1;
column = 10;
this.relativeRow = 1;
this.relativeColumn = 2;
break;
}
this.x = gameAreaStartX + this.column*brickSize;
this.y = gameAreaStartY + this.row*brickSize;
}
|
b048e456-6680-4fc8-b0f5-05806043332f
| 6
|
public synchronized void register(Cancelable current, Cancelable parent) {
if (parent == null) {
TreeNode currentNode = findNodeInTaskTrees(current);
if (currentNode instanceof TreeNode) {
TreeNode currentParent = currentNode.getParent();
if (currentParent instanceof TreeNode) {
Tree.removeFromParentChildren(currentNode);
} else {
removeFromTaskTrees(currentNode);
}
addToTaskTrees(new Tree(current, currentNode.getChildren(), null));
} else {
addToTaskTrees(new Tree(current, new ArrayList(), null));
}
} else {
TreeNode parentNode = findNodeInTaskTrees(parent);
TreeNode currentNode = findNodeInTaskTrees(current);
Tree childNode;
if (currentNode instanceof TreeNode) {
childNode = new Tree(current, currentNode.getChildren(), parentNode);
TreeNode currentParent = currentNode.getParent();
if (currentParent instanceof TreeNode) {
Tree.removeFromParentChildren(currentNode);
} else {
removeFromTaskTrees(currentNode);
}
} else {
childNode = new Tree(current, new ArrayList(), parentNode);
}
if (parentNode instanceof TreeNode) {
parentNode.children.add(childNode);
} else {
addToTaskTrees(childNode);
}
}
}
|
1fe68887-ab79-44b0-b97e-f5034da4d3fa
| 1
|
public void incrementCount(Class animalClass)
{
Counter count = counters.get(animalClass);
if(count == null) {
// We do not have a counter for this species yet.
// Create one.
count = new Counter(animalClass.getName());
counters.put(animalClass, count);
}
count.increment();
}
|
9301aedd-6c4e-407d-b289-f686f9a11f86
| 8
|
public boolean equals( Object obj ){
if (this == obj){
return true;
}
if (obj == null){
return false;
}
if (obj instanceof Locomotive ){
Locomotive temp = (Locomotive) obj;
return ( this.engine.equals(temp.getEngine()))&&
( this.model.equals(temp.getModel() ))&&
( this.getComfortPercent() == temp.getComfortPercent())&&
( this.getHeight() == temp.getHeight() )&&
( this.getTonsWeight() == temp.getTonsWeight() )&&
( this.horsePowers == temp.getHorsePowers() );
} else {
return false;
}
}
|
456cae2f-def4-4d6b-a252-508d1daf4358
| 3
|
public EU2Country getController() {
int id = getId();
String sid = go.getString("id");
if (!scenario.provCanHaveOwner(id))
return null;
for (GenericObject c : scenario.countries)
if (c.getChild("controlledprovinces").contains(sid))
return scenario.getCountry(c.getString("tag"));
return null; //not found
}
|
4acd1838-26a7-44ab-863b-062ad610eb27
| 2
|
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), this);
for(int y = 0; y < 12; y++) {
for(int x = 0; x < 16; x++) {
g.drawImage(creationWindow.getImages()[creationWindow.getMatrix()[y][x]], x*caseSize + 150, y*caseSize + 100, caseSize, caseSize, this);
}
}
String test = String.valueOf(imageNb);
g.drawString(String.valueOf(imageNb), 120, 120);
}
|
f42e276c-3320-4ae8-a18a-e57ca5764bec
| 8
|
private boolean changeField(Object component, String text, String insert,
int movestart, int moveend, int start, int end) {
movestart = Math.max(0, Math.min(movestart, text.length()));
moveend = Math.max(0, Math.min(moveend, text.length()));
if ((insert == null) && (start == movestart) && (end == moveend)) {
return false;
}
if (insert != null) {
int min = Math.min(movestart, moveend);
set(component, "text", text.substring(0, min) + insert +
text.substring(Math.max(movestart, moveend)));
movestart = moveend = min + insert.length();
invoke(component, null, "action"); // deprecated
}
if (start != movestart) { setInteger(component, "start", movestart, 0); }
if (end != moveend) { setInteger(component, "end", moveend, 0); }
validate(component);
invoke(component, null, (insert != null) ?
((insert.length() > 0) ? "insert" : "remove") : "caret");
return true;
}
|
f9bf9304-f380-4d68-9b96-64a6763a76c2
| 5
|
public void setResult(String src, String tgt, String compare) {
if (compare == null) {
// simple move
board.movePiece(src, tgt);
board.updatePiece(tgt);
}
else if (compare.equals(">")) {
// the piece on the source position
// killed the piece on the target position
board.updatePiece(src, tgt, false);
board.deletePiece(tgt);
board.movePiece(src, tgt);
}
else if (compare.equals("<")) {
// the piece on the source position
// was killed by the piece on the target one
board.updatePiece(tgt, src, true);
board.deletePiece(src);
}
else if (compare.equals("=")) {
// both two pieces were killed
board.updatePiece(src, tgt);
board.deletePiece(src);
board.deletePiece(tgt);
}
else {
if (DEBUG) {
System.out.println("src:" + src);
System.out.println("tgt:" + tgt);
System.out.println("com:" + compare);
}
throw new IllegalArgumentException
("Invalid compare input!");
}
board.updateHQs();
}
|
e5fa47ab-6e12-4b1f-a986-4c693af654b2
| 9
|
public static boolean isPacketDropped(int x1, int y1, int x2, int y2)
{
double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
int probability = new Random().nextInt(100);
if (distance <= 80)
{
return false;
}
else if (distance <= 90)
{
if (probability < 20)
{
return true;
}
else
{
return false;
}
}
else if (distance <= 100)
{
if (probability < 40)
{
return true;
}
else
{
return false;
}
}
else if (distance <= 110)
{
if (probability < 60)
{
return true;
}
else
{
return false;
}
}
else if (distance < 120)
{
if (probability < 80)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
|
3cbb845b-ba7a-4021-aaa4-48621038eaca
| 5
|
public Grid(boolean isPlaceholder) {
// Make default background transparent
this.setOpaque(false);
if (isPlaceholder) {
visibleRows = 4; rows = 4; cols = 4;
insertion = new Point(-1, -1);
}
else {
visibleRows = 20; rows = 24; cols = 10;
insertion = new Point(5, 20);
}
this.setLayout(new GridLayout(visibleRows, cols));
gridCells = new GridCell[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
gridCells[i][j] = new GridCell(!isPlaceholder);
}
}
// Second for loop because GridLayout inserts left to right top to bottom, and we want left to right bottom to top
for (int i = rows - visibleRows; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
this.add(gridCells[rows - 1 - i][j]);
}
}
}
|
926e48d3-83e7-457d-9261-4a1b2d912201
| 3
|
public void run(String givenWord,String[] book){
for(String word:book){
word=word.toLowerCase();
if(word.trim()!=""){
if(!map.containsKey(word)){
map.put(word, 1);
}else{
map.put(word, map.get(word)+1);
}
}
}
}
|
ee72d41f-e713-4f84-b623-6e7d1a273239
| 9
|
public List<Quiz> getFilteredQuizzes()
{
List<Quiz> returnList = new ArrayList<Quiz>();
for(int i = 0; i < quizList.size(); i++)
{
if(filter == 1)
{
if(quizList.get(i).getUserId() == correspondingId)
returnList.add(quizList.get(i));
}
else if (filter == 2)
{
if(quizList.get(i).getUserId() < 0)
returnList.add(quizList.get(i));
}
else
returnList.add(quizList.get(i));
}
if(searchStr != null && !searchStr.trim().equals(""))
{
for(int i = 0; i < returnList.size(); i++)
{
if(!returnList.get(i).getTitle().trim().toLowerCase().contains(searchStr.trim().toLowerCase()))
{
returnList.remove(i);
i--;
}
}
}
return returnList;
}
|
eb33bade-e179-444e-9cc2-5445dc807fcc
| 6
|
public boolean setClassConstant(String clazzName) {
if (constant != null)
return false;
if (clazzName.charAt(0) == '[') {
if (clazzName.charAt(clazzName.length() - 1) == ';')
clazzName = clazzName.substring(0, clazzName.length() - 1);
if (fieldName.equals("array"
+ (clazzName.replace('[', '$').replace('.', '$')))) {
analyzedSynthetic();
return true;
}
} else {
if (fieldName.equals("class$" + clazzName.replace('.', '$'))
|| fieldName
.equals("class$L" + clazzName.replace('.', '$'))) {
analyzedSynthetic();
return true;
}
}
return false;
}
|
d5606aab-aad4-47e4-bedf-a3e33c9c39fc
| 1
|
static private int decodeDoubleSign(long longBits) {
final int signBit = (int) ((longBits >> 63) & 1L);
if (signBit == 0) {
return 1;
} else {
return -1;
}
}
|
57b5d9fc-cb57-4886-be6b-0698394cbc5d
| 8
|
@Override
public void paintComponent(final Graphics the_graphics)
{
super.paintComponent(the_graphics);
final Color clear = new Color(0, 0, 0, 0);
final Graphics2D g2d = (Graphics2D) the_graphics;
if (my_board.gameIsOver())
{
setBackground(Color.BLACK);
g2d.setPaint(NERV_RED);
final Font newfont = my_font.deriveFont(50f);
g2d.setFont(newfont);
g2d.drawString("Game Over", STRING_X, STRING_Y);
}
else if (my_paused.isPaused())
{
setBackground(Color.BLACK);
g2d.setPaint(NERV_RED);
final Font newfont = my_font.deriveFont(50f);
g2d.setFont(newfont);
g2d.drawString("Paused", STRING_X, STRING_Y);
}
else
{
setBackground(new Color(0, 0, 0, ALPHA));
paintFrozenBlocks(g2d, clear);
final MutablePiece piece = my_board.getCurrentPiece();
int[][] loc;
if (piece instanceof IPiece)
{
final IPiece ipiece = (IPiece) piece;
loc = ipiece.getBoardCoordinates();
g2d.setPaint(ipiece.getBlock().getColor());
}
else if (piece instanceof JPiece)
{
final JPiece jpiece = (JPiece) piece;
loc = jpiece.getBoardCoordinates();
g2d.setPaint(jpiece.getBlock().getColor());
}
else if (piece instanceof LPiece)
{
final LPiece lpiece = (LPiece) piece;
loc = lpiece.getBoardCoordinates();
g2d.setPaint(lpiece.getBlock().getColor());
}
else if (piece instanceof OPiece)
{
final OPiece opiece = (OPiece) piece;
loc = opiece.getBoardCoordinates();
g2d.setPaint(opiece.getBlock().getColor());
}
else if (piece instanceof SPiece)
{
final SPiece spiece = (SPiece) piece;
loc = spiece.getBoardCoordinates();
g2d.setPaint(spiece.getBlock().getColor());
}
else if (piece instanceof TPiece)
{
final TPiece tpiece = (TPiece) piece;
loc = tpiece.getBoardCoordinates();
g2d.setPaint(tpiece.getBlock().getColor());
}
else
{
final ZPiece zpiece = (ZPiece) piece;
loc = zpiece.getBoardCoordinates();
g2d.setPaint(zpiece.getBlock().getColor());
}
g2d.fill(new Rectangle2D.Double(loc[0][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[0][1] * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE));
g2d.fill(new Rectangle2D.Double(loc[1][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[1][1] * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE));
g2d.fill(new Rectangle2D.Double(loc[2][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[2][1] * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE));
g2d.fill(new Rectangle2D.Double(loc[INDEX_SIZE][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[INDEX_SIZE][1] * BLOCK_SIZE), BLOCK_SIZE,
BLOCK_SIZE));
g2d.setPaint(Color.BLACK);
g2d.draw(new Rectangle2D.Double(loc[0][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[0][1] * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE));
g2d.draw(new Rectangle2D.Double(loc[1][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[1][1] * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE));
g2d.draw(new Rectangle2D.Double(loc[2][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[2][1] * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE));
g2d.draw(new Rectangle2D.Double(loc[INDEX_SIZE][0] * BLOCK_SIZE, my_height - BLOCK_SIZE
- (loc[INDEX_SIZE][1] * BLOCK_SIZE), BLOCK_SIZE,
BLOCK_SIZE));
}
}
|
8926ec9d-85fb-4b07-b217-f83fc771e96f
| 9
|
public boolean camposobrigatoriospreenchidos() {
if (TfDescricao.getText().equals("")) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Digite a descrição do produto!");
TfDescricao.grabFocus();
return false;
}
if (!especproduto.getTipoproduto().isServico() && TfQtEstoqueMin.getValue() == BigDecimal.valueOf(0)) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Digite a quantidade mínima do estoque do produto!");
TfQtEstoqueMin.grabFocus();
return false;
}
if (CbTipoProduto.getSelectedItem() == null) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Selecione ou insira o tipo de produto deste produto!");
CbTipoProduto.grabFocus();
return false;
}
if (!especproduto.getTipoproduto().isServico() && TbProduto.getRowCount() == 0) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Selecione ou insira as características do produto!");
return false;
}
if (!especproduto.getTipoproduto().isServico() && TbProduto.getRowCount() != TbCarcteristica.getRowCount()) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Selecione ou insira todas as características do produto!");
return false;
}
if (TbFornecedoresProd.getRowCount() == 0) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Selecione ou insira o fornecedor do produto!");
return false;
}
return true;
}
|
44d76580-f487-4ec1-95e5-60e0a8735184
| 4
|
public void draw(Graphics2D g) {
g.drawImage(image, (int)x, (int)y, null);
if(x < 0) {
g.drawImage(image, (int)x + StatePanel.PWIDTH, (int)y, null);
}
if(x > 0) {
g.drawImage(image, (int)x - StatePanel.PWIDTH, (int)y, null);
}
if(y < 0) {
g.drawImage(image, (int)x, (int)y + StatePanel.PHEIGHT, null);
}
if(y > 0) {
g.drawImage(image, (int)x, (int)y - StatePanel.PHEIGHT, null);
}
}
|
81108306-02c7-45a9-9f05-83797c1b5c34
| 3
|
private char[] hashPassword(char[] password)
throws CharacterCodingException {
byte[] bytes = null;
char[] result = null;
String charSet = getProperty(PARAM_CHARSET);
bytes = Utility.convertCharArrayToByteArray(password, charSet);
if (md != null) {
synchronized (md) {
md.reset();
bytes = md.digest(bytes);
}
}
String encoding = getProperty(PARAM_ENCODING);
if (HEX.equalsIgnoreCase(encoding)) {
result = hexEncode(bytes);
} else if (BASE64.equalsIgnoreCase(encoding)) {
result = base64Encode(bytes).toCharArray();
} else { // no encoding specified
result = Utility.convertByteArrayToCharArray(bytes, charSet);
}
return result;
}
|
be948560-4c8d-4790-9e63-b69a51802361
| 2
|
private int incrementItem(String item, String storage) {
String[] split = storage.split(" ");
int count = 0;
for (String s : split) {
if (s.contains(item)) {
count++;
}
}
return count;
}
|
a73fdb62-4678-4ef1-a342-818ae538b427
| 1
|
private void loadTextures() {
String name = "";
for (GameButton button : buttons) {
name = button.getName();
this.name2texture.put(name, new Texture(Gdx.files.internal("model/flag/" + name + ".png")));
}
this.name2texture.put("background",new Texture(Gdx.files.internal("model/titleScreen.jpg")));
}
|
5bece080-537e-435d-8691-15d21cf022cd
| 4
|
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tm_development",
"root",
"shilpa");
System.out.println("Creating statement...");
try {
DatabaseMetaData dbm = conn.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbm.getTables(null, null, "%", types);
while(rs.next()){
String table = rs.getNString("TABLE_NAME");
System.out.println(table);
conn.close();
}
}
catch (Exception e){
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
|
06b8fa0f-5d0d-4d51-b5aa-f5f75fb0b090
| 5
|
@Test
public void testBinomialSequence()
{
final int numRuns = (int) 1e5;
final double[] testCases =
{
// 100, 0.5, //
// 250, 0.1, //
500, 0.05, //
// 100, 0.05, //
};
for (int test = 0; test < testCases.length / 2; ++test)
{
int size = (int) testCases[2 * test];
double prob = testCases[2 * test + 1];
final List<Integer> sizes = new ArrayList<Integer>();
// System.out.println("# --------------------------------------");
// System.out.println("#" + size + " " + prob);
for (int i = 0; i < numRuns; ++i)
{
final List<Long> list =
Sequences.binomialSequence(prob, size);
sizes.add(list.size());
for (final long elem : list)
{
Assert.assertTrue(0 <= elem && elem < size);
}
}
final int[] histogram = new int[size];
for (final Integer val : sizes)
{
++histogram[val];
}
// int ctr = 0;
// for (final int h : histogram)
// {
// System.out.println(++ctr + " " + h);
// }
}
}
|
f4c8ddb5-6155-451d-b19a-f350cd7d26ed
| 0
|
public byte[] getData() {
return data;
}
|
0c570b2f-d2c6-44fe-89c2-d50b93592353
| 3
|
public void setData(byte[] data) throws IllegalArgumentException
{
/* if (data == null)
data = new byte[0];
*/
if (data == null || data.length == 0)
throw new IllegalArgumentException("The data field in the " + frameType.getId() + " frame may not be empty.");
if (data.length > MAX_DATA_LENGTH)
throw new IllegalArgumentException("The data field in the " + frameType.getId() + " frame contains an invalid value. It must be < " + MAX_DATA_LENGTH + " bytes long.");
this.data = data;
this.dirty = true;
}
|
45b82f7d-f82d-4205-9ac5-229f6dc522f5
| 9
|
private void program(SmartBasicSubroutine subroutine) throws Exception {
while (scanner.currentLexeme != SourceLexemeType.FILE_END) {
if (scanner.currentLexeme == SourceLexemeType.ENDSUB) {
scanner.getNextLexeme();
if (subroutine.name.equals(SmartBasicProgram.MAIN_SUBROUTINE_NAME)) {
scanner.showErrorMessage("unexpected lexeme");
scanner.getNextLexeme();
} else {
if (!scanner.isEndingLexeme()) {
scanner.showErrorMessage("need end of line");
} else {
scanner.getNextLexeme();
}
return;
}
}
if (scanner.currentLexeme == SourceLexemeType.SUB) {
scanner.getNextLexeme();
if (scanner.currentLexeme != SourceLexemeType.IDENTIFIER) {
scanner.showErrorMessage("need subroutine name");
scanner.skipAllToTheEndOfLine();
} else {
String subName = scanner.currentString;
scanner.getNextLexeme();
if (!scanner.isEndingLexeme()) {
scanner.showErrorMessage("need end of line");
} else {
scanner.getNextLexeme();
}
SmartBasicSubroutine sub = new SmartBasicSubroutine();
sub.name = subName;
if (program.subroutines.containsKey(subName)) {
scanner.showErrorMessage("such subroutine already exists");
} else {
program.subroutines.put(subName, sub);
}
program(sub);
}
}
// TODO: if you have created methods for processing expressions then create methods for processing operators
}
if (!subroutine.name.equals(SmartBasicProgram.MAIN_SUBROUTINE_NAME)) {
scanner.showErrorMessage("unexpected end of file");
throw new Exception("fileend");
}
}
|
df8079f3-bc78-4870-a2d4-5ccc5eb5e80c
| 2
|
public void download() throws IOException {
HttpURLConnection httpConnect = null;
float totalDataRead;
BufferedInputStream bufferedIStream;
FileOutputStream fileOStream;
BufferedOutputStream bufferedOStream;
byte[] data = new byte[1024];
int i = 0;
try {
httpConnect = (HttpURLConnection)dlURL.openConnection();
fileSize = httpConnect.getContentLengthLong();
totalDataRead = 0;
bufferedIStream = new BufferedInputStream(httpConnect.getInputStream());
fileOStream = new FileOutputStream(dlPath);
bufferedOStream = new BufferedOutputStream(fileOStream, 1024);
// Download file
while ((i = bufferedIStream.read(data, 0, 1024)) >= 0) {
totalDataRead += i;
bufferedOStream.write(data, 0, i);
progress = (totalDataRead / fileSize) * 100;
for (DownloadProgressChangedEventListener evt : dlChangedEventList)
evt.onDownloadProgressChanged(
new DownloadProgressChangedEvent(this, dlPath, dlURL, (int)progress, fileSize, (long)totalDataRead));
}
} finally {
}
}
|
03667c2d-bb94-46ea-b5ef-026dec28158a
| 0
|
public int getNumberOfWins() {
return _wins;
}
|
bd554e71-fd24-4d8e-8d9a-9975a0d28967
| 9
|
public Queue<String> panzerXMLUnit (){
try {
path = new File(".").getCanonicalPath();
FileInputStream file =
new FileInputStream(new File(path + "/xml/papabicho.xml"));
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("************************************");
String expression01 = "/Units/Unit[@class='Panzer']";
NodeList nodeList;
Node node01 = (Node) xPath.compile(expression01)
.evaluate(xmlDocument, XPathConstants.NODE);
if(null != node01) {
nodeList = node01.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
System.out.println(nodeList.item(i).getNodeName()
+ " : " + nod.getFirstChild().getNodeValue());
list.append(nod.getFirstChild().getNodeValue());
}
}
}
System.out.println("************************************");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
}
|
5e065e10-f2a1-43dc-8c06-b81a7979b6d0
| 7
|
static final Class142_Sub27_Sub13 method1614(Class73 class73, boolean flag, int i, int j, Class73 class73_1) {
int ai[] = class73_1.method772((byte) -69, j);
boolean flag1 = true;
for (int k = 0; ai.length > k; k++) {
byte abyte0[] = class73_1.method799(ai[k], true, j);
if (abyte0 == null) {
flag1 = false;
} else {
int l = abyte0[1] & 0xff | abyte0[0] << 8 & 0xff00;
byte abyte1[];
if (flag) {
abyte1 = class73.method799(l, true, 0);
} else {
abyte1 = class73.method799(0, true, l);
}
if (abyte1 == null) {
flag1 = false;
}
}
}
if (!flag1) {
return null;
}
if (i <= 58) {
anIntArray3594 = null;
}
try {
return new Class142_Sub27_Sub13(class73_1, class73, j, flag);
} catch (Exception _ex) {
return null;
}
}
|
89c672a5-768c-4ab0-8d03-6e6aeef1e662
| 3
|
private Object readObjectFieldValue() throws IOException, JSONException {
Object value = this.readValue();
int c = this.skipWSRead();
if (c == JSON.VALUE_SEPARATOR || c == JSON.END_OBJECT) {
if (c == JSON.END_OBJECT)
this.unread(c);
return value;
}
else {
String message = String.format(this.bundle.getString("ILLEGAL_CHARACTER"), (char)c);
throw this.syntaxException(message);
}
}
|
e2d272a8-dac2-476f-9248-023c6673cce2
| 0
|
private static void createWindow(Serializable object) {
DIALOG.setVisible(false);
FrameFactory.createFrame(object);
}
|
f2dc7a31-f8c1-42d8-b707-2d7a6e39abfa
| 7
|
public static IFiniteAutomata getFiniteAutomataFromStringList(
List<String> list)
throws FailedToGetFiniteAutomataFromStringListException
{
if (list == null)
{
throw new IllegalArgumentException("Argument can't be null: list.");
}
int listSize = list.size();
if (listSize < 5)
{
throw new FailedToGetFiniteAutomataFromStringListException(
"Invalid list format: list must contain at least 5 items.");
}
IFiniteAutomata finiteAutomata = new FiniteAutomata();
try
{
finiteAutomata
.setAlphabetCardinality(Integer.parseInt(list.get(0)));
finiteAutomata.setStatesCardinality(Integer.parseInt(list.get(1)));
finiteAutomata.setInitialState(Integer.parseInt(list.get(2)));
String[] finiteStatesLine = list.get(3).split(" ");
// Ignore the first parameter - cardinality of the finiteStates set.
if (finiteStatesLine.length <= 1)
{
throw new FailedToGetFiniteAutomataFromStringListException(
"Finite automata must have at least one finite state.");
}
for (int i = 1, count = finiteStatesLine.length; i < count; i++)
{
finiteAutomata.addFiniteState(Integer
.parseInt(finiteStatesLine[i]));
}
for (int i = 4; i < listSize; i++)
{
String[] transitionLine = list.get(i).split(" ");
Transition transition = new Transition(
Integer.parseInt(transitionLine[0]),
transitionLine[1].charAt(0),
Integer.parseInt(transitionLine[2]));
finiteAutomata.addTransition(transition);
}
}
catch (FailedToGetFiniteAutomataFromStringListException exception)
{
throw exception;
}
catch (Exception exception)
{
throw new FailedToGetFiniteAutomataFromStringListException(
"Failed to get finite automata from list.", exception);
}
return finiteAutomata;
}
|
1a885f61-ebac-44e6-814c-42c5ed901b5a
| 0
|
public void removeVictim(int index) {
victims.remove(index);
}
|
053d37e4-1f37-4574-a3a8-c4f4cc9c193f
| 3
|
public List<LoginEntry> readLogins() {
List<LoginEntry> retList = new ArrayList<LoginEntry>();
try {
ResultSet rs = _sqLite.query("SELECT login.*, player.playername as playername FROM player, login "
+ "WHERE player.id = login.id_player "
+ "ORDER BY time_login DESC;");
while (rs.next()) {
try {
LoginEntry le = new LoginEntry(rs.getString("playername"),
rs.getString("time_login"),
rs.getInt("time_online"),
rs.getInt("blocks_placed"),
rs.getInt("blocks_broken"));
retList.add(le);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return retList;
}
|
cfc9066c-ed3d-4f04-a679-a8e96e60e10b
| 4
|
private void addToList(MainContainer main, int count)
{
switch(count){
case 0 : containersnul.add(main); break;
case 1 : containerseen.add(main);break;
case 2 : containerstwee.add(main); break;
case 3 : containersdrie.add(main); break;
}
}
|
86e921f6-9834-4604-8bcd-89f659d09fb6
| 8
|
public Object[][] listSeries() {
Logger.getLogger(BooksFolderAnalyser.class.getName()).entering(BooksFolderAnalyser.class.getName(), "listSeries");
try {
File[] allfiles = null;
if (booksDirectory == null || !booksDirectory.exists()) {
Logger.getLogger(BooksFolderAnalyser.class.getName()).exiting(BooksFolderAnalyser.class.getName(), "listSeries", null);
return null;
}
try {
allfiles = booksDirectory.listFiles((File pathname) -> {
return pathname.isDirectory() && !pathname.isHidden();
});
} catch(SecurityException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
new InfoInterface(InfoInterface.InfoLevel.ERROR, "rights", booksDirectory);
}
if (allfiles == null) {
Logger.getLogger(BooksFolderAnalyser.class.getName()).exiting(BooksFolderAnalyser.class.getName(), "listSeries", null);
return null;
}
Arrays.sort(allfiles);
final File[] allFilesValue = allfiles;
List<Object[]> series = new ArrayList<>();
for (int i = 0; allFilesValue.length > i; i++) {
File[] albumsFiles = new BooksFolderAnalyser(allFilesValue[i]).listAlbumsFiles();
if (albumsFiles != null) {
series.add(new Object[] {allFilesValue[i].getName(), albumsFiles.length});
}
}
Logger.getLogger(BooksFolderAnalyser.class.getName()).exiting(BooksFolderAnalyser.class.getName(), "listSeries", series.toArray(new Object[0][0]));
return series.toArray(new Object[0][0]);
} catch (Exception ex) {
Logger.getLogger(BooksFolderAnalyser.class.getName()).log(Level.SEVERE, "Unknown exception", ex);
new InfoInterface(InfoInterface.InfoLevel.ERROR, "unknown");
}
Logger.getLogger(BooksFolderAnalyser.class.getName()).exiting(BooksFolderAnalyser.class.getName(), "listSeries", new Object[][] {});
return new Object[0][0];
}
|
41a2003b-72f6-49d1-8bfc-de9a81783a09
| 1
|
public boolean equal(Hexpos hp) {
return hp.col() == j+1 && hp.row() == i+1;
}
|
6f54d0d2-9026-452e-8e3d-53284ed5d031
| 7
|
@Override
public void doLoopAction()
{
sound.playBackGround("/sound/background/Yoster Island.wav");
for(GameObject gameObject : StageSelectorObjects)
{
gameObject.doLoopAction();
}
if (!stageSelectorMario.isFindPath())
{
if (confirm == true)
{
marioWorld.setStage(nodes.get(marioData.getNode()).getStageName());
confirm = false;
marioWorld.setWhatcha(Doing.PLAYING);
}
if (left == true)
{
stageSelectorMario.setFindPath(true);
stageSelectorMario.setDirection(Direction.LEFT);
stageSelectorMario.moveLeft();
}
if (right == true)
{
stageSelectorMario.setFindPath(true);
stageSelectorMario.setDirection(Direction.RIGHT);
stageSelectorMario.moveRight();
}
if (up == true)
{
stageSelectorMario.setFindPath(true);
stageSelectorMario.setDirection(Direction.UP);
}
if (down == true)
{
stageSelectorMario.setFindPath(true);
stageSelectorMario.setDirection(Direction.DOWN);
}
}
}
|
271bcd9f-145b-4bb3-a980-2143179c1312
| 0
|
Decoder2 GetDecoder(int pos, byte prevByte)
{
return m_Coders[(((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> 8 - m_NumPrevBits))];
}
|
0954c672-9876-4ee0-a65f-508141d74907
| 8
|
final synchronized boolean registerMerge(MergePolicy.OneMerge merge) throws MergePolicy.MergeAbortedException {
if (merge.registerDone)
return true;
if (stopMerges) {
merge.abort();
throw new MergePolicy.MergeAbortedException("merge is aborted: " + merge.segString(directory));
}
final int count = merge.segments.size();
boolean isExternal = false;
for(int i=0;i<count;i++) {
final SegmentInfo info = merge.segments.info(i);
if (mergingSegments.contains(info))
return false;
if (segmentInfos.indexOf(info) == -1)
return false;
if (info.dir != directory)
isExternal = true;
}
ensureContiguousMerge(merge);
pendingMerges.add(merge);
if (infoStream != null)
message("add merge to pendingMerges: " + merge.segString(directory) + " [total " + pendingMerges.size() + " pending]");
merge.mergeGen = mergeGen;
merge.isExternal = isExternal;
// OK it does not conflict; now record that this merge
// is running (while synchronized) to avoid race
// condition where two conflicting merges from different
// threads, start
for(int i=0;i<count;i++)
mergingSegments.add(merge.segments.info(i));
// Merge is now registered
merge.registerDone = true;
return true;
}
|
bb531ab7-30dc-465a-8dc9-4930df84e69f
| 1
|
private StringBuffer appendCharToBuffer(StringBuffer chunk, char c) {
if (chunk == null) {
chunk = new StringBuffer();
}
chunk.append(c);
return chunk;
}
|
8d427bd8-b911-45d3-8f0e-c5be015e686c
| 6
|
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onDropFromLockedSlot(PlayerDropItemEvent event) {
Player player = event.getPlayer();
if (player.getItemOnCursor() == null
|| player.getItemOnCursor().getType() == Material.AIR) {
PlayerInventory inv = player.getInventory();
int slot = inv.getHeldItemSlot();
if (player.hasPermission("cyom.slot.lock." + slot)
&& !player.hasPermission("disable.slot.locking")) {
// Replace the item back where it was
ItemStack item = event.getItemDrop().getItemStack();
ItemStack slotItem = inv.getItem(slot);
if (slotItem == null || slotItem.getTypeId() == 0) {
inv.setItem(slot, item.clone());
} else {
slotItem.setAmount(slotItem.getAmount() + item.getAmount());
inv.setItem(slot, slotItem);
}
// Stop it from being dropped
event.getItemDrop().remove();
// Make sure player sees everything as normal
player.updateInventory();
}
}
}
|
f11fd458-1c02-4968-aad5-7210dcb6bd7a
| 3
|
public boolean write_data(String filename) throws IOException {
if(!ok) {
return false;
}
else {
FileWriter fout = new FileWriter(filename);
Enumeration e, k;
String sec, key, value;
Properties p;
e=sections.keys();
while(e.hasMoreElements()) {
sec =(String) e.nextElement();
fout.write("["+sec+"]\n");
p = (Properties) sections.get(sec);
k = p.keys();
while(k.hasMoreElements()) {
key = (String) k.nextElement();
value = (String) p.get(key);
fout.write(key+"="+value+"\n");
}
fout.write("\n");
}
fout.close();
}
return true;
}
|
c9278ea0-48c0-40c4-bb3b-d3902085616c
| 0
|
private void info(final String msg) {
logger.info(msg);
}
|
0a949cf3-1dd1-4c69-8251-f0a762932c51
| 4
|
protected void startGame() {
Card lowestCard = null;
for (int i = 0; i < players.length; i++) {
Card playerLowest = getLowestCard(players[i]);
if (playerLowest != null && (lowestCard == null || playerLowest.getRank().compareTo(lowestCard.getRank()) < 0)) {
lowestCard = playerLowest;
currentPlayer = i;
}
}
players[currentPlayer].getHand().remove(lowestCard);
players[currentPlayer].getHand().add(draw());
players[currentPlayer].sortHand();
addToDiscardPile(lowestCard);
}
|
98fea215-8113-455a-bc3e-db4e78f08a4b
| 9
|
public void initTransient() {
if(this.blocks == null) {
throw new RuntimeException("The level is corrupt!");
} else {
this.listeners = new ArrayList();
this.blockers = new int[this.width * this.height];
Arrays.fill(this.blockers, this.depth);
this.calcLightDepths(0, 0, this.width, this.height);
this.random = new Random();
this.randId = this.random.nextInt();
this.tickList = new ArrayList();
if(this.waterLevel == 0) {
this.waterLevel = this.depth / 2;
}
if(this.skyColor == 0) {
this.skyColor = 10079487;
}
if(this.fogColor == 0) {
this.fogColor = 16777215;
}
if(this.cloudColor == 0) {
this.cloudColor = 16777215;
}
if(this.xSpawn == 0 && this.ySpawn == 0 && this.zSpawn == 0) {
this.findSpawn();
}
if(this.blockMap == null) {
this.blockMap = new BlockMap(this.width, this.depth, this.height);
}
}
}
|
9f4d0f5b-81cb-4b67-94ef-d78b39b31238
| 6
|
public synchronized void update(Collection<Snake> snakes) {
Location nextLocation = head.getAdjacentLocation(direction);
if (nextLocation.x >= SnakeWebSocketServlet.PLAYFIELD_WIDTH) {
nextLocation.x = 0;
}
if (nextLocation.y >= SnakeWebSocketServlet.PLAYFIELD_HEIGHT) {
nextLocation.y = 0;
}
if (nextLocation.x < 0) {
nextLocation.x = SnakeWebSocketServlet.PLAYFIELD_WIDTH;
}
if (nextLocation.y < 0) {
nextLocation.y = SnakeWebSocketServlet.PLAYFIELD_HEIGHT;
}
if (direction != Direction.NONE) {
tail.addFirst(head);
if (tail.size() > length) {
tail.removeLast();
}
head = nextLocation;
}
handleCollisions(snakes);
}
|
cef721dc-41f7-4459-8671-b820eb658fd5
| 0
|
public KeyHandler getKeyHandler() {
return kh;
}
|
4d728b0a-d301-4c94-8a59-f563f8a036c4
| 9
|
private boolean doAction(final String action, SceneObject obj) {
if(Players.getLocal().getAnimation() == -1 && !Players.getLocal().isMoving()) {
if(obj.getLocation().distanceTo() > 5) {
Walking.walk(obj.getLocation());
} else {
if(!obj.isOnScreen()) {
Walking.walk(obj.getLocation());
} else {
if(obj.interact(action, obj.getDefinition().getName())) {
while(true) {
if (Players.getLocal().getAnimation() == -1) {
sleep(1750,2250);
if (Players.getLocal().getAnimation() == -1 || Ivy.nest) {
System.out.println("Looking for a new ivy.");
break;
} else {
sleep(50);
}
}
}
}
return true;
}
}
}
return false;
}
|
13055a1c-667a-4f58-9018-5f1792722e8c
| 1
|
private int getGCD(int a, int b){
if(b==0)
return a;
else
return getGCD(b, a % b);
}
|
69b3af4a-b1a2-4a2d-8f75-dd58a44fdcd5
| 0
|
public StepButtonListener(GraphDrawer d) {
this.d = d;
}
|
abd51599-f84c-4c37-8828-fb1a6096e716
| 3
|
public static ArrayList<Quiz> getQuizListByTag(String tagString) {
ArrayList<Quiz> quizList = new ArrayList<Quiz>();
if (tagString.trim().isEmpty())
return quizList;
String statement = new String("SELECT * FROM " + TagDBTable + " WHERE tag = ?");
PreparedStatement stmt;
try {
stmt = DBConnection.con.prepareStatement(statement);
stmt.setString(1, tagString);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Quiz quiz = Quiz.getQuizByQuizID(rs.getInt("qid"));
quizList.add(quiz);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return quizList;
}
|
a8c3f41d-bc88-4796-985c-0c2485182452
| 1
|
Point p(int i, float t)
{
float px = 0;
float py = 0;
for (int j = -2; j <= 1; j++)
{
px += b(j, t) * ptsIn.xpoints[i + j];
py += b(j, t) * ptsIn.ypoints[i + j];
}
return new Point((int) Math.round(px), (int) Math.round(py));
}
|
26e1af76-afa7-498f-9df5-6d2a53b3753c
| 5
|
private String generateCSVRow(List row) {
//this.totalRowsGenerated++;
String retval = "";
for (int i=0; i < row.size(); i++) {
String fieldVal = (String) row.get(i);
if (this.quoteAllOutputFields)
retval += "\"";
if (row.get(i) != null) {
retval += row.get(i);
}
if (this.quoteAllOutputFields)
retval += "\"";
// Add comma after field (unless last field)
String comma = (i < row.size() - 1) ? "," : "";
retval += comma;
}
retval += "\n";
return retval;
}
|
1f42c329-e393-4679-8e96-49961f5ccb08
| 9
|
private int[][] scheduleInstructions() {
int[][] schedule = new int[executed.size()][4];
int dependancy;
boolean reset = false;
boolean cdbEmpty;
Instruction instruction;
for (int i = 0; i < schedule.length; i++) {
instruction = executed.get(i);
if (i == 0)
schedule[i][0] = 1;
else if (reset)
schedule[i][0] = schedule[i - 1][3] + 1;
else
schedule[i][0] = Math.max(getIssueCycle1(schedule, i), getIssueCycle2(schedule, i));
dependancy = getDependancy(i);
schedule[i][1] = (dependancy == -1)? schedule[i][0] : Math.max(schedule[dependancy][2], schedule[i][0]);
schedule[i][1] += executed.get(i).getExecutionTime();
schedule[i][2] = schedule[i][1] + 1;
do {
cdbEmpty = true;
for (int j = 0; j < i; j++) {
if (schedule[i][2] == schedule[j][2]) {
cdbEmpty = false;
schedule[i][2]++;
break;
}
}
} while(!cdbEmpty);
schedule[i][3] = ((i == 0)? schedule[0][2] : Math.max(schedule[i - 1][3], schedule[i][2])) + 1;
reset = false;
if (instruction.getFunction() == FunctionType.BRANCH) {
int takenAddress = instruction.getAddress() + (Integer)instruction.getOperands()[2] + 2;
boolean taken = takenAddress == instruction.getEffectiveAddress();
boolean prediction = (Integer)instruction.getOperands()[2] >= 0;
reset = taken != prediction;
}
}
return schedule;
}
|
7e451d27-e8c0-4ac5-9a9d-434f7606447f
| 5
|
@Override
public void deserialize(Buffer buf) {
super.deserialize(buf);
partyType = buf.readByte();
if (partyType < 0)
throw new RuntimeException("Forbidden value on partyType = " + partyType + ", it doesn't respect the following condition : partyType < 0");
partyLeaderId = buf.readInt();
if (partyLeaderId < 0)
throw new RuntimeException("Forbidden value on partyLeaderId = " + partyLeaderId + ", it doesn't respect the following condition : partyLeaderId < 0");
maxParticipants = buf.readByte();
if (maxParticipants < 0)
throw new RuntimeException("Forbidden value on maxParticipants = " + maxParticipants + ", it doesn't respect the following condition : maxParticipants < 0");
int limit = buf.readUShort();
members = new PartyMemberInformations[limit];
for (int i = 0; i < limit; i++) {
members[i] = ProtocolTypeManager.getInstance().build(buf.readShort());
members[i].deserialize(buf);
}
limit = buf.readUShort();
guests = new PartyGuestInformations[limit];
for (int i = 0; i < limit; i++) {
guests[i] = new PartyGuestInformations();
guests[i].deserialize(buf);
}
restricted = buf.readBoolean();
}
|
1abae550-784f-4fff-aef1-a0bb7e3d77c4
| 0
|
public static void main(String[] args) {
// ConfigManager configManager = ConfigManager.getInstance();
MainService is = new MainService();
is.getLogger().info("start-------------------");
is.fetch();
is.extract();
is.initOnGoing();
}
|
5b3b5293-ccbf-48b6-add9-0fc1537e71c1
| 6
|
private int divide(int start, int end) {
int separatorPos = getSeparatorPos(start, end);
swap(end, separatorPos);
int firstGreatPos = -1;
int separator = get(end);
for (int i = start; i < end; i++) {
if(get(i) <= separator) {
if(firstGreatPos != -1) {
swap(firstGreatPos, i);
firstGreatPos++;
}
} else {
if(firstGreatPos == -1) {
firstGreatPos = i;
}
}
}
if(firstGreatPos != -1) swap(firstGreatPos, end);
return firstGreatPos == -1 ? end: firstGreatPos;
}
|
068ab5fe-fefc-4748-a38b-16e23b4b80a4
| 8
|
public Unit findStudent(final Unit teacher) {
if (getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION))
return null; // No automatic assignment
Unit student = null;
GoodsType expertProduction = teacher.getType().getExpertProduction();
int skillLevel = INFINITY;
for (Unit potentialStudent : getUnitList()) {
/**
* Always pick the student with the least skill first.
* Break ties by favouring the one working in the teacher's trade,
* otherwise first applicant wins.
*/
if (potentialStudent.getTeacher() == null
&& potentialStudent.canBeStudent(teacher)
&& (student == null
|| potentialStudent.getSkillLevel() < skillLevel
|| (potentialStudent.getSkillLevel() == skillLevel
&& potentialStudent.getWorkType() == expertProduction))) {
student = potentialStudent;
skillLevel = student.getSkillLevel();
}
}
return student;
}
|
2db2deb3-5882-46df-a848-bfaf733f5708
| 1
|
@Test
public void testPermutate2() {
int[] testExpansionTabel = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
byte[] block = new byte[]{10, 12, 11, 13};
byte[] expected = new byte[]{10, 12, 11,13, 10, 12};
byte[] result = ByteHelper.permutate(block, testExpansionTabel);
for (int i = 0; i < block.length; i++) {
assertEquals(result[i], expected[i]);
}
}
|
c3558cc5-d711-4a03-928b-584c3b0741d6
| 9
|
public static PVector resolveAny(ENeighbour neighbour, PVector v) {
switch( neighbour) {
case TOPLEFT: return resolveTopLeft(v);
case TOP: return resolveTopMiddle(v);
case TOPRIGHT: return resolveTopRight(v);
case RIGHT: return resolveRight(v);
case BOTRIGHT: return resolveBottomRight(v);
case BOTTOM: return resolveBottomMiddle(v);
case BOTLEFT: return resolveBottomLeft(v);
case LEFT: return resolveLeft(v);
case CENTRE:
break;
default:
break;
}
return null;
}
|
443858a6-4ade-47e9-89fd-5cedce9c491c
| 0
|
public Cat(String name, float weight, FlyingAbility flyingAbility) {
super(name, weight, "meow", flyingAbility);
}
|
80ccd9ba-8b8f-4765-b1de-600624283e29
| 3
|
public static double trapecio(double extremoIzq, double extremoDer, Funcion fun, double k) {
double n = 1;
double h = extremoDer - extremoIzq;
double t0 = (h / 2) * (fun.f(extremoIzq) + fun.f(extremoDer));
if (k == 0) {
return t0;
}
n = n * 2;
h = h / 2;
double t1 = (0.5 * t0) + h * fun.f(extremoIzq + h);
while (k > n / 2) {
t0 = t1;
n = n * 2;
h = h / 2;
double s = 0;
for (int i = 1; i < n; i = i + 2) {
s = s + fun.f(extremoIzq + (i * h));
}
t1 = (0.5 * t0) + (h * s);
}
return t1;
}
|
de4fbebe-a846-43ef-856f-18f3266bca9b
| 6
|
public boolean typeBoolean(String op1, boolean bool1, String op2, boolean bool2){
if (bool1 == bool2){
if (op1.equals("=") && op2.equals("!=")){
return false;
}else if(op1.equals("!=") && op2.equals("=")){
return false;
}else{
return true;
}
}else{ //if (bool1 != bool2) {
if (op1.equals(op2)){
return false;
}else{
return true;
}
}
}
|
efa0e3f1-ef30-4a01-8187-79f17331d39f
| 6
|
public String processInput(int time, String inputString, boolean verbose) {
String outputString = null;
// Read input into a HashMap
HashMap<String, String> messageMap = new HashMap<String, String>();
String[] split = inputString.split(" ");
for (String s : split) {
String[] tempS = s.split("=");
messageMap.put(tempS[0], tempS[1]);
}
if (!messageMap.containsKey("action")) {
outputString = "Error, message must contain action";
} else {
String action = messageMap.get("action");
switch (action) {
case "market": {
// Submit a market order to the LOB
String side = messageMap.get("side");
int qty = Integer.parseInt(messageMap.get("qty"));
String takerId = messageMap.get("firmId");
lob.processMarketOrder(time, side, qty, takerId, verbose);
break;
}
case "limit": {
// do limit stuff
String side = messageMap.get("side");
int qty = Integer.parseInt(messageMap.get("qty"));
String firmId = messageMap.get("firmId");
double price = Double.parseDouble(messageMap.get("price"));
lob.processLimitOrder(time, side, qty, price, firmId, verbose);
break;
}
case "cancel":
// Cancel an order:
int orderId = Integer.getInteger(messageMap.get("ordeId"));
lob.cancelOrder(orderId);
break;
case "modify":
// modify an order
break;
}
}
return outputString;
}
|
1b46923e-6bd4-4aa5-9309-a71fa38f8110
| 9
|
private boolean camposCompletos (){
if((!field_fec_alta.getText().equals(""))&&
(!field_limite_cred.getText().equals(""))&&
(!field_dni.getText().equals(""))&&
(!field_nombre.getText().equals(""))&&
(!field_apellido.getText().equals(""))&&
(!field_telefono.getText().equals(""))&&
(!field_direccion.getText().equals(""))&&
(!field_sueldo.getText().equals(""))&&
(!field_fec_cbo_est.getText().equals(""))
){
return true;
}
else{
return false;
}
}
|
59718ea9-cff0-44a7-a71e-917c364efecc
| 8
|
private String formatMass(double mass, boolean isForce) {
final int ZERO_DIGIT = 4;
String massStr = String.valueOf(mass);
if (isForce) {
// 強制的に全ての桁を統一する(0埋めと切捨てを行う)
if (massStr.indexOf(".") == -1) {
massStr += ".0000";
}
else {
if (massStr.indexOf(".") != -1) {
String [] tmpMzStr = massStr.split("\\.");
if (tmpMzStr[1].length() <= ZERO_DIGIT) {
int addZeroCnt = ZERO_DIGIT - tmpMzStr[1].length();
for (int j=0; j<addZeroCnt; j++) {
massStr += "0";
}
}
else {
if (tmpMzStr[1].length() > ZERO_DIGIT) {
massStr = tmpMzStr[0] + "." + tmpMzStr[1].substring(0, ZERO_DIGIT);
}
}
}
}
}
else {
// 桁を超える場合のみ桁を統一する(切捨てのみ行う)
if (massStr.indexOf(".") != -1) {
String [] tmpMzStr = massStr.split("\\.");
if (tmpMzStr[1].length() > ZERO_DIGIT) {
massStr = tmpMzStr[0] + "." + tmpMzStr[1].substring(0, ZERO_DIGIT);
}
}
}
return massStr;
}
|
a1507873-ca93-4123-90f5-0d73e122f1d0
| 8
|
public void setVisited(String direction) {
switch(direction){
case "north":
// Maak van .getNorth een String
String convertString = "" + myRooms[myPlayer.getCurrentroom()].getNorth();
// Als de visited string het nummer van de kamer al in zich heeft, doe dan niks
if (this.visited.contains(convertString)){
}
else{// Anders, voeg kamernummer toe aan string visited.
this.visited = getVisited() + "/" + myRooms[myPlayer.getCurrentroom()].getNorth();
}
break;
case "east":
convertString = "" + myRooms[myPlayer.getCurrentroom()].getEast();
// Als de visited string het nummer van de kamer al in zich heeft, doe dan niks
if (this.visited.contains(convertString)){
}
else{// Anders, voeg kamernummer toe aan string visited.
this.visited = getVisited() + "/" + myRooms[myPlayer.getCurrentroom()].getEast();
}
break;
case "south":
convertString = "" + myRooms[myPlayer.getCurrentroom()].getSouth();
// Als de visited string het nummer van de kamer al in zich heeft, doe dan niks
if (this.visited.contains(convertString)){
}
else{// Anders, voeg kamernummer toe aan string visited.
this.visited = getVisited() + "/" + myRooms[myPlayer.getCurrentroom()].getSouth();
}break;
case "west":
convertString = "" + myRooms[myPlayer.getCurrentroom()].getWest();
// Als de visited string het nummer van de kamer al in zich heeft, doe dan niks
if (this.visited.contains(convertString)){
}
else{// Anders, voeg kamernummer toe aan string visited.
this.visited = getVisited() + "/" + myRooms[myPlayer.getCurrentroom()].getWest();
}
break;
}
}
|
f5021553-b141-4e16-8851-eab0ad387431
| 9
|
public void paint(Graphics g){
TheColor TC = new TheColor(Color.black); // Set initial color of TheColor class to a default black
for(InputSaver s : opener.newPhrase){
// If statements to draw proper shapes on to canvas
if(s.phrase.equals("line")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int x1 = Integer.parseInt(s.var1);
int y1 = Integer.parseInt(s.var2);
Line li = new Line(TC.color, x, y, x1, y1);
li.paintLine(getGraphics());
}
else if(s.phrase.equals("circle")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int r = Integer.parseInt(s.var1);
Circle circ = new Circle(TC.color, x, y, r);
circ.paintCircle(getGraphics());
}
else if(s.phrase.equals("filledcircle")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int r = Integer.parseInt(s.var1);
FilledCircle fcirc = new FilledCircle(TC.color, x, y, r);
fcirc.paintCircle(getGraphics());
}
else if(s.phrase.equals("rectangle")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int w = Integer.parseInt(s.var1);
int h = Integer.parseInt(s.var2);
Rectangle r = new Rectangle(TC.color, x, y, w, h);
r.paintRectangle(getGraphics());
}
else if(s.phrase.equals("filledrectangle")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int w = Integer.parseInt(s.var1);
int h = Integer.parseInt(s.var2);
FilledRectangle fr = new FilledRectangle(TC.color, x, y, w, h);
fr.paintRectangle(getGraphics());
}
else if(s.phrase.equals("square")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int wh = Integer.parseInt(s.var1);
Square sq = new Square(TC.color, x, y, wh);
sq.paintRectangle(getGraphics());
}
else if(s.phrase.equals("filledsquare")){
int x = Integer.parseInt(s.xCoord);
int y = Integer.parseInt(s.yCoord);
int wh = Integer.parseInt(s.var1);
FilledSquare fsq = new FilledSquare(TC.color, x, y, wh);
fsq.paintRectangle(getGraphics());
}
//Sets new color of the super class for all other shapes to inherit
else if(s.phrase.equals("color")){
int r = Integer.parseInt(s.xCoord);
int gr = Integer.parseInt(s.yCoord);
int b = Integer.parseInt(s.var1);
Color newColor = new Color(r, gr, b);
TC.color = newColor;
}
}// End for loop
}// End paint class
|
e6a5d5e0-c482-4047-824a-05f0109da943
| 4
|
@SuppressWarnings("unused")
private void testImage(CoordXZ region, List<Boolean> data) {
int width = 32;
int height = 32;
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
int current = 0;
g2.setColor(Color.BLACK);
for (int x = 0; x < 32; x++) {
for (int z = 0; z < 32; z++) {
if (data.get(current).booleanValue())
g2.fillRect(x, z, x + 1, z + 1);
current++;
}
}
File f = new File("region_" + region.x + "_" + region.z + "_.png");
Config.Log(f.getAbsolutePath());
try {
// png is an image format (like gif or jpg)
ImageIO.write(bi, "png", f);
} catch (IOException ex) {
Config.Log("[SEVERE]" + ex.getLocalizedMessage());
}
}
|
624cd6a7-97f4-45e0-90ae-b30c4d041da3
| 2
|
public Set<T> append(T a)// append the element a at the end of a set.
{ Set<T> res=this;
if(res.hasElement(a))
{ return res;
}
else
{ if(res.next==null)
{ return new Set(res.a, new Set(a,null));}
else
{ return new Set(res.a, res.next.append(a));
}
}
}
|
be23fb56-6e87-4446-841b-e1f824f60928
| 4
|
protected void actualizarDisparos(){
if(!disparos.isEmpty()){
Iterator<Disparo> itDisparo = disparos.iterator();
try{
while(itDisparo.hasNext()){
Disparo d = itDisparo.next();
//Movemos el disparo y nos retorna su salud
//eliminamos el disparo o salido de la pantalla
if(d.mover() < 0) itDisparo.remove();
}
}catch(java.util.ConcurrentModificationException e){
System.err.println("Disparador.actualizarDisparos()>ConcurrentModificationException");
}
}
}
|
8ef3d4ef-091f-47ba-93e9-5b1e1dc5ab6f
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
|
de86988f-5420-4431-a952-0431bf864388
| 5
|
private int minimax(int m, int dt, Board b, boolean max) {
int bestValue;
int val;
if (dt == 0 || findPossibleMoves(max, b).length == 0) {
return getRating(max, b, m);
} else if (max == true) {
bestValue = Integer.MIN_VALUE;
for (int i : findPossibleMoves(true, b)) {
Board nb = b;
nb.move(max, m);
val = minimax(i, dt - 1, nb, false);
bestValue = Math.max(bestValue, val);
}
return bestValue;
} else {
bestValue = Integer.MAX_VALUE;
for (int i : findPossibleMoves(false, b)) {
Board nb = b;
nb.move(max, m);
val = minimax(i, dt - 1, nb, true);
bestValue = Math.min(bestValue, val);
}
return bestValue;
}
}
|
dafdbf9a-fd6f-416f-918f-afa6dcd526ec
| 7
|
@Override
public void actionPerformed(ActionEvent event) {
String url = event.getActionCommand();
if (SITE_URL.equals(url) || PROJECT_URL.equals(url)) {
String os = System.getProperty("os.name");
String[] cmd = null;
if (os == null) {
// error, the operating system could not be determined
return;
} else if (os.toLowerCase().contains("mac")) {
// Apple Macintosh, Safari is the main browser
cmd = new String[] { "open" , "-a", "Safari", url };
} else if (os.toLowerCase().contains("windows")) {
// Microsoft Windows, use the default browser
cmd = new String[] { "rundll32.exe", "url.dll,FileProtocolHandler", url};
} else if (os.toLowerCase().contains("linux")) {
// GNU Linux, use xdg-utils to launch the default browser (portland.freedesktop.org)
cmd = new String[] {"xdg-open", url};
} else {
// Unix, ...
// TODO: should we just call an arbitrary browser like this?
//cmd = new String[] { "netscape", "-remote", "openURL(" + url + ")"};
cmd = new String[] { "firefox", url};
}
try {
Runtime.getRuntime().exec(cmd);
} catch(IOException x) {
// couldn't start browser
}
} else {
super.actionPerformed(event);
}
}
|
4e60dde4-8217-4f69-ac3b-ae3c6ca74fc4
| 5
|
public static void getHrefOfContent(String content)
{
System.out.println("ʼ");
String[] contents = content.split("<a href=\"");
for (int i = 1; i < contents.length; i++)
{
int endHref = contents[i].indexOf("\"");
//
String aHref = FunctionUtils.getHrefOfInOut(contents[i].substring(0,endHref));
if (aHref != null)
{
String href = FunctionUtils.getHrefOfInOut(aHref);
if (!UrlQueue.isContains(href)
&& href.indexOf("/code/explore") != -1
&& !VisitedUrlQueue.isContains(href))
{
UrlQueue.addElem(href);
}
}
}
System.out.println(UrlQueue.size() + "--ץȡ");
System.out.println(VisitedUrlQueue.size() + "--Ѵҳ");
}
|
008a6dcf-9a6f-4caa-b01d-f4335ed57802
| 6
|
private boolean requiresDownload(Repository repository, Release latestRelease) {
boolean requiresDownload = false;
HashMap<String, DataFile> fileData = repoFileCache.getIfPresent(repository.getName());
if (fileData == null) {
// We have no cached data for this repo.
logger.log(Level.INFO, "File data for {0} not yet cached.", repository.getName());
requiresDownload = true;
}
if (!repoReleaseDates.containsKey(repository.getName())) {
// We haven't seen a release for this repo yet.
logger.log(Level.INFO, "Last release date for {0} not yet cached.", repository.getName());
requiresDownload = true;
}
else if (latestRelease != null && latestRelease.getPublishedAt().after(repoReleaseDates.get(repository.getName()))) {
// Latest release is newer than the one we last downloaded
logger.log(Level.INFO, "Latest release date for {0} is after cached last release date.", repository.getName());
requiresDownload = true;
}
if (requiresDownload) {
if (latestRelease != null) {
repoReleaseDates.put(repository.getName(), latestRelease.getPublishedAt());
}
else {
repoReleaseDates.put(repository.getName(), new Date());
}
}
return requiresDownload;
}
|
967ecb09-2d2c-4908-983c-b56593795b46
| 0
|
public ClientThread(Socket connectionSocket) {
this.connectionSocket = connectionSocket;
this.connectionID = nextClientThreadID++;
}
|
0fcf573b-5d17-44c6-aed6-eb1cac198990
| 6
|
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
try {
if (!isLookingForGame() && (sessionImpl == null || !hasGameStarted())) {
//unwise
System.setSecurityManager(null);
//String serverAddress = (GameFrame.ARGS.length < 1) ? "localhost" : GameFrame.ARGS[0];
String serverAddress = "localhost";
//when trying to find a game, try to connect to server first
//register clientStub at remote server
Registry remoteRegistry = LocateRegistry.getRegistry(serverAddress, RMI_PORT);
server = (IYAPTServer) remoteRegistry.lookup(IYAPTServer.class.getSimpleName());
//create RMI-stub for a ClientImpl
sessionImpl = new Session(server);
final ISession sessionStub = (ISession) UnicastRemoteObject.exportObject(sessionImpl, 0);
server.register(sessionStub);
//start pushing messages to the server
server.onMessage("Connected");
sessionImpl.onMessage("pushLookingForGame", null);
button1.setLabel("Disconnect...");
this.setFocusable(true);
this.requestFocusInWindow();
gameloop = new Thread(r);
gameloop.start();
//if we are looking for game and button is pressed, we should disconnect from the server
//OR if we're playing a game (gameStarted == true) and we pushed the button, we should also disc
} else if (hasGameStarted()) {
System.out.println("Leaving game!");
gameloop.interrupt();
sessionImpl.onMessage("pushDisconnect", null);
button1.setLabel("Find Game!");
} else if (isLookingForGame()) {
System.out.println("Leaving que!");
gameloop.interrupt();
sessionImpl.onMessage("leaveQue", null);
button1.setLabel("Find Game!");
}
} catch (NotBoundException | RemoteException t) {
Logger.getLogger(IYAPTServer.class.getName()).log(
Level.SEVERE,
"An error ocurred. Ensure that no RMI server is running, then run this class as follows:\n"
+ "java -Djava.rmi.server.hostname=PUBLIC_CLIENT_IP -cp RMI-project-1.0-SNAPSHOT.jar nl.fontys.vangeenen.rmi.ClientImpl PUBLIC_SERVER_IP\n"
+ "* The value PUBLIC_SERVER_IP must equal the publicly routable IP of the server.\n"
+ "* The value PUBLIC_CLIENT_IP must equal YOUR routable IP.",
t
);
System.exit(1);
}
}//GEN-LAST:event_button1ActionPerformed
|
fa0efb3a-cf61-4937-9d64-751e28f4f051
| 5
|
public boolean equals( Object o )
{
// Si l'objecte es null retornem false directament.
if ( o == null )
{
return false;
}
// Si és ell mateix retornem true (reciprocitat).
if ( o == this )
{
return true;
}
// Si no és una casella, retornem false.
if ( !( o instanceof Casella ) )
{
return false;
}
//Un cop descartats tots els casos anteriors, calculem el resultat d'equals.
Casella c = ( Casella ) o;
if ( c.getFila() == fila && c.getColumna() == columna )
{
return true;
}
return false;
}
|
0a17da60-7c74-4435-a107-0646716d3a34
| 9
|
private static void handleDir(File dir, ZipOutputStream zipOut) throws IOException {
// System.out.println("-----------dir: " + dir.getAbsolutePath());
// System.out.println("-----------dir.isDirectory: " + dir.isDirectory());
FileInputStream fileIn=null;
int readedBytes = 0;
byte[] buf = new byte[512];
File[] files;
files = dir.listFiles();
// System.out.println("-----------files.length: " + files.length);
if (files==null || files.length == 0) {// 如果目录为空,则单独创建之.
// ZipEntry的isDirectory()方法中,目录以"/"结尾.
zipOut.putNextEntry(new ZipEntry(dir.toString() + "/"));
zipOut.closeEntry();
}else {// 如果目录不为空,则分别处理目录和文件.
for (File file : files) {
// System.out.println("-----------file: " + file.getName());
if (file.isDirectory()) {
handleDir(file, zipOut);
}else{
try{
fileIn = new FileInputStream(file);
if(!file.toString().endsWith(".zip")){
String temp="";
if(file.toString().indexOf("com")>0){
temp=file.toString().substring(file.toString().indexOf("com"), file.toString().length());
}else{
temp=file.getName();
}
// System.out.println("-----------temp: " + temp);
zipOut.putNextEntry(new ZipEntry(temp));
while ((readedBytes = fileIn.read(buf)) > 0) {
zipOut.write(buf,0,readedBytes);
}
zipOut.closeEntry();
}
}catch(Exception e){
}finally{
if(fileIn!=null){
fileIn.close();
}
}
}
}
}
}
|
446ddca3-00cf-4e31-b62e-65b30fe95f63
| 2
|
private boolean checkExistingTab(String className)
{
boolean exist = false;
int count = tabbedPane.getTabCount();
for (int i = 0; i < count; i++) {
Component comp = tabbedPane.getComponentAt(i);
if(className == comp.getClass().getName())
{
tabbedPane.setSelectedIndex(i);
exist = true;
//reBuildJToolBar(comp);
break;
}
}
return exist;
}
|
0f5d3738-f098-447a-9318-62c35e47ae03
| 9
|
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
Raster source = sources[0];
Rectangle srcRect = mapDestRect(destRect, 0);
int formatTag = MediaLibAccessor.findCompatibleTag(sources,dest);
MediaLibAccessor srcAccessor =
new MediaLibAccessor(source,srcRect,formatTag);
MediaLibAccessor dstAccessor =
new MediaLibAccessor(dest,destRect,formatTag);
mediaLibImage[] srcML = srcAccessor.getMediaLibImages();
mediaLibImage[] dstML = dstAccessor.getMediaLibImages();
switch (dstAccessor.getDataType()) {
case DataBuffer.TYPE_BYTE:
case DataBuffer.TYPE_USHORT:
case DataBuffer.TYPE_SHORT:
case DataBuffer.TYPE_INT:
for (int i = 0; i < dstML.length; i++) {
double[] mlconstants = dstAccessor.getDoubleParameters(i, constants);
Image.ConstDiv(dstML[i], srcML[i], mlconstants);
}
break;
case DataBuffer.TYPE_FLOAT:
case DataBuffer.TYPE_DOUBLE:
for (int i = 0; i < dstML.length; i++) {
double[] mlconstants = dstAccessor.getDoubleParameters(i, constants);
Image.ConstDiv_Fp(dstML[i], srcML[i], mlconstants);
}
break;
default:
String className = this.getClass().getName();
throw new RuntimeException(className + JaiI18N.getString("Generic2"));
}
if (dstAccessor.isDataCopy()) {
dstAccessor.clampDataArrays();
dstAccessor.copyDataToRaster();
}
}
|
4377987b-6ebd-4a3d-9970-38f210d6a74e
| 1
|
@Override
public void run() {
for (i=0; i <= aantal; i++){
System.out.print(i);
}
}
|
b88fb0e3-9ac8-4e8d-a052-4222987efc09
| 4
|
public static void parseParameter(String arg1, String arg2)
{
if(arg1.equalsIgnoreCase("-g"))
game = arg2;
else if(arg1.equalsIgnoreCase("-l"))
level = arg2;
else if(arg1.equalsIgnoreCase("-a"))
actionFile = arg2;
else if(arg1.equalsIgnoreCase("-d"))
delay = Integer.parseInt(arg2);
}
|
65401286-d3f2-4d82-8109-e900dbe38438
| 6
|
public void setExplored(Tile tile) {
tile.setExploredBy(this, true);
}
|
b89856eb-afa6-4e57-a7e7-fc9a53130563
| 1
|
public float getCurrentBoxFrame(int x) {
float total = 0;
for(int a = 0; a<=x; a++) {
total += boxFrame.get(a);
}
return total;
}
|
f7a092c4-e651-4f6b-b039-689b211b6fa1
| 1
|
public InputStreamSource(InputStream in)
{
if (in==null)
throw new NullPointerException("in");
this.in = in;
}
|
af913bf4-a58b-4d9a-a3ad-60a4145f4bea
| 1
|
public Type getSpecializedType(Type type) {
if (type.typecode == TC_RANGE)
type = ((RangeType) type).getBottom();
return type;
}
|
cf60152b-c687-458d-8015-79c910aab1eb
| 4
|
public int evalMove(Move m, State s, int depth) {
if (depth == 0) { // cutting off search -> evaluate resulting state
return evalState(s.tryMove(m));
} else { // minimax-search
// update the state
State newstate = s.tryMove(m);
// get a list of possible moves from newstate
MyList moves = newstate.findMoves();
// shuffle so we don't always find the same maximum
Collections.shuffle(moves);
// return utility of state if there are no new moves
if (moves.size() == 0)
return evalState(newstate);
// Iterate over all moves
Iterator it = moves.iterator();
// We already know there is at least one move, so use it to
// initialize minimaxvalue
int minimaxvalue = evalMove((Move) it.next(), newstate, depth - 1);
// now the rest of the moves
while (it.hasNext()) {
Move newmove = (Move) it.next();
int eval = evalMove(newmove, newstate, depth - 1);
// if this is our turn, save the maximumvalue, otherwise
// the mimimumvalue
if (newstate.whoseTurn().equals(me)) // our turn
minimaxvalue = Math.max(minimaxvalue, eval);
else // opponent's turn
minimaxvalue = Math.min(minimaxvalue, eval);
}
return minimaxvalue;
}
}
|
8d2a20c3-686f-4b2c-ad79-0e4d36764a56
| 6
|
public int cdlAbandonedBabyLookback( double optInPenetration )
{
if( optInPenetration == (-4e+37) )
optInPenetration = 3.000000e-1;
else if( (optInPenetration < 0.000000e+0) || (optInPenetration > 3.000000e+37) )
return -1;
return ((( ((( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) > ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ? ( ((( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) : ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) +
2;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.