text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Header readFrame() throws BitstreamException
{
Header result = null;
try
{
result = readNextFrame();
// E.B, Parse VBR (if any) first frame.
if (firstframe == true)
{
result.parseVBR(frame_bytes);
firstframe = false;
}
}
catch (BitstreamException ex)
{
if ((ex.getErrorCode()==INVALIDFRAME))
{
// Try to skip this frame.
//System.out.println("INVALIDFRAME");
try
{
closeFrame();
result = readNextFrame();
}
catch (BitstreamException e)
{
if ((e.getErrorCode()!=STREAM_EOF))
{
// wrap original exception so stack trace is maintained.
throw newBitstreamException(e.getErrorCode(), e);
}
}
}
else if ((ex.getErrorCode()!=STREAM_EOF))
{
// wrap original exception so stack trace is maintained.
throw newBitstreamException(ex.getErrorCode(), ex);
}
}
return result;
} | 6 |
public void insert(Person person) {
if (isAlmostFull()) {
doubleArraySize();
}
personArray[queueSize] = person;
personArray[queueSize].setPosition(queueSize);
queueSize++;
} | 1 |
public void testSubtract()
{
System.out.println("From Subtract Test !");
} | 0 |
@Override
public synchronized void removeFromFloor(ElevatorInterface elevatorToEnter, Direction directionToGo)
{
if(directionToGo != Direction.IDLE)
{
ArrayList<Person> peopleToRemove;
if(directionToGo == Direction.UP)
{
peopleToRemove = this.goingUp;
}
else
{
peopleToRemove = this.goingDown;
}
int i;
boolean bRemovalSuccessful = true;
for(i = 0; i < peopleToRemove.size() && bRemovalSuccessful; ++i)
{
Person curPerson = peopleToRemove.get(i);
try
{
bRemovalSuccessful = elevatorToEnter.addPassenger(curPerson);
}
catch (NullPassengerException | NegativeFloorException e)
{
e.printStackTrace();
}
}
int removalIndex;
if(!bRemovalSuccessful)
{
removalIndex = i;
}
else
{
removalIndex = peopleToRemove.size();
}
for(int j = 0; j < removalIndex; ++j)
{
try
{
peopleToRemove.remove(0);
}
catch(IndexOutOfBoundsException e)
{
e.printStackTrace();
}
}
}
} | 8 |
private void setRemoteServerConnection(IRemoteServerConnection rsc) {
if (rsc == null) {
throw new IllegalArgumentException("aRemoteServerConnection is null");
}
this.remoteServerConnection = rsc;
} | 1 |
public void readFunction(Element function) throws MaltChainedException {
boolean hasSubFunctions = function.getAttribute("hasSubFunctions").equalsIgnoreCase("true");
boolean hasFactory = false;
if (function.getAttribute("hasFactory").length() > 0) {
hasFactory = function.getAttribute("hasFactory").equalsIgnoreCase("true");
}
Class<?> clazz = null;
try {
if (PluginLoader.instance() != null) {
clazz = PluginLoader.instance().getClass(function.getAttribute("class"));
}
if (clazz == null) {
clazz = Class.forName(function.getAttribute("class"));
}
} catch (ClassNotFoundException e) {
throw new FeatureException("The feature system could not find the function class"+function.getAttribute("class")+".", e);
}
if (hasSubFunctions) {
NodeList subfunctions = function.getElementsByTagName("subfunction");
for (int i = 0; i < subfunctions.getLength(); i++) {
readSubFunction((Element)subfunctions.item(i), clazz, hasFactory);
}
} else {
int i = 0;
String n = null;
while (true) {
n = function.getAttribute("name") + "~~" + i;
if (!containsKey(n)) {
break;
}
i++;
}
put(n, new FunctionDescription(function.getAttribute("name"), clazz, false, hasFactory));
}
} | 9 |
protected void defineWorld(int worldType) {
world = new HashMap<Position,Tile>();
String[] layout;
if ( worldType == 1 ) {
layout = new String[] {
"...ooMooooo.....",
"..ohhoooofffoo..",
".oooooMooo...oo.",
".ooMMMoooo..oooo",
"...ofooohhoooo..",
".ofoofooooohhoo.",
"...ooo..........",
".ooooo.ooohooM..",
".ooooo.oohooof..",
"offfoooo.offoooo",
"oooooooo...ooooo",
".ooMMMoooo......",
"..ooooooffoooo..",
"....ooooooooo...",
"..ooohhoo.......",
".....ooooooooo..",
};
} else {
layout = new String[] {
"...ooo..........",
".ooooo.ooohooM..",
".ooooo.oohooof..",
"offfoooo.offoooo",
"oooooooo...ooooo",
".ooMMMoooo......",
".....ooooooooo..",
"...ooMooooo.....",
"..ohhoooofffoo..",
"...ofooohhoooo..",
".oooooMooo...oo.",
".ooMMMoooo..oooo",
".ofoofooooohhoo.",
"..ooooooffoooo..",
"....ooooooooo...",
"..ooohhoo.......",
};
}
String line;
for ( int r = 0; r < GameConstants.WORLDSIZE; r++ ) {
line = layout[r];
for ( int c = 0; c < GameConstants.WORLDSIZE; c++ ) {
char tileChar = line.charAt(c);
String type = "error";
if ( tileChar == '.' ) { type = GameConstants.OCEANS; }
if ( tileChar == 'o' ) { type = GameConstants.PLAINS; }
if ( tileChar == 'M' ) { type = GameConstants.MOUNTAINS; }
if ( tileChar == 'f' ) { type = GameConstants.FOREST; }
if ( tileChar == 'h' ) { type = GameConstants.HILLS; }
Position p = new Position(r,c);
world.put( p, new StubTile(p, type));
}
}
} | 8 |
@Override
public void render (float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
countdown.update(delta);
if(countdown.isDone()){
Objects.playScreen = new PlayScreen();
ld.setScreen(new MainMenu(ld));
}
Objects.BATCH.begin();
Objects.FONT.draw(Objects.BATCH, score, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
countdown.render(50, 50);
Objects.BATCH.end();
} | 1 |
@Override
public void mouseMoved(MouseEvent event) {
//System.out.println(event.getX() + " " + event.getY());
int x, y;
x = event.getX();
y = event.getY();
if(buttonArea.contains(x, y))
hoverButton = true;
else
hoverButton = false;
if(boundLeft.contains(x, y) || boundRight.contains(x, y) || boundTop.contains(x, y) || boundDown.contains(x, y) || hoverButton)
frame.setCursor(Cursor.HAND_CURSOR);
else
frame.setCursor(Cursor.DEFAULT_CURSOR);
} | 6 |
private void parseResponse(String rawResponse, GoogleResponse gr) {
if (rawResponse == null || !rawResponse.contains("\"result\"") || rawResponse.equals("{\"result\":[]}")) {
return;
}
if (rawResponse.contains("\"confidence\":")) {
String confidence = StringUtil.substringBetween(rawResponse, "\"confidence\":", "}");
gr.setConfidence(confidence);
} else {
gr.setConfidence(String.valueOf(1d));
}
String array = StringUtil.trimString(rawResponse, "[", "]");
if (array.contains("[")) {
array = StringUtil.trimString(array, "[", "]");
}
if (array.contains("\"confidence\":")) {// Removes confidence phrase if
// it exists.
array = array.substring(0, array.lastIndexOf(','));
}
String[] parts = array.split(",");
gr.setResponse(parseTranscript(parts[0]));
for (int i = 1; i < parts.length; i++) {
gr.getOtherPossibleResponses().add(parseTranscript(parts[i]));
}
} | 7 |
public static Integer getInteger(final Context context, final int position) {
if (position < 0 || context.arguments.size() <= position) return null;
if (!Parser.isInteger(context.arguments.get(position))) return null;
return Integer.parseInt(context.arguments.get(position));
} | 3 |
public static String getDirectoryName(){
String relativeWdPath,workingDirectory;
String inputFileName;
//Folder workingDirectory;
//Because userHome is a public static field, it can be used without having initialized any instance of Folder:
//This because the static variables have their own memory space and are initialized by their own;
System.out.println(Folder.userHome);
//Also the static method can be called without any instantiation of a Folder object.
String ynf="No";
do{
System.out.println("Input the relative path of the working directory");
relativeWdPath=TextIO.getlnWord();
workingDirectory=Folder.folderRequest(relativeWdPath);
new ListFiles(workingDirectory);
System.out.println("Do you want to change directory ? [write 'Y' or the name of the file you want to read or write]");
ynf=TextIO.getlnWord();
}while(ynf.equalsIgnoreCase("Yes") || ynf.equalsIgnoreCase("Y") || ynf.equalsIgnoreCase("Ye"));
if(ynf.equalsIgnoreCase("No")||ynf.equalsIgnoreCase("N")){
//Here would be better to add some treatment of the inputs
System.out.println("Enter the directory name");
inputFileName=workingDirectory+File.separator+TextIO.getln();
//System.out.println("*Input:"+inputFileName);
/* File test=new File(inputFileName);
while(!test.exists()){
System.out.println("Enter the correct file name");
inputFileName=workingDirectory+File.separator+TextIO.getlnWord();
test=new File(inputFileName);
}*/
}else{
//The case where the directory name is given as input for short
inputFileName=workingDirectory+File.separator+ynf;
/*File test=new File(inputFileName);
while(!test.exists()){
System.out.println("Enter the correct file name");
inputFileName=workingDirectory+File.separator+TextIO.getlnWord();
test=new File(inputFileName);
} */
}
return inputFileName;
} | 5 |
public static ArrayList<String> selectRecursion(char[] arr, int start, int num, Stack<Character> stack, ArrayList<String> arrayList, boolean print) {
if(start == arr.length) {
return arrayList;
}
if(arrayList == null) {
arrayList = new ArrayList<String>();
}
for(int i=start;i<arr.length;i++) {
stack.add(arr[i]);
if(stack.size() == num) {
resultCount++;
Object[] list = stack.toArray();
if(print)
System.out.print(resultCount + ": ");
StringBuilder builder = new StringBuilder();
for(Object ch : list) {
if(print)
System.out.print(ch.toString());
builder.append(ch.toString());
}
arrayList.add(builder.toString());
if(print)
System.out.println();
} else {
selectRecursion(arr, i+1, num, stack, arrayList, print);
}
stack.pop();
}
return arrayList;
} | 8 |
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPickUpItemIntoLockedSlot(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
if (player.hasPermission("disable.slot.locking")) {
return;
}
PlayerInventory inv = player.getInventory();
ItemStack pickup = event.getItem().getItemStack();
int toAdd = pickup.getAmount() - event.getRemaining();
for (int i = 0; i < inv.getSize(); i++) {
ItemStack slot = inv.getItem(i);
if (slot == null || slot.getType() == Material.AIR) {
if (player.hasPermission("cyom.slot.lock." + i)) {
event.setCancelled(true);
overrideItemPickup(player, event.getItem());
}
break;
} else if (slot.isSimilar(pickup) && slot.getAmount() < slot.getMaxStackSize()) {
toAdd -= slot.getMaxStackSize() - slot.getAmount();
if (toAdd <= 0) {
break;
}
}
}
} | 8 |
public Document merge(XPathExpression expression,
List<String> excludedTags,
Set<String> files)
throws ParserConfigurationException,
IOException,
SAXException,
XPathExpressionException
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setEntityResolver(new EntityResolver()
{
public InputSource resolveEntity(String publicId,
String systemId)
throws SAXException, IOException
{
// System.out.println("Ignoring " + publicId + ", " + systemId);
final InputStream schemaInputStream = getInputStreamForSchema(systemId);
if (schemaInputStream != null)
{
return new InputSource(schemaInputStream);
}
else
{
System.out.println("WARNING: Could not resolve '" + systemId + "' from classpath.");
return new InputSource("");
}
}
private InputStream getInputStreamForSchema(String systemId)
{
return getClass().getClassLoader().getResourceAsStream(SCHEMA_PATHS.get(systemId));
}
});
Document outputDocument = docBuilder.parse(new FileInputStream(getOutputFileName()));
Node results = (Node) expression.evaluate(outputDocument, XPathConstants.NODE);
if (results == null)
{
throw new IOException(outputFileName + ": the expression does not evaluate to a node!");
}
if (!files.isEmpty())
{
System.out.println("Merging web.xml files...");
}
for (String file : files)
{
InputStream is = null;
JarFile jarFile = null;
try
{
if (file.toLowerCase().endsWith(".war"))
{
jarFile = new JarFile(file);
ZipEntry entry = jarFile.getEntry("WEB-INF/web.xml");
is = jarFile.getInputStream(entry);
System.out.println(" -> Applying " + file + "/WEB-INF/web.xml");
}
else
{
is = new FileInputStream(file);
System.out.println(" -> Applying " + file);
}
performMerge(expression, excludedTags, docBuilder, outputDocument, results, is);
}
finally
{
if (jarFile != null)
{
jarFile.close();
}
if (is != null)
{
is.close();
}
}
}
return outputDocument;
} | 7 |
private static String trim(String text)
{
String result = text;
if (text != null && text.length() > 0)
{
int start = 0;
int end = text.length();
char firstChar = text.charAt(start);
char lastChar = text.charAt(end - 1);
if (firstChar == lastChar)
{
if (firstChar == '\'' || firstChar == '"')
{
start++;
}
if (lastChar == '\'' || lastChar == '"')
{
end--;
}
result = text.substring(start, end);
}
}
return result;
} | 7 |
private void invokeKrisletAction(DataInstance di, SoccerAction action) {
ObjectInfo object;
if (action == null) {
defaultAction();
} else {
switch (action) {
case DASH:
object = di.getObject("ball");
if (object != null)
m_krislet.dash(10 * object.m_distance);
else {
defaultAction(); // TODO We were told to
// dash...but we're not?
}
break;
case KICK:
// We know where the ball is and we can kick it
// so look for goal
if (m_side == 'l')
object = di.getObject("goal r");
else
object = di.getObject("goal l");
if (object != null)
m_krislet.kick(100, object.m_direction);
else {
defaultAction(); // TODO We were told to
// kick...but we're not?
}
break;
case TURN:
object = di.getObject("ball");
if (object != null) {
m_krislet.turn(object.m_direction);
} else
m_krislet.turn(40); // TODO Determine default angle
break;
default:
defaultAction();
break;
}
}
} | 8 |
private static String lineFlow(String line, boolean insideTable, boolean isALastLine) {
// TODO : documentation
if (insideTable == true) {
if (line.startsWith("|")) {
line = line.substring(1, line.length());
}
if (line.endsWith("|")) {
line = line.substring(0, line.length() - 1);
}
if (line.startsWith("{{עמודות")) {
return "";
}
if (line.startsWith("{{קצרמר}}")) {
return "{{קצרמר}}";
}
if (line.startsWith("{{")) {
// return line.substring(2, line.length());
}
}
if (isALastLine == true) {
if (line.endsWith("}}")) {
return line.substring(0, line.length() - 2);
}
} else {
if (line.startsWith("{{")) {
// return line.substring(2, line.length());
}
}
return line;
} | 9 |
public void addNewPlayer(String username){
try {
cs = con.prepareCall("{call addNewPlayer(?)}");
cs.setString(1, username);
cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
public void setArrivalCity(String arrivalCity) {
this.arrivalCity = arrivalCity;
} | 0 |
public void updatePosition() {
if (xPos < xDestination)
xPos+=2;
else if (xPos > xDestination)
xPos-=2;
if (yPos < yDestination)
yPos+=2;
else if (yPos > yDestination)
yPos-=2;
if (xPos == xDestination && yPos == yDestination) {
if (command==Command.GoToSeat) agent.msgAnimationFinishedGoToSeat();
else if (command==Command.LeaveRestaurant) {
agent.msgAnimationFinishedLeaveRestaurant();
//System.out.println("about to call gui.setCustomerEnabled(agent);");
isHungry = false;
gui.setCustomerEnabled(agent);
}
else if (command==Command.GoToCashier) {
agent.msgAnimationFinishedGoToCashier();
//agent.
}
command=Command.noCommand;
}
} | 9 |
@Override
public boolean afterEpoch(Inference inferenceImpl, Model model,
int epoch, double loss, int iteration) {
if (averaged) {
try {
// Clone the current model to average it, if necessary.
LOG.info(String.format(
"Cloning current model with %d parameters...",
((DPGSModel) model).getParameters().size()));
model = (Model) model.clone();
} catch (CloneNotSupportedException e) {
LOG.error(
String.format(
"Cloning current model with %d parameters on epoch %d and iteration %d",
((DPGSModel) model).getParameters().size(),
epoch, iteration), e);
return true;
}
/*
* The averaged perceptron averages the final model only in the
* end of the training process, hence we need to average the
* temporary model here in order to have a better picture of its
* current (intermediary) performance.
*/
LOG.info("Averaging model...");
model.average(iteration);
}
LOG.info("Predicting outputs...");
// Use other inference if it has been given in constructor.
if (inference != null)
inferenceImpl = inference;
// Fill the list of predicted outputs.
DPGSInput[] inputs = testset.getInputs();
// DPOutput[] outputs = testset.getOutputs();
for (int idx = 0; idx < inputs.length; ++idx) {
// Predict (tag the output sequence).
inferenceImpl.inference(model, inputs[idx], predicteds[idx]);
if ((idx + 1) % 100 == 0) {
System.out.print(".");
System.out.flush();
}
}
// TODO test
LOG.info(String.format("# subgradient steps / prediction: %d",
((DPGSDualInference) inferenceImpl)
.getMaxNumberOfSubgradientSteps()));
try {
// Delete previous epoch output file if it exists.
File o = new File(conllPredicted);
if (o.exists())
o.delete();
LOG.info(String
.format("Saving input CoNLL file (%s) to output file (%s) with predicted columns",
conllGolden, conllPredicted));
testset.save(conllGolden, conllPredicted, predicteds);
try {
LOG.info("Evaluation after epoch " + epoch + ":");
// Execute CoNLL evaluation scripts.
evaluateWithConllScripts(script, conllGolden,
conllPredicted, quiet);
} catch (Exception e) {
LOG.error("Running evaluation scripts", e);
}
} catch (IOException e) {
LOG.error("Saving test file with predicted column", e);
} catch (DatasetException e) {
LOG.error("Saving test file with predicted column", e);
}
return true;
} | 9 |
private void doDeleteTest() {
System.out.print("\n[Performing DELETING CHOCOLAT FROM COFFEES] ... ");
try {
Statement st = conn.createStatement();
st.executeUpdate("DELETE FROM COFFEES WHERE COF_NAME='chocolat'");
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
} | 1 |
public long getMin() {
return min;
} | 0 |
public ArrayList viewBooking() {
ArrayList temp = new ArrayList();
Query q = em.createQuery("SELECT t from BookingEntity t");
for (Object o : q.getResultList()) {
BookingEntity p = (BookingEntity) o;
System.out.println("viewbooking: reached 1" + userId);
if (p.getAccount().getId() == userId) {
System.out.println(p.getAccount());
temp.add(String.valueOf(p.getId()));
}
System.out.println("viewbooking: " + temp.size());
}
return temp;
} | 2 |
private String[] showList(ArrayList<String> players, Integer pageNum) {
Iterator<String> it = players.iterator();
String[] str = new String[players.size()];
Integer i = Integer.valueOf(0);
while(it.hasNext()) {
String play = (String)it.next();
String playJobList = "";
Iterator<Map.Entry<String, PlayerJobs>> its = PlayerJobs.getJobsList().entrySet().iterator();
while(its.hasNext()) {
Map.Entry<String, PlayerJobs> pair = (Map.Entry)its.next();
if(PlayerCache.hasJob(play, (String)pair.getKey()))
playJobList = playJobList.concat(" " + ChatColor.GOLD + (String)pair.getKey() + ChatColor.GRAY + ",");
}
if(playJobList.isEmpty())
playJobList = _modText.getAdminList("nojobs", PlayerCache.getLang(play)).addVariables("", play, "");
else {
playJobList = playJobList.substring(0, playJobList.length() - 1);
playJobList = playJobList.concat(".");
}
str[i.intValue()] = _modText.getAdminList("playerlist", PlayerCache.getLang(play)).addVariables("", play, playJobList);
i = Integer.valueOf(i.intValue() + 1);
}
Integer iLength = Integer.valueOf(str.length);
Integer allowedPages = Integer.valueOf(1);
Integer page = pageNum;
while (iLength.intValue() > 10) {
iLength = Integer.valueOf(iLength.intValue() - 10);
allowedPages = Integer.valueOf(allowedPages.intValue() + 1);
}
if (page.intValue() > allowedPages.intValue())
page = Integer.valueOf(1);
String[] modStr = new String[iLength.intValue()];
for (int x = 0; x < modStr.length; x++)
modStr[x] = str[(10 * (page.intValue() - 1) + x)];
return str;
} | 7 |
@Override
public boolean isWebDriverType(String type)
{
return StringUtils.equalsIgnoreCase("ie", type);
} | 0 |
@Override
public List<String> onTabComplete(CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args) {
for (CommandGroup command : commands) {
if (command.getName().equalsIgnoreCase(cmd.getName())) {
if (args.length > 0) {
int commandAmount = 1;
for (String arg : args) {
if (command.hasChildCommand(arg)) {
command = command.getChildCommand(arg);
commandAmount++;
}
}
String[] newArgs;
if (args.length == 1) {
newArgs = new String[0];
} else {
newArgs = new String[args.length - commandAmount];
System.arraycopy(args, commandAmount, newArgs, 0, args.length - commandAmount);
}
return command.getTabCompleteList(newArgs);
}
return command.getTabCompleteList(args);
}
}
return new ArrayList<>();
} | 6 |
protected void _toTerminal(String string, int l) {
if (l == 0) {
System.err.print(string);
} else {
System.out.print(string);
}
} | 1 |
private void handle_start(Message msg) {
System.out.println("Handle start process cmd!");
// response message prepared!
Message response=new Message(msgType.RESPONSE);
response.setResponseId(ResponseType.STARTRES);
response.setProcessId(msg.getProcessId());
response.setProcessName(msg.getProcessName());
//start the process
Class processClass;
try {
processClass = WorkerNode.class.getClassLoader().loadClass(
msg.getProcessName());
Constructor constructor;
constructor = processClass.getConstructor(String[].class);
System.out.println(msg.getArgs().length);
Object[] passed = { msg.getArgs() };
MigratableProcess process = (MigratableProcess) constructor.newInstance(passed);
process.setProcessID(msg.getProcessId()); // method needed to be created in MigratableProcess
System.out.println("run process");
runProcess(process);
}catch (ClassNotFoundException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("Class not Found!");
sendToManager(response);
return;
}catch (NoSuchMethodException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("No such method!");
sendToManager(response);
return;
} catch (SecurityException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("Security Exception!");
sendToManager(response);
return;
} catch (InstantiationException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("Instantiation Exception!");
sendToManager(response);
return;
} catch (IllegalAccessException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("Illegal Access !");
sendToManager(response);
return;
} catch (IllegalArgumentException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("Illegal Argument!");
sendToManager(response);
return;
} catch (InvocationTargetException e) {
response.setResult(Message.msgResult.FAILURE);
response.setCause("Invocation Target Exception!");
sendToManager(response);
return;
}
// send the response back to the master
response.setResult(Message.msgResult.SUCCESS);
sendToManager(response);
System.out.println("Process has been started!");
} | 7 |
public String getParam(String key)
{
String value = queryData.get(key);
if ( value == null )
return "";
return value;
} | 1 |
public boolean isUnstyled() {
if (font != null)
return false;
if (rise != 0)
return false;
if (metrics != null)
return false;
if (foreground != null)
return false;
if (background != null)
return false;
if (fontStyle != SWT.NORMAL)
return false;
if (underline)
return false;
if (strikeout)
return false;
if (borderStyle != SWT.NONE)
return false;
return true;
} | 9 |
public void carrega(String arq) {
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(arq));
contaRaiz = (ContaComposite) is.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
contaSelec = contaRaiz;
contaDe = contaRaiz;
contaPara = contaRaiz;
} | 3 |
private boolean valid() {
String clientname = (String) clientBox.getSelectedItem();
Contact _client = Database.driver().getClientsAlphabetically().get(clientname.toLowerCase());
if (clientBox.getSelectedIndex() == 0 || _client == null) {
JOptionPane.showMessageDialog(null, "Gelieve een klant te kiezen!", "Fout!", JOptionPane.ERROR_MESSAGE);
clientBox.requestFocus();
return false;
}
if (!txtNumber.getInputVerifier().verify(txtNumber)) {
JOptionPane.showMessageDialog(null, "Gelieve het factuur nummer na te kijken! De eerste twee tekens\nmoeten overeenkomen met het jaartal van de gekozen datum.\nDit nummer moet precies 6 tekens lang en geldig uniek zijn", "Fout!", JOptionPane.ERROR_MESSAGE);
txtNumber.requestFocus();
return false;
}
if (!txtReduction.getInputVerifier().verify(txtReduction)) {
JOptionPane.showMessageDialog(null, "Gelieve de korting na te kijken!", "Fout!", JOptionPane.ERROR_MESSAGE);
txtReduction.requestFocus();
return false;
}
if (tablemodel.getRowCount() == 0) {
JOptionPane.showMessageDialog(null, "Gelieve minstens 1 artikel toe te voegen aan deze factuur!", "Fout!", JOptionPane.ERROR_MESSAGE);
autobox.requestFocus();
return false;
}
if (!quantityoutlet.getInputVerifier().verify(quantityoutlet)) {
JOptionPane.showMessageDialog(null, "Gelieve een geldige hoeveelheid in te voeren!", "Fout!", JOptionPane.ERROR_MESSAGE);
quantityoutlet.requestFocus();
return false;
}
return true;
} | 6 |
private void tick() {
StringBuilder sb = new StringBuilder();
for (Iterator<Snake> iterator = getSnakes().iterator();
iterator.hasNext();) {
Snake snake = iterator.next();
snake.update(getSnakes());
sb.append(snake.getLocationsJson());
if (iterator.hasNext()) {
sb.append(',');
}
}
broadcast(String.format("{'type': 'update', 'data' : [%s]}",
sb.toString()));
} | 2 |
public HashMap<String, String> parseXml (String fileName) {
try {
HashMap<String, String> hmap = new HashMap<>();
DocumentBuilder rBuilder = init();
Document rDoc = rBuilder.parse(fileName);
Element root = rDoc.getDocumentElement();
iterativeParseElement(root, hmap);
// System.out.println(hmap);
return hmap;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
}catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
} | 3 |
public static long getBanTime(String playerName){
long bantime = 0;
if(isBanned(playerName)){
try {
SQL_STATEMENT = SQL_CONNECTION.createStatement();
SQL_RESULTSET = SQL_STATEMENT.executeQuery("SELECT * FROM bans WHERE username='" + playerName + "'");
// This loop checks all bans on record for the user to see if any tempbans are still active
// Note tempbans are done in DAYS, the argument is a Double
// For example 0.5 would be 0.5(1 day)=12hours
// .1 -> 2.4 hours
// 7 = 7 days, etc.
while (SQL_RESULTSET.next()) {
if(SQL_RESULTSET.getLong("expire") > System.currentTimeMillis()){
bantime = SQL_RESULTSET.getLong("time");
}
}
SQL_RESULTSET.close();
SQL_STATEMENT.close();
} catch(SQLException e){
e.printStackTrace();
}
}
return bantime;
} | 4 |
public static String encode(byte[] input) {
StringBuilder result = new StringBuilder();
int outputCharCount = 0;
for (int i = 0; i < input.length; i += 3) {
int remaining = Math.min(3, input.length - i);
int oneBigNumber = (input[i] & 0xff) << 16 | (remaining <= 1 ? 0 : input[i + 1] & 0xff) << 8 | (remaining <= 2 ? 0 : input[i + 2] & 0xff);
for (int j = 0; j < 4; j++)
result.append(remaining + 1 > j ? SIXTY_FOUR_CHARS[0x3f & oneBigNumber >> 6 * (3 - j)] : '=');
if ((outputCharCount += 4) % 76 == 0) result.append('\n');
}
return result.toString();
} | 6 |
protected List refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
List result = new java.util.ArrayList();
result.clear();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
double size = getTickUnit().getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = getTickUnit().valueToString(currentTickValue);
}
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = -Math.PI / 2.0;
}
else {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
Tick tick = new NumberTick(
new Double(currentTickValue), tickLabel, anchor,
rotationAnchor, angle
);
result.add(tick);
}
}
return result;
} | 7 |
public boolean stillRoom() {
int zeroCnt = 0;
for (int i = 0; i < 6; i++) {
for (int n = 0; n < 7; n++) {
if (_board[i][n] == 0) {
zeroCnt++;
}
}
}
if (zeroCnt == 0) {
return false;
}
else {
return true;
}
} | 4 |
private static ChemistryUnit apart(ChemistryUnit unit){
if(unit.getType() == ChemistryUnit.TYPE_BASE){
return unit;
}
ChemistryUnit unitValue = new ChemistryUnit();
for(Map.Entry<ChemistryUnit, Integer> unitPart : unit.getUnitEntrySet()){
ChemistryUnit unitPartValue = new ChemistryUnit();
ChemistryUnit unitPartApartValue = apart(unitPart.getKey());
if(unitPartApartValue.getType() == ChemistryUnit.TYPE_BASE){
unitPartValue.putUnit(unitPartApartValue, 1);
}
else{
for(Map.Entry<ChemistryUnit, Integer> xZero : unitPartApartValue.getUnitEntrySet()){
ChemistryUnit xKey = xZero.getKey();
if(unitPartValue.containsUnitKey(xKey)){
unitPartValue.putUnit(xKey, unitPartApartValue.getUnit(xKey) + xZero.getValue());
}
else{
unitPartValue.putUnit(xKey, xZero.getValue());
}
}
}
for(Map.Entry<ChemistryUnit, Integer> un : unitPartValue.getUnitEntrySet()){
ChemistryUnit unKey = un.getKey();
if(unitValue.containsUnitKey(unKey)){
unitValue.putUnit(unKey, unitValue.getUnit(unKey) + unitPartValue.getUnit(unKey) * unitPart.getValue());
}
else{
unitValue.putUnit(unKey, unitPartValue.getUnit(unKey) * unitPart.getValue());
}
}
}
return unitValue;
} | 7 |
@After
public void tearDown() {
} | 0 |
public static void main(String[] args) {
EvolvingGlobalProblemSetInitialisation starter = new EvolvingGlobalProblemSetInitialisation();
starter.initLanguage(new char[] { '0', '1' }, 10, "(0|101|11(01)*(1|00)1|(100|11(01)*(1|00)0)(1|0(01)*(1|00)0)*0(01)*(1|00)1)*");
int solutionFoundCounter = 0;
int noSolutionFound = 0;
List<Long> cycleCount = new LinkedList<Long>();
long tmpCycle;
long timeStamp;
int[] problemCount = new int[5];
int[] candidatesCount = new int[5];
int[] noCycles = new int[2];
problemCount[0] = 10;
problemCount[1] = 20;
problemCount[2] = 30;
problemCount[3] = 40;
problemCount[4] = 50;
candidatesCount[0] = 10;
candidatesCount[1] = 20;
candidatesCount[2] = 30;
candidatesCount[3] = 40;
candidatesCount[4] = 50;
noCycles[0] = 250;
noCycles[1] = 500;
int pc = 0;
int cc = 0;
int nc = 0;
for (int x = 0; x < 1; x++) {
System.out.println("x:" + x);
for (int n = 0; n < 25; n++) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
Logger l = new Logger("E_G_" + df.format(new Date()) + ".log",
true);
pc = problemCount[n % 5];
cc = candidatesCount[(int) Math.floor(n / 5)];
nc = noCycles[1];
l.log("Problem Count: " + pc);
l.log("CandidatesCount: " + cc);
l.log("Max Cycles: " + nc);
solutionFoundCounter = 0;
noSolutionFound = 0;
cycleCount = new LinkedList<Long>();
for (int i = 0; i < 100; i++) {
timeStamp = System.currentTimeMillis();
starter.initProblems(pc);
starter.initCandidates(cc);
tmpCycle = starter.startEvolution(nc);
l.log(i + ": finished ("
+ (System.currentTimeMillis() - timeStamp) + "ms, "
+ tmpCycle + "cycles)");
if (starter.getWinner() != null) {
solutionFoundCounter++;
starter.getWinner().getObj().minimizeAutomaton();
GraphvizRenderer.renderGraph(starter.getWinner().getObj(), "div5_solution_"+String.valueOf(solutionFoundCounter)+".svg");
cycleCount.add(tmpCycle);
l.log(i + ": Solution found.");
} else {
noSolutionFound++;
l.log(i + ": No solution found.");
}
}
long max = 0;
long min = 10000;
long sum = 0;
for (long no : cycleCount) {
sum += no;
max = (no > max ? no : max);
min = (no < min ? no : min);
}
l.log("Solution Found: " + solutionFoundCounter);
l.log("Avg cycles: "
+ (cycleCount.size() > 0 ? sum / cycleCount.size()
: '0'));
l.log("Max cycles: " + max);
l.log("Min cycles: " + min);
l.log("No solution found: " + noSolutionFound);
l.finish();
}
}
} | 8 |
public void fusionWithDodgeFullAlpha(CPLayer fusion, CPRect rc) {
CPRect rect = new CPRect(0, 0, width, height);
rect.clip(rc);
for (int j = rect.top; j < rect.bottom; j++) {
int off = rect.left + j * width;
for (int i = rect.left; i < rect.right; i++, off++) {
int color1 = data[off];
int alpha1 = (color1 >>> 24) * alpha / 100;
if (alpha1 == 0) {
continue;
}
int color2 = fusion.data[off];
int alpha2 = (color2 >>> 24) * fusion.alpha / 100;
int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;
if (newAlpha > 0) {
int alpha12 = alpha1 * alpha2 / 255;
int alpha1n2 = alpha1 * (alpha2 ^ 0xff) / 255;
int alphan12 = (alpha1 ^ 0xff) * alpha2 / 255;
int invColor1 = color1 ^ 0xffffffff;
fusion.data[off] = newAlpha << 24
| (((color1 >>> 16 & 0xff) * alpha1n2) + ((color2 >>> 16 & 0xff) * alphan12) + alpha12
* (((invColor1 >>> 16 & 0xff) == 0) ? 255 : Math.min(255, 255
* (color2 >>> 16 & 0xff) / (invColor1 >>> 16 & 0xff))))
/ newAlpha << 16
| (((color1 >>> 8 & 0xff) * alpha1n2) + ((color2 >>> 8 & 0xff) * alphan12) + alpha12
* (((invColor1 >>> 8 & 0xff) == 0) ? 255 : Math.min(255, 255
* (color2 >>> 8 & 0xff) / (invColor1 >>> 8 & 0xff))))
/ newAlpha << 8
| (((color1 & 0xff) * alpha1n2) + ((color2 & 0xff) * alphan12) + alpha12
* (((invColor1 & 0xff) == 0) ? 255 : Math.min(255, 255 * (color2 & 0xff)
/ (invColor1 & 0xff)))) / newAlpha;
}
}
}
fusion.alpha = 100;
} | 7 |
public float[] getInput(){
float[] values = new float[2];
values[0] = 0;
values[1] = 0;
if(Gdx.input.isKeyPressed(Keys.W)){
values[1] += 1;
}
if(Gdx.input.isKeyPressed(Keys.A)){
values[0] += -1;
}
if(Gdx.input.isKeyPressed(Keys.S)){
values[1] += -1;
}
if(Gdx.input.isKeyPressed(Keys.D)){
values[0] += 1;
}
return values;
} | 4 |
private String getNextWord(String line) {
StringBuffer buff = new StringBuffer(line);
StringBuffer ret = new StringBuffer();
while ((buff.length() > 0) && Character.isWhitespace(buff.charAt(0))) {
buff.deleteCharAt(0);
}
while ((buff.length() > 0) && !(buff.charAt(0) == ' ')){
if (isEndingPunctuation(buff.charAt(0))) {
ret.append('\n');
} else {
ret.append(buff.charAt(0));
}
buff.deleteCharAt(0);
}
return ret.toString();
} | 5 |
static protected void AdjustBuffSize()
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = 0;
available = tokenBegin;
}
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
} | 4 |
public static void calculateP1(double[] lambda, int[] MAXBUFFER, double mu, int lambdaNum,int bufferNum){
double currentTime = 0;
double nextArrivTime;
int queueSize = 0; //This is the 'length' in the instructions
GEL eventList = new GEL();
Queue<Node> packetQueue = new LinkedList<Node>(); //Queue represents the packets, every time we have a new packet, we insert into Queue
Statistics stats = new Statistics();
//currentTime = currentTime + negative_exponentially_distributed_time(lambda[lambdaNum]);
currentTime = currentTime + ParetoDistr(lambda[lambdaNum]);
Events FirstEvent = new Events("arrival",currentTime);
eventList.insert(FirstEvent);
for (int i = 0; i < 100000; i++){
Events currentEvent = eventList.removeFirstEvent();
//Processing Events
//Arrival Event
/*-----------------------------------------------------------------------------------------*/
if(currentEvent.getType() == "arrival"){
stats.calcQueueLength(queueSize, currentEvent.getTime());
//Creating next arrival event
currentTime = currentEvent.getTime();
//nextArrivTime = currentTime + negative_exponentially_distributed_time(lambda[lambdaNum]);
nextArrivTime = currentTime + ParetoDistr(lambda[lambdaNum]);
//Create new packet (insert in queue)
Node packet = new Node(negative_exponentially_distributed_time(mu));
Events arrEvent = new Events("arrival",nextArrivTime);
eventList.insert(arrEvent);
//Processing Arrival Event
//Server is free
/*---------------------------------------------------------------------------------------*/
if(queueSize == 0){
Events depEvent = new Events("departure",currentEvent.getTime() + packet.getPacketSize());
eventList.insert(depEvent);
queueSize++;
stats.calcBusyTime(currentEvent.getTime(), depEvent.getTime());
stats.setServerTotalTime(depEvent.getTime());
}
//Server is busy
else if(queueSize > 0){
if(MAXBUFFER[bufferNum] == -1){
packetQueue.add(packet);
queueSize++;
}
else if(queueSize - 1 < MAXBUFFER[bufferNum]){ //MAXBUFFER INDEX SHOULD BE SET DEPENDING ON FOR LOOP
packetQueue.add(packet);
queueSize++;
}
else{
stats.setNumDroppedPackets(stats.getNumDroppedPackets() + 1);
//DROP PACKET HERE
}
}
}
//Departure Events
/*---------------------------------------------------------------------------------------*/
else if(currentEvent.getType() == "departure"){
stats.calcQueueLength(queueSize, currentEvent.getTime());
currentTime = currentEvent.getTime();
queueSize--;
if(queueSize > 0){
Node temp = packetQueue.remove();
Events depEvent = new Events("departure",currentTime + temp.getPacketSize());
eventList.insert(depEvent);
stats.calcBusyTime(currentEvent.getTime(), depEvent.getTime());
stats.setServerTotalTime(depEvent.getTime());
}
}
}
stats.outputStats(lambda[lambdaNum],mu,MAXBUFFER[bufferNum]);
//System.out.print("\n" + ParetoDistr(lambda[lambdaNum]) + "\n");
} | 8 |
public boolean onCommand(CommandSender sender, String[] args) {
if(args.length != 1) {
return false;
}
//go through all players to find ours
OfflinePlayer[] players = plugin.getServer().getOfflinePlayers();
int total = players.length;
boolean found = false;
String player = "";
for(int i = 0; i < total; i++) {
if(players[i].getName().equalsIgnoreCase(args[0])){
found = true;
player = players[i].getName();
}
}
//did it find a player?
if(found != true){
MCNSARanksCommandExecutor.returnMessage(sender, "&cError: player '"+args[0]+"' could not be found!");
return true;
}
/*
// query the player
Player player = plugin.getServer().getPlayer(args[0]);
if(player == null) {
MCNSARanksCommandExecutor.returnMessage(sender, "&cError: player '"+args[0]+"' could not be found!");
return true;
}
*/
PermissionUser user = plugin.permissions.getUser(player);
// ok, we have the player.. get their group!
PermissionGroup[] groups = user.getGroups();
// make sure they have at least 1 group
if(groups.length < 1) {
MCNSARanksCommandExecutor.returnMessage(sender, "&cError: player '"+player+"' doesn't have a rank!");
return true;
}
// get the best-ranked group
int lowest = 9999;
PermissionGroup group = groups[0];
for(int i = 1; i < groups.length; i++) {
if(groups[i].getRank() < lowest) {
lowest = groups[i].getRank();
group = groups[i];
}
}
// now report it!
MCNSARanksCommandExecutor.returnMessage(sender, player + " is ranked as a: " + group.getPrefix() + group.getName() + "&f!");
return true;
} | 7 |
@Override
public void endElement(String uri, String localName, String qName) throws SAXException
{
switch (qName) {
case "node":
if (convertRoadTypeToInt(roadType) != -1)
{
edges.add(new Edge(placeNameNode, placeNameNode, convertRoadTypeToInt(roadType), placeName, 0, convertRoadTypeToSpeedLimit(roadType)));
}
roadType = "";
placeName = "";
createNode = false;
placeNameNode = null;
break;
case "way":
Node fromNode = null;
if (convertRoadTypeToInt(roadType) != -1 || convertRoadTypeToInt(roadType) == 99)
{
for (Node node : nodesOnWay)
{
if (fromNode != null)
{
edges.add(new Edge(fromNode, node, convertRoadTypeToInt(roadType), roadName, 0, convertRoadTypeToSpeedLimit(roadType)));
nodesDownloadedPct += (double) 1 / 6500000;
fromNode = node;
} else
{
fromNode = node;
}
}
}
// reset
roadName = "";
roadType = "";
fromNode = null;
nodesOnWay = new ArrayList<>();
createWay = false;
break;
}
} | 7 |
@Override
public void actionOnPChoice(int choice, int player) {
if(victory){
switch(choice){
case PlayersChoices.CHOOSE_THRONE :
putInFirstPlace(model.getThrone(), player);
end();
break;
case PlayersChoices.CHOOSE_BLADE :
putInFirstPlace(model.getFiefdoms(), player);
updateFiefdom();
end();
break;
case PlayersChoices.CHOOSE_RAVEN:
putInFirstPlace(model.getCourt(), player);
end();
break;
}
}else{
switch(choice){
case PlayersChoices.CHOOSE_THRONE :
putInLastPlace(model.getThrone(), player);
i++;
break;
case PlayersChoices.CHOOSE_BLADE :
putInLastPlace(model.getFiefdoms(), player);
updateFiefdom();
i++;
break;
case PlayersChoices.CHOOSE_RAVEN :
putInLastPlace(model.getCourt(), player);
i++;
break;
}
checkFinish();
}
} | 7 |
public boolean isFinished() {
if (!canStillMoveToAPosition(getActivePlayer()))
return true;
for (Player p : players) {
for (Player p2 : players) {
if (p2 != p && p.getPosition().equals(p2.beginPosition))
return true;
}
}
return false;
} | 5 |
public static boolean show(final BookDraggable b) {
if (b == null)
return false;
if (!b.getTab().open()) {
return false;
}
final WidgetChild window = Widgets.get(BookDraggable.BOOK_WIDGET, BookDraggable.CLICK_WINDOW);
final WidgetChild wc = b.getChild();
final WidgetChild scrollbar = Widgets.get(BookDraggable.BOOK_WIDGET, BookDraggable.SCROLLBAR);
if (!WidgetUtil.visible(window, wc) || !WidgetUtil.validate(scrollbar)) {
return false;
}
if (window.getBoundingRectangle().contains(wc.getBoundingRectangle())) {
return isVisible(b);
}
if (!Widgets.scroll(wc, scrollbar)) {
return false;
}
return isVisible(b)
|| (WidgetUtil.visible(window, wc, scrollbar) && WidgetUtil.scroll(wc, scrollbar) && isVisible(b));
} | 9 |
public void setSourceText(String sourceText) {
if( !sourceText.equals(AlchemyAPI_LanguageParams.CLEANED_OR_RAW)
&& !sourceText.equals(AlchemyAPI_LanguageParams.CQUERY)
&& !sourceText.equals(AlchemyAPI_LanguageParams.XPATH))
{
throw new RuntimeException("Invalid setting " + sourceText + " for parameter sourceText");
}
this.sourceText = sourceText;
} | 3 |
public Map<String, Map<String, Boolean>> getPermissions(String world) {
Map<String, Map<String, Boolean>> result = new LinkedHashMap<String, Map<String, Boolean>>();
Map<String, Boolean> groupperms = new LinkedHashMap<String, Boolean>();
//add group permissions
groupperms.put("droxperms.meta.group." + name, true);
if (world != null) {
groupperms.put("droxperms.meta.group." + name + "." + Config.getRealWorld(world), true);
}
result.put("group", groupperms);
//add subgroup permissions
if (subgroups != null) {
Map<String, Boolean> subgroupperms = new LinkedHashMap<String, Boolean>();
for (Iterator<String> iterator = subgroups.iterator(); iterator.hasNext();) {
String subgroup = iterator.next();
subgroupperms.put("droxperms.meta.group." + subgroup, true);
if (world != null) {
subgroupperms.put("droxperms.meta.group." + subgroup + "." + Config.getRealWorld(world), true);
}
}
result.put("subgroups", subgroupperms);
}
//add global permissions
if (globalPermissions != null) {
result.put("global", globalPermissions);
}
//add world permissions
if (world != null && permissions != null) {
Map<String, Boolean> worldperms = new LinkedHashMap<String, Boolean>();
if (permissions.get(Config.getRealWorld(world)) != null) {
worldperms.putAll(permissions.get(Config.getRealWorld(world)));
}
result.put("world", worldperms);
}
return result;
} | 8 |
public static int windowImgs(String wnd, boolean free) {
int cnt = 0;
Widget root = UI.instance.root;
for (Widget wdg = root.child; wdg != null; wdg = wdg.next) {
if (wdg instanceof Window)
if (((Window) wdg).cap.text.equals(wnd))
for (Widget img = wdg.child; img != null; img = img.next)
if (img instanceof Img) {
Img i = (Img) img;
if (i != null) {
if (free) {
if (i.textureName.contains("/invsq")) cnt++;
} else if (!i.textureName.contains("/invsq")) cnt++;
}
}
}
return cnt;
} | 9 |
public void loadPlugins(){
String runPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
try {
List<File> files = Util.getFileList(Folders.PLUGIN.getAbsolutePath());
for(File f: files){
if(!f.getName().endsWith(".jar"))
return;
URL path = new URL("jar:" + f.toURI().toURL() + "!/plugin.yml");
YAMLFile pluginFile = new YAMLFile(true);
pluginFile.Load(path);
if(pluginFile.getString("name") == null || pluginFile.getString("main") == null){
continue;
}
Plugin p = (Plugin)Class.forName(pluginFile.getString("main")).newInstance();
plugins.add(p);
pluginNames.put(p, pluginFile.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
if(!runPath.endsWith(".jar")){
try{
File pluginYML = new File(runPath + "/plugin.yml");
YAMLFile pluginFile = new YAMLFile(false);
pluginFile.Load(pluginYML);
if(pluginFile.getString("name") == null || pluginFile.getString("main") == null){
return;
}
Plugin p = (Plugin)Class.forName(pluginFile.getString("main")).newInstance();
plugins.add(p);
pluginNames.put(p, pluginFile.getString("name"));
}catch(Exception e){
e.printStackTrace();
}
}
} | 9 |
int test4( ) throws MiniDB_Exception{
int points = 0;
// IN_SOLUTION_START
MiniDB db = new MiniDB( "minidb.test4" );
BufMgr bm = db.getBufMgr();
BPlusTree bpt = db.createNewBPlusTreeIndex( "table", "val", 8 );
BPlusTreeLeafNode leaf = (BPlusTreeLeafNode)bpt.getRootNode();
int slot;
slot = leaf.getSlotForValue( 15 );
System.out.println( "getSlotForValue( 15 )" );
System.out.println( "Expect 0, got " + slot );
if( slot == 0 ){ points++; }else{ System.out.println( " incorrect" ); }
System.out.println( "insertRecord(500,15)" );
bpt.insertRecord(500, 15);
slot = leaf.getSlotForValue(300); // should be 0
System.out.println( "getSlotForValue(300)" );
System.out.println( "Expect 0, got " + slot );
if( slot == 0 ){ points++; }else{ System.out.println( " incorrect" ); }
slot = leaf.getSlotForValue(500); // should be 0
System.out.println( "getSlotForValue(500)" );
System.out.println( "Expect 0, got " + slot );
if( slot == 0 ){ points++; }else{ System.out.println( " incorrect" ); }
slot = leaf.getSlotForValue(700); // should be 0
System.out.println( "getSlotForValue(700)" );
System.out.println( "Expect 1, got " + slot );
if( slot == 1 ){ points++; }else{ System.out.println( " incorrect" ); }
if( points == 3 ){
long checkLong = leaf.readLong( leaf.offset_valueSlot(0) );
if( checkLong != 500 ){
System.err.println( leaf.toString() );
System.err.println( "check failed in MiniDB_grade, 500 is 0x1F4 in hex" );
System.exit(0);
}
}
// Add some values (all less than 500 );
long valuesInsert[] = {2, -10, 20, -5, 7};
long valuesGet[] = {-30, -10, 0, 2, 5, 100000};
int expectedSlots[] = {0, 0, 2, 2, 3, 6};
for (int i=0; i<valuesInsert.length; i++){
long value = valuesInsert[i];
int blockID = (i+1)*100;
bpt.insertRecord(value, blockID);
System.out.println( "insertRecord(" + value + "," + blockID + ")" );
MiniDB_Record rec = new MiniDB_Record(blockID,value);
System.out.println( "Inserted " + rec );
}
for (int i=0; i<valuesGet.length; i++){
System.out.println( "getSlotForValue(" + valuesGet[i] + ")" );
slot = leaf.getSlotForValue(valuesGet[i]);
System.out.println( "Expect " + expectedSlots[i] + ", got " + slot );
if( expectedSlots[i] == slot ) points++; else{ System.out.println( " incorrect" ); }
}
// IN_SOLUTION_END
return points;
} | 9 |
public String getLabel() {
return label;
} | 0 |
public static void displayHP(Graphics g, GameController gc, ImageLoader il, int x, int y, int progress) {
int xPos, yPos;
int progressWidth;
BufferedImage bi;
x = x - (CONTAINER_WIDTH / 2);
y = y + CONTAINER_HEIGHT;
//container
bi = il.getImage("Misc/BarBG");
if(bi != null) {
xPos = gc.mapToPanelX(x);
yPos = gc.mapToPanelY(y);
//flip the yPos since drawing happens top down versus bottom up
yPos = gc.getPHeight() - yPos;
//subtract the block height since points are bottom left and drawing starts from top left
yPos -= gc.getBlockHeight();
g.drawImage(bi, xPos, yPos, null);
}
//ar
bi = il.getImage("Misc/Bar");
if(bi != null) {
if(progress < 0) {
progress = 0;
}
if(progress > 100) {
progress = 100;
}
progressWidth = (BAR_MAX_WIDTH * progress) / 100;
xPos = gc.mapToPanelX(x + BAR_OFFSET_X);
yPos = gc.mapToPanelY(y - BAR_OFFSET_Y);
//flip the yPos since drawing happens top down versus bottom up
yPos = gc.getPHeight() - yPos;
//subtract the block height since points are bottom left and drawing starts from top left
yPos -= gc.getBlockHeight();
g.drawImage(bi, xPos, yPos, progressWidth, BAR_HEIGHT, null);
}
} | 4 |
@Override
public void mousePressed(MouseEvent e) {
for(int i = 0; i < Rocket.getRocket().currentGui.compList.toArray().length; i++){
if(((Button) Rocket.getRocket().currentGui.compList.get(i)).isInside(e.getX(), e.getY())){
((Button) Rocket.getRocket().currentGui.compList.get(i)).click(true);
if(((Button) Rocket.getRocket().currentGui.compList.get(i)).isCheckBox()) {
Rocket.getRocket().currentGui.preform(i);
}
}
}
} | 3 |
public void setLeft(Node<K> left) {
this.left = left;
} | 0 |
public void setPosition(Point position) {
int x, y;
// Make sure the position is a legal position(not to far to the sides so view space is given away)
if (position.x < this.viewWidth / 2) {
x = (int) Math.ceil(this.viewWidth / 2.0);
} else if (position.x > (this.plan.getWidth() - (int) Math.ceil(this.viewWidth / 2.0))) {
x = this.plan.getWidth() - (int) Math.ceil(this.viewWidth / 2.0);
} else {
x = position.x;
}
if (position.y < this.viewHeight / 2) {
y = (int) Math.ceil(this.viewHeight / 2.0);
} else if (position.y > (this.plan.getHeight() - (int) Math.ceil(this.viewHeight / 2.0))) {
y = this.plan.getHeight() - (int) Math.ceil(this.viewHeight / 2.0);
} else {
y = position.y;
}
this.position = new Point(x, y);
} | 4 |
public static void requestToTeleportToPlayer( String player, String target ) {
final BSPlayer bp = PlayerManager.getPlayer( player );
final BSPlayer bt = PlayerManager.getSimilarPlayer( target );
if ( playerHasPendingTeleport( bp ) ) {
bp.sendMessage( Messages.PLAYER_TELEPORT_PENDING );
return;
}
if ( bt == null ) {
bp.sendMessage( Messages.PLAYER_NOT_ONLINE );
return;
}
if ( !playerIsAcceptingTeleports( bt ) ) {
bp.sendMessage( Messages.TELEPORT_UNABLE );
return;
}
if ( playerHasPendingTeleport( bt ) ) {
bp.sendMessage( Messages.PLAYER_TELEPORT_PENDING_OTHER );
return;
}
pendingTeleportsTPA.put( bt, bp );
bp.sendMessage( Messages.TELEPORT_REQUEST_SENT );
bt.sendMessage( Messages.PLAYER_REQUESTS_TO_TELEPORT_TO_YOU.replace( "{player}", bp.getDisplayingName() ) );
ProxyServer.getInstance().getScheduler().schedule( BungeeSuite.instance, new Runnable() {
@Override
public void run() {
if ( pendingTeleportsTPA.containsKey( bt ) ) {
if ( !pendingTeleportsTPA.get( bt ).equals( bp ) ) {
return;
}
if ( bp != null ) {
bp.sendMessage( Messages.TPA_REQUEST_TIMED_OUT.replace( "{player}", bt.getDisplayingName() ) );
}
pendingTeleportsTPA.remove( bt );
if ( bt != null ) {
bt.sendMessage( Messages.TP_REQUEST_OTHER_TIMED_OUT.replace( "{player}", bp.getDisplayingName() ) );
}
}
}
}, expireTime, TimeUnit.SECONDS );
} | 8 |
public void fillGaps() {
// Utilisation du générateur de nombres aléatoires :
// x.nextInt(6) + 1
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (matrix[i][j] == 0)
matrix[i][j] = x.nextInt(6) + 1;
}
}
} | 3 |
public App(ASMController a) {
this.asmController = a;
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initialize();
// When in doubt, add moar threads
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.execute(new Runnable() {
@Override
public void run() {
getSimpleModePanel();
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
getHelpPanel();
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
getInstructionPanel();
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
getHelpPanel();
}
});
executorService.shutdown();
} | 4 |
private Node<K, V> lowerAll( V value ) {
if( value == null ) { return null; }
Node<K, V> node = mAllRoot;
Node<K, V> ret = null;
if( mValueComparator != null ) {
Comparator<? super V> comp = mValueComparator;
while( node != null ) {
int c = comp.compare( value, node.mValue );
if( c <= 0 ) {
node = node.mAllLeft;
} else {
ret = node;
node = node.mAllRight;
}
}
} else {
Comparable<? super V> comp = (Comparable<? super V>)value;
while( node != null ) {
int c = comp.compareTo( node.mValue );
if( c <= 0 ) {
node = node.mAllLeft;
} else {
ret = node;
node = node.mAllRight;
}
}
}
return ret;
} | 9 |
@Override
public void addResourceLoader(Class<? extends ResourceLoader<?>> clazz)
throws ResourceException {
ChronosLogger.info("Register loader: " + clazz.getSimpleName());
// Check if the class is registered
ResourceType annotation = clazz.getAnnotation(ResourceType.class);
if (annotation != null) {
if (annotation.value().isEmpty()) {
throw new ResourceException("The annotation in loader class '"
+ clazz.getSimpleName() + "' needs a value");
}
ResourceLoader<?> loader = ClassUtils.createObject(clazz);
String resourceClass = loader.getResourceClass().getName();
loaders.put(resourceClass, loader);
translations.put(annotation.value(), resourceClass);
} else {
throw new ResourceException("loader class '"
+ clazz.getSimpleName()
+ "' needs a @RegisteredLoader annotation");
}
} | 5 |
@Override
public void visitLocalVariable(final String name, final String desc,
final String signature, final Label start, final Label end,
final int index) {
if (signature != null) {
if (localVarType == null) {
localVarType = new ByteVector();
}
++localVarTypeCount;
localVarType.putShort(start.position)
.putShort(end.position - start.position)
.putShort(cw.newUTF8(name)).putShort(cw.newUTF8(signature))
.putShort(index);
}
if (localVar == null) {
localVar = new ByteVector();
}
++localVarCount;
localVar.putShort(start.position)
.putShort(end.position - start.position)
.putShort(cw.newUTF8(name)).putShort(cw.newUTF8(desc))
.putShort(index);
if (compute != NOTHING) {
// updates max locals
char c = desc.charAt(0);
int n = index + (c == 'J' || c == 'D' ? 2 : 1);
if (n > maxLocals) {
maxLocals = n;
}
}
} | 7 |
public List<String> parse(String line) {
StringBuffer sb = new StringBuffer();
list.clear(); // recycle to initial state
int i = 0;
if (line.length() == 0) {
list.add(line);
return list;
}
do {
sb.setLength(0);
if (i < line.length() && line.charAt(i) == '"')
i = advQuoted(line, sb, ++i); // skip quote
else
i = advPlain(line, sb, i);
list.add(sb.toString());
log.fine(sb.toString());
i++;
} while (i < line.length());
return list;
} | 4 |
@Override
public void mouseEntered(MouseEvent e) {
} | 0 |
private void solve(int n, short[][] board)
{
SudokuBoard sudoku = new SudokuBoard(n, board);
System.out.format("Initial %d x %d Board {\n", n, n);
System.out.print(sudoku);
System.out.println("}");
Solver<SudokuMove> solver = new Solver<SudokuMove>();
solver.setInitialState(sudoku);
// True since there can never be duplicate states
solver.setRevisitStates(true);
solver.solve();
System.out.format("Solved in %d ms\n", solver.getSolveTime());
System.out.format("States created: %d\n", solver.getStatesCreated());
System.out.format("States visited: %d\n", solver.getStatesVisited());
System.out.format("States duplicated: %d\n", solver.getStatesDuplicates());
System.out.format("States pooled: %d\n", solver.getUniqueStates());
System.out.format("States branched: %d\n", solver.getStatesDeviated());
List<SudokuBoard> solutions = solver.getSolutions();
System.out.format("Solutions (%d) {\n", solutions.size());
for (int i = 0; i < solutions.size(); i++) {
if (i > 0) System.out.println("AND ");
System.out.print(solutions.get(i));
}
System.out.println("}");
System.out.println();
} | 2 |
public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
int port = 1099;
InetAddress localhost = null;
try {
localhost = InetAddress.getLocalHost();
System.err.println("Host name : "+localhost.getHostName());
} catch (Exception ex) {
ex.printStackTrace();
}
String name;
if (localhost != null) {
name = localhost.getHostName();
} else {
name = "localhost";
}
// get optional port
try {
String portOption = Utils.getOption("p", args);
if (!portOption.equals(""))
port = Integer.parseInt(portOption);
} catch (Exception ex) {
System.err.println("Usage : -p <port>");
}
if (port != 1099) {
name = name + ":" + port;
}
name = "//"+name+"/RemoteEngine";
try {
Compute engine = new RemoteEngine(name);
try {
Naming.rebind(name, engine);
System.out.println("RemoteEngine bound in RMI registry");
} catch (RemoteException ex) {
// try to bootstrap a new registry
System.err.println("Attempting to start RMI registry on port " + port + "...");
java.rmi.registry.LocateRegistry.createRegistry(port);
Naming.bind(name, engine);
System.out.println("RemoteEngine bound in RMI registry");
}
} catch (Exception e) {
System.err.println("RemoteEngine exception: " +
e.getMessage());
e.printStackTrace();
}
} | 8 |
public java.lang.Float get() {
elapsed = ((double) System.currentTimeMillis() - timeStart) / timeAnim;
if (elapsed > 1.0)
elapsed = 1.0;
switch (method) {
case -METHOD_LINE://line
elapsed = elapsed * 2 - 1;
break;
case METHOD_SINE:
elapsed = Math.sin(elapsed * Math.PI / 2);
break;
case -METHOD_SINE:
elapsed = Math.sin(elapsed * Math.PI);
break;
case METHOD_TAN:
elapsed = Math.tan(elapsed * Math.PI / 4);
break;
case -METHOD_TAN:
elapsed = Math.tan(elapsed * Math.PI / 2);
break;
}
return (float) (varOld * (1 - elapsed) + varNew * elapsed);
} | 6 |
private boolean diagonalIncrementingBlock(int[][] grid, LinkedList<Square> squareStore, boolean pickOne) {
//Block - Diagonal Inc
if ((grid[2][0] == 1 && grid[1][1] == 1) && grid[0][2] != 2) {
BuildAndAddSquareZeroTwo(squareStore);
pickOne = updateGridZeroTwo(grid);
} else if ((grid[1][1] == 1 && grid[0][2] == 1) && grid[2][0] != 2) {
BuildAndAddSquareTwoZero(squareStore);
pickOne = updateGridTwoZero(grid);
} else if ((grid[2][0] == 1 && grid[0][2] == 1) && grid[1][1] != 2) {
BuildAndAddSquareOneOne(squareStore);
pickOne = updateGridOneOne(grid);
}
return pickOne;
} | 9 |
public static HashSet getRandomIndexes_HashSet(
Vector aVector,
int aNumberOfIndexes,
Random aRandom) {
HashSet tIndexesToSwap_HashSet = new HashSet();
int aIndex;
int count = 0;
if (aNumberOfIndexes > aVector.size() / 2) {
for (aIndex = 0; aIndex < aVector.size(); aIndex++) {
tIndexesToSwap_HashSet.add(aIndex);
count++;
}
while (count != aNumberOfIndexes) {
do {
aIndex = aRandom.nextInt(aVector.size());
} while (!tIndexesToSwap_HashSet.remove(aIndex));
count--;
}
} else {
while (count < aNumberOfIndexes) {
do {
aIndex = aRandom.nextInt(aVector.size());
} while (!tIndexesToSwap_HashSet.add(aIndex));
count++;
}
}
return tIndexesToSwap_HashSet;
} | 6 |
@Override
public TLValue evaluate() {
TLValue a = lhs.evaluate();
TLValue b = rhs.evaluate();
// number + number
if(a.isNumber() && b.isNumber()) {
return new TLValue(a.asDouble() - b.asDouble());
}
// list + any
if(a.isList()) {
List<TLValue> list = a.asList();
list.remove(b);
return new TLValue(list);
}
// // string + any
// if(a.isString()) {
// // return new TLValue(a.asString() + "" + b.toString());
// }
// // any + string
// if(b.isString()) {
// return new TLValue(a.toString() + "" + b.asString());
// }
throw new RuntimeException("illegal expression: " + this);
} | 3 |
private Class<?> transformInPrimitive(final Object param) {
Class<?> retorno = null;
if (param instanceof Byte) {
retorno = byte.class;
} else if (param instanceof Short) {
retorno = short.class;
} else if (param instanceof Integer) {
retorno = int.class;
} else if (param instanceof Long) {
retorno = long.class;
} else if (param instanceof Float) {
retorno = float.class;
} else if (param instanceof Double) {
retorno = double.class;
} else if (param instanceof Boolean) {
retorno = boolean.class;
} else
retorno = param.getClass();
return retorno;
} | 9 |
private ListElement progressRoboMeeting(ListElement currentRobot) {
ListElement helpRobot = currentRobot;
while (helpRobot != null) {
if (helpRobot.getNext() != null) {
if (!this.robotPlace.exist(helpRobot.getNext().getId())) {
helpRobot.setNext(helpRobot.getNext().getNext());
}
}
helpRobot = helpRobot.getNext();
}
return currentRobot;
} | 3 |
public void visit_i2f(final Instruction inst) {
stackHeight -= 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
private STS createSemaphore() {
init();
State initState = this.createState("s0");
List<State> stateList = new ArrayList<State>();
stateList.add(initState);
int index = 1;
for (Correction corr : corrections) {
State s = createState("s" + index);
stateList.add(s);
index++;
}
STS sem = new DefaultSTS(states, initState, inputActions,
outputActions, transitions);
sem.labelState(initState, "flag0");
for (Transition trans : this.mainSTS.getTransitions()) {
if (!trans.getAction().getName().contains("Resume")) {
trans.addGuardClause(new DefaultClause(new DefaultLiteral("flag0")));
}
}
index = 1;
for (Correction corr : corrections) {
sem.labelState(stateList.get(index), "flag" + index);
Adaptation adaptation = corr.getAdaptation();
STS adSTS = this.adaptationSTSs.get(adaptation);
State initial = adSTS.getInitialState();
int prevIndex = this.getIndexOfPreviousAdaptation(index);
for (Transition initTrans : adSTS.getTransitionsFromState(initial)) {
for (int i = prevIndex; i <= index; i++) {
Action act = initTrans.getAction();
if (!act.getName().contains("Resume")) {
sem.addAction(act);
Transition newTrans = new DefaultTransition(stateList.get(i),
new StateFormula(), act, stateList.get(index));
sem.addTransition(newTrans);
}
}
}
Action action = adSTS.getAction("Resume"+index);
sem.addAction(action);
// Transition resTrans1 = new DefaultTransition(initState,
// new StateFormula(), action, initState);
// sem.addTransition(resTrans1);
Transition resTrans = new DefaultTransition(stateList.get(index),
new StateFormula(), action, initState);
sem.addTransition(resTrans);
index++;
}
return sem;
} | 7 |
@Override
protected NodeValue exec(Node[] nodes, FunctionEnv env, SPINModuleRegistry registry) {
Model baseModel = ModelFactory.createModelForGraph(env.getActiveGraph());
Node exprNode = nodes[0];
if(exprNode == null) {
throw new ExprEvalException("No expression specified");
}
else if(exprNode.isLiteral()) {
return NodeValue.makeNode(exprNode);
}
else {
Model model = baseModel;
if(!model.contains(SPIN._arg1, RDF.type, SP.Variable)) {
MultiUnion multiUnion = new MultiUnion(new Graph[] {
env.getActiveGraph(),
SPIN.getModel().getGraph()
});
model = ModelFactory.createModelForGraph(multiUnion);
}
Resource exprRDFNode = (Resource) model.asRDFNode(exprNode);
QuerySolutionMap bindings = getBindings(nodes, model);
org.topbraid.spin.model.Query spinQuery = SPINFactory.asQuery((Resource)exprRDFNode);
if(spinQuery instanceof Select || spinQuery instanceof Ask) {
Query query = ARQFactory.get().createQuery((org.topbraid.spin.model.Query)spinQuery, registry);
QueryExecution qexec = ARQFactory.get().createQueryExecution(query, model, bindings);
if(query.isAskType()) {
boolean result = qexec.execAsk();
return NodeValue.makeBoolean(result);
}
else {
ResultSet rs = qexec.execSelect();
String var = rs.getResultVars().get(0);
if(rs.hasNext()) {
RDFNode r = rs.next().get(var);
qexec.close();
if(r != null) {
return NodeValue.makeNode(r.asNode());
}
}
}
}
else {
RDFNode expr = SPINFactory.asExpression(exprRDFNode);
RDFNode result = SPINExpressions.evaluate((Resource) expr, model, bindings, registry);
if(result != null) {
return NodeValue.makeNode(result.asNode());
}
}
throw new ExprEvalException("Expression has no result");
}
} | 9 |
public static Node treeSearch2(Node root,int key){
while(root != null && root.key != key){
if(key < root.key)
root = root.left;
else
root = root.right;
}
return root;
} | 3 |
public void setActive(int x, int y) {
activeX = x;
activeY = y;
switch(actualRole)
{
case Leader:
if (cells[activeX][activeY].valueState == committedByTesterByRows || cells[activeX][activeY].valueState == committedByTesterByColumns ||
cells[activeX][activeY].valueState == committedByTesterBySquares || cells[activeX][activeY].valueState == committedByTesterByUser)
{
acceptValueLeader.setVisible(true);
removeValueLeader.setVisible(true);
}
else {
acceptValueLeader.setVisible(false);
removeValueLeader.setVisible(false);
}
break;
default:
break;
}
} | 5 |
private List setCurrentConnection(int nodeId) {
List list = new List();
for (int i = 0; i < this.connection.length; i++) {
int upI = i + 1;
if (robotPlace.existConnection(upI) && this.connection[nodeId - 1][i] == 1) {
list.add(true, upI);
} else {
if (this.connection[nodeId - 1][i] == 1) {
list.add(false, upI);
}
}
}
return list;
} | 4 |
public void func_4059_a(int var1, int var2, byte[] var3) {
byte var4 = 4;
byte var5 = 32;
int var6 = var4 + 1;
byte var7 = 17;
int var8 = var4 + 1;
this.field_4163_o = this.func_4057_a(this.field_4163_o, var1 * var4, 0, var2 * var4, var6, var7, var8);
for(int var9 = 0; var9 < var4; ++var9) {
for(int var10 = 0; var10 < var4; ++var10) {
for(int var11 = 0; var11 < 16; ++var11) {
double var12 = 0.125D;
double var14 = this.field_4163_o[((var9 + 0) * var8 + var10 + 0) * var7 + var11 + 0];
double var16 = this.field_4163_o[((var9 + 0) * var8 + var10 + 1) * var7 + var11 + 0];
double var18 = this.field_4163_o[((var9 + 1) * var8 + var10 + 0) * var7 + var11 + 0];
double var20 = this.field_4163_o[((var9 + 1) * var8 + var10 + 1) * var7 + var11 + 0];
double var22 = (this.field_4163_o[((var9 + 0) * var8 + var10 + 0) * var7 + var11 + 1] - var14) * var12;
double var24 = (this.field_4163_o[((var9 + 0) * var8 + var10 + 1) * var7 + var11 + 1] - var16) * var12;
double var26 = (this.field_4163_o[((var9 + 1) * var8 + var10 + 0) * var7 + var11 + 1] - var18) * var12;
double var28 = (this.field_4163_o[((var9 + 1) * var8 + var10 + 1) * var7 + var11 + 1] - var20) * var12;
for(int var30 = 0; var30 < 8; ++var30) {
double var31 = 0.25D;
double var33 = var14;
double var35 = var16;
double var37 = (var18 - var14) * var31;
double var39 = (var20 - var16) * var31;
for(int var41 = 0; var41 < 4; ++var41) {
int var42 = var41 + var9 * 4 << 11 | 0 + var10 * 4 << 7 | var11 * 8 + var30;
short var43 = 128;
double var44 = 0.25D;
double var46 = var33;
double var48 = (var35 - var33) * var44;
for(int var50 = 0; var50 < 4; ++var50) {
int var51 = 0;
if(var11 * 8 + var30 < var5) {
var51 = Block.lavaStill.blockID;
}
if(var46 > 0.0D) {
var51 = Block.netherrack.blockID;
}
var3[var42] = (byte)var51;
var42 += var43;
var46 += var48;
}
var33 += var37;
var35 += var39;
}
var14 += var22;
var16 += var24;
var18 += var26;
var20 += var28;
}
}
}
}
} | 8 |
private static boolean processOneTokenForWrapToPixelWidth(String token, Font font, StringBuilder buffer, StringBuilder lineBuffer, int width, int[] lineWidth, boolean hasBeenWrapped) {
int tokenWidth = getSimpleWidth(font, token);
if (lineWidth[0] + tokenWidth <= width) {
lineBuffer.append(token);
lineWidth[0] += tokenWidth;
} else if (lineWidth[0] == 0) {
// Special-case a line that has not had anything put on it yet
int count = token.length();
lineBuffer.append(token.charAt(0));
for (int i = 1; i < count; i++) {
lineBuffer.append(token.charAt(i));
if (getSimpleWidth(font, lineBuffer.toString()) > width) {
lineBuffer.deleteCharAt(lineBuffer.length() - 1);
buffer.append(lineBuffer);
buffer.append(NEWLINE);
hasBeenWrapped = true;
lineBuffer.setLength(0);
lineBuffer.append(token.charAt(i));
}
}
lineWidth[0] = getSimpleWidth(font, lineBuffer.toString());
} else {
buffer.append(lineBuffer);
buffer.append(NEWLINE);
hasBeenWrapped = true;
lineBuffer.setLength(0);
lineWidth[0] = 0;
if (!token.equals(SPACE)) {
return processOneTokenForWrapToPixelWidth(token, font, buffer, lineBuffer, width, lineWidth, hasBeenWrapped);
}
}
return hasBeenWrapped;
} | 5 |
@Override
public void mouseClicked(MouseEvent arg0) {
if (Player == tg.gl.getTurn()) {
JButton l = (JButton) arg0.getSource();
int move = tg.getInt(l.getName());
if (tg.gl.validMove(move, this.Player)) {
TiarUserMessage tum = new TiarUserMessage(move, this.Player);
try {
sendMessage(enc.encode(tum));
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
JOptionPane.showMessageDialog(null, "Not your turn!",
"Warning", JOptionPane.ERROR_MESSAGE);
}
} | 3 |
public void pollControls() {
while (mainState != KeyState.NONE) {
Set<String> keyNames = KEYS.keySet();
for (String str : keyNames) {
if(mainState.getKeyCode() == KEYS.get(str)) {
keyStates[KEYS.get(str)] = mainState.getState();
}
}
setMainState();
}
} | 3 |
public static AnvilSlot bySlot(int slot) {
for (AnvilSlot anvilSlot : values()) {
if (anvilSlot.getSlot() == slot) {
return anvilSlot;
}
}
return null;
} | 2 |
public void printlnToLog(String s) {
synchronized (this) {
printToLog(s + System.getProperty("line.separator"));
}
} | 0 |
@Override
public Date read(String value) throws Exception {
for (SimpleDateFormat df : KNOWN_FORMATS) {
try {
Date result = df.parse(value);
return result;
} catch (ParseException e) {}
}
throw new ParseException("Unparseable date: " + value, 0);
} | 2 |
public static void updateTva(int idtva,String libelle, Float taux) throws SQLException {
String query;
try {
query = "UPDATE TVA set TVALIBELLE=?,TVATX=? WHERE ID_TVA=? ";
PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(3, idtva);
pStatement.setString(1, libelle);
pStatement.setFloat(2, taux);
pStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RequetesTva.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
public void setSumbitTime(Timestamp sumbitTime) {
this.sumbitTime = sumbitTime;
} | 0 |
@Override
public void onEnable() {
PluginDescriptionFile pdfFile = this.getDescription();
// load configuration, this way dis&enabling the plugin will read changes in the config file
this.config = new SheepFeedConfig(this);
// only register event listeners once
//TODO will need to unregister the listeners when that feature is added
if ( !this.hasRegisteredEventListeners ) {
PluginManager pm = this.getServer().getPluginManager();
// register entities receiving damage and dieing
pm.registerEvents(this.entityListener, this);
this.hasRegisteredEventListeners = true;
this.setupPermissions();
}
log.info( pdfFile.getName() + " version " + pdfFile.getVersion() + " by "+ pdfFile.getAuthors().get(0) +" is enabled!" );
} | 1 |
public boolean checkHitPlatform(Object obj) {
Platform other = (Platform) obj;
if (getX() + getWidth() >= other.getX()
&& getX() <= other.getX() + other.getWidth()
&& getY() + getHeight() >= other.getY()
&& getY() + getHeight() <= other.getY() + other.getHeight())
return true;
return false;
} | 4 |
public void testProperty() {
TimeOfDay test = new TimeOfDay(10, 20, 30, 40);
assertEquals(test.hourOfDay(), test.property(DateTimeFieldType.hourOfDay()));
assertEquals(test.minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour()));
assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute()));
assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond()));
try {
test.property(DateTimeFieldType.millisOfDay());
fail();
} catch (IllegalArgumentException ex) {}
try {
test.property(null);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
public void executeTask() {
if (!isModifyAction()) {
if (getSelectedStudent() == null) {
showError("No Student Found", "Please select a student");
} else if (courseList.isEmpty()) {
showError("No Courses Found", "Please select at least one Course to proceed");
}
List savingList = new ArrayList();
Iterator<Course> it = courseList.iterator();
StudentRegisteredCourse srCourse = null;
long sid = getSelectedStudent().getId();
while (it.hasNext()) {
Course course = it.next();
srCourse = new StudentRegisteredCourse();
srCourse.setCourseID(course.getId());
srCourse.setStudentID(sid);
savingList.add(srCourse);
}
boolean success = dao.saveStudentCourseRegistration(savingList);
} else {
List dueRomoveList = new ArrayList();
List dueSaveList = new ArrayList();
for (Course c : getOldCourseList()) {
if (!getCourseList().contains(c)) {
dueRomoveList.add(c);
}
}
long sid= getSelectedStudent().getId();
for (Course c : getCourseList()) {
if (!getOldCourseList().contains(c)) {
StudentRegisteredCourse srCourse = new StudentRegisteredCourse();
srCourse.setCourseID(c.getId());
srCourse.setStudentID(sid);
dueSaveList.add(srCourse);
}
}
dao.saveStudentCourseRegistration(dueSaveList);
boolean b= dao.removeStudentCourseRegistration(dueRomoveList,getSelectedStudent());
}
} | 8 |
private static void testListReader(String listWithBrackets) {
System.out.println("Parsing list:\n"+listWithBrackets);
List<DaTextVariable> l = ListHandler.parseListString(listWithBrackets);
/* boolean first = true;
StringBuilder postProcessed = new StringBuilder();
postProcessed.append("[");
for(DaTextVariable v : l){
if(!first){
postProcessed.append(", ");
}
postProcessed.append(v.asText());
first = false;
}
postProcessed.append("]\n");
System.out.println("parsed result:\n"+postProcessed.toString());*/
String output = ListHandler.listToString(l);//postProcessed.toString();
System.out.println("parsed result:\n");//+output);
for(int i = 0; i < l.size(); i++){
System.out.println("<"+i+">\t"+l.get(i).asText());
}
List<DaTextVariable> l2 = ListHandler.parseListString(output);
boolean theSame =(l.size() == l2.size());
if(!theSame){
System.out.println("Length mismatch: "+l.size() + " != " + l2.size());
}
for(int i = 0; i < l.size() && i < l2.size(); i++){
theSame = theSame && l.get(i).asText().equals(l2.get(i).asText());
if((l.get(i).asText().equals(l2.get(i).asText())) == false){
System.out.println("mismatched list entry: '" + l.get(i).asText() + "' != '"+l2.get(i).asText()+"'");
}
}
theSame = theSame && (ListHandler.listToString(l).equals(ListHandler.listToString(l2)));
System.out.println("Test result:"+theSame);
} | 7 |
public boolean containsSegment(Segment s) {
Iterator<Point> it = this.iterator();
while (it.hasNext()) {
Point p = it.next();
if (p.equals(s.getP1())) {
Point q;
if (it.hasNext()) {
q = it.next();
} else {
q = this.getFirst();
}
if (q.equals(s.getP2())) {
return true;
}
} else if (p.equals(s.getP2())) {
Point q;
if (it.hasNext()) {
q = it.next();
} else {
q = this.getFirst();
}
if(q.equals(s.getP1())) {
return true;
}
}
}
return false;
} | 7 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.