text stringlengths 14 410k | label int32 0 9 |
|---|---|
protected void testPower() {
if (!(this instanceof ITrackPowered))
return;
int i = tileEntity.xCoord;
int j = tileEntity.yCoord;
int k = tileEntity.zCoord;
ITrackPowered r = (ITrackPowered) this;
int meta = tileEntity.getBlockMetadata();
boolean powered = getWorld().isBlockIndirectlyGettingPowered(i, j, k) || testPowerPropagation(getWorld(), i, j, k, getTrackSpec(), meta, r.getPowerPropagation());
if (powered != r.isPowered()) {
r.setPowered(powered);
Block blockTrack = getBlock();
getWorld().notifyBlocksOfNeighborChange(i, j, k, blockTrack);
getWorld().notifyBlocksOfNeighborChange(i, j - 1, k, blockTrack);
if (meta == 2 || meta == 3 || meta == 4 || meta == 5)
getWorld().notifyBlocksOfNeighborChange(i, j + 1, k, blockTrack);
sendUpdateToClient();
// System.out.println("Setting power [" + i + ", " + j + ", " + k + "]");
}
} | 7 |
public static void openURL(String url) {
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,
new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString());
}
}
} | 9 |
protected void filter() throws LexerException {
if (state.equals(State.COMENTARIO)) {
if (comment == null) {
comment = (TComentAninhado) token;
text = new StringBuffer(comment.getText());
count = 1;
token = null;
} else {
text.append(token.getText());
if (token instanceof TComentAninhado) {
count++;
} else if (token instanceof TComentFim) {
count--;
}
if (token instanceof EOF) {
throw new LexerException(null, "token comentario desbalanceado");
}
if (count != 0) {
token = null;
} else {
//Final de um aninhamento
String texto = text.toString();
comment.setText(texto);
token = comment;
state = State.NORMAL;
comment = null;
}
}
}
} | 6 |
public static void main(String[] args) {
File mountPath = null;
FileSystem fsMount = new StaticFileSystem();
//this line turns the static file system into a static file system with RAM-Disk :)
fsMount = new jfilesyslib.filesystems.MergeDirectlyFs(new MemoryFs(), fsMount)
{
@Override
public String getFileSystemName() {
return "StaticFs";
}
@Override
public String getVolumeName() {
return "Static file system";
}
};
//We want advanced features (symbolic links, extended attributes, file permissions, etc.)
//w/o writing any extra code.
fsMount = new ExtendedSupportFs(fsMount);
try {
TestFileSystem.testFileSystemUnmounted(fsMount, true);
} catch (TestFailedException e) {
e.printStackTrace();
System.exit(1);
}
//To enable the builtin logging feature, uncomment the following line
//fsMount = new jfilesyslib.filesystems.LoggingFs(fsMount);
if (args.length > 0)
mountPath = new File(args[0]);
else
{
try {
mountPath = jfilesyslib.Mounter.chooseMountPath(fsMount);
} catch (NoDriveLetterLeftException e) {
e.printStackTrace();
System.exit(1);
}
}
//We do not have a registration key...
//jfilesyslib.JFileSysLibInfo.register("", "");
jfilesyslib.Mounter.mount(fsMount, mountPath);
Mounter.openExplorerWindow(mountPath);
System.out.println("Press enter to unmount.");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Unmounting...");
Mounter.unmount(fsMount);
System.out.println("Unmounted");
} | 4 |
public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
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("JSONObject[" + quote(key)
+ "] is not a Boolean.");
} | 6 |
private boolean dansRectangle(int x1, int y1, int x2, int y2, int x, int y){
if ((x1<=x && x<=x2) && (y1<=y && y<=y2)) return true;
return false;
} | 4 |
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
String identificador = null;
try {
identificador = obtemIdentificador(req);
} catch (RecursoSemIdentificadorException e) {
resp.sendError(400, e.getMessage());
}
if(identificador != null && estoque.recuperarCervejaPeloNome(identificador) != null){
resp.sendError(409, "Ja existe uma cerveja com esse nome");
return;
}
String tipoDeConteudo = req.getContentType();
Cerveja cerveja = null;
Unmarshaller unmarshaller = context.createUnmarshaller();
if(tipoDeConteudo == null || tipoDeConteudo.contains("application/xml")){
cerveja = (Cerveja) unmarshaller.unmarshal(req.getInputStream());
cerveja.setNome(identificador);
estoque.adicionarCerveja(cerveja);
String requestURI = req.getRequestURI();
resp.setHeader("Location", requestURI);
resp.setStatus(201);
escreveXML(req, resp);
}else if(tipoDeConteudo.contains("application/json")){
List<String> lines = IOUtils.readLines(req.getInputStream());
StringBuilder builder = new StringBuilder();
for (String line : lines) {
builder.append(line);
}
MappedNamespaceConvention con = new MappedNamespaceConvention();
JSONObject jsonObject = new JSONObject(builder.toString());
XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(jsonObject, con);
cerveja = (Cerveja) unmarshaller.unmarshal(xmlStreamReader);
cerveja.setNome(identificador);
estoque.adicionarCerveja(cerveja);
String requestURI = req.getRequestURI();
resp.setHeader("Location", requestURI);
resp.setStatus(201);
escreveJSON(req, resp);
}else{
resp.sendError(415);
return;
}
} catch (Exception e) {
resp.sendError(500, e.getMessage());
}
} | 8 |
public static Area getArea(double robotX, double robotY, double battleFiledWidth,
double battleFieldHeight, double widthOffset, double heightOffset) {
boolean nearWallXMin = robotX < widthOffset;
boolean nearWallXMax = robotX > battleFiledWidth - widthOffset;
boolean nearWallYMin = robotY < heightOffset;
boolean nearWallYMax = robotY > battleFieldHeight - heightOffset;
if (nearWallYMax) {
if (nearWallXMax) {
return Area.valueOf(1);
}
else if (nearWallXMin) {
return Area.valueOf(7);
}
else {
return Area.valueOf(0);
}
}
else if (nearWallYMin) {
if (nearWallXMax) {
return Area.valueOf(3);
}
else if (nearWallXMin) {
return Area.valueOf(5);
}
else {
return Area.valueOf(4);
}
}
else {
if (nearWallXMax) {
return Area.valueOf(2);
}
else if (nearWallXMin) {
return Area.valueOf(6);
}
else {
return Area.valueOf(-1);
}
}
} | 8 |
public static void load(int num) throws IOException {
File f = new File(Util.getDataPath() + File.separator + "world" + num + ".jmp");
if (!f.exists()) {
System.out.println("Could not find file: " + f.getAbsolutePath());
return;
}
FileInputStream fis = new FileInputStream(f);
byte[] compressed = new byte[(int) f.length()];
fis.read(compressed);
fis.close();
byte[] decompressed = null;
try {
decompressed = Util.decompress(compressed);
} catch (DataFormatException e) {
e.printStackTrace();
Gui.addMessage("Failed to decompress bytes");
return;
}
// Decompressed
DataInputStream in = new DataInputStream(new ByteArrayInputStream(decompressed));
int pre = in.readInt();
if (pre != PREFIX) {
System.out.println("Invalid World Prefix. Cancelling World Load Process!");
in.close();
return;
}
int ver = in.readShort();
if (ver != WORLDSAVE_VERSION) {
Gui.addMessage("Invalid World Version!");
in.close();
return;
}
int pX = in.readInt();
int pY = in.readInt();
int width = in.readInt();
int height = in.readInt();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
byte id = (byte) in.readByte();
Jomapat.game.getWorld().setBlock(x, y, id != (byte)0xFF ? BlockType.values()[id] : null);
}
}
Jomapat.game.getWorld().finish();
for(int i = 0; i < BlockType.values().length; i++) {
int amount = in.readInt();
Jomapat.game.getInventory().setBlockAmount(BlockType.values()[i], amount);
}
Jomapat.game.getPlayer().setX(pX);
Jomapat.game.getPlayer().setY(pY);
in.close();
Gui.addMessage("World Loaded!");
} | 8 |
public HomeScreen() {
// Set the displayed title of the screen
setTitle("TravelSDK Example");
CustomButtonField buttonFlightSearch = new CustomButtonField("Flight search");
buttonFlightSearch.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!TravelSDK.INSTANCE.isInitialized()) {
Dialog.alert("Travel SDK isn't initialized");
return;
}
UiApplication.getUiApplication().pushScreen(new FlightSearchScreen());
}
});
CustomButtonField buttonHotelSearch = new CustomButtonField("Hotel search");
buttonHotelSearch.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!TravelSDK.INSTANCE.isInitialized()) {
Dialog.alert("Travel SDK isn't initialized");
return;
}
UiApplication.getUiApplication().pushScreen(new HotelSearchScreen());
}
});
CustomButtonField buttonRentacarSearch = new CustomButtonField("Renta car search");
buttonRentacarSearch.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!TravelSDK.INSTANCE.isInitialized()) {
Dialog.alert("Travel SDK isn't initialized");
return;
}
UiApplication.getUiApplication().pushScreen(new RentacarSearchScreen());
}
});
CustomButtonField buttonExcursionSearch = new CustomButtonField("Excursion search");
buttonExcursionSearch.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!TravelSDK.INSTANCE.isInitialized()) {
Dialog.alert("Travel SDK isn't initialized");
return;
}
UiApplication.getUiApplication().pushScreen(new ExcursionSearchScreen());
}
});
CustomButtonField buttonBasket = new CustomButtonField("Basket");
buttonBasket.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!TravelSDK.INSTANCE.isInitialized()) {
Dialog.alert("Travel SDK isn't initialized");
return;
}
UiApplication.getUiApplication().pushScreen(new BasketScreen());
}
});
CustomButtonField buttonBookings = new CustomButtonField("Bookings");
buttonBookings.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (!TravelSDK.INSTANCE.isInitialized()) {
Dialog.alert("Travel SDK isn't initialized");
return;
}
ProcessBookingsList processBookingsList = new ProcessBookingsList() {
public void onComplete() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
if(getErrorCode() != null) {
Dialog.alert("Error: " + errorCode);
return;
}
UiApplication.getUiApplication().pushScreen(new BookingsScreen(getResult()));
}
});
}
public String getLoadingMessage() {
return "Receiving bookings ...";
}
};
TravelSDK.INSTANCE.receiveBookings(processBookingsList);
}
});
CustomButtonField buttonDebugLog = new CustomButtonField("Debug information");
buttonDebugLog.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
try {
Logger.sendLog();
} catch (IOException e) {
e.printStackTrace();
}
}
});
this.add(buttonFlightSearch);
this.add(buttonHotelSearch);
this.add(buttonRentacarSearch);
this.add(buttonExcursionSearch);
this.add(buttonBasket);
this.add(buttonBookings);
this.add(buttonDebugLog);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// Init travel SDK
init();
}
});
} | 8 |
public static String removeStylename(String style, String stylename)
{
StringBuffer buffer = new StringBuffer();
if (style != null)
{
String[] tokens = style.split(";");
for (int i = 0; i < tokens.length; i++)
{
if (!tokens[i].equals(stylename))
{
buffer.append(tokens[i] + ";");
}
}
}
return (buffer.length() > 1) ? buffer.substring(0, buffer.length() - 1)
: buffer.toString();
} | 4 |
private void modifyNote(Map<String, Object> jsonrpc2Params) throws Exception {
Map<String, Object> params = getParams(jsonrpc2Params,
new NullableExtendedParam(Constants.Param.Name.NOTE_ID, false),
new NullableExtendedParam(Constants.Param.Name.TEXT, true),
new NullableExtendedParam(Constants.Param.Name.HEADLINE, true));
int noteId = (Integer)params.get(Constants.Param.Name.NOTE_ID);
String text = (String)params.get(Constants.Param.Name.TEXT);
String headline = (String)params.get(Constants.Param.Name.HEADLINE);
Note note = em.find(Note.class, noteId);
if(note == null){
responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.OBJECT_NOT_FOUND);
return;
}
if(note.getAccount().getId() != accountId){
throwJSONRPC2Error(JSONRPC2Error.INVALID_PARAMS, Constants.Errors.ACTION_NOT_ALLOWED);
}
if(text != null){
note.setText(text);
}
if(headline != null){
note.setHeadLine(headline);
}
persistObjects(note);
responseParams.put(Constants.Param.Name.NOTE, serialize(note));
responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.SUCCESS);
} | 4 |
public static void validatePassword(String password) throws TechnicalException {
if (password == null || password.isEmpty() || password.length() > PASSWORD_SIZE) {
throw new TechnicalException(PASSWORD_ERROR_MSG);
}
String regex = "[\\w]{4,}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(password);
if (! m.matches()) {
throw new TechnicalException(PASSWORD_ERROR_MSG);
}
} | 4 |
private int obtenerParametros(String s, ArrayList<Integer> parametros){
String cadAux;
int delim1, delim2;
while (s.compareTo("")!=0){
delim1=s.indexOf('<');
delim2=s.indexOf('>');
if ((delim1 < delim2)&&(delim1!= -1)&&(delim2!=-1)){
cadAux = s.substring(delim1+1, delim2);
if (esEntero(cadAux)){
parametros.add(Integer.parseInt(cadAux));
s = s.substring(delim2+1);
}
else{
s = "";
}
}
else{
s = "";
}
}
return parametros.size();
} | 5 |
private void fillChengWeights() {
for (Bookmark data : trainList) {
int user = data.getUserID();
int resource = data.getWikiID();
List<Integer> tags = data.getTags();
Map<Integer, Double> tagUserWeights = null;
if (user >= userTagWeights.size()) {
tagUserWeights = new LinkedHashMap<Integer, Double>();
userTagWeights.add(tagUserWeights);
} else {
tagUserWeights = userTagWeights.get(user);
}
Map<Integer, Double> tagResourceWeights = resourceTagWeights.get(resource);
if (tagResourceWeights == null) {
tagResourceWeights = new HashMap<Integer, Double>();
}
for (Integer tag : tags) {
if (!tagUserWeights.containsKey(tag)) {
tagUserWeights.put(tag, huangApproach.getUserTagWeight(user, tag));
}
if (!tagResourceWeights.containsKey(tag)) {
tagResourceWeights.put(tag, huangApproach.getItemTagWeight(resource, tag));
}
}
resourceTagWeights.put(resource, tagResourceWeights);
}
} | 6 |
private JPanel getPanCode() {
if (panCode == null) {
panCode = new JPanel();
panCode.setBorder(BorderFactory.createTitledBorder("Code :"));
panCode.setLayout(new BoxLayout(this.panCode,BoxLayout.Y_AXIS));
ButtonGroup group=new ButtonGroup();
for(int i=0;i<=Interface.CODES.values().length;i++) {
final int l=i;
if(i!=Interface.CODES.values().length) {
if(Interface.CODES.values()[i].estCryptanalysable()) {
JRadioButton temp=new JRadioButton(Interface.CODES.values()[i].getNom());
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionne=Interface.CODES.values()[l];
}
});
group.add(temp);
panCode.add(temp);
}
}
else {
JRadioButton temp=new JRadioButton("Tous");
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionne=null;
}
});
group.add(temp);
panCode.add(temp);
}
}
}
return panCode;
} | 4 |
List<CourseListing> getByCategoryAndType(String selectedCategory, String selectedType) {
List<CourseListing> courseListing = new ArrayList<CourseListing>();
try {
//Connect to database
conn = DriverManager.getConnection(url, userName, password);
stmt = conn.createStatement();
ResultSet rset = null, rset1 = null;
PreparedStatement pstmt = null, pstmt1 = null;
pstmt = conn.prepareStatement("select * FROM CourseProduct "
+ "INNER JOIN Course "
+ "ON CourseProduct.number=Course.number "
+ "inner join Product "
+ "on CourseProduct.P_ID=Product.P_ID "
+ "where category = ? "
+ "and type = ? "
+ "group by Course.number");
pstmt.setString(1, selectedCategory);
pstmt.setString(2, selectedType);
rset = pstmt.executeQuery();
while (rset.next()) {
String tempNumber = rset.getString("number");
pstmt1 = conn.prepareStatement("select distinct product FROM "
+ "CourseProduct INNER JOIN Course "
+ "ON CourseProduct.number=Course.number "
+ "inner join Product "
+ "on CourseProduct.P_ID=Product.P_ID "
+ "WHERE "
+ "Course.number = ? order by product");
pstmt1.setString(1, tempNumber);
rset1 = pstmt1.executeQuery();
String tempProduct = "";
while (rset1.next()) {
tempProduct += " " + rset1.getString("product") + ",";
}
tempProduct = tempProduct.substring(0, tempProduct.length() - 1);
courseListing.add(new CourseListing(
rset.getDouble("price"),
rset.getString("number"),
rset.getString("name"),
rset.getString("location"),
rset.getString("unit"),
rset.getString("duration"),
rset.getString("type"),
rset.getString("role"),
rset.getString("category"),
rset.getString("maxNumStudents"),
rset.getString("superProduct"),
rset.getString("subProduct"),
tempProduct));
}
} catch (SQLException e) {
response = "SQLException: " + e.getMessage();
while ((e = e.getNextException()) != null) {
response = e.getMessage();
}
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
response = "SQLException: " + e.getMessage();
while ((e = e.getNextException()) != null) {
response = e.getMessage();
}
}
}
this.response = "Done";
return courseListing;
} | 8 |
public int getMachineIndexByName(String machineFileName){
ArrayList machines = getEnvironment().myObjects;
if(machines == null) return -1;
for(int k = 0; k < machines.size(); k++){
Object current = machines.get(k);
if(current instanceof Automaton){
Automaton cur = (Automaton)current;
if(cur.getFileName().equals(machineFileName)){
return k;
}
}
else if(current instanceof Grammar){
Grammar cur = (Grammar)current;
if(cur.getFileName().equals(machineFileName)){
return k;
}
}
}
return -1;
} | 6 |
public void executaMutacao() {
for (int i = 1; i < cromossomos.size(); i++) {
int rand1 = 0 + (int) (Math.random() * (cromossomos.size() - 0));
if (cromossomos.get(rand1).best) {
continue;
}
int pontoMutacao = 0 + (int) (Math.random() * (1000 - 0));
Mutacao.MutacaoPresente(cromossomos.get(i).getGenesPresente(), pontoMutacao, deslocamento);
}
List<Future> futures = new ArrayList<>();
ExecutorService pool = Executors.newFixedThreadPool(cromossomos.size());
//int pronto = 0;
for (Cromossomo cromossomo : cromossomos) {
//cromossomo.atualizaFitness();
if (cromossomo.best && count > 0) {
continue;
}
Future f = pool.submit(cromossomo);
futures.add(f);
}
Instant inicio = Instant.now();
for (Future future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(AlgoritmoGenetico.class.getName()).log(Level.SEVERE, null, ex);
}
}
Instant fim = Instant.now();
Duration duracao = Duration.between(inicio, fim);
long duracaoEmMilissegundos = duracao.toMillis();
System.out.println(duracaoEmMilissegundos);
} | 7 |
void createColorAndFontGroup () {
super.createColorAndFontGroup();
TableItem item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Item_Foreground_Color"));
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Item_Background_Color"));
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Item_Font"));
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Cell_Foreground_Color"));
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Cell_Background_Color"));
item = new TableItem(colorAndFontTable, SWT.None);
item.setText(ControlExample.getResourceString ("Cell_Font"));
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
if (itemBackgroundColor != null) itemBackgroundColor.dispose();
if (itemForegroundColor != null) itemForegroundColor.dispose();
if (itemFont != null) itemFont.dispose();
if (cellBackgroundColor != null) cellBackgroundColor.dispose();
if (cellForegroundColor != null) cellForegroundColor.dispose();
if (cellFont != null) cellFont.dispose();
itemBackgroundColor = null;
itemForegroundColor = null;
itemFont = null;
cellBackgroundColor = null;
cellForegroundColor = null;
cellFont = null;
}
});
} | 6 |
public void pop() throws java.lang.Exception
{
if (vstack.empty())
throw new Exception(
"Internal parser error: pop from empty virtual stack");
/* pop it */
vstack.pop();
/* if we are now empty transfer an element (if there is one) */
if (vstack.empty())
get_from_real();
} | 2 |
private List<MazeCell> getNNodesDiagonal(MazeCell node) {
ArrayList<MazeCell> nbrs = new ArrayList<>();
int x = node.getX();
int y = node.getY();
int xmin = x;
int xmax = x;
int ymin = y;
int ymax = y;
if (x - 1 >= 0) {
xmin = x - 1;
}
if (x + 1 < allCells.length) {
xmax = x + 1;
}
if (y - 1 >= 0) {
ymin = y - 1;
}
if (y + 1 < allCells.length) {
ymax = y + 1;
}
for (int i = xmin; i <= xmax; i++) {
for (int k = ymin; k <= ymax; k++) {
if (allCells[i][k] != null) {
if (!allCells[i][k].equals(node)) { //Not the node istelf
nbrs.add(allCells[i][k]);
}
}
}
}
return nbrs;
} | 8 |
public synchronized void editar(int i)
{
try
{
new PalavraChaveView(this, list.get(i));
}
catch (Exception e)
{
}
} | 1 |
public void direction() {
if (untouchable > 0) {
Dolphin dolphin = (Dolphin) getWorld().getObjects(Dolphin.class).get(0);
if (dolphin.direction == 0) {
setRotation(0);
}
else if (dolphin.direction == 1) {
setRotation(-45);
}
else if (dolphin.direction == 2) {
setRotation(-90);
}
else if (dolphin.direction == 3) {
setRotation(-135);
}
else if (dolphin.direction == 4) {
setRotation(-180);
}
else if (dolphin.direction == 5) {
setRotation(-225);
}
else if (dolphin.direction == 6) {
setRotation(-270);
}
else if (dolphin.direction == 7) {
setRotation(-315);
}
}
} | 9 |
protected void heapifyDown(int loc) {
int max = loc;
int leftChild = leftChild(loc);
if (leftChild < size()) {
double priority = priorities[loc];
double leftChildPriority = priorities[leftChild];
if (leftChildPriority > priority)
max = leftChild;
int rightChild = rightChild(loc);
if (rightChild < size()) {
double rightChildPriority = priorities[rightChild(loc)];
if (rightChildPriority > priority && rightChildPriority > leftChildPriority)
max = rightChild;
}
}
if (max == loc)
return;
swap(loc, max);
heapifyDown(max);
} | 6 |
protected void processElement(IXMLReader reader,
IXMLEntityResolver entityResolver)
throws Exception
{
String str = XMLUtil.read(reader, '%');
char ch = str.charAt(0);
if (ch != '!') {
XMLUtil.skipTag(reader);
return;
}
str = XMLUtil.read(reader, '%');
ch = str.charAt(0);
switch (ch) {
case '-':
XMLUtil.skipComment(reader);
break;
case '[':
this.processConditionalSection(reader, entityResolver);
break;
case 'E':
this.processEntity(reader, entityResolver);
break;
case 'A':
this.processAttList(reader, entityResolver);
break;
default:
XMLUtil.skipTag(reader);
}
} | 5 |
private void loadConfig( String filename )
{
try{
File file = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(file));
String str;
while((str = br.readLine()) != null)
{
if( str != null )
{
String item[] = str.split(":");
if( item[0].equals( "port" ) )
{
try
{
mPortNum = Integer.parseInt(item[1]);
}
catch( NumberFormatException e )
{
mPortNum = -1;
}
}
else if(item[0].equals( "debug" ) )
{
if( item[1].equals( "true" ) )
{
mIsDebug = true;
}
}
}
}
br.close();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
} | 8 |
private Collision trace(Scene scene, Ray ray) {
Collision nearestCollision = null;
for (SceneObject sceneObject : scene.getSceneObjects()) {
if (sceneObject.checkIntersectionPossibility(ray)) {
Collision collisions[] = sceneObject.trace(ray);
if (collisions.length > 0 && collisions[0].getDistance() >= MathUtils.GEOMETRY_THRESHOLD) {
if (nearestCollision == null || nearestCollision.getDistance() > collisions[0].getDistance()) {
nearestCollision = collisions[0];
}
}
}
}
return nearestCollision;
} | 6 |
public static void main(String[] args) {
int[][] arr={{1,2,3},{1,2,3},{1,2,3}};
NumMatrix numMatrix=new NumMatrix(arr);
System.out.println(numMatrix.getRangeSum(1,1));
System.out.println(numMatrix.getRangeSum(0,1));
System.out.println(numMatrix.sumRegion(1,1,1,1));
} | 0 |
private void initTradeElement(){ // Cree 5 TradeElement ( des JPanel contenant 2 paire de +/- et des labels indiquant les quantites echange )
for (int i=0;i<5;i++)
{
switch(i) // Correspondance entier-ressource : 0 = bois ; 1 = mouton ; 2 = ble ; 3 = argile ; 4 = minerai.
{
case 0:
tradeElement[i] = new TradeElement("Biere",model.getActivePlayer().getRessource(i),model.getPlayer(nameSelectedPlayer).getRessource(i),controlerBank);
center.add(tradeElement[i]);
break;
case 1:
tradeElement[i] = new TradeElement("Cafe",model.getActivePlayer().getRessource(i),model.getPlayer(nameSelectedPlayer).getRessource(i),controlerBank);
center.add(tradeElement[i]);
break;
case 2:
tradeElement[i] = new TradeElement("Cours",model.getActivePlayer().getRessource(i),model.getPlayer(nameSelectedPlayer).getRessource(i),controlerBank);
center.add(tradeElement[i]);
break;
case 3:
tradeElement[i] = new TradeElement("Nourriture",model.getActivePlayer().getRessource(i),model.getPlayer(nameSelectedPlayer).getRessource(i),controlerBank);
center.add(tradeElement[i]);
break;
case 4:
tradeElement[i] = new TradeElement("Sommeil",model.getActivePlayer().getRessource(i),model.getPlayer(nameSelectedPlayer).getRessource(i),controlerBank);
center.add(tradeElement[i]);
break;
default:
tradeElement[i] = new TradeElement("Erreur",model.getActivePlayer().getRessource(i),model.getPlayer(nameSelectedPlayer).getRessource(i),controlerBank);
center.add(tradeElement[i]);
}
}
} | 6 |
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
} | 1 |
private void scanProjectLessFiles() {
List<LessFileStatus> lstAddedLfs = new ArrayList<LessFileStatus>();
synchronized (WATCH_LOCK) {
if (conf.isRecursive())
recursiveScanDir("", dir, lstAddedLfs);
else
scanDir(dir, lstAddedLfs);
}
// - Not synchronized in order to avoid dead locks
for (LessFileStatus lfs : lstAddedLfs)
report.add(lfs);
} | 2 |
protected void save(Map<String,String> values) throws SQLException {
if(isNew()) {
Data.create(this, values);
return;
}
int nColumn = values.size();
String[] aPiece = new String[nColumn];
String[] aValue = new String[nColumn];
Iterator<Entry<String,String>> it = values.entrySet().iterator();
for(int i=0; it.hasNext(); i++) {
Entry pairs = it.next();
aPiece[i] = " `" + (String)pairs.getKey() + "` = ? ";
aValue[i] = (String)pairs.getValue();
it.remove(); // avoids a ConcurrentModificationException
}
// update `$tableName` set `col1` = ? , `col2` = ?, ... where `id` = $id
PreparedStatement statement = connect.prepareStatement(
" update `" + tableName + "` set "
+ StringUtils.join(aPiece, ",")
+ "where `id` = " + this.id
);
// fill values
for(int i=0; i<nColumn; i++) {
statement.setString(i+1, aValue[i]);
}
// execute query
statement.executeUpdate();
} | 3 |
public boolean cast (Sorcerer sorcerer, Trigger trigger, Event event)
{
PlayerInteractEvent interactEvent = (PlayerInteractEvent) event;
interactEvent.setCancelled(true);
final Location origin;
if (trigger.isBlockTriggered())
{
origin = interactEvent.getClickedBlock().getLocation().add(0, 1, 0);
}
else
{
origin = sorcerer.getPlayer().getLocation();
}
int radius = 5;
final World world = origin.getWorld();
final int blockX = origin.getBlockX();
final int blockY = origin.getBlockY();
final int blockZ = origin.getBlockZ();
int iter = 0;
int x = radius, z = 0;
int radiusError = 1 - x;
while (x >= z)
{
final int finalX = x, finalZ = z;
Merlin.getInstance().getServer().getScheduler()
.scheduleSyncDelayedTask(Merlin.getInstance(), new Runnable()
{
public void run ()
{
setFires(world, blockX, blockY, blockZ, finalX, finalZ);
}
}, iter);
z++;
if (radiusError < 0)
{
radiusError += 2 * z + 1;
}
else
{
x--;
radiusError += 2 * (z - x) + 1;
}
iter += 3;
}
return true;
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pojo other = (Pojo) obj;
if (dateTime == null) {
if (other.dateTime != null)
return false;
} else if (!dateTime.equals(other.dateTime))
return false;
return true;
} | 6 |
@Override
public List<T> sort(List<T> list) {
// Iterate over the list, starting from the first element going to the last element.
for (int outer = 1; outer < list.size(); outer++) {
// In each iteration, perform another iteration from the very beginning of the list
// to the point at which the outer loop has placed an element in its final position.
// At each step, compare whether the element to the right is out of place with the current
// element and if so, swap.
for (int left = 0; left < (list.size() - outer); left++) {
int right = left + 1;
if (list.get(left).compareTo(list.get(right)) > 0) {
listSorterHelper.swap(list, left, right);
}
}
}
return list;
} | 3 |
int decodevs(float[] a, int index, Buffer b, int step, int addmul){
int entry=decode(b);
if(entry==-1)
return (-1);
switch(addmul){
case -1:
for(int i=0, o=0; i<dim; i++, o+=step)
a[index+o]=valuelist[entry*dim+i];
break;
case 0:
for(int i=0, o=0; i<dim; i++, o+=step)
a[index+o]+=valuelist[entry*dim+i];
break;
case 1:
for(int i=0, o=0; i<dim; i++, o+=step)
a[index+o]*=valuelist[entry*dim+i];
break;
default:
//System.err.println("CodeBook.decodeves: addmul="+addmul);
}
return (entry);
} | 7 |
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
if(k<=0) return new int[0];
int[] result={};
for(int i=0;i<=k;++i){
int[] a=search(nums1,i);
int[] b=search(nums2,k-i);
result=max(result,merger(a,b));
}
return result;
} | 2 |
@Override
public Group parse() {
if(!this.prepared) {
this.prepared = true;
StringBuilder sB = new StringBuilder();
sB.append("(");
Iterator<Object> elemIterator = this.elems.iterator();
while(elemIterator.hasNext()) {
Object eRaw = elemIterator.next();
if(eRaw instanceof Elem) {
Elem e = (Elem)eRaw;
sB.append(e.getType().getTextual());
String v = e.getValue() == null ? "" : e.getValue();
ValueType vT = e.getValueType();
String vTS = vT.getTextual().replace("%1", e.getField().replace("#__", this.db.getPrefix()));
vTS = vTS.replace("%2", v);
sB.append(vTS);
/*sB.append(e.getField().replace("#__", this.db.getPrefix()));
sB.append(" = ");
sB.append(e.getValue());*/
}else if(eRaw instanceof Group) {
Group e = (Group)eRaw;
sB.append(e.getType().getTextual());
if(!e.isParsed()) {
e.parse();
}
sB.append(e.getParsedGroup());
}
}
sB.append(")");
this.group = sB.toString();
}
return this;
} | 6 |
public boolean setupBall(double ang)
{
boolean positivex = (Math.cos(ang) > 0);
boolean positivey = (Math.sin(ang) > 0);
ball = new Ball(0, 0, ang);
ball.update();
boolean b1 = (positivex && ball.X() > 0.01) || (!positivex && ball.X() < -0.01);
boolean b2 = (positivey && ball.Y() > 0.01) || (!positivey && ball.Y() < -0.01);
return b1 && b2;
} | 7 |
public Set<Key> getKeys() {
HashSet<Key> keySet = new HashSet<Key>();
for (ArrayList<Key> keyList : keys.values()) {
keySet.addAll(keyList);
}
return keySet;
} | 1 |
private void sendHeader(OutputStream out, long dataLength, int filetype)
throws IOException
{
out.write("HTTP/1.0 200 OK".getBytes());
out.write(endofline);
out.write("Content-Length: ".getBytes());
out.write(Long.toString(dataLength).getBytes());
out.write(endofline);
if (filetype == typeClass)
out.write("Content-Type: application/octet-stream".getBytes());
else if (filetype == typeHtml)
out.write("Content-Type: text/html".getBytes());
else if (filetype == typeGif)
out.write("Content-Type: image/gif".getBytes());
else if (filetype == typeJpeg)
out.write("Content-Type: image/jpg".getBytes());
else if (filetype == typeText)
out.write("Content-Type: text/plain".getBytes());
out.write(endofline);
out.write(endofline);
} | 5 |
private void init() {
GameWorld temp = new SolarSystemLoc(ticker);
locations.add(temp);
} | 0 |
public void countStress(Boolean[] stresses) {
// Add to observed stresses
for(int i = 0; i < stresses.length; i++) {
observedStresses[i] += stresses[i] ? 1 : 0;
}
observedStressCount++;
} | 2 |
public void setB(float b) {
this.b = b;
} | 0 |
public static void removeConnections(BeanInstance instance) {
Vector instancesToRemoveFor = new Vector();
if (instance.getBean() instanceof MetaBean) {
instancesToRemoveFor =
((MetaBean)instance.getBean()).getBeansInSubFlow();
} else {
instancesToRemoveFor.add(instance);
}
Vector removeVector = new Vector();
for (int j = 0; j < instancesToRemoveFor.size(); j++) {
BeanInstance tempInstance =
(BeanInstance)instancesToRemoveFor.elementAt(j);
for (int i = 0; i < CONNECTIONS.size(); i++) {
// In cases where this instance is the target, deregister it
// as a listener for the source
BeanConnection bc = (BeanConnection)CONNECTIONS.elementAt(i);
BeanInstance tempTarget = bc.getTarget();
BeanInstance tempSource = bc.getSource();
EventSetDescriptor tempEsd = bc.getSourceEventSetDescriptor();
if (tempInstance == tempTarget) {
// try to deregister the target as a listener for the source
try {
Method deregisterMethod = tempEsd.getRemoveListenerMethod();
Object targetBean = tempTarget.getBean();
Object [] args = new Object[1];
args[0] = targetBean;
deregisterMethod.invoke(tempSource.getBean(), args);
// System.err.println("Deregistering listener");
removeVector.addElement(bc);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (tempInstance == tempSource) {
removeVector.addElement(bc);
if (tempTarget.getBean() instanceof BeanCommon) {
// tell the target that the source is going away, therefore
// this type of connection is as well
((BeanCommon)tempTarget.getBean()).
disconnectionNotification(tempEsd.getName(),
tempSource.getBean());
}
}
}
}
for (int i = 0; i < removeVector.size(); i++) {
// System.err.println("removing connection");
CONNECTIONS.removeElement((BeanConnection)removeVector.elementAt(i));
}
} | 8 |
private boolean isBlocked(float x, float y) {
boolean blocked = false;
float tweakedX = x + 4;
float tweakedY = y + 8;
beeBoundingRect.setLocation(tweakedX,tweakedY);
for(int i = 0; i < map.length; i++){
if(beeBoundingRect.intersects(map[i])){
if(map[i].type != 0){
blocked = true;
}
}
}
return blocked;
} | 3 |
public static float getOppositeAngleRad(float angle) {
if(angle - PI > 0) {
return angle - PI;
}
else {
return angle + PI;
}
} | 1 |
@Override
public Object readItem() throws Exception {
String string = null;
try {
string = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return string;
} | 1 |
GrantEntry readGrantEntry( StreamTokenizer st )
throws IOException,
InvalidFormatException
{
String signer = null, codebase = null;
Collection<PrincipalEntry> principals = new ArrayList<PrincipalEntry>();
Collection<PermissionEntry> permissions = null;
parsing:
while( true )
{
switch( st.nextToken() )
{
case StreamTokenizer.TT_WORD:
if( "signedby".equalsIgnoreCase( st.sval ) )
{
if( st.nextToken() == '"' )
{
signer = st.sval;
}
else
{
handleUnexpectedToken( st, "Expected syntax is : signedby \"name1,...,nameN\"" );
}
}
else if( "codebase".equalsIgnoreCase( st.sval ) )
{
if( st.nextToken() == '"' )
{
codebase = st.sval;
}
else
{
handleUnexpectedToken( st, "Expected syntax is : codebase \"url\"" );
}
}
else if( "principal".equalsIgnoreCase( st.sval ) )
{
principals.add( readPrincipalEntry( st ) );
}
else
{
handleUnexpectedToken( st );
}
break;
case ',': //just delimiter of entries
break;
case '{':
permissions = readPermissionEntries( st );
break parsing;
default: // handle token in the main loop
st.pushBack();
break parsing;
}
}
return new GrantEntry( signer, codebase, principals, permissions );
} | 9 |
public Mob nextEnemy(boolean pourVrai,long time)
{
if(cptMob>=listMobs.size()){System.out.println("NextEnemy-> Plus d'enemy");return null;}
if(listMobs.get(cptMob).getSpawnTime()<=time)
{
Mob m = listMobs.get(cptMob);
m.setMovable(true);
if(pourVrai)cptMob++; //Incremente que dans le cas ou on le fait vraiment, pas en test
return m;
}
return null;
} | 3 |
@Override
public void keyPressed(KeyEvent e) {
LOGGER.info("KeyEvent " + e.toString());
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
cliente.teclado(CoreComando.DIREITA);
break;
case KeyEvent.VK_LEFT:
cliente.teclado(CoreComando.ESQUERDA);
break;
case KeyEvent.VK_DOWN:
cliente.teclado(CoreComando.ABAIXA);
break;
case KeyEvent.VK_SPACE:
cliente.teclado(CoreComando.PULA);
break;
case KeyEvent.VK_Z:
cliente.teclado(CoreComando.ATACA);
}
} | 5 |
public HexGrid(GUI g) {
gui = g;
worlds = new ArrayList();
brains = new ArrayList();
} | 0 |
public long inserir(Local local) throws Exception
{
String sql = "INSERT INTO local(cidade, estado, descricao) VALUES (?, ?, ?)";
long idGerado = 0;
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, local.getCidade());
stmt.setString(2, local.getEstado());
stmt.setString(3, local.getDescricao());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next())
{
idGerado = rs.getLong(1);
}
}
catch (SQLException e)
{
throw e;
}
return idGerado;
} | 2 |
public void setFill(Color fill) {
this.fill = fill;
} | 0 |
public String getNextComponent(Identifier ident) {
if (isOr == AND) {
for (int i = 0; i < matchers.length; i++) {
String next = matchers[i].getNextComponent(ident);
if (next != null && matchesSub(ident, next))
return next;
}
return null;
}
// OR case
String next = null;
for (int i = 0; i < matchers.length; i++) {
if (!matchesSub(ident, null))
continue;
if (next != null
&& !matchers[i].getNextComponent(ident).equals(next))
return null;
next = matchers[i].getNextComponent(ident);
if (next == null)
return null;
}
return next;
} | 9 |
@Override
public void fatalError(SAXParseException e) {
System.out.println("SAXParserException Fatal Error: " + e.getMessage());
this.errorOccurred = true;
} | 0 |
public void uimsg(String name, Object... args) {
if(name == "log") {
log.append((String)args[0]);
} else {
super.uimsg(name, args);
}
} | 1 |
private Value funcCall_rest() throws Exception
{
Identifier funcName = ident();
ArrayList<Value> args = new ArrayList<Value>();
do {
if(scan.sym == Token.openparen) {
scan.next();
if(scan.sym == Token.closeparen) {
scan.next();
break;
}
args.add(expression());
while(scan.sym == Token.comma) {
scan.next();
args.add(expression());
}
if(scan.sym == Token.closeparen) {
scan.next();
break;
}
throw new Exception("funcCall: no closing ')'");
}
} while (false);
Instruction rval = makeCall(funcName, args);
currentBB.addInstruction(rval);
return rval;
} | 5 |
static final private ArrayList<AbsValueNode> listArg() throws ParseException, CompilationException {
Token t;
ArrayList<AbsValueNode> result = new ArrayList<AbsValueNode>();
ArrayList<AbsValueNode> value = new ArrayList<AbsValueNode>();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case NUMBER:
t = jj_consume_token(NUMBER);
value = listArgRecurs();
result.add(new NumberVNode(t.image,currentLine));
result.addAll(value);
{if (true) return result;}
break;
case TOKENWORD:
t = jj_consume_token(TOKENWORD);
value = listArgRecurs();
result.add(new WordDataVNode(t.image,currentLine));
result.addAll(value);
{if (true) return result;}
break;
case NONEVALUATE:
jj_consume_token(NONEVALUATE);
t = jj_consume_token(TOKENWORD);
value = listArgRecurs();
result.add(new WordDataVNode(t.image,currentLine));
result.addAll(value);
{if (true) return result;}
break;
case ACCESSOP:
jj_consume_token(ACCESSOP);
t = jj_consume_token(TOKENWORD);
value = listArgRecurs();
result.add(new ThingVNode(t.image,currentLine));
result.addAll(value);
{if (true) return result;}
break;
default:
jj_la1[17] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
} | 9 |
protected void performDestroyCallback(){
if (parent == null){
return;
}
if (!parent.isVisible()){
return;
}
if (parent.gamestate.gameFinished){
return; //game is over
}
AIBundle bundle = null;
try {
bundle = workerThread.get();
} catch (InterruptedException e) {
} catch( ExecutionException e) {
e.printStackTrace();
}
GamePiece destroyPoint = bundle.getDestroy();
GamePieceButton piece = parent.pieces[destroyPoint.getR()][destroyPoint.getP()];
piece.setBlinkMode(GamePieceButton.BREAKING_MODE); //this should finish the turn for us, as it will destroy the piece, and turn over control.
} | 5 |
public ArrayRandomAccessor(T[] source)
{
this._source = source;
} | 0 |
public static boolean isHTML(String s) {
if (isNull(s)) {
return false;
}
if (((s.indexOf("<html>") != -1) || (s.indexOf("<HTML>") != -1))
&& ((s.indexOf("</html>") != -1) || (s.indexOf("</HTML>") != -1))) {
return true;
}
return false;
} | 5 |
public static String getExtension(File f)
{
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
} | 2 |
@Override
public void update(float delta) {
if (!player.isAlive()) {
setCurrentState(new GameOverState(playerScore / 100));
}
playerScore += 1;
if (playerScore % 500 == 0) {
blockSpeed -= 10;
}
cloud.update(delta);
cloud2.update(delta);
Resources.runAnim.update(delta);
player.update(delta);
updateBlocks(delta);
} | 2 |
@Override
public GraphOperation next()
{
final byte opCode = this.opCodes.get(++opIndex);
GraphOperation result = null;
if (opCode == 2)
{
int arg0 = this.arguments.get(++argIndex);
return GraphOperation.newCreateRemoveNodeOp(arg0);
}
else if (opCode >= 1 && opCode <= 6)
{
int arg0 = this.arguments.get(++argIndex);
int arg1 = this.arguments.get(++argIndex);
switch (opCode)
{
case ((byte) 1):
result = GraphOperation.newCreateNodeOp(arg0, arg1);
break;
case ((byte) 3):
result = GraphOperation.newCreateEdgeOp(arg0, arg1);
break;
case ((byte) 4):
result = GraphOperation.newRemoveEdgeOp(arg0, arg1);
break;
case ((byte) 5):
result = GraphOperation.newSetClusterOp(arg0, arg1);
break;
case ((byte) 6):
result = GraphOperation.newSetRefClusterOp(arg0, arg1);
break;
}
}
else if (opCode == 7)
{
return GraphOperation.newNextStepOp();
}
return result;
} | 9 |
public SurveyCompletionList getSurveyCompletions(String asSurveyId, String asRegId) {
String lsParam = "";
if (UtilityMethods.isValidString(asSurveyId)) {
lsParam += asSurveyId;
}
if (UtilityMethods.isValidString(asRegId)) {
lsParam += "/" + asRegId;
}
return get(SurveyCompletionList.class, REST_URL_SURVEY_COMPLETION + lsParam);
} | 2 |
public static GeodeticCoord jauGc2gde ( double a, double f, double xyz[] ) throws JSOFAIllegalParameter
{
double aeps2, e2, e4t, ec2, ec, b, x, y, z, p2, absz, p, s0, pn, zc,
c0, c02, c03, s02, s03, a02, a0, a03, d0, f0, b0, s1,
cc, s12, cc2;
double phi, height;
/* ------------- */
/* Preliminaries */
/* ------------- */
/* Validate ellipsoid parameters. */
if ( f < 0.0 || f >= 1.0 ) throw new JSOFAIllegalParameter("bad f", -1);
if ( a <= 0.0 ) throw new JSOFAIllegalParameter("bad a", -2);
/* Functions of ellipsoid parameters (with further validation of f). */
aeps2 = a*a * 1e-32;
e2 = (2.0 - f) * f;
e4t = e2*e2 * 1.5;
ec2 = 1.0 - e2;
if ( ec2 <= 0.0 ) throw new JSOFAIllegalParameter("bad f", -1);
ec = sqrt(ec2);
b = a * ec;
/* Cartesian components. */
x = xyz[0];
y = xyz[1];
z = xyz[2];
/* Distance from polar axis squared. */
p2 = x*x + y*y;
/* Longitude. */
double elong = p2 > 0.0 ? atan2(y, x) : 0.0;
/* Unsigned z-coordinate. */
absz = abs(z);
/* Proceed unless polar case. */
if ( p2 > aeps2 ) {
/* Distance from polar axis. */
p = sqrt(p2);
/* Normalization. */
s0 = absz / a;
pn = p / a;
zc = ec * s0;
/* Prepare Newton correction factors. */
c0 = ec * pn;
c02 = c0 * c0;
c03 = c02 * c0;
s02 = s0 * s0;
s03 = s02 * s0;
a02 = c02 + s02;
a0 = sqrt(a02);
a03 = a02 * a0;
d0 = zc*a03 + e2*s03;
f0 = pn*a03 - e2*c03;
/* Prepare Halley correction factor. */
b0 = e4t * s02 * c02 * pn * (a0 - ec);
s1 = d0*f0 - b0*s0;
cc = ec * (f0*f0 - b0*c0);
/* Evaluate latitude and height. */
phi = atan(s1/cc);
s12 = s1 * s1;
cc2 = cc * cc;
height = (p*cc + absz*s1 - a * sqrt(ec2*s12 + cc2)) /
sqrt(s12 + cc2);
} else {
/* Exception: pole. */
phi = DPI / 2.0;
height = absz - b;
}
/* Restore sign of latitude. */
if ( z < 0 ) phi = -phi;
/* OK status. */
return new GeodeticCoord(elong, phi, height);
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FieldMetadata other = (FieldMetadata) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (qualifiedClassName == null) {
if (other.qualifiedClassName != null)
return false;
} else if (!qualifiedClassName.equals(other.qualifiedClassName))
return false;
return true;
} | 9 |
@EventHandler(ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent e) {
Dodgeball ab = mm.getPlayerMinigame(e.getPlayer().getName());
if(ab == null) {
return;
}
ab.handlePlayerMove(e);
} | 1 |
protected void process() {
if(consumer_lock.tryLock()) {
try {
while(true) {
T element=queue.poll();
if(element != null && handler != null) {
try {
handler.handle(element);
}
catch(Throwable t) {
t.printStackTrace(System.err);
}
}
producer_lock.lock();
try {
if(count == 0 || count-1 == 0) {
count=0;
consumer_lock.unlock();
return;
}
count--;
}
finally {
producer_lock.unlock();
}
}
}
finally {
if(consumer_lock.isHeldByCurrentThread())
consumer_lock.unlock();
}
}
} | 8 |
private static int getColor(ColorType c) {
switch (c) {
case PLAYER:
return currentPlayerColor;
case WALL:
return currentWallColor;
case SLOW_WALL:
return currentSlowWallColor;
case OBJECT:
break;
case PROJECTILE:
break;
default:
break;
}
return 0;
} | 5 |
public static String encode(String message) {
String hdb3stream = message;
int index0;
index0 = hdb3stream.indexOf("0000");
int index1 = 0;
while (index0 != -1) {
if ((index0 - index1) % 2 == 1)
hdb3stream = hdb3stream.substring(0, index0) + "000V"
+ hdb3stream.substring(index0 + 4);
else
hdb3stream = hdb3stream.substring(0, index0) + "B00V"
+ hdb3stream.substring(index0 + 4);
index1 = index0 + 4;
index0 = hdb3stream.indexOf("0000");
}
int signal = 0;
char last1bit = '0';
char lastbit = '0';
for (int pos = 0; pos < message.length(); pos++) {
if (hdb3stream.charAt(pos) == '1') {
if (signal % 2 == 0) {
last1bit = '+';
} else {
last1bit = '-';
}
lastbit = last1bit;
hdb3stream = hdb3stream.substring(0, pos) + lastbit
+ hdb3stream.substring(pos + 1);
signal++;
} else if (hdb3stream.charAt(pos) == 'V') {
hdb3stream = hdb3stream.substring(0, pos) + lastbit
+ hdb3stream.substring(pos + 1);
} else if (hdb3stream.charAt(pos) == 'B') {
if (last1bit == '+')
lastbit = '-';
else
lastbit = '+';
signal++;
hdb3stream = hdb3stream.substring(0, pos) + lastbit
+ hdb3stream.substring(pos + 1);
}
}
return hdb3stream;
} | 8 |
@Override
public String getProjectName() {
if (displayedBugProject == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugProject;
} | 2 |
public String mirrored() {
Stack<String> stack = new Stack<String>();
StringBuffer sBuff = new StringBuffer();
for (int i=0; i < SIZE1; i++){
if ((i+1)%(H1) == 0) {
stack.push(sBuff.toString());
sBuff = new StringBuffer();
continue;
}
int firstBoard = getBit(boards[0], i);
int secondBoard = getBit(boards[1], i);
String slotState ="";
if (secondBoard == 1) {
slotState = "o";
} else if (firstBoard == 1) {
slotState = "x";
} else {
slotState = "b";
}
sBuff.append(slotState);
if(i != HEIGHT-1){
sBuff.append(",");
}
}
String ret = "";
while(!stack.empty()){
ret += stack.pop();
}
return ret;
} | 6 |
@Override
public void mouseReleased(MouseEvent mouseEvent) {
start = false;
if (fromList.isEmpty()) {
return;
}
to = null;
for (Planet planet : gameplay.planets) {
double distance = Math.sqrt(Math.pow(mouseEvent.getX() - planet.getX(), 2) +
Math.pow(mouseEvent.getY() - planet.getY(), 2));
if (distance < planet.radius) {
to = planet;
break;
}
}
if(to==null){
return;
}
fromList.remove(to);
gameplay.sendShips(fromList, to);
} | 4 |
private void comandoSe() {
// <se> ::= “se” “(“<exp_logica> ”)” “{“ <lista_comandos> “}” <compl_se>
// <compl_se> ::= <senao> | “;”
// <senao> ::= “senao” “{“ <lista_comandos> “}” “;”
System.out.println("tô no if");
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" (")) {
this.expLogica();
System.out.println("achei a expressão" + tipoDoToken[1]);
// if (!acabouListaTokens()) {
// nextToken();
if (tipoDoToken[1].equals(" )")) {
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" {")) {
System.out.println("achei a chave");
if (!acabouListaTokens()) {
nextToken();
this.listaComandos();
System.out.println("Não tem mais comandos");
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
// if (!acabouListaTokens()) {
// //nextToken();
System.out.println(tipoDoToken[1]);
if (tipoDoToken[1].equals(" }")) {
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" ;")) {
System.out.println("TENHO COMANDO SE AQUI");
//FIM DO COMANDO se
} else {
this.comandoSenao();
}
// } else {
// errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
// zerarTipoToken();
// }
}
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
}
// } else {
// errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
// zerarTipoToken();
// }
}
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
}
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
} | 9 |
public int login(String name, String password)
{
if (!users.containsKey(name))
return -1;
if (!users.get(name).getPassword().equals(password))
return -2;
Trader t = users.get(name);
if (active.contains(t))
return -3;
active.add(t);
t.openWindow();
if (!t.hasMessages())
t.receiveMessage("Welcome to SafeTrade!");
return 0;
} | 4 |
public Text render(Text.Foundry f) {
if((tcache == null) || (tcache.text != line))
tcache = f.render(line);
return(tcache);
} | 2 |
public int saveFile(String path, InputStream inputStream, long freeDiskSpace) throws NotEnoughFreeDiskSpaceException {
int bytesCount = 0;
final File file = new File(path);
createFolder(file.getParent());
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException("Can't create file.");
}
OutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("Problem with reading file.");
}
byte[] buffer = new byte[1024];
int bytesRead;
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
bytesCount += bytesRead;
}
} catch (IOException e) {
throw new RuntimeException("Problem with storing data. " + e.getMessage());
}
if (bytesCount > freeDiskSpace) {
throw new NotEnoughFreeDiskSpaceException("Not enough free disk space.");
}
return bytesCount * Byte.SIZE;
} | 5 |
@SuppressWarnings("rawtypes")
public static void quickSort(Comparable[] a, int min, int max){
if(max <= min) return;
int j = partition(a, min, max);
quickSort(a, min, j - 1);
quickSort(a, j + 1, max);
} | 1 |
static ArrayList<NoSchemaDocument> generateAddresses(int count) {
ArrayList<NoSchemaDocument> addresses = new ArrayList<NoSchemaDocument>();
for (int i=0;i<count;i++) {
NoSchemaDocument address = new NoSchemaDocument();
address.put("street","One Memorial Drive");
if (i == 0) {
address.put("city","Cambridge");
address.put("state","MA");
address.put("zip",randomZip());
}
if (i % 2 == 0) {
address.put("city","Cambridge");
address.put("state","MA");
} else {
address.put("zip",randomZip());
}
if ((i % 4 == 0) || (i % 3 == 0)) {
address.put("country","USA");
}
addresses.add(address);
}
return addresses;
} | 5 |
public boolean tableExists(String tableName) throws Exception {
if (!isConnected())
throw new IllegalStateException("Not connected, please connect first!");
if (m_Debug) {
System.err.println("Checking if table " + tableName + " exists...");
}
DatabaseMetaData dbmd = m_Connection.getMetaData();
ResultSet rs;
if (m_checkForUpperCaseNames) {
rs = dbmd.getTables (null, null, tableName.toUpperCase(), null);
} else if (m_checkForLowerCaseNames) {
rs = dbmd.getTables (null, null, tableName.toLowerCase(), null);
} else {
rs = dbmd.getTables (null, null, tableName, null);
}
boolean tableExists = rs.next();
if (rs.next()) {
throw new Exception("This table seems to exist more than once!");
}
rs.close();
if (m_Debug) {
if (tableExists) {
System.err.println("... " + tableName + " exists");
} else {
System.err.println("... " + tableName + " does not exist");
}
}
return tableExists;
} | 7 |
public void drawSpeelveld(Graphics g) {
Graphics2D mazeUI = (Graphics2D) g;
mazeUI.setBackground(Color.WHITE);
mazeUI.setColor(Color.GRAY);
for (int i = 0; i < speelveld.length; i++) {
for (int j = 0; j < speelveld[i].length; j++) {
if (speelveld[i][j] == VeldType.MUUR) {
mazeUI.fillRect(j * 20, i * 20, 20, 20);
} else {
mazeUI.drawRect(j * 20, i * 20, 20, 20);
}
}
}
} | 3 |
private static boolean intersectsLineStrictInternal(Line2D.Double l1, Line2D.Double l2) {
if (l1.intersectsLine(l2) == false) {
return false;
}
assert l1.intersectsLine(l2);
Point2D.Double l1a = (Point2D.Double) l1.getP1();
Point2D.Double l1b = (Point2D.Double) l1.getP2();
Point2D.Double l2a = (Point2D.Double) l2.getP1();
Point2D.Double l2b = (Point2D.Double) l2.getP2();
if (l1a.equals(l2a) == false && l1a.equals(l2b) == false && l1b.equals(l2a) == false
&& l1b.equals(l2b) == false) {
return true;
}
if (l1a.equals(l2b)) {
final Point2D.Double tmp = l2a;
l2a = l2b;
l2b = tmp;
} else if (l2a.equals(l1b)) {
final Point2D.Double tmp = l1a;
l1a = l1b;
l1b = tmp;
} else if (l1b.equals(l2b)) {
Point2D.Double tmp = l2a;
l2a = l2b;
l2b = tmp;
tmp = l1a;
l1a = l1b;
l1b = tmp;
}
assert l1a.equals(l2a);
return false;
} | 8 |
private void isCorrect() {
File file = new File(dataBaseDirectory);
if (file.isFile()) {
throw new MultiDataBaseException(dataBaseDirectory + " isn't directory!");
}
String[] dirs = file.list();
checkNames(dirs, "dir");
for (int i = 0; i < dirs.length; ++i) {
if (!dirs[i].equals("signature.tsv")) {
isCorrectDirectory(dataBaseDirectory + File.separator + dirs[i]);
}
}
} | 3 |
private synchronized void moveEnts()
{
float time = 1.0f;
//apply constant forces
do
{
float tMin = time;
for (int i = 0; i < main.living.size(); i++)
{
Ball s = main.living.get(i);
for (int y = 0;y < main.lines.size();y++)
{
ObstacleLine l = main.lines.get (y);
//There is a little gap that balls can get into
s.intersect (l,tMin);
if (s.getEarliestCollisionResponse().getTime() < tMin)
{
tMin = s.getEarliestCollisionResponse().getTime();
}
}
for (int y = 0;y < main.pseudoPaddles.size();y++)
{
PseudoPaddle p = main.pseudoPaddles.get (y);
s.intersect (p,tMin);
if (s.getEarliestCollisionResponse().getTime() < tMin)
{
tMin = s.getEarliestCollisionResponse().getTime();
}
}
for (int c = 0; c < main.buttons.size();c++)
{
ButtonObstacle b = main.buttons.get (c);
s.intersect (b,tMin);
if (s.getEarliestCollisionResponse().getTime() < tMin)
{
tMin = s.getEarliestCollisionResponse().getTime();
}
}
s.update (tMin);
for (PseudoPaddle p : main.pseudoPaddles)
{
p.updatePos (p.getX() + p.getMoveSpeed() *tMin);
}
}
time -= tMin;
} while (time > 1e-2f);
} | 9 |
public void setServiceID(String serviceID) {
ServiceID = serviceID;
} | 0 |
@Override
public void run() {
if (Updater.this.url != null) {
// Obtain the results of the project's file feed
if (Updater.this.read()) {
if (Updater.this.versionCheck(Updater.this.versionName)) {
if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) {
String name = Updater.this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (Updater.this.versionLink.endsWith(".zip")) {
final String[] split = Updater.this.versionLink.split("/");
name = split[split.length - 1];
}
Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink);
} else {
Updater.this.result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
}
} | 6 |
static final boolean method3649(boolean bool, int i, int i_2_, int i_3_) {
anInt4010++;
if (!Class12.aBoolean194 || !Mobile_Sub1.aBoolean10959) {
return false;
}
if (Class233.anInt2786 < 100) {
return false;
}
if (bool != true) {
method3649(true, 77, 66, -67);
}
int i_4_ = Class240.anIntArrayArrayArray2948[i_2_][i_3_][i];
if ((-Class359.anInt4465 ^ 0xffffffff) == (i_4_ ^ 0xffffffff)) {
return false;
}
if (Class359.anInt4465 == i_4_) {
return true;
}
if (Class368.aPlaneArray4548 == Class320_Sub10.aPlaneArray8300) {
return false;
}
int i_5_ = i_3_ << Class36.anInt549;
int i_6_ = i << Class36.anInt549;
if (Class99.method1087(-1 + (i_5_ + Class179.anInt2129), i_6_ + 1, Class320_Sub10.aPlaneArray8300[i_2_].method3251(1 + i, i_3_ + 1, (byte) -118), Class320_Sub10.aPlaneArray8300[i_2_].method3251(1 + i, i_3_, (byte) -118), Class320_Sub10.aPlaneArray8300[i_2_].method3251(i, i_3_, (byte) -118), (byte) 89, -1 + (i_6_ - -Class179.anInt2129), Class179.anInt2129 + i_6_ + -1, 1 + i_5_, 1 + i_5_) && Class99.method1087(-1 + (Class179.anInt2129 + i_5_), 1 + i_6_, Class320_Sub10.aPlaneArray8300[i_2_].method3251(i, i_3_ + 1, (byte) -118), Class320_Sub10.aPlaneArray8300[i_2_].method3251(i + 1, i_3_ + 1, (byte) -118), Class320_Sub10.aPlaneArray8300[i_2_].method3251(i, i_3_, (byte) -118), (byte) 89, 1 + i_6_, Class179.anInt2129 + i_6_ + -1, i_5_ + 1, -1 + (Class179.anInt2129 + i_5_))) {
ProducingGraphicsBuffer.anInt9880++;
Class240.anIntArrayArrayArray2948[i_2_][i_3_][i] = Class359.anInt4465;
return true;
}
Class240.anIntArrayArrayArray2948[i_2_][i_3_][i] = -Class359.anInt4465;
return false;
} | 9 |
private void addLinkStatement(StatementPrototype sp, ObjectStack propertyStack, Class<?> propertyClass)
{
Node objRep = propertyStack.getNode(propertyClass);
for(ObjectRepresentation rep:propertyStack.getAllRepresentations())
{
if(!rep.equals(objRep.getRepresentation())
&& ObjectTools.isA(rep.getRepresentedClass(),propertyClass)
&& rep.belongsInJoin())
{
sp.getIdStatementGenerator().addLinkStatement(objRep.getRepresentation(),rep);
}
}
if (objRep.getRepresentation().isArray())
{
sp.getIdStatementGenerator().addPropertyTableToJoin(NameGenerator.getArrayTablename(adapter), objRep.getRepresentation().getAsName());
}
else
{
sp.getIdStatementGenerator().addPropertyTableToJoin(objRep.getRepresentation().getTableName(), objRep.getRepresentation().getAsName());
}
} | 6 |
public String getComments()
{
return comments;
} | 0 |
public static boolean getCommand()
{
boolean sentinel = true;
Request r;
// Should pass
try
{
r = new Request(JSON_TO_PARSE_1);
}
catch(NullJsonException nj)
{
return false;
}
catch(JsonCommandNotFoundException jc)
{
return false;
}
String json = r.getCommand();
if(!assertEquals("Incorrect Command!", Command.GET_MOVIES, json))
{
sentinel = false;
}
// Should fail
try
{
r = new Request(JSON_TO_PARSE_2);
}
catch(NullJsonException nj)
{
return false;
}
catch(JsonCommandNotFoundException jc)
{
// This should happen
}
return sentinel;
} | 5 |
public static boolean dragItem(final Item i, final int slot) {
return i != null
&& (SlotData.getItemId(slot) == i.getId() || MainTabs.INVENTORY.open()
&& dragChild(i.getWidgetChild(), slot) && new TimedCondition(700) {
@Override
public boolean isDone() {
return i.getId() == SlotData.getItemId(slot);
}
}.waitStop());
} | 4 |
public void Imprimir(){
NodosListaProceso aux = PrimerNodo;
System.out.println("Nombre del proceso\n__\t__________________\n");
while (aux!=null) {
System.out.println(aux.nombreProceso+" ");
aux = aux.siguiente;
}
} | 1 |
public String getCardSuit(Card card)
{
String suit = null;
if ("DIAMOND".equals(card.getSuit().toString()))
{
suit = "d";
}
else if ("CLUB".equals(card.getSuit().toString()))
{
suit = "c";
}
else if ("HEART".equals(card.getSuit().toString()))
{
suit = "h";
}
else if ("SPADE".equals(card.getSuit().toString()))
{
suit = "s";
}
return suit;
} | 4 |
public void writeTable() {
TranslationTable table = new TranslationTable();
basePackage.writeTable(table, false);
try {
OutputStream out = new FileOutputStream(outTableFile);
table.store(out);
out.close();
} catch (java.io.IOException ex) {
GlobalOptions.err.println("Can't write rename table "
+ outTableFile);
ex.printStackTrace(GlobalOptions.err);
}
} | 1 |
public Map<String, Object> getProperties()
{
return properties;
} | 0 |
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other == this)
return true;
Movie otherMovie = (Movie) other;
return this.name.equals(otherMovie.name);
} | 2 |
public static void keepDirWithinSize(File dir, int size) {
if (!dir.isDirectory()) return;
File[] files = dir.listFiles();
if (files == null) return;
long dirSize = countDirSize(dir);
if (dirSize < size) return;
Arrays.sort(files, new FileDateComparator());
int count = files.length;
File file;
for (int i = 0; i < count; i++) {
file = files[i];
long currentSize = file.isDirectory() ? 0l : file.length();
if (file.delete()) {
dirSize -= currentSize;
if (dirSize < size) break;
}
}
} | 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.