method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
93c1ff5b-9b54-4bdd-aca2-11ee65c7691b
| 5
|
public int getSecondOrderClassification(GraphPoint p)
{
List<GraphPoint> neighbourhood = new ArrayList<GraphPoint>();
for(GraphPoint neighbour: p.getEdges())
{
if(neighbour.getClassification() == p.getClassification())
{
for(GraphPoint edge: neighbour.getEdges())
{
if(edge != neighbour && !neighbourhood.contains(edge))
neighbourhood.add(edge);
}
}
}
return getFirstOrderClassification(neighbourhood);
}
|
e78e6588-1bc7-4d21-8b93-d3f4ccb4a232
| 3
|
private static void test_onesCount(TestCase t) {
// Print the name of the function to the log
pw.printf("\nTesting %s:\n", t.name);
// Run each test for this test case
int score = 0;
for (int i = 0; i < t.tests.length; i += 2) {
int bits = (Integer) t.tests[i];
int exp = (Integer) t.tests[i + 1];
try {
field.setInt(vec, bits);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int res = vec.onesCount();
boolean cor = exp == res;
if (cor) {
++score;
}
pw.printf(
"%s(): Bits: %8X Expected: %2d Result: %2d Correct: %5b\n",
t.name, bits, exp, res, cor);
pw.flush();
}
// Set the score for this test case
t.score = (double) score / (t.tests.length / 2);
}
|
93cac647-d329-4f3a-9b20-2c0fe8c44bcd
| 8
|
@SuppressWarnings({ "rawtypes", "unchecked" })
private void initPageRender() {
try {
Element root = configXml.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("pageRender");
if (nodeList.getLength() == 0) {// 如果没有配置则默认是freemarker渲染
RenderFactory.setPageRender(new FreemarkerRender());
} else if (nodeList.getLength() > 1) {// 配置了多个抛错
throw new WqMvcException(
"It must be only one node of 'pageRender'...");
} else {
// 取class属性值:page渲染器的实现类
Node node = nodeList.item(0);
String clsName = node.getAttributes().getNamedItem("class")
.getNodeValue();
if (clsName == null) {
throw new WqMvcException(
"There is no attribute of 'class' in the node of 'pageRender'...");
}
Class cls = Class.forName(clsName);
// 必须实现Render接口
if (!ReflectUtil.isImplementsInterface(cls,
Render.class.getName())) {
throw new WqMvcException(
"PageRender must implements 'com.wq.web.servlet.render.Render'...");
}
// 初始化Render实例
RenderFactory.setPageRender((Render) ReflectUtil
.newInstance(cls));
// 设置页面地址前缀和后缀
NodeList childs = node.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
Node child = childs.item(i);
if (child.getNodeName().equals("prefix")) {
PageRenderConfig.pagePrefix = child.getTextContent();
} else if (child.getNodeName().equals("suffix")) {
PageRenderConfig.pageSuffix = child.getTextContent();
}
}
}
} catch (ClassNotFoundException e) {
throw new WqMvcException(e);
}
}
|
60e6bc95-b710-4763-8c1e-9664beb5e6a7
| 0
|
public static Pet randomPet() {
return creator.randomPet();
}
|
83f99e35-ac84-429a-befc-9c99daed1ffd
| 1
|
public void activePlayerEndTurn(){
int lastIndexOfActivePlayer = getPlayerNumber(getActivePlayer());
lastIndexOfActivePlayer++;
if (lastIndexOfActivePlayer >= players.size()){
lastIndexOfActivePlayer = 0;
}
setActivePlayer(players.get(lastIndexOfActivePlayer));
getActivePlayer().incrementTurnsWithThree();
}
|
99759d21-6990-4c2c-9b0b-ad57b37f396f
| 9
|
public void handleKeyStroke(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_SPACE:
if (!inGame) {
this.startSnake();
}
break;
case KeyEvent.VK_UP:
snake.setCurrentDirection(Direction.UPARROW);
break;
case KeyEvent.VK_DOWN:
snake.setCurrentDirection(Direction.DOWNARROW);
break;
case KeyEvent.VK_LEFT:
snake.setCurrentDirection(Direction.LEFTARROW);
break;
case KeyEvent.VK_RIGHT:
snake.setCurrentDirection(Direction.RIGHTARROW);
break;
case KeyEvent.VK_P:
isPaused = !isPaused;
if(isPaused){timer.stop();}
else{timer.start();}
break;
case KeyEvent.VK_Q:
this.endGame();
break;
}
}
|
58dcd90c-6923-41d8-9011-8b1c198f065a
| 2
|
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e.getSQLState()
+ "\nCaused by\n"
+ e.getCause(), e);
}
}
}
|
f1ac298f-81c0-462a-883b-18d96758d077
| 7
|
public static long findMaxPrime(long value){
//long bigValue = value;
//save the factor which have try
long factor = 1;
//save the max factor
long lastFactor = 1;
//remove the only one even factor
if(value%2==0){
lastFactor=2;
factor = 2;
value = value/2;
while(value%2==0){
value /= 2;
}
}
factor = 3;
while(value>1&&(factor*factor<value)){
if(value%factor==0){
System.out.println(factor);
lastFactor = factor;
value /= factor;
while(value%factor==0){
value /= factor;
}
System.out.println("value"+value);
}
factor +=2;
}
return value==1?lastFactor:value;
}
|
e9daa74f-9eb0-454a-8ce1-c4e44bd5c085
| 4
|
private static String LetterOrNumber(String string) {
final String works = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
String finals = "";
boolean change = true;
for (char c : string.toCharArray()) {
for (char x : works.toCharArray()) {
if (x == c) {
change = false;
break;
}
}
if (change)
finals += works.toCharArray()[new Random().nextInt(works.toCharArray().length)];
else
finals += c;
change = true;
}
return finals;
}
|
e0ae8861-428d-48ab-b5a0-f59bf1ee4038
| 1
|
public boolean canHaveAsCreditLimit(BigInteger creditLimit) {
return (creditLimit != null) && (creditLimit.compareTo(BigInteger.ZERO) <= 0);
}
|
a13b73fd-d75e-43fa-af7c-60a18589455d
| 0
|
public int hashCode()
{
return super.hashCode() ^ myUnprocessedInput.hashCode() ^ myOutput.hashCode();
}
|
2c64a3ea-92b6-419c-8f7b-54d1fa41c811
| 6
|
public long[] next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
// save current
long current[] = new long[numberOfLevels];
for (int i = 0; i < numberOfLevels; i += 1) {
current[i] = axisWithoutMeaning[i];
}
// iterate next
Stack<Level> levelsStack = new Stack<Level>();
for (Level level : levels) {
levelsStack.push(level);
}
for (int i = numberOfLevels - 1; i >= 0; i -= 1) {
Level level = levelsStack.pop();
if (axisWithoutMeaning[i] < level.getBegin()
+ level.getLength() - 1) {
axisWithoutMeaning[i] += 1;
break;
} else {
if (i != 0) {
axisWithoutMeaning[i] = 0;
} else {
axisWithoutMeaning[i] += 1;
}
}
}
return current;
}
|
e8fa7d90-8775-4e2b-bd56-08dbb0bba3b0
| 7
|
private void processScreenBlt(RdpPacket_Localised data,
ScreenBltOrder screenblt, int present, boolean delta) {
if ((present & 0x01) != 0)
screenblt.setX(setCoordinate(data, screenblt.getX(), delta));
if ((present & 0x02) != 0)
screenblt.setY(setCoordinate(data, screenblt.getY(), delta));
if ((present & 0x04) != 0)
screenblt.setCX(setCoordinate(data, screenblt.getCX(), delta));
if ((present & 0x08) != 0)
screenblt.setCY(setCoordinate(data, screenblt.getCY(), delta));
if ((present & 0x10) != 0)
screenblt.setOpcode(ROP2_S(data.get8()));
if ((present & 0x20) != 0)
screenblt.setSrcX(setCoordinate(data, screenblt.getSrcX(), delta));
if ((present & 0x40) != 0)
screenblt.setSrcY(setCoordinate(data, screenblt.getSrcY(), delta));
// if(logger.isInfoEnabled())
// logger.info("opcode="+screenblt.getOpcode());
surface.drawScreenBltOrder(screenblt);
}
|
0bfb4635-36d9-4584-812f-4da666dad0c1
| 6
|
@EventHandler
public void IronGolemMiningFatigue(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem.MiningFatigue.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getIronGolemConfig().getBoolean("IronGolem.MiningFatigue.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getIronGolemConfig().getInt("IronGolem.MiningFatigue.Time"), plugin.getIronGolemConfig().getInt("IronGolem.MiningFatigue.Power")));
}
}
|
3b4a4c82-c057-4e6f-913a-1b468b31121a
| 7
|
public void mainMenu()
{
System.out.println("Welcome grand overlord, What is your bidding?");
System.out.println("1:Print monthly sales");
System.out.println("2:Change Status");
System.out.println("3:Make Replenishment Order");
System.out.println("4:Delete Unneeded Sales");
System.out.println("5:Change Price");
System.out.println("6:Exit");
int input = scanner.nextInt();
switch (input)
{
case 1:
printSalesMenu();
break;
case 2:
statusChangeMenu();;
break;
case 3:
WarehouseController wcon = new WarehouseController(Main.EMART_CONNECTION);
int id = wcon.getShipId();
System.out.println("To which company?");
makeReplenishMenu(id, scanner.next());
break;
case 4:
System.out.println("Precious Customer Information has been deleted");
controller.deleteNotNeededSale();
break;
case 5:
System.out.println("Which product price to change?");
String cc = scanner.next();
System.out.println("Which price to change to?");
double ss = scanner.nextDouble();
controller.changePrice(cc, ss);
case 6:
try
{
Main.EMART_CONNECTION.close();
} catch (SQLException e)
{
e.printStackTrace();
}
System.exit(0);
break;
}
mainMenu();
}
|
2f7e79bb-6f8b-44fe-b789-d25f2b652601
| 8
|
private static Node add(Node node, Argument left, Argument right)
{
if (left.getType() == String.class || right.getType() == String.class ||
left.getType() == Character.class || right.getType() == Character.class)
{
String ls = left.asString();
String rs = right.asString();
return new StringArgument(node, ls + rs);
}
if (left.getType() == double.class || right.getType() == double.class)
{
double ld = left.asDouble();
double rd = right.asDouble();
return new FloatArgument(node, ld + rd);
}
if (left.isNumber() && right.isNumber())
{
long li = left.asLong();
long ri = right.asLong();
return new IntegerArgument(node, li + ri);
}
throw new EvaluationException(node, "Invalid Type for Operation: ADD");
}
|
c4ebd529-adc1-4965-bba1-c86c75e818b0
| 5
|
public ShopConfigurationPanel() {
super();
setLayout(new BorderLayout());
contents = new ShopData();
PropertySet ps = new PropertySet();
final FileProperty fpShopBackground = new FileProperty(
"Shop background image (160 \u00d7 120)", null);
final FileProperty fpShopButtonImage = new FileProperty(
"Shop button up image (64 \u00d7 64)", null);
final FileProperty fpShopButtonHover = new FileProperty(
"Shop button hover image", null);
final FileProperty fpShopButtonPressed = new FileProperty(
"Button pressed image", null);
final TextProperty tpUpgrade = new TextProperty("Upgrade text", null);
final TextProperty tpNotEnoughMoney = new TextProperty(
"Not enough money text", null);
final FileProperty fpPurchaseSound = new FileProperty("Purchase sound",
null);
final FileProperty fpInvalidPurchaseSound = new FileProperty(
"Invalid purchase sound", null);
ps.add(fpShopBackground);
ps.add(null);
ps.add(fpShopButtonImage);
ps.add(fpShopButtonHover);
ps.add(fpShopButtonPressed);
ps.add(null);
ps.add(tpUpgrade);
ps.add(tpNotEnoughMoney);
ps.add(null);
ps.add(fpPurchaseSound);
ps.add(fpInvalidPurchaseSound);
FileProperty[] images = { fpShopBackground, fpShopButtonImage,
fpShopButtonHover, fpShopButtonPressed };
for (FileProperty imageProperty : images) {
imageProperty.setFilter(ffImage);
}
fpPurchaseSound.setFilter(ffSoundWav);
fpInvalidPurchaseSound.setFilter(ffSoundWav);
fpShopBackground.setDescription("The background image for the shop.");
fpShopButtonImage
.setDescription("This is the button used for the background of shop items. It need not be optimized for nine-slice scaling.");
fpShopButtonHover
.setDescription("This image will be displayed when the user's mouse pointer is over a shop button.");
fpShopButtonPressed
.setDescription("This image will be displayed when the user is pressing a shop button.");
tpUpgrade
.setDescription("The text to display on the \"purchase upgrade\" button.");
tpNotEnoughMoney
.setDescription("The text to display on the \"purchase upgrade\" button when the user cannot afford the upgrade.");
fpPurchaseSound
.setDescription("The sound played on a purchase or upgrade.");
fpInvalidPurchaseSound
.setDescription("The sound played when the user cannot afford a purchase.");
ChangeListener cl = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
if (!isUpdating()) {
contents.shopBackground = fpShopBackground.getValue();
contents.shopButtonImage = fpShopButtonImage.getValue();
contents.shopButtonImageHover = fpShopButtonHover
.getValue();
contents.shopButtonImagePressed = fpShopButtonPressed
.getValue();
contents.doUpgrade = tpUpgrade.getValue();
contents.notEnoughMoney = tpNotEnoughMoney.getValue();
contents.purchaseSound = fpPurchaseSound.getValue();
contents.invalidPurchaseSound = fpInvalidPurchaseSound
.getValue();
}
}
};
for (AbstractProperty<?> p : ps) {
if (p != null) {
p.addChangeListener(cl);
}
}
rUpdate = new Runnable() {
@Override
public void run() {
fpShopBackground.setValue(contents.shopBackground);
fpShopButtonImage.setValue(contents.shopButtonImage);
fpShopButtonHover.setValue(contents.shopButtonImageHover);
fpShopButtonPressed.setValue(contents.shopButtonImagePressed);
tpUpgrade.setValue(contents.doUpgrade);
tpNotEnoughMoney.setValue(contents.notEnoughMoney);
fpPurchaseSound.setValue(contents.purchaseSound);
fpInvalidPurchaseSound.setValue(contents.invalidPurchaseSound);
}
};
add(new PropertyPanel(ps, true, false), BorderLayout.CENTER);
}
|
a1a9b90b-72f8-41c0-a8d1-054f297a41b0
| 7
|
public void setEmass(String emass) {
// 精密質量設定
this.emass = emass;
// 精密質量からソート用精密質量設定
if (!emass.equals("") && emass.length() != 0) {
this.sortEmass = Float.parseFloat(emass);
}
// 精密質量から表示用精密質量設定
StringBuffer dispEmass = new StringBuffer();
if (!emass.equals("") && emass.length() != 0) {
String forePeriod = ""; // ピリオド前
String backPeriod = ""; // ピリオド以降
if (emass.indexOf(".") != -1) {
forePeriod = emass.substring(0, emass.indexOf("."));
backPeriod = emass.substring(emass.indexOf("."));
}
else {
forePeriod = emass;
}
// 整数部を3桁にフォーマット(左空白詰め)
for (int i=4; i>0; i--) {
if (i == forePeriod.length()) {
dispEmass.append(forePeriod);
break;
}
else {
dispEmass.append(" ");
}
}
// 小数部を小数点付き5桁にフォーマット(右0詰め)
backPeriod = "0" + backPeriod;
backPeriod = backPeriodFormat.format(Double.parseDouble(backPeriod));
backPeriod = backPeriod.substring(backPeriod.indexOf("."));
// 整数部+小数部(小数点付き)
dispEmass.append(backPeriod);
}
this.dispEmass = dispEmass.toString();
}
|
0bd5d12d-cd35-45ca-8b25-391224bf0c6b
| 1
|
public static void UnloadWorld(String name, Boolean save) {
if (Core.getPlugin().getServer().getWorld(name) != null) {
Core.getPlugin().getServer().unloadWorld(name, save);
}
}
|
b59698c0-cfc5-4e72-827b-82634360691c
| 6
|
private void animate(Entity entity, int delta) {
combinedDelta += delta;
if(previousDir != dir){
if(previousDir == Direction.RIGHT && dir == Direction.LEFT ||
previousDir == Direction.LEFT && dir == Direction.RIGHT){
entity.flip();
previousDir = dir;
}
}
if(combinedDelta > 140){
nextFrame(entity);
combinedDelta = 0;
}
}
|
a6de6977-c7b4-4e6e-ac69-ef1be7e80419
| 9
|
public Query setParamsToQuery(Query query)
{
if (params != null)
{
for (int i = 0; i < params.size(); i++)
{
if (types.get(i) == null)
{
query.setParameter(params.get(i), values.get(i));
} else
{
query.setParameter(params.get(i), values.get(i),
types.get(i));
}
}
}
if (paramsList != null)
{
for (int i = 0; i < paramsList.size(); i++)
{
if (typesList.get(i) == null)
{
query.setParameterList(paramsList.get(i), valuesList.get(i));
} else
{
query.setParameterList(paramsList.get(i),
valuesList.get(i), typesList.get(i));
}
}
}
if (paramsArray != null)
{
for (int i = 0; i < paramsArray.size(); i++)
{
if (typesArray.get(i) == null)
{
query.setParameterList(paramsArray.get(i),
valuesArray.get(i));
} else
{
query.setParameterList(paramsArray.get(i),
valuesArray.get(i), typesArray.get(i));
}
}
}
return query;
}
|
965089df-77a7-4f4f-9b47-feb3355c9d46
| 8
|
public void checkCollisionWithWeapons() {
for (int i = 0; i < weaponList.size(); i++) {
for (int j = 0; j < boardSpawn.getEnemies().size(); j++) {
if (weaponList.get(i).getShape().intersects(boardSpawn.getEnemies().get(j).getShape())) {
if (weaponList.get(i) instanceof Star) {
weaponList.remove(i);
}
boardSpawn.getEnemies().remove(j);
}
}
}
for (int i = 0; i < weaponList.size(); i++) {
for (int j = 0; j < birdSpawn.getEnemies().size(); j++) {
if (weaponList.get(i).getShape().intersects(birdSpawn.getEnemies().get(j).getShape())) {
if (weaponList.get(i) instanceof Star) {
weaponList.remove(i);
}
birdSpawn.getEnemies().remove(j);
}
}
}
}
|
869cd0be-4855-4834-b4fc-e96095888a78
| 9
|
static void checkMethodDesc(final String desc) {
if (desc == null || desc.length() == 0) {
throw new IllegalArgumentException(
"Invalid method descriptor (must not be null or empty)");
}
if (desc.charAt(0) != '(' || desc.length() < 3) {
throw new IllegalArgumentException("Invalid descriptor: " + desc);
}
int start = 1;
if (desc.charAt(start) != ')') {
do {
if (desc.charAt(start) == 'V') {
throw new IllegalArgumentException("Invalid descriptor: "
+ desc);
}
start = checkDesc(desc, start, false);
} while (start < desc.length() && desc.charAt(start) != ')');
}
start = checkDesc(desc, start + 1, true);
if (start != desc.length()) {
throw new IllegalArgumentException("Invalid descriptor: " + desc);
}
}
|
b93acc84-0140-4153-9609-905b6310176b
| 8
|
private Command parse(String userInput) {
if (userInput == null) {
return null;
}
StringTokenizer tokenizer = new StringTokenizer(userInput);
if (tokenizer.countTokens() == 0) {
return null;
}
CommandName commandName = null;
String userName = null;
float amount = 0;
int userInputTokenNo = 1;
while (tokenizer.hasMoreTokens()) {
switch (userInputTokenNo) {
case 1:
try {
String commandNameString = tokenizer.nextToken();
commandName = CommandName.valueOf(CommandName.class, commandNameString);
} catch (IllegalArgumentException commandDoesNotExist) {
System.out.println("Illegal command");
return null;
}
break;
case 2:
userName = tokenizer.nextToken();
break;
case 3:
try {
amount = Float.parseFloat(tokenizer.nextToken());
} catch (NumberFormatException e) {
System.out.println("Illegal amount");
return null;
}
break;
default:
System.out.println("Illegal command");
return null;
}
userInputTokenNo++;
}
return new Command(commandName, userName, amount);
}
|
f552bc6c-9b0d-48eb-bcd9-7d9dff0db22e
| 9
|
@Override
public Node parse(Token token) throws IOException {
AttrNode node = null;
if (ExpressionParser.START.contains(token.type())) {
node = new AttrNode(startLine());
token = tokenizer().peek();
Token var = tokenizer().current();
if (ATTR.contains(token.type())) {
boolean first = true;
while (ATTR.contains(token.type())) {
Node n = null;
if (tokenizer().peek().type() == TokenType.LEFT_PAREN) {
CallParser call = new CallParser(this);
n = call.parse(var);
} else if (ExpressionParser.START.contains(var.type())) {
if (first) {
n = ParseUtil.value(var);
first = false;
} else {
n = ParseUtil.var(var);
}
} else {
error(ErrorCode.INVALID_EXPR);
}
if (n != null) {
node.add(n);
token = tokenizer().next();
if (ATTR.contains(token.type())) {
var = tokenizer().next();
}
}
}
} else if (tokenizer().current().type() == TokenType.LEFT_BRACKET) {
ArrayParser arrp = new ArrayParser(this);
Node n = arrp.parse(tokenizer().current());
node.add(n);
} else {
node.add(ParseUtil.value(tokenizer().current()));
tokenizer().next();
}
} else {
error(ErrorCode.INVALID_EXPR);
}
return node;
}
|
56c3414a-f844-4c00-99ca-196863ba504f
| 7
|
@SuppressWarnings("deprecation")
private boolean setAirIfAllowed(World world, int x, int y, int z, boolean dungeonGen)
{
if(canSetAir(world, x, y, z, dungeonGen))
{
setBlock(world, x, y, z, 0);
int id = getBlock(world, x, y+1, z);
if(id == Material.SNOW.getId() ||
id == Material.YELLOW_FLOWER.getId() ||
id == Material.RED_ROSE.getId() ||
id == Material.LONG_GRASS.getId() ||
id == Material.RED_MUSHROOM.getId() ||
id == Material.BROWN_MUSHROOM.getId())
setBlock(world, x, y+1, z, 0);
return true;
}
return false;
}
|
2fe0d4ad-420f-4c68-a149-3e86c8d55d47
| 7
|
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
// Make sure we are responding to the right event.
if (propertyName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
File selection = (File)e.getNewValue();
String name;
if (selection == null)
return;
else
name = selection.getAbsolutePath();
if ((name != null) &&
name.toLowerCase().endsWith(".jpg") ||
name.toLowerCase().endsWith(".jpeg") ||
name.toLowerCase().endsWith(".gif") ||
name.toLowerCase().endsWith(".png")){
icon = new ImageIcon(name);
image = icon.getImage();
scaleImage();
repaint();
}
}
}
|
f8d3e14c-7ba4-4903-97af-b16359edb0b8
| 1
|
private static void method501(char arg0[]) {
char ac1[] = arg0.clone();
char ac2[] = { '(', 'a', ')' };
Censor.method509(null, ac1, ac2);
char ac3[] = arg0.clone();
char ac4[] = { 'd', 'o', 't' };
Censor.method509(null, ac3, ac4);
for (int i = Censor.aCharArrayArray623.length - 1; i >= 0; i--) {
Censor.method502(arg0, Censor.aCharArrayArray623[i], ac3, ac1);
}
}
|
01262c61-0d63-4d26-8485-c6c7085c3f8c
| 7
|
@Override
public void paint(Graphics2D g) {
if (drawAll && StateHandler.instance.getCurrentState() == State.PLAYING) {
for (int i = 0; i < rectangles.size(); i++) {
g.setColor(ColorUtils.getAlpha(BOX_COLOR, 150));
g.fillRoundRect(rectangles.get(i).x, rectangles.get(i).y,
rectangles.get(i).width, rectangles.get(i).height, 10,
10);
g.setColor(Color.WHITE);
g.drawRoundRect(rectangles.get(i).x, rectangles.get(i).y,
rectangles.get(i).width, rectangles.get(i).height, 10,
10);
if (rectangles.get(i).contains(
InputHandler.instance.getMouseLocation())
&& !InputHandler.instance.mouseIsPressed()) {
g.setColor(ColorUtils.getAlpha(Color.WHITE, 35));
g.fillRoundRect(rectangles.get(i).x, rectangles.get(i).y,
rectangles.get(i).width, rectangles.get(i).height,
10, 10);
inactiveTimer.reset();
} else if (rectangles.get(i).contains(
InputHandler.instance.getMouseLocation())
&& InputHandler.instance.mouseIsPressed()) {
g.setColor(ColorUtils.getAlpha(Color.WHITE, 20));
g.fillRoundRect(rectangles.get(i).x, rectangles.get(i).y,
rectangles.get(i).width, rectangles.get(i).height,
10, 10);
inactiveTimer.reset();
}
}
} else {
g.setColor(ColorUtils.getAlpha(BOX_COLOR, 150));
g.fillRoundRect(rectangles.get(0).x, rectangles.get(0).y,
rectangles.get(0).width, rectangles.get(0).height, 10, 10);
g.setColor(Color.WHITE);
g.drawRoundRect(rectangles.get(0).x, rectangles.get(0).y,
rectangles.get(0).width, rectangles.get(0).height, 10, 10);
}
}
|
9e1ec15b-99cf-414e-aad9-6f1163804481
| 0
|
public void registerStopWatchListener(StopWatchListener listener) {
this.listener = listener;
}
|
8582ead8-367b-499c-8130-bd5aeb4cf4b3
| 6
|
public static void main(String[] args) throws NumberFormatException, IOException{
BufferedReader strin;
boolean choice = true;
int gameNum = 0;
int win = 0;
int lose = 0;
while (choice){
Random random = new Random();
int n = random.nextInt(10);
boolean success = false;
gameNum++;
int count = 0;
while (count++ < 3){
strin = new BufferedReader(new InputStreamReader(System.in));
int un = Integer.parseInt(strin.readLine());
if (un > n){
System.out.println("你猜的数字太大了");
}else if (un < n){
System.out.println("你猜的数字太小了");
}else{
System.out.println("恭喜你,猜对了");
success = true;
win++;
break;
}
}
if (!success){
System.out.println("游戏失败");
lose++;
}
System.out.println("是否继续新的游戏?y or n");
strin = new BufferedReader(new InputStreamReader(System.in));
choice = strin.readLine().equalsIgnoreCase("y");
if (!choice){
break;
}
}
System.out.println("你共进行了"+gameNum+"次游戏,成功"+win+"次,失败"+lose+"次");
}
|
e5eeffc5-395b-46d1-bd6d-6ff00ec24ac6
| 0
|
public synchronized void addUnsearchList(String url){
this.unsearchSitesList.add(url);
}
|
4aba884b-f602-4810-b074-dc17f3b4128e
| 8
|
@Override
public FSMNode<EventType> nodeToTransitTo(StateMachineEvent<EventType> event) throws InvalidEventException {
if (aspects != null && !aspects.onTransitionStart(event))
return null;
try {
FSMNode<EventType> target = delegate.nodeToTransitTo(event);
if (target == null) {
if (aspects != null)
aspects.onNullTransition(event);
return null;
}
if (aspects != null && !aspects.onControlLeavesState(event, delegate.getState(), target.getState()))
return null;
else
return target;
} catch(InvalidEventException e){
if (aspects != null)
aspects.onTransitionFinish(event, delegate.getState(), delegate.getState());
throw e;
}
}
|
a237818b-7dca-4c54-855c-988f3a78af6b
| 0
|
public OnlineSearch(Settings settings)
{
SEARCH_JUMPLENGTH = settings.getSearchJumpLength();
SEARCH_SENTENCELENGTH = settings.getCompareSentenceLength();
MAX_URLS = settings.getSearchNumLinks();
URL = settings.getSearchURL();
URL_ARGS = settings.getSearchURLArgs();
URL_ARG_AUTH = settings.getSearchAuthArg();
URL_ARG_SEARCH = settings.getSearchSearchArg();
_logger.debug("URL: " + URL);
_logger.debug("URL_ARGS: " + URL_ARGS);
_logger.debug("URL_ARG_AUTH: " + URL_ARG_AUTH);
_logger.debug("URL_ARG_SEARCH: " + URL_ARG_SEARCH);
}
|
ab40bdee-f0ce-44b4-9838-1506f4422067
| 3
|
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
pressed = true;
}
if (pressed && e.getKeyCode() == KeyEvent.VK_V) {
adaptee.pasteClipboard();
}
}
|
ca5e2760-1003-4ce1-93b0-04e37c84e4e7
| 3
|
public void writeExternalWithoutImages(ObjectOutput paramObjectOutput) throws IOException
{
paramObjectOutput.writeObject(this.location);
paramObjectOutput.writeObject(this.LastPosition);
paramObjectOutput.writeObject(this.LastCell);
boolean[][] arrayOfBoolean = new boolean[this.shape.length][this.shape[0].length];
for (int i = 0; i < this.shape.length; i++)
for (int j = 0; j < this.shape[0].length; j++)
if (this.shape[i][j] == null)
arrayOfBoolean[i][j] = false;
else
arrayOfBoolean[i][j] = true;
paramObjectOutput.writeObject(arrayOfBoolean);
paramObjectOutput.writeObject(this.ID);
paramObjectOutput.writeBoolean(this.animated);
paramObjectOutput.writeObject(this.url_target);
paramObjectOutput.writeObject(this.frame);
paramObjectOutput.writeObject(this.layer);
}
|
05b1b8f5-f0fd-46e2-b58f-0bb78a132728
| 4
|
public static int getGreatestProdDownColumns(int[][] arr, int maxDigits, int columns, int rows) {
int sum = 0;
for(int i = 0; i < rows; i++) {
int prod = 0;
while((prod) < (columns-(maxDigits-1))) {
int tmpProd = 1;
int curr = prod;
for(int it = 0; it < maxDigits; it++) {
tmpProd = tmpProd * arr[curr + it][i];
// System.out.print(curr + it + ", ");
// System.out.print(i + ":");
// System.out.print(arr[curr + it][i] + " ");
}
if(sum < tmpProd)
sum = tmpProd;
prod++;
// System.out.println();
}
// System.out.println();
}
return sum;
}
|
95fd2eb7-f81a-4126-acf5-f028cb9dc398
| 7
|
public Symbol debug_parse()
throws java.lang.Exception
{
/* the current action code */
int act;
/* the Symbol/stack element returned by a reduce */
Symbol lhs_sym = null;
/* information about production being reduced with */
short handle_size, lhs_sym_num;
/* set up direct reference to tables to drive the parser */
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
debug_message("# Initializing parser");
/* initialize the action encapsulation object */
init_actions();
/* do user initialization */
user_init();
/* the current Symbol */
cur_token = scan();
debug_message("# Current Symbol is #" + cur_token.sym);
/* push dummy Symbol with start state to get us underway */
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START",0, start_state()));
tos = 0;
/* continue until we are told to stop */
for (_done_parsing = false; !_done_parsing; )
{
/* Check current token for freshness. */
if (cur_token.used_by_parser)
throw new Error("Symbol recycling detected (fix your scanner).");
/* current state is always on the top of the stack */
//debug_stack();
/* look up action out of the current state with the current input */
act = get_action(stack.peek().parse_state, cur_token.sym);
/* decode the action -- > 0 encodes shift */
if (act > 0)
{
/* shift to the encoded state by pushing it on the stack */
cur_token.parse_state = act-1;
cur_token.used_by_parser = true;
debug_shift(cur_token);
stack.push(cur_token);
tos++;
/* advance to the next Symbol */
cur_token = scan();
debug_message("# Current token is " + cur_token);
}
/* if its less than zero, then it encodes a reduce action */
else if (act < 0)
{
/* perform the action for the reduce */
lhs_sym = do_action((-act)-1, this, stack, tos);
/* look up information about the production */
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
debug_reduce((-act)-1, lhs_sym_num, handle_size);
/* pop the handle off the stack */
for (int i = 0; i < handle_size; i++)
{
stack.pop();
tos--;
}
/* look up the state to go to from the one popped back to */
act = get_reduce(stack.peek().parse_state, lhs_sym_num);
debug_message("# Reduce rule: top state " +
stack.peek().parse_state +
", lhs sym " + lhs_sym_num + " -> state " + act);
/* shift to that state */
lhs_sym.parse_state = act;
lhs_sym.used_by_parser = true;
stack.push(lhs_sym);
tos++;
debug_message("# Goto state #" + act);
}
/* finally if the entry is zero, we have an error */
else if (act == 0)
{
/* call user syntax error reporting routine */
syntax_error(cur_token);
/* try to error recover */
if (!error_recovery(true))
{
/* if that fails give up with a fatal syntax error */
unrecovered_syntax_error(cur_token);
/* just in case that wasn't fatal enough, end parse */
done_parsing();
} else {
lhs_sym = stack.peek();
}
}
}
return lhs_sym;
}
|
cd11d85c-442d-4cb0-918d-a20dd840c086
| 4
|
@Override
public void scoreRound(boolean won, int score) {
if (TRAIN_score && old_score != null){
//Final target value is the final score
old_score.output = score / max_points;
//old_score.output = won ? 1 : 0;
train_data.add(old_score);
//Train the network
//Give higher learning rate to more recent data
double rate = LEARN_RATE - train_data.size()*learn_rate_decay;
//double rate = .01;
double[] target = new double[1];
for (DataInstance d: train_data){
//Wait until learning rate breaks above zero
rate += learn_rate_decay;
if (rate <= 0) continue;
//Train this data
target[0] = d.output;
score_net.compute(d.inputs);
score_net.trainBackprop(rate, target);
}
train_data.clear();
}
}
|
e9731f9d-f21e-4996-9339-b581b1659e82
| 8
|
@Override
public void deserialize(Buffer buf) {
super.deserialize(buf);
maxPods = buf.readShort();
if (maxPods < 0)
throw new RuntimeException("Forbidden value on maxPods = " + maxPods + ", it doesn't respect the following condition : maxPods < 0");
prospecting = buf.readShort();
if (prospecting < 0)
throw new RuntimeException("Forbidden value on prospecting = " + prospecting + ", it doesn't respect the following condition : prospecting < 0");
wisdom = buf.readShort();
if (wisdom < 0)
throw new RuntimeException("Forbidden value on wisdom = " + wisdom + ", it doesn't respect the following condition : wisdom < 0");
taxCollectorsCount = buf.readByte();
if (taxCollectorsCount < 0)
throw new RuntimeException("Forbidden value on taxCollectorsCount = " + taxCollectorsCount + ", it doesn't respect the following condition : taxCollectorsCount < 0");
taxCollectorAttack = buf.readInt();
kamas = buf.readInt();
if (kamas < 0)
throw new RuntimeException("Forbidden value on kamas = " + kamas + ", it doesn't respect the following condition : kamas < 0");
experience = buf.readDouble();
if (experience < 0)
throw new RuntimeException("Forbidden value on experience = " + experience + ", it doesn't respect the following condition : experience < 0");
pods = buf.readInt();
if (pods < 0)
throw new RuntimeException("Forbidden value on pods = " + pods + ", it doesn't respect the following condition : pods < 0");
itemsValue = buf.readInt();
if (itemsValue < 0)
throw new RuntimeException("Forbidden value on itemsValue = " + itemsValue + ", it doesn't respect the following condition : itemsValue < 0");
}
|
7b7170de-f7b4-44b2-ad28-1220d373a39a
| 4
|
private static void compare(List<String> urlsOrFiles, String[] testSetIdArr) throws Exception {
List<TestResultData> testNgResultData = parseTestNgResultFromFilesOrUrls(urlsOrFiles);
List<String> testNgTests =
(List<String>) CollectionUtils
.collect(testNgResultData, new BeanToPropertyValueTransformer("testName"));
Collections.sort(testNgTests);
List<QcTestCase> qcTestCases = getAllTestCasesFromTestSets(testSetIdArr);
List<String> qcTestNames =
(List<String>) CollectionUtils.collect(qcTestCases, new BeanToPropertyValueTransformer("name"));
Collections.sort(qcTestNames);
File csvFile = new File("testNgQcDiv.csv");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(csvFile));
for (String testNgTestName : testNgTests) {
bw.write(testNgTestName + ",");
// for(String qcTestName: qcTestNames){
// if(qcTestName.contains(testNgTestName)){
if (qcTestNames.contains(testNgTestName)) {
bw.write(testNgTestName);
}
// break;
// }
// }
bw.write("\n");
}
} catch (Exception e) {
throw e;
} finally {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
4bffe9a5-08a9-4071-877b-a3319a41f5cf
| 9
|
public SetupHeader(VorbisStream vorbis, BitInputStream source) throws VorbisFormatException,
IOException {
if (source.getLong(48) != HEADER) {
throw new VorbisFormatException("The setup header has an illegal leading.");
}
// read code books
int codeBookCount = source.getInt(8) + 1;
codeBooks = new CodeBook[codeBookCount];
for (int i = 0; i < codeBooks.length; i++) {
codeBooks[i] = new CodeBook(source);
}
// read the time domain transformations,
// these should all be 0
int timeCount = source.getInt(6) + 1;
for (int i = 0; i < timeCount; i++) {
if (source.getInt(16) != 0) {
throw new VorbisFormatException("Time domain transformation != 0");
}
}
// read floor entries
int floorCount = source.getInt(6) + 1;
floors = new Floor[floorCount];
for (int i = 0; i < floorCount; i++) {
floors[i] = Floor.createInstance(source, this);
}
// read residue entries
int residueCount = source.getInt(6) + 1;
residues = new Residue[residueCount];
for (int i = 0; i < residueCount; i++) {
residues[i] = Residue.createInstance(source, this);
}
// read mapping entries
int mappingCount = source.getInt(6) + 1;
mappings = new Mapping[mappingCount];
for (int i = 0; i < mappingCount; i++) {
mappings[i] = Mapping.createInstance(vorbis, source, this);
}
// read mode entries
int modeCount = source.getInt(6) + 1;
modes = new Mode[modeCount];
for (int i = 0; i < modeCount; i++) {
modes[i] = new Mode(source, this);
}
if (!source.getBit()) {
throw new VorbisFormatException("The setup header framing bit is incorrect.");
}
}
|
b54d9033-8043-4ecf-b34b-b6001c27888f
| 0
|
private void listen() {
ListenThread thread = new ListenThread();
thread.start();
}
|
f3e0bab2-c106-497a-8bc5-b9c11955dfc4
| 9
|
private void cleaningText() {
int latinCount = 0, nonLatinCount = 0;
for(int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c <= 'z' && c >= 'A') {
++latinCount;
} else if (c >= '\u0300' && UnicodeBlock.of(c) != UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) {
++nonLatinCount;
}
}
if (latinCount * 2 < nonLatinCount) {
StringBuffer textWithoutLatin = new StringBuffer();
for(int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c > 'z' || c < 'A') textWithoutLatin.append(c);
}
text = textWithoutLatin;
}
}
|
efe7764e-a6e9-41e2-9e53-15ad4e9d992f
| 7
|
private void solve() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
skill = new int[n];
gender = new char[n];
out = new boolean[n];
prev = new int[n];
next = new int[n];
prev[0] = 0;
next[0] = 1;
prev[n-1] = n-2;
next[n-1] = n-1;
for (int i = 1; i <= n-2; i++) {
prev[i] = i-1;
next[i] = i+1;
}
String s = sc.next();
int numBoy = 0;
for (int i = 0; i < n; i++) {
gender[i] = s.charAt(i);
if (gender[i] == 'B') numBoy++;
}
for (int i = 0; i < n; i++) {
skill[i] = sc.nextInt();
}
System.out.println(Math.min(numBoy, n-numBoy));
for (int i = 0; i < n-1; i++) {
if (gender[i] != gender[i+1]) {
queue.add(new Pair(i, i+1, calcSkillDiff(i, i+1)));
}
}
while(!queue.isEmpty()) {
Pair pair = queue.poll();
processPair(pair);
}
}
|
ddee6cce-a57f-4e9e-bf79-f9723516bada
| 2
|
public int compareTo(FolderWatcherQueue t1) {
{
if (date.before(t1.getDate())) {
return -1;
}
if (date.after(t1.getDate())) {
return 1;
}
return 0;
}
}
|
11be2bb3-813e-4839-8828-688b9b3d58fb
| 7
|
public void establishInitialConnection() throws FileNotFoundException , IOException{
String line_in_file, full_html = "";
FileReader html_file = new FileReader("page.html");
//FileWriter temp = new FileWriter("tmp.abc")
BufferedReader html_file_br = new BufferedReader(html_file);
while( (line_in_file=html_file_br.readLine() ) != null){
full_html= full_html + line_in_file + "\n";
}
System.out.println("Waiting for connection ");
ServerSocket Server;
try{
Server = new ServerSocket (SERVER_PORT);
Server.setReuseAddress(true);
}catch(Exception e){
System.out.println("Issue with close connection ?? !!!!!!!!! " + e.toString() +"\n\n" );
//System.out.println("Cause : " + e.getCause() );
return;
}
Socket connection = Server.accept();
try{
InputStream input_stream= connection.getInputStream();
int num_of_chars = input_stream.available();
try{
Thread.currentThread().sleep(200);
}catch(InterruptedException e){
System.out.println("NOT able to sleep :( :( :( ");
}
num_of_chars = input_stream.available();
//System.out.println("Inside while loop");
char input_char_seq[] = new char[num_of_chars];
for(int j =0;j<input_stream.available() ; j++){
input_char_seq[j] = (char) input_stream.read();
}
String client_string = new String(input_char_seq);
//System.out.println( "Intial connection url : " + client_string );
if(client_string.indexOf("server.html") > 0)
html_sent++;
}catch(IOException io){
}
connection.setSoLinger(false, 0);
PrintWriter outToClient = new PrintWriter(connection.getOutputStream(),true);
String header="HTTP/1.1: 200 OK\r\n"+"Content-Type: text/html\r\n" + "\r\n";
outToClient.println(header + full_html);
connection.shutdownOutput();
outToClient.close();
connection.close();
if(!connection.isClosed() ) {
System.out.println("Cannot close the connection and create another 1 ");
return;
}
System.out.println("Sent the html ");
Server.close();
return;
}
|
52958a0b-bba4-4e88-99f1-10d836d2062b
| 0
|
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
Outliner.documents.addTreeSelectionListener(this);
setEnabled(false);
}
|
9aa5c156-9870-43b0-9797-0a46dcc4cce8
| 9
|
public static int getItemBurnTime(ItemStack par1ItemStack)
{
if (par1ItemStack == null)
{
return 0;
}
else
{
int var1 = par1ItemStack.getItem().shiftedIndex;
if (var1 < 256 && Block.blocksList[var1].blockMaterial == Material.wood) return 300;
if (var1 == Item.stick.shiftedIndex) return 100;
if (var1 == Item.coal.shiftedIndex) return 1600;
if (var1 == Item.bucketLava.shiftedIndex) return 20000;
if (var1 == Block.sapling.blockID) return 100;
if (var1 == Item.blazeRod.shiftedIndex) return 2400;
int ret = ForgeHooks.getItemBurnTime(par1ItemStack);
return (ret > 0 ? ret : ModLoader.addAllFuel(par1ItemStack.itemID, par1ItemStack.getItemDamage()));
}
}
|
12b60b2b-28a4-45c3-8971-0f17030b1b8d
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PacketEntry other = (PacketEntry) obj;
if (underlyingPacket == null) {
if (other.underlyingPacket != null)
return false;
} else if (!underlyingPacket.equals(other.underlyingPacket))
return false;
return true;
}
|
e7b22b79-8f0a-4e5a-933d-5f6b0b3ab20f
| 1
|
protected Class<? extends AnnotatedElement> getAnnotatedElementType()
{
return this.annotatedElementType;
}
|
a7a9b8ab-787d-4c6b-a10d-628a380439be
| 8
|
private final void enableDeviceSpecificEvents (boolean b)
{
enableMotorVelocityChangeEvents (b && motorVelocityChangeListeners.size () > 0);
enableCurrentChangeEvents (b && currentChangeListeners.size () > 0);
enableCurrentUpdateEvents (b && currentUpdateListeners.size () > 0);
enableInputChangeEvents (b && inputChangeListeners.size () > 0);
enableEncoderPositionChangeEvents (b && encoderPositionChangeListeners.size () > 0);
enableEncoderPositionUpdateEvents (b && encoderPositionUpdateListeners.size () > 0);
enableBackEMFUpdateEvents (b && backEMFUpdateListeners.size () > 0);
enableSensorUpdateEvents (b && sensorUpdateListeners.size () > 0);
}
|
cd550d45-f9cc-4449-b39a-cfa18737f43a
| 6
|
@Override
public void paintComponent(Graphics g) {
Object map = Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); //$NON-NLS-1$
if (map != null) {
((Graphics2D) g).addRenderingHints((Map<?, ?>) map);
}
Rectangle clip = this.getVisibleRect();
// line numbering is always there regardless of horizontal scroll
// if you don't make the width static and drag the code editor
// so that line numbers are outside the mdi area, the numbers smudge
clip.setSize(this.getWidth(), clip.height);
final int insetY = metrics.getLeading() + metrics.getAscent();
final int gh = metrics.getHeight();
int lineNum = clip.y / gh;
final int start = lineNum * gh + insetY;
final int end = clip.y + clip.height + gh;
if (!startZero) {
lineNum++;
}
g.setColor(bgColor);
// g.fillRect(clip.x,clip.y,clip.width,clip.height);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(fgColor);
g.setFont(new Font("Monospace", Font.PLAIN, 12)); //$NON-NLS-1$
for (int y = start; lineNum < lines && y <= end; lineNum++, y += gh) {
String str = Integer.toString(lineNum);
int strw = (int) g.getFontMetrics().getStringBounds(str, g).getWidth();
g.drawString(str, clip.width - strw - 3, y);
}
}
|
6095d91a-c385-4ad5-a554-779e1d113ec2
| 8
|
public void nettavisen(URL uri, String url) {
try {
HttpURLConnection web = (HttpURLConnection) uri.openConnection();
web.setRequestMethod("GET");
web.connect();
int code = web.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
web.getInputStream()));
String httpString;
String title = null;
int i = 0;
while ((httpString = in.readLine()) != null) {
if (httpString.length() > 0)
i++;
if (httpString.indexOf("<h1 class=\"title\">") >= 0) {
httpString = in.readLine();
title = httpString.trim();
}
if (title != null) {
if (url.length() >= 70) {
URL tu = new URL(
"http://tinyurl.com/api-create.php?url="
+ url);
HttpURLConnection tuweb = (HttpURLConnection) tu
.openConnection();
tuweb.setRequestMethod("GET");
tuweb.connect();
int tucode = web.getResponseCode();
if (tucode == HttpURLConnection.HTTP_OK) {
BufferedReader tuin = new BufferedReader(
new InputStreamReader(tuweb
.getInputStream()));
String turl = tuin.readLine();
System.out.println(turl);
Actions.say("[" + title.replace('\n', ' ')
+ "] - " + turl, channel, server);
}
}
else
Actions.say("[" + title.replace('\n', ' ') + "]",
channel, server);
in.close();
break;
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
514625fa-38fa-4afc-894a-03aac8e6fd68
| 1
|
public void restoreScreen() {
Window window = device.getFullScreenWindow();
if(window != null) {
window.dispose();
}
device.setFullScreenWindow(null);
}
|
5ae247e1-5bfe-4141-aef7-8d4f91d754b1
| 2
|
public static Node followXpath (Node start, String Xpath) throws DOMException {
StringTokenizer tokenizer = new StringTokenizer(Xpath, "/");
if (tokenizer.countTokens() == 0) {
String invalidXpath = Xpath + " is an invalid Xpath!";
throw new DOMException(DOMException.SYNTAX_ERR, invalidXpath);
}
Node current = start;
String localXpath;
while (tokenizer.hasMoreTokens()) {
localXpath = tokenizer.nextToken();
current = followLocalXpath(current, localXpath);
}
return current;
}
|
94df1f84-94b4-481c-b193-190e1226ad4b
| 9
|
public void run() {
Vector<Long> historyBytes = new Vector<Long>();
int maxSize = 20;
while (true) {
long timeInit = System.currentTimeMillis();
if (!copier.getPause()){
historyBytes.add(0,copier.readAndInitBytesCounter());
if (historyBytes.size() > maxSize) historyBytes.removeElementAt(historyBytes.size()-1);
double average = 0;
for (long l : historyBytes){
average += l;
}
try{
average /= (historyBytes.size()*refreshRate/1000f);
//System.out.println(DialogMsg.prettySize((long)average));
String totalETA = "%";
String currentETA = "%";
String currentSpeed = "";
if (average > 0){
if (copier.getTotalBytesRemaining()>0) {
totalETA += " - "+DialogMsg.prettyTime((long)(copier.getTotalBytesRemaining()/average));
currentSpeed = " ("+DialogMsg.prettySpeed((long)average)+")";
}
if (copier.getCurrentBytesRemaining()>0)
currentETA += " - "+DialogMsg.prettyTime((long)(copier.getCurrentBytesRemaining()/average));
}
supPanel.mainBar.setValue(copier.getTotalPercent());
supPanel.fileBar.setValue(copier.getCurrentPercent());
supPanel.mainBar.setString(copier.getTotalPercent()+totalETA);
supPanel.fileBar.setString(copier.getCurrentPercent()+currentETA);
setTitle(copier.getTotalPercent()+"%"+currentSpeed+" MiniCopier");
} catch (Exception e){e.printStackTrace();}
}
try {Thread.sleep(refreshRate-(int)(System.currentTimeMillis()-timeInit));}
catch (Exception e){}
}
}
|
cb3bb6ab-72a1-45a0-b140-286305c63bea
| 7
|
public Item(String name, String catagoryStr, String type) throws SalesTaxApplicationException {
super();
if (name != null && name.length() > 0) {
this.name = name;
} else {
throw new SalesTaxApplicationException("No item name specified !");
}
if (catagoryStr.equals("FOOD"))
this.catagory = Catagory.FOOD;
else if (catagoryStr.equals("BOOK"))
this.catagory = Catagory.BOOK;
else if (catagoryStr.equals("MEDICAL"))
this.catagory = Catagory.MEDICAL;
else if (catagoryStr.equals("OTHER"))
this.catagory = Catagory.OTHER;
else
throw new SalesTaxApplicationException("No such item catagory !");
this.isImported = type.equalsIgnoreCase("import") ? true : false;
}
|
f1811197-d586-4f97-a23f-3ded28f86ae4
| 8
|
public void initControllers() throws SlickException {
if (controllersInited) {
return;
}
controllersInited = true;
try {
Controllers.create();
int count = Controllers.getControllerCount();
for (int i = 0; i < count; i++) {
Controller controller = Controllers.getController(i);
if ((controller.getButtonCount() >= 3) && (controller.getButtonCount() < MAX_BUTTONS)) {
controllers.add(controller);
}
}
Log.info("Found "+controllers.size()+" controllers");
for (int i=0;i<controllers.size();i++) {
Log.info(i+" : "+((Controller) controllers.get(i)).getName());
}
} catch (LWJGLException e) {
if (e.getCause() instanceof ClassNotFoundException) {
throw new SlickException("Unable to create controller - no jinput found - add jinput.jar to your classpath");
}
throw new SlickException("Unable to create controllers");
} catch (NoClassDefFoundError e) {
// forget it, no jinput availble
}
}
|
36e83298-d5bc-43cf-a800-d02243840920
| 7
|
public static boolean isSupport(ABObject o2, ABObject o1) {
if (o2.x == o1.x && o2.y == o1.y && o2.width == o1.width
&& o2.height == o1.height)
return false;
int ex_o1 = o1.x + o1.width;
int ex_o2 = o2.x + o2.width;
int ey_o2 = o2.y + o2.height;
if ((Math.abs(ey_o2 - o1.y) < gap)
&& !(o2.x - ex_o1 > gap || o1.x - ex_o2 > gap))
return true;
return false;
}
|
5a7f7a33-80e0-4901-9d26-dbb97ce253d0
| 4
|
public static Input readInput(File file) throws InputException {
if ((file != null) && (file.canRead())) {
try {
Input input = readInputFromFile(file);
verifyInput(input);
return input;
} catch (InputException exception) {
throw exception;
} catch (IOException e) {
throw new InputException(ERR_READ_FILE);
}
}
throw new InputException(ERR_READ_FILE);
}
|
a3f185f7-6588-4f41-a8d7-5123d708b82b
| 9
|
public synchronized int getNextIndex() {
int i, count = dataListModel.getSize();
if (nextIndex == -1) {
switch(playMode) {
case 1: break; //不改变
case 3: curIndex = (int)(Math.random()*count); break; //任意的
default: curIndex = (curIndex + 1 == count) ? 0 : curIndex + 1; break;
}
}
else {
curIndex = nextIndex;
nextIndex = -1;
}
for (i = 0; i < count; i++) {
PlayListItem item = (PlayListItem) dataListModel.get(curIndex);
if (item.available()) {
repaint();
return curIndex;
}
switch(playMode) {
case 1: break;
case 3: curIndex = (int)(Math.random()*count); break;
default: curIndex = (curIndex + 1 == count) ? 0 : curIndex + 1; break;
}
}
return -1;
}
|
0c268a77-b08d-4e92-8a07-39d3500dfa24
| 0
|
public final URL getDownloadUrl() {
return downloadUrl;
}
|
fac559d1-f9ca-4e6f-8f1c-1dc96ba0fb79
| 7
|
@SuppressWarnings("unchecked")
<T> T convertInternal(Object value, Type type) throws JSONException {
if (type instanceof TypeReference<?>) {
type = ((TypeReference<?>)type).getType();
}
Class<?> cls = ClassUtil.getRawType(type);
T result = null;
try {
enter('$', null);
result = (T)postparse(this, value, cls, type);
exit();
} catch (Exception e) {
String text;
if (value instanceof CharSequence) {
text = "\"" + value + "\"";
} else {
try {
text = value.toString();
} catch (Exception e2) {
text = value.getClass().toString();
}
}
throw new JSONException(getMessage("json.parse.ConversionError", text, type, this),
JSONException.POSTPARSE_ERROR, e);
}
return result;
}
|
072e366e-5d75-4d6f-a8d5-7fc1cb0ef6aa
| 3
|
@Override
public BufferedImage generate() {
BufferedImage completePic = new BufferedImage(xSize, ySize,
BufferedImage.TYPE_INT_RGB);
// initialises to false
completedPixels = new boolean[xSize][ySize];
for (int i = 0; i < xSize; i++) {
for (int j = 0; j < ySize; j++) {
// spots() may have got here first!
if (completedPixels[i][j] == false) {
Color newPixel = colGen.getPixel();
completePic.setRGB(i, j, newPixel.getRGB());
completedPixels[i][j] = true;
this.spots(i, j, completePic, newPixel.getRGB());
}
}
}
return completePic;
}
|
36cb6998-9143-43e3-bf1c-51a630ca0c59
| 7
|
public boolean eventGeneratable(String eventName) {
if (eventName.equals("configuration") && m_Filter != null) {
return true;
}
// can't generate the named even if we are not receiving it as an
// input!
if (!m_listenees.containsKey(eventName)) {
return false;
}
Object source = m_listenees.get(eventName);
if (source instanceof EventConstraints) {
if (!((EventConstraints)source).eventGeneratable(eventName)) {
return false;
}
}
if (eventName.compareTo("instance") == 0) {
if (!(m_Filter instanceof StreamableFilter)) {
return false;
}
}
return true;
}
|
465cd67b-d7fe-4886-ae36-34b90c1f73dd
| 5
|
public void renderSprites(Bitmap bm) {
boolean visible = true;
TreeSet<Sprite> sortedSprites = new TreeSet<Sprite>(spriteComparator);
for (Sprite s : entities) {
if (visible) sortedSprites.add(s);
}
for (Sprite s : particles) {
if (visible) sortedSprites.add(s);
}
sortedSprites.addAll(mapSprites);
for (Sprite s : sortedSprites) {
s.render(bm);
}
}
|
b3ad4b37-43ed-4622-ae84-db52df982083
| 0
|
public Scene(Ticker ticker, GameWorld gameWorld) {
buffer = new FrameBuffer(1024, 768, FrameBuffer.SAMPLINGMODE_NORMAL);
buffer.disableRenderer(IRenderer.RENDERER_SOFTWARE);
buffer.enableRenderer(IRenderer.RENDERER_OPENGL);
this.gameWorld = gameWorld;
camera = new Camera(gameWorld, ticker, buffer);
gameWorld.tunePositionCamera(camera);
}
|
45202917-0007-48aa-919a-2d2c8b353cdf
| 1
|
public static List<TreeWorker> getsavedTrees() {
if(savedTreeWorker==null)savedTreeWorker=new ArrayList<TreeWorker>();
return savedTreeWorker;
}
|
bd658153-6b5b-4258-90e7-966b38b24364
| 4
|
void bounce(Dimension size) {
if ((position.x <= 0 & xOffset < 0)
|| (position.x >= size.width & xOffset > 0)) {
xOffset *= -1;
}
if ((position.y <= 0 & yOffset < 0)
|| (position.y >= size.height & yOffset > 0)) {
yOffset *= -1;
}
}
|
cfc88b55-b464-42f3-9799-62ef83f0f48f
| 3
|
public static void main(String[] args) throws InterruptedException {
JFrame view = initWindow();
Supervisor.registerFrame(view);
Stats constStatsInit = new HashMapStats();
constStatsInit.put(new Stat(StatType.C_CREATURE_CLASS, 1.0));
constStatsInit.put(new Stat(StatType.C_ATTACK, 10.0));
constStatsInit.put(new Stat(StatType.C_MAX_HEALTH, 100.0));
constStatsInit.put(new Stat(StatType.C_VISION_RADIUS, 2000.0));
Stats dynamicStatsInit = new HashMapStats();
dynamicStatsInit.put(new Stat(StatType.D_HEALTH, 100.0));
dynamicStatsInit.put(new Stat(StatType.D_HUNGER, 30.0));
dynamicStatsInit.put(new Stat(StatType.D_EATEN, 10.0));
CellCreature cc;
int seed = 40;
int initialCreatureCount = 1;
for (int i = 0; i < initialCreatureCount; i++) {
double x = -150 + 300 / initialCreatureCount * i; //Random.getGaussian()*seed - seed/2;
double y = Random.getGaussian(-200, 200); //Random.getGaussian()*seed - seed/2;
cc = new CellCreature(new Point3(x, y, 0), constStatsInit, dynamicStatsInit.clone(), WorldPhysics.nextID());
Supervisor.getSupervisor().registerBeing(cc);
}
while (true) {
if (Supervisor.getSupervisor().getBeings().size() < 2) {
double x = Random.getGaussian(-200, 200);
double y = Random.getGaussian(-200, 200);
cc = new CellCreature(new Point3(x, y, 0), constStatsInit, dynamicStatsInit.clone(), WorldPhysics.nextID());
Supervisor.getSupervisor().registerBeing(cc);
}
Supervisor.update();
Thread.sleep(500);
}
}
|
f3eb7fa8-4bb6-47ed-8696-482ed875c6d9
| 7
|
public static int colisamax_f77 (int n, double x[][], int incx,
int begin, int j) {
double xmax;
int isamax,i,ix;
if (n < 1) {
isamax = 0;
} else if (n == 1) {
isamax = 1;
} else if (incx == 1) {
isamax = 1;
ix = begin;
xmax = Math.abs(x[ix][j]);
ix++;
for (i = 2; i <= n; i++) {
if (Math.abs(x[ix][j]) > xmax) {
isamax = i;
xmax = Math.abs(x[ix][j]);
}
ix++;
}
} else {
isamax = 1;
ix = begin;
xmax = Math.abs(x[ix][j]);
ix += incx;
for (i = 2; i <= n; i++) {
if (Math.abs(x[ix][j]) > xmax) {
isamax = i;
xmax = Math.abs(x[ix][j]);
}
ix += incx;
}
}
return isamax;
}
|
b94e5d11-9a95-411f-9547-d60ebfc4b96c
| 9
|
public void disconnectFromURL()
{
connected=false;
try
{
if(out!=null)
{
out.write(new byte[]{(byte)255,(byte)253,18}); //iac, iacdo, logout
out.flush();
}
}
catch(final Exception e) { }
try
{
if((in!=null)&&(in[0]!=null))
in[0].close();
}
catch(final Exception e) { }
try
{
if(out!=null)
out.close();
}
catch(final Exception e) { }
try
{
if(sock!=null)
sock.close();
}
catch(final Exception e) { }
in=null;
out=null;
sock=null;
}
|
09413c88-d1a6-4b6e-b9d5-25d6fae218d1
| 5
|
private void moveBodyAndSetSprites() {
Vector2D currentBodyPos = new Vector2D(lastHeadPos.x(), lastHeadPos.y());
Vector2D lastBodyPos = new Vector2D(0, 0);
for(int i = 1; i < snake.size(); i++) {
lastBodyPos.setCoords(bodyPartPos.get(i).x(), bodyPartPos.get(i).y());
bodyPartPos.get(i).setCoords(currentBodyPos.x(), currentBodyPos.y());
if(currentBodyPos.y() - lastBodyPos.y() < 0) {
snake.set(i, sprites[4]);
} else if(currentBodyPos.y() - lastBodyPos.y() > 0) {
snake.set(i, sprites[5]);
} else if(currentBodyPos.x() - lastBodyPos.x() < 0) {
snake.set(i, sprites[6]);
} else if(currentBodyPos.x() - lastBodyPos.x() > 0) {
snake.set(i, sprites[7]);
}
currentBodyPos.setCoords(lastBodyPos.x(), lastBodyPos.y());
}
}
|
389a045c-8540-444b-8d0e-3504feb87526
| 2
|
@Override
public boolean isOpen() {
return inputStream != null && outputStream != null && serialPort != null;
}
|
f732d0f8-51f1-4922-9ad2-ec2879f1edec
| 5
|
@Override
public List<Role> findRoleAll() {
List<Role> list = new ArrayList<Role>();
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = ConnectionHelper.getConnection();
ps = cn.prepareStatement(QTPL_SELECT_ALL);
rs = ps.executeQuery();
while (rs.next()) {
list.add(processResultSet(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
try { cn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
return list;
}
|
ea4a0516-d5e2-4198-82f6-b1dea58d474e
| 1
|
private void preencheTabela(List<Venda> lista){
this.modelo = new DefaultTableModel();
modelo.addColumn("Id");
modelo.addColumn("Cliente");
modelo.addColumn("Usuario");
modelo.addColumn("Horario");
modelo.addColumn("Forma de Pagamento");
modelo.addColumn("Valor Total");
ItemVenda iv;
//ItemVendaDAO
for(Venda u : lista){
Vector v = new Vector();
v.add(0,u.getId());
v.add(1,u.getCliente().getNome());
v.add(2,u.getUsuario().getNome());
v.add(3,u.getHorario());
v.add(4,u.getFormaPagamento().getNome());
v.add(5, u.getValor());
modelo.addRow(v);
}
this.tblListagem.setModel(modelo);
this.tblListagem.repaint();
}
|
5ea16e1f-c76d-4cfe-82d0-a33a758db4ad
| 6
|
public void actualizar(float tpf, float speed)
{
time += tpf / speed;
if (time > 1f && state == 0){
flash.emitAllParticles();
spark.emitAllParticles();
smoketrail.emitAllParticles();
debris.emitAllParticles();
shockwave.emitAllParticles();
state++;
}
if (time > 1f + .05f / speed && state == 1){
flame.emitAllParticles();
roundspark.emitAllParticles();
state++;
}
// rewind the effect
if (time > 5 / speed && state == 2){
System.out.println("Boooooooooooooooom!! ");
reiniciar();
flash.killAllParticles();
spark.killAllParticles();
smoketrail.killAllParticles();
debris.killAllParticles();
flame.killAllParticles();
roundspark.killAllParticles();
shockwave.killAllParticles();
}
}
|
eddd16ea-4507-486f-abea-1f96530c2890
| 0
|
public void update() {
moveCamera();
movePlayer();
}
|
242f1796-cb1f-43aa-8c85-61535eee0a50
| 8
|
@Test
public void testConcurrency1() {
final int clientThreadCount = 5;
final int machineId = 1;
int total = 0;
int count = 0;
for (int i = 0; i < mServerCount; i++) {
try {
mDhtClientArray[i].purge();
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("dhtClient: " + e.getMessage());
}
}
ClientThread[] clientThreadArray = new ClientThread[clientThreadCount];
// create and run client threads
for (int i = 0; i < clientThreadCount; i++) {
try {
clientThreadArray[i] = new ClientThread(machineId, i * 1000 + 1, (i + 1) * 1000 + 1);
} catch (Exception e) {
e.printStackTrace();
}
clientThreadArray[i].start();
}
for (int i = 0; i < clientThreadCount; i++) {
try {
clientThreadArray[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// client threads are done, get the count on each server
for (int i = 0; i < mServerCount; i++) {
try {
count = mDhtClientArray[i].count();
total += count;
System.out.println("DHTServer[" + (i + 1) + "] count " + count);
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("dhtClient: " + e.getMessage());
}
}
assertTrue(total == 1000 * clientThreadCount);
}
|
c3d5ddb0-e9a2-4965-a742-f3a96254bee1
| 4
|
public Boolean getValid() {
boolean test = false;
if (test || m_test) {
System.out.println("Loader :: loadAll() BEGIN");
}
if (test || m_test) {
System.out.println("Loader :: loadAll() END");
}
return m_allValid;
}
|
89186080-f0c1-4b01-adee-b25640603342
| 9
|
public static boolean parseAccessTokenAndOpenId(String responseData, OAuthV2 oAuth) {
if (!QStrOperate.hasValue(responseData)) {
return false;
}
oAuth.setMsg(responseData);
String[] tokenArray = responseData.split("&");
log.info("parseToken response=>> tokenArray.length = " + tokenArray.length);
if (tokenArray.length < 4) {
return false;
}
String tmpStr;
for (int i = 0; i < tokenArray.length; i++) {
if (tokenArray[i].startsWith("access_token=")) {
tmpStr = tokenArray[i].substring(tokenArray[i].indexOf('=') + 1, tokenArray[i].length());
if (!QStrOperate.hasValue(tmpStr)) {
return false;
}
oAuth.setAccessToken(tmpStr);
}
if (tokenArray[i].startsWith("expires_in=")) {
tmpStr = tokenArray[i].substring(tokenArray[i].indexOf('=') + 1, tokenArray[i].length());
if (!QStrOperate.hasValue(tmpStr)) {
return false;
}
oAuth.setExpiresIn(tmpStr);
}
if (tokenArray[i].startsWith("openid=")) {
oAuth.setOpenid(tokenArray[i].substring(tokenArray[i].indexOf('=') + 1, tokenArray[i].length()));
}
if (tokenArray[i].startsWith("openkey=")) {
oAuth.setOpenkey(tokenArray[i].substring(tokenArray[i].indexOf('=') + 1, tokenArray[i].length()));
}
}
return true;
}
|
0875aa14-0c62-42a4-bc86-edd303e30c9f
| 8
|
public PixImage boxBlur(int numIterations) {
// Replace the following line with your solution.
PixImage blur = new PixImage(this.pixWidth, this.pixHeight);
if(numIterations < 1){
return this;
}
else{
for(int x = 0; x<blur.pixWidth; x++){
for(int y = 0; y<blur.pixHeight;y++){ // 2 main for loops for the blur PixImage
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){//2 additional loops to check 9 pixels around the given pixel, including itself.
if(this.isValid(x+i, y+j)){
blur.pixImg[x][y].totalRed += this.pixImg[x+i][y+j].getRed();
blur.pixImg[x][y].totalGreen += this.pixImg[x+i][y+j].getGreen();
blur.pixImg[x][y].totalBlue += this.pixImg[x+i][y+j].getBlue();
blur.pixImg[x][y].neighbors += 1;
}
}
}
}
}
for(int x = 0; x<blur.pixWidth; x++){
for(int y = 0; y<blur.pixHeight;y++){
blur.pixImg[x][y].setRed((short)(blur.pixImg[x][y].totalRed/blur.pixImg[x][y].neighbors));
blur.pixImg[x][y].setGreen((short)(blur.pixImg[x][y].totalGreen/blur.pixImg[x][y].neighbors));
blur.pixImg[x][y].setBlue((short)(blur.pixImg[x][y].totalBlue/blur.pixImg[x][y].neighbors));
}
}
return blur.boxBlur(numIterations-1);
}
}
|
651dd551-34f3-40dd-b3ad-9c37d371b8f9
| 7
|
public void moveRow(int start, int end, int to)
{
if (start < 0)
{
String message = "Start index must be positive: " + start;
throw new IllegalArgumentException( message );
}
if (end > getRowCount() - 1)
{
String message = "End index must be less than total rows: " + end;
throw new IllegalArgumentException( message );
}
if (start > end)
{
String message = "Start index cannot be greater than end index";
throw new IllegalArgumentException( message );
}
int rowsMoved = end - start + 1;
if (to < 0
|| to > getRowCount() - rowsMoved)
{
String message = "New destination row (" + to + ") is invalid";
throw new IllegalArgumentException( message );
}
// Save references to the rows that are about to be moved
ArrayList<T> temp = new ArrayList<T>(rowsMoved);
for (int i = start; i < end + 1; i++)
{
temp.add(modelData.get(i));
}
// Remove the rows from the current location and add them back
// at the specified new location
modelData.subList(start, end + 1).clear();
modelData.addAll(to, temp);
// Determine the rows that need to be repainted to reflect the move
int first;
int last;
if (to < start)
{
first = to;
last = end;
}
else
{
first = start;
last = to + end - start;
}
fireTableRowsUpdated(first, last);
}
|
246ca3c4-3a68-4104-b37c-0110e0a0e79a
| 4
|
public void basicSetMeteo(Meteo myMeteo) {
if (this.meteo != myMeteo) {
if (myMeteo != null) {
if (this.meteo != myMeteo) {
Meteo oldmeteo = this.meteo;
this.meteo = myMeteo;
if (oldmeteo != null)
oldmeteo.removeWorkout(this);
}
}
}
}
|
4244d4a2-bb12-4d77-9b53-450c496dfcb5
| 7
|
private void fillDocumentPositions(BooleanQuery boolQuery) throws IOException, XMLStreamException{
for(BooleanImpl clause: boolQuery.getBooleanClauses()) {
if (clause instanceof BooleanClause)
clause.getDocPositionST().addAll((this.getDocumentPositions((BooleanClause)clause)));
if (clause instanceof PhraseClause)
clause.getDocPositionST().addAll(this.getDocumentPositions((PhraseClause)clause));
this.docPositionST.addAll(clause.getDocPositionST());
}
for(BooleanImpl clause: boolQuery.getBooleanClauses()) {
switch (clause.getBoolOp()){
case SHOULD:
//do nothing
break;
case MUST:
this.docPositionST.retainAll(clause.getDocPositionST());
break;
case MUSTNOT:
this.docPositionST.removeAll(clause.getDocPositionST());
break;
}
}
}
|
02f2968b-238a-4efb-aef7-76b7f7116f3b
| 8
|
public void begin() {
int numberOfCases = Integer.parseInt(readLine( 100 ));
readLine( 100 ); // blank line
for( int cases = 0 ; cases < numberOfCases; cases++ ){
Map<String,String> registers = new HashMap<String,String>(10);
for( int inx = 0 ; inx < 10 ; inx++ ){
registers.put(String.valueOf(inx), "000");
}
List<String> ram = new ArrayList<String>(1000);
while( true ){
String instruction = readLine( 100 );
if( instruction== null || instruction.trim().length() < 1) break;
ram.add(instruction);
}
int instructionSize = ram.size();
for( int inx= ram.size() ; inx < 1000; inx++ ){
ram.add("000");
}
int totalExecuted = 0;
currentRegisterPos = 0;
while( currentRegisterPos < instructionSize ){
totalExecuted = totalExecuted + executeInstruction(ram.get(currentRegisterPos), registers, ram);
}
System.out.println(totalExecuted);
if(cases < numberOfCases - 1){
System.out.println();
}
}
}
|
887318e3-7228-48c6-a408-60666ef149f4
| 0
|
@Override
public int getWidth() { return width; }
|
405ff6f3-7678-4828-b8fb-61bd5216b18c
| 0
|
public String getVis_matricule() {
return vis_matricule;
}
|
5da93c7b-80c1-40cf-a537-c40964f79429
| 6
|
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
|
cab71b87-2f45-45fe-8fd5-ca7a65b9f840
| 4
|
public boolean frogIsOnLog(Rectangle log){
boolean collision = log.contains(leftHalf) || log.contains(rightHalf) || log.contains(backHalf) ||
log.contains(frontHalf);
if(collision){
return true;
}else{
return false;
}
}
|
78449eb4-f7aa-41e7-aaa3-648eff8dbd9a
| 7
|
protected void addColumnHeaders(Worksheet worksheet) {
List<String[]> rawColumnHeadersList = worksheet.getRowsByRegex("^Druh kriminality.*");
Helper.isTrue(rawColumnHeadersList.size()==1,"Nemozno urcit na ktorom riadku su nazvy stlpcov");
String[] rawColumnHeaders = rawColumnHeadersList.get(0);
List<String> columnHeaders = new ArrayList<String>();
for(int i=1;i<rawColumnHeaders.length;i++){
if(Helper.isNotBlank(rawColumnHeaders[i])){
if(i==3){
continue;
}
if(i==4){
columnHeaders.add(rawColumnHeaders[i]+" (tisíc €)");
continue;
}
if(i>=6 && i<=9){
columnHeaders.add(rawColumnHeaders[i]+" (počet činov)");
continue;
}
if(i>=11){
columnHeaders.add(rawColumnHeaders[i]+" (počet osôb)");
continue;
}
columnHeaders.add(rawColumnHeaders[i]);
}
}
worksheet.getDatatable().setColumnHeaders(columnHeaders);
}
|
dc892c0a-59cd-48ff-a6b9-864834e673d4
| 8
|
@Override
public void setLock(String resource, String transaction,
LockType requestType) {
if (requestType != LockType.READ && requestType != LockType.WRITE) {
System.err
.println("error: site.ImpLockManager.setLock\n invalid coming request "
+ requestType);
return;
}
ResourceLock thisLock = locksOfR.get(resource);
// If this resource is under Recovery
if (thisLock != null && thisLock.getType() == LockType.RECOVERY) {
if (requestType == LockType.READ)
System.err
.println("error: site.ImpLockManager.setLock\n when recoverying get read request, ["
+ resource + "] is under recovery");
if (!this.resourcesOfT.containsKey(transaction))
this.resourcesOfT.put(transaction, new HashSet<String>());
this.resourcesOfT.get(transaction).add(resource);
return;
}
// There is no lock on this resource yet.
if (thisLock == null) {
thisLock = new ResourceLock(resource);
locksOfR.put(resource, thisLock);
}
thisLock.addLock(resource, transaction, requestType);
if (!this.resourcesOfT.containsKey(transaction))
this.resourcesOfT.put(transaction, new HashSet<String>());
this.resourcesOfT.get(transaction).add(resource);
}
|
3a4b7850-931a-4ac2-a233-1ad57f62bb63
| 5
|
public Bipartite(Graph<?> g) {
this.marked = new ListOrderedMap<>();
this.color = new ListOrderedMap<>();
this.isBipartite = true;
for (Object x : g.getAllVertices()) {
this.marked.put(x, false);
this.color.put(x, false);
}
for (Object x : g.getAllVertices()) {
if (!this.marked.get(x) && this.isBipartite)
dfs(g, x, true);
}
}
|
5448a8d8-06fc-4727-a9fa-0126f3e70e2a
| 7
|
public void actionPerformed(ActionEvent e)
{
// get the button that was pressed
JButton b = (JButton)e.getSource();
// fire appropriate event
if (b.getText().equals("Normal Setup"))
{
// set up for normal simulation
fireSimulationEvent(SimulationEvent.NORMAL_SETUP_EVENT);
}
else if (b.getText().equals("Queen Test"))
{
// set for testing the queen ant
fireSimulationEvent(SimulationEvent.QUEEN_TEST_EVENT);
}
else if (b.getText().equals("Scout Test"))
{
// set for testing the scout ant
fireSimulationEvent(SimulationEvent.SCOUT_TEST_EVENT);
}
else if (b.getText().equals("Forager Test"))
{
// set for testing the forager ant
fireSimulationEvent(SimulationEvent.FORAGER_TEST_EVENT);
}
else if (b.getText().equals("Soldier Test"))
{
// set for testing the soldier ant
fireSimulationEvent(SimulationEvent.SOLDIER_TEST_EVENT);
}
else if (b.getText().equals("Run"))
{
// run the simulation continuously
fireSimulationEvent(SimulationEvent.RUN_EVENT);
}
else if (b.getText().equals("Step"))
{
// run the simulation one turn at a time
fireSimulationEvent(SimulationEvent.STEP_EVENT);
}
}
|
8b25abcc-4d46-4beb-9928-ca92a3cf0a04
| 1
|
@Override
public void mark(int boardPosition, Cell[] cellBoard, int rows, int columns) throws IllegalMark {
//Find the column.
int boardPositionColumn = boardPosition % columns;
if (boardPositionColumn > 0){
//It's not the first column.
int oneLeftCellPosition = boardPosition - 1;
mark(boardPosition,oneLeftCellPosition,cellBoard);
}
}
|
24de4020-f3f5-4e2a-b6ce-e268889390b7
| 7
|
private static int checkAck(InputStream in) throws IOException {
int b = in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0)
return b;
if (b == -1)
return b;
if (b == 1 || b == 2) {
StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
} while (c != '\n');
if (b == 1) { // error
System.out.print(sb.toString());
}
if (b == 2) { // fatal error
System.out.print(sb.toString());
}
}
return b;
}
|
9b15429a-573c-486e-a1d4-fb30d6f35446
| 5
|
public void draw() {
// draw board
drawBoard();
// draw pieces
double x = 0;
double y = 0;
for (int i = 1; i <= model.getPoints().size(); i++) {
drawPoint(i);
}
// draw rails
// player 2 on top, player 1 on bottom
x = WIDTH/2;
y = HEIGHT/2;
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.text(x, y, "Rail");
StdDraw.setPenColor(model.getPlayer1());
for (int i = 0; i < model.getPlayer1Rail().size(); i++) {
y -= baseUnit;
StdDraw.filledCircle(x, y, 0.5 * baseUnit);
}
// reset
y = HEIGHT/2;
StdDraw.setPenColor(model.getPlayer2());
for (int i = 0; i < model.getPlayer2Rail().size(); i++) {
y += baseUnit;
StdDraw.filledCircle(x, y, 0.5 * baseUnit);
}
// draw homes
// player 2 on top
x = 0.5*baseUnit;
y = HEIGHT; // top down
StdDraw.text(x, y, "B");
StdDraw.text(x, 0, "W");
StdDraw.setPenColor(model.getPlayer1());
for (int i = 0; i < model.getPlayer1Home().size(); i++) {
y -= 0.15*baseUnit;
StdDraw.filledRectangle(x, y, 0.5 * baseUnit, 0.1 * baseUnit);
}
// player 1 on bottom
y = 0; // bottom up
StdDraw.setPenColor(model.getPlayer2());
for (int i = 0; i < model.getPlayer2Home().size(); i++) {
y += 0.15*baseUnit;
StdDraw.filledRectangle(x, y, 0.5 * baseUnit, 0.1 * baseUnit);
}
// current player indicator
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.text(18.5 * baseUnit, 9 * baseUnit, "Current Player");
StdDraw.setPenColor(model.getCurrentPlayer());
StdDraw.filledCircle(21 * baseUnit, 9 * baseUnit, 0.5 * baseUnit);
// Roll dice button. Does not do anything yet. Its just there as a
// reminder.
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.filledRectangle(18 * baseUnit, 10.5 * baseUnit, baseUnit,
0.5 * baseUnit);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(18 * baseUnit, 10.5 * baseUnit, "Skip Turn");
// Undo button
StdDraw.setPenColor(StdDraw.PINK);
StdDraw.filledRectangle(21 * baseUnit, 10.5 * baseUnit, baseUnit,
0.5 * baseUnit);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(21 * baseUnit, 10.5 * baseUnit, "Undo");
// dice
drawDice();
// draw moving piece under mouse
drawCurrentPiece();
StdDraw.show(40);
}
|
0c349c07-1d89-4f14-98f9-a4568efdb637
| 5
|
public boolean boundingBoxContains( double x, double y, double z ) {
return
x >= x0 && x <= x1 &&
y >= y0 && y <= y1 &&
z >= z0 && z <= z1;
}
|
71daed16-295c-4cbd-ac12-9ce5baf8f866
| 6
|
@EventHandler
public void PigZombieNightVision(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPigZombieConfig().getDouble("PigZombie.NightVision.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getPigZombieConfig().getBoolean("PigZombie.NightVision.Enabled", true) && damager instanceof PigZombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getPigZombieConfig().getInt("PigZombie.NightVision.Time"), plugin.getPigZombieConfig().getInt("PigZombie.NightVision.Power")));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.