method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
b329167a-8e7e-4648-90bb-4b803f11e47d | 9 | public static User getUserFromJson(JSONObject obj){
if(obj == null)
return null;
User user = new User();
Object value = obj.get("id");
if(value != null)
{
user.setId(value.toString());
}
value = obj.get("id_room");
if(value!=null)
{
user.setId_room(value.toString());
}
value = obj.get("nickname");
if(value!=null)
{
user.setNickname(value.toString());
}
value = obj.get("phone");
if(value!=null)
{
user.setPhone(value.toString());
}
value = obj.get("latitude");
if(value!=null)
{
user.setLatitude(Double.parseDouble(value.toString()));
}
value = obj.get("longitude");
if(value!=null)
{
user.setLongitude(Double.parseDouble(value.toString()));
}
value = obj.get("id_team");
if(value!=null)
{
user.setId_team(Integer.parseInt(value.toString()));
}
value = obj.get("future_id_team");
if(value!=null)
{
user.setFuture_id_team(Integer.parseInt(value.toString()));
}
return user;
} |
6b4d5550-14ff-4191-9423-24e817121fb0 | 6 | public static int getDepth(Node<Integer> p){
if(p == null) return 0;
int h1 = getDepth(p.left);
if(h1 == -1) return -1;
int h2 = getDepth(p.right);
if(h2 == -1) return -1;
if(h1 >= h2){
if(h1 - h2 < 2) return h1 + 1;
return -1;
} else {
if(h2 - h1 < 2) return h2 + 1;
return -1;
}
} |
db339697-dd5e-46ff-a4d0-5a0b04b2c587 | 9 | protected void readChildren(XMLStreamReader in) throws XMLStreamException {
Settlement oldSettlement = settlement;
Player oldSettlementOwner = (settlement == null) ? null
: settlement.getOwner();
settlement = null;
super.readChildren(in);
// Player settlement list is not passed in player updates
// so do it here. TODO: something better.
Player settlementOwner = (settlement == null) ? null
: settlement.getOwner();
if (settlement == null && oldSettlement != null) {
// Settlement disappeared
logger.info("Settlement " + oldSettlement.getName() + " removed.");
oldSettlementOwner.removeSettlement(oldSettlement);
} else if (settlement != null && oldSettlement == null) {
// Settlement appeared
settlementOwner.addSettlement(settlement);
owner = settlementOwner;
} else if (settlementOwner != oldSettlementOwner) {
// Settlement changed owner
logger.info("Settlement " + oldSettlement.getName() + " captured"
+ " from " + oldSettlement.getOwner()
+ " to " + settlementOwner);
settlement.setOwner(settlementOwner);
oldSettlementOwner.removeSettlement(oldSettlement);
settlementOwner.addSettlement(settlement);
owner = settlementOwner;
}
if (getColony() != null && getColony().isTileInUse(this)) {
getColony().invalidateCache();
}
} |
d378fddb-dfb6-4be2-8f03-29b5f795734f | 6 | public int diff_xIndex(LinkedList<Diff> diffs, int loc) {
int chars1 = 0;
int chars2 = 0;
int last_chars1 = 0;
int last_chars2 = 0;
Diff lastDiff = null;
for (Diff aDiff : diffs) {
if (aDiff.operation != Operation.INSERT) {
// Equality or deletion.
chars1 += aDiff.text.length();
}
if (aDiff.operation != Operation.DELETE) {
// Equality or insertion.
chars2 += aDiff.text.length();
}
if (chars1 > loc) {
// Overshot the location.
lastDiff = aDiff;
break;
}
last_chars1 = chars1;
last_chars2 = chars2;
}
if (lastDiff != null && lastDiff.operation == Operation.DELETE) {
// The location was deleted.
return last_chars2;
}
// Add the remaining character length.
return last_chars2 + (loc - last_chars1);
} |
df474600-0d99-4a71-9d31-dbbc43d9c683 | 8 | @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerTeleport(PlayerTeleportEvent event){
Player player = event.getPlayer();
String playerName = player.getName();
Location location = event.getFrom();
String worldName = location.getWorld().getName();
if (!worldName.equals(plugin.lobbyWorld)){
for (String worldN : plugin.mainWorlds){
if (worldName.startsWith(worldN + "_")){
//World is a copy world
//START - Check if player is in DB, and if not, update DB with player + world he is in
customConfigurationFile = new File(plugin.getDataFolder(), "players.yml");
customConfig = YamlConfiguration.loadConfiguration(customConfigurationFile);
InputStream defConfigStream = plugin.getResource("players.yml");
if (defConfigStream != null) {
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
customConfig.setDefaults(defConfig);
}else{
plugin.logMessage("Plugin error: Error while loading config file players.yml");
}
String worldet = customConfig.getString(player.getName() + ".world");
if (worldet != null){
customConfig.set(playerName + ".x", location.getX());
customConfig.set(playerName + ".z", location.getZ());
customConfig.set(playerName + ".y", location.getY());
customConfig.set(playerName + ".world", worldName);
}else{
customConfig.createSection(playerName);
customConfig.createSection(playerName + ".x");
customConfig.createSection(playerName + ".z");
customConfig.createSection(playerName + ".y");
customConfig.createSection(playerName + ".world");
customConfig.set(playerName + ".x", location.getX());
customConfig.set(playerName + ".z", location.getZ());
customConfig.set(playerName + ".y", location.getY());
customConfig.set(playerName + ".world", worldName);
}
if (customConfig == null || customConfigurationFile == null) {
return;
}
try {
customConfig.save(customConfigurationFile);
} catch (IOException ex) {
plugin.logMessage("Could not save config to " + customConfigurationFile);
}
//END - Check if player is in DB, and if not, update DB with player + world he is in
}
}
}
} |
1a87ed71-2a72-44a4-bb7f-3d69e2ff1a4d | 2 | private void getPicturesPath(JTextField field) {
JFileChooser chooser = new JFileChooser();
if(ProjectMainView.actualFolder!=null)
chooser.setCurrentDirectory(ProjectMainView.actualFolder);
chooser.setDialogTitle("Chose JPEG file");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String str = chooser.getSelectedFile().getPath();
ProjectMainView.actualFolder=chooser.getSelectedFile().getParentFile();
field.setText(str);
} else {
System.out.println("No Selection ");
}
} |
735c363f-54e2-4b59-81b3-b0b256d13ca4 | 0 | public int getOrthoHeight() {
return 600;
} |
b9794e59-04cf-4499-8000-7fcb4a2c2e5c | 6 | public void fixOutOfBounds()
{
// prevent any invalid permeabilities
if(perm > 100)
perm = 100;
if(perm < 0)
perm = 0;
// prevent any invalid temperatures
if(temp > maxTemp)
temp = maxTemp;
if(temp < minTemp)
temp = minTemp;
// prevent any invalid pressures
if(pres > maxPres)
pres = maxPres;
if(pres < minPres)
pres = minPres;
} |
be0b8f3c-f7e1-4a67-86aa-79502779de8f | 4 | void floyd() {
int rows = d.length;
for (int k = 0; k < rows; k++)
for (int i = 0; i < rows; i++)
for (int j = 0; j < rows; j++)
if (d[i][j] > d[i][k] + d[k][j]) {
d[i][j] = d[i][k] + d[k][j];
}
} |
4d84d5ba-cf0b-4d36-97dd-6b42f9ef1d07 | 1 | public ImageProcessor canny(ImageProcessor ip){
//Filter out noise
ImageProcessor result = ip.duplicate();
result.blurGaussian(sigma);
//Compute the intensity gradient using Sobel
ImageProcessor Gx = xGradient(result);
ImageProcessor Gy = yGradient(result);
//Compute the magnitude of the gradient
FloatProcessor gradientMag = gradientStrength(Gx, Gy);
gradientMag.resetMinAndMax();
if(gradientMag.getMax() > 0) gradientMag.multiply(1.0/gradientMag.getMax());
//Perform non-Maximum Supression to remove weak edges
ImageProcessor suppressed = nonMaxSuppression(Gx, Gy, gradientMag);
double highThreshold = getHighThreshold(gradientMag.convertToByteProcessor(false), percentNotEdges);
double lowThreshold = thresholdRatio * highThreshold;
//now perform hysterisis
result = doHysterisis(suppressed, gradientMag, lowThreshold, highThreshold);
return result;
} |
bfae6a3c-fc3b-4db2-a58a-1fa44fff134f | 7 | public static long parseTimeInterval(String str) {
try {
int len = str.length();
char suffix = str.charAt(len - 1);
String numstr;
long mult = 1;
if (Character.isDigit(suffix)) {
numstr = str;
} else {
numstr = str.substring(0, len - 1);
switch (Character.toUpperCase(suffix)) {
case 'S':
mult = Constants.SECOND;
break;
case 'M':
mult = Constants.MINUTE;
break;
case 'H':
mult = Constants.HOUR;
break;
case 'D':
mult = Constants.DAY;
break;
case 'W':
mult = Constants.WEEK;
break;
default:
throw new NumberFormatException("Illegal time interval suffix");
}
}
return Long.parseLong(numstr) * mult;
} catch (IndexOutOfBoundsException e) {
throw new NumberFormatException("empty string");
}
} |
baf70604-86a8-49ee-ab72-05d370e23b85 | 5 | public void cellRCDraw(int x, int y){
if( y % 2 == 1 ^ x % 2 == 1){
if(!sedna.getSelected() ||sedna.getSelection(x,y)){cellDraw(x,y);}}
else{
if(!sedna.getSelected() ||sedna.getSelection(x,y)){cellRandDraw(x,y);}}
} |
1c088fe4-cbbf-490e-b2f5-d08fd8f301ac | 7 | public void keyPressed(int code) {
if (onMenuScreen)
return;
else {
if (code >= 37 && code <= 40) { // ARROW KEYS
int dn = code - 38;
if (dn == -1)
dn = 3;
character.startMoving(directions[dn]);
}
if (code == 32) { // SPACEBAR
if (jump > 0) {
character.jump();
jump--;
}
} else if (code == 27) { // "ESC"
quitToMenu();
}
}
} |
915f092a-f167-4144-9e10-bdb2669eb1b4 | 4 | public Wave(int n, int d){
waveNumber = n;
difficulty = d;
waveHealth += waveNumber*10;
strengthInNumbers += waveNumber;
if (waveNumber % 10 == 0){
boss = true;
strengthInNumbers = 1;
}
if (waveNumber % 3 == 0){
status = "Heavy";
}
else if(waveNumber % 4 == 0){
status = "Light";
}
if (waveNumber % 5 == 0){
tenacious = true;
}
findEndpoints();
statusChanger();
enemySpawner();
} |
7c2782ec-f259-4295-a455-649ccd066c23 | 0 | public void setTrainingName(String trainingName) {
this.trainingName = trainingName;
} |
b4b0eed7-2901-4770-8f08-fb62f10671ee | 0 | public int getQuestTimeout() {
return QuestTimeout;
} |
4348595e-d421-4396-8f58-932436e36d79 | 7 | private boolean encercleAdversaire(Couleur uneCouleur,
Position unePosition, Direction uneDirection)
{
Position laPositionVoisine = unePosition.obtenirVoisine(uneDirection);
if (!this.plateau.estPositionValide(laPositionVoisine))
return false;
Case laCaseVoisine = this.plateau.obtenirCase(laPositionVoisine);
if (!laCaseVoisine.estOccupee())
return false;
if (laCaseVoisine.obtenirPion().obtenirCouleur() == uneCouleur)
return false;
Position positionSuivante = laPositionVoisine;
while (true)
{
positionSuivante = positionSuivante.obtenirVoisine(uneDirection);
if (!this.plateau.estPositionValide(positionSuivante))
return false;
Case caseSuivante = this.plateau.obtenirCase(positionSuivante);
if (!caseSuivante.estOccupee())
return false;
if (caseSuivante.obtenirPion().obtenirCouleur() == uneCouleur)
return true;
}
} |
5c2f7c68-8658-43f3-a298-4c980c1e9313 | 0 | public void create(int roomNumber) {
this.setRoomNumber(roomNumber);
} |
6e8f9e49-082a-4ae6-8976-442d3c45888b | 9 | public CmdAbst getCmdInstance(String xml) throws CumExcpIllegalCmdXML,
CumExcpIllegalCmdDoc {
Document doc = getDom(xml);
Node cmdNode = getCmdNode(doc);
String type = getCmndType(cmdNode);
String action = getAction(cmdNode);
Class<? extends CmdAbst> myClass = classMap.get(getClassName(type,
action));
Class<?>[] types = new Class[] { Document.class };
Object[] args = { doc };
CmdAbst cmd;
try {
Constructor<? extends CmdAbst> constructor = myClass
.getConstructor(types);
cmd = constructor.newInstance(args);
} catch (NoSuchMethodException e) {
throw new CumExcpIllegalCmdDoc(xml);
} catch (SecurityException e) {
throw new CumExcpIllegalCmdDoc(xml);
} catch (InstantiationException e) {
throw new CumExcpIllegalCmdDoc(xml);
} catch (IllegalAccessException e) {
throw new CumExcpIllegalCmdDoc(xml);
} catch (IllegalArgumentException e) {
throw new CumExcpIllegalCmdDoc(xml);
} catch (InvocationTargetException e) {
throw new CumExcpIllegalCmdDoc(xml);
}
return cmd;
} |
de0d5daf-21a8-4f6a-87da-0857f42b7eef | 7 | public static void printTime() {
// Store the minutes, seconds and milliseconds of each lap
int[] minutes = new int[lapTimes.length];
int[] seconds = new int[lapTimes.length];
int[] milliseconds = new int[lapTimes.length];
// For each lap, calculate the minutes, seconds and milliseconds
for (int lap = 0; lap < lapTimes.length && lap < currentLap; lap++) {
minutes[lap] = (int) Math.floor(lapTimes[lap] / 60);
seconds[lap] = (int) Math.floor(lapTimes[lap] % 60);
milliseconds[lap] = Math.round((lapTimes[lap] % 1f) * 100);
}
// Based on what lap the player is currently in, print the current lap
// time and money, and the lap times and money for the last 3 laps
// (empty if the player didn't drive that lap yet)
if (currentLap > 0 && currentLap < 4) {
print(20, viewportH - 50, String.format(
"Current Lap: %d:%02d:%02d Money: $%d",
minutes[currentLap - 1], seconds[currentLap - 1],
milliseconds[currentLap - 1], lapMoney[currentLap - 1]),
28, "Font/timeFont.png");
} else {
print(20, viewportH - 50, "Current Lap: -:--:-- Money: $0", 28,
"Font/timeFont.png");
}
if (currentLap > 1) {
print(40, viewportH - 80, String.format(
"Lap 1: %d:%02d:%02d Money: $%d", minutes[0], seconds[0],
milliseconds[0], lapMoney[0]), 20, "Font/timeFont.png");
} else {
print(40, viewportH - 80, "Lap 1: -:--:-- Money: $0", 20,
"Font/timeFont.png");
}
if (currentLap > 2) {
print(40, viewportH - 105, String.format(
"Lap 2: %d:%02d:%02d Money: $%d", minutes[1], seconds[1],
milliseconds[1], lapMoney[1]), 20, "Font/timeFont.png");
} else {
print(40, viewportH - 105, "Lap 2: -:--:-- Money: $0", 20,
"Font/timeFont.png");
}
if (currentLap > 3) {
print(40, viewportH - 130, String.format(
"Lap 3: %d:%02d:%02d Money: $%d", minutes[2], seconds[2],
milliseconds[2], lapMoney[2]), 20, "Font/timeFont.png");
} else {
print(40, viewportH - 130, "Lap 3: -:--:-- Money: $0", 20,
"Font/timeFont.png");
}
} |
683f6976-1fde-450e-9344-4315cb08c094 | 4 | private void notifySearchListeners(){
String recipeName = recipeList.getSelectedValue();
boolean match = false;
Recipe foundRecipe = null;
for( Recipe recipe : recipes ){
if ( recipe.getName().equals(recipeName)){
foundRecipe = recipe;
match = true;
break;
}
}
if ( match ){
for ( SearchCompletedListener listener: listeners ){
listener.searchCompleted(foundRecipe);
}
} else {
showErrorMessage("The recipe matching \"" + recipeName + "\" is no longer available, try and open up a new search.",
"Recipe unavailable");
}
} |
9408138b-bb5a-4df1-867f-370b625ec195 | 7 | public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} |
79a8c2e5-c929-4d41-9a12-a4d5f6a67af1 | 1 | @Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2;
g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
if (activeLeftPanel) {
g2.setColor(new java.awt.Color(240, 240, 240));
drawLeftPanel(g2);
g2.setColor(Color.gray);
drawRightPanel(g2);
} else {
g2.setColor(Color.gray);
drawLeftPanel(g2);
g2.setColor(new java.awt.Color(240, 240, 240));
drawRightPanel(g2);
}
g.dispose();
} |
feea748f-1f01-4f23-835d-ab087e560320 | 9 | public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_DeltaCols.setUpper(getInputFormat().numAttributes() - 1);
int selectedCount = 0;
for (int i = getInputFormat().numAttributes() - 1; i >= 0; i--) {
if (m_DeltaCols.isInRange(i)) {
selectedCount++;
if (!getInputFormat().attribute(i).isNumeric()) {
throw new UnsupportedAttributeTypeException("Selected attributes must be all numeric");
}
}
}
if (selectedCount == 1) {
throw new Exception("Cannot select only one attribute.");
}
// Create the output buffer
FastVector newAtts = new FastVector();
boolean inRange = false;
String foName = null;
int clsIndex = -1;
for(int i = 0; i < instanceInfo.numAttributes(); i++) {
if (m_DeltaCols.isInRange(i) && (i != instanceInfo.classIndex())) {
if (inRange) {
Attribute newAttrib = new Attribute(foName);
newAtts.addElement(newAttrib);
}
foName = instanceInfo.attribute(i).name();
foName = "'FO " + foName.replace('\'', ' ').trim() + '\'';
inRange = true;
} else {
newAtts.addElement((Attribute)instanceInfo.attribute(i).copy());
if ((i == instanceInfo.classIndex()))
clsIndex = newAtts.size() - 1;
}
}
Instances data = new Instances(instanceInfo.relationName(), newAtts, 0);
data.setClassIndex(clsIndex);
setOutputFormat(data);
return true;
} |
eb0e49fa-e746-4dcf-9ec8-0ff8589cf626 | 3 | @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String input = request.getParameter("input");
ArrayList<Result> values = new ArrayList<Result>();
for(String key : context.getMapKeys()){
if(input.toLowerCase().contains(key.toLowerCase())){
values.addAll(context.getAllResults(key));
}
}
if(values.isEmpty()){
values.add(new Result("Nothing", "It appears we don't have any feedback for the given input."));
}
request.setAttribute("list", values);
RequestDispatcher view = request.getRequestDispatcher("WEB-INF/GeneratedSolution.jsp");
view.forward(request, response);
} |
97f3f845-63a0-4b32-9e07-97d6c0b82a64 | 2 | public int cld(Model model){
int res = 0;
for(Generalization g : model.getGeneralization()){
if(g.getIdentifier().equals(this.identifier)){
res = cheminPlusLongVersFeuille(model, g);
}
}
//System.out.println(res);
return res;
} |
c4085f5d-091d-4986-b143-a3b7bae7ca85 | 9 | public Boolean checkNewRoom(Tile cTile, Room nRoom){
int newRoomX = 0;
int newRoomY = 0;
/*
if (cRoom.getXPos()+nRoom.getDX() + 1 > newMap.getDim() || cRoom.getYPos()+nRoom.getDY() + 1 > newMap.getDim()){
return false;
}
if (cRoom.getXPos()-nRoom.getDX() - 1 < 0 || cRoom.getYPos()+nRoom.getDY() - 1 < 0){
return false;
}
*/
if (branchDir == NORTH){
newRoomX = cTile.getX() - (nRoom.getDX()/2) + 1;
newRoomY = cTile.getY() - nRoom.getDY();
}else if (branchDir == SOUTH){
newRoomX = cTile.getX() - (nRoom.getDX()/2);
newRoomY = cTile.getY() + 1;
}else if (branchDir == WEST){
newRoomX = cTile.getX() - nRoom.getDX();
newRoomY = cTile.getY() - (nRoom.getDY()/2);
}else if (branchDir == EAST){
newRoomX = cTile.getX() +1;
newRoomY = cTile.getY() - (nRoom.getDY()/2);
}
for (int x = newRoomX; x < newRoomX+nRoom.getDX(); x++){
for (int y = newRoomY; y < newRoomY+nRoom.getDY(); y++){
if (newMap.getTileFG(x, y) != VOID){
return false;
}
}
}
nRoom.setXPos(newRoomX);
nRoom.setYPos(newRoomY);
for (int x = 0; x < nRoom.getDX(); x++){
for (int y = 0; y < nRoom.getDY(); y++){
nRoom.getTile(x, y).setX(newRoomX+x);
nRoom.getTile(x, y).setY(newRoomY+y);
}
}
return true;
} |
4aa89d9c-f76d-4062-bc31-891fea550a1b | 3 | public static Collection<SerialPortChannel> findAll() throws ChannelException {
try {
Collection<SerialPortChannel> all = new ArrayList<>();
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getName().startsWith("COM")) {
all.add(new SerialPortChannel(portId));
}
}
return all;
}
catch (Throwable t) {
throw new ChannelException(t);
}
} |
b8538f72-c66b-4a20-8ea0-9bc816d16b03 | 7 | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
if (commandLabel.equalsIgnoreCase("Heavy") && sender instanceof Player){
if (player.hasPermission("EasyPvpKits.Heavy")){
if (!plugin.kits.contains(player.getName())){
player.sendMessage(ChatColor.GOLD + "You have been given the Heavy kit!");
if(plugin.getConfig().getBoolean("options.sound-effects"))
{
player.playSound(player.getLocation(), Sound.LEVEL_UP, 2.0F, 2.0F);
}
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, Integer.MAX_VALUE, 1));
plugin.kits.add(player.getName());
player.getInventory().clear();
player.getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD));
player.getInventory().setHelmet(new ItemStack(Material.DIAMOND_HELMET));
player.getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
player.getInventory().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS));
player.getInventory().setBoots(new ItemStack(Material.DIAMOND_BOOTS));
if(plugin.getConfig().getBoolean("options.soup-in-kits"))
{
for (int i = 0; i < 35; i++){
player.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP));
}
}
}
else {
player.sendMessage(ChatColor.RED + "You have already picked a kit!");
}
}
else player.sendMessage(ChatColor.RED + "You don't have permission to recieve this kit.");
return true;
}
return false;
} |
d56eaf3d-5ba2-43da-beb3-132028b0587b | 3 | public int stringHeight(String str)
{
if (str == null)
return 0;
int height = 0;
int length = str.length();
for (int i = 0; i != length; ++i)
{
int h = charHeight(str.charAt(i));
if (height < h)
height = h;
}
return height;
} |
2826c28b-4588-4783-b1d4-42a5dfe0c7ac | 1 | public Boolean update(String query) {
if(this.autoCommit){
return writeData(query.replace(" ", "+"));
}
this.queries +=query.replace(" ", "+")+"\n";
return null;
} |
db42c257-c043-4ada-81e5-157d7d27c814 | 4 | public void IndexCedd(String indexLoc){
System.out.println("-----Indexing images for CEDD descriptor in: " + FileLocation + "-----");
//Get all files from sub-directory
ArrayList<String> imagePaths = getFilesFromDirectory();
//Create standard config file for the index writer
IndexWriterConfig conf = new IndexWriterConfig(LuceneUtils.LUCENE_VERSION,
new WhitespaceAnalyzer(LuceneUtils.LUCENE_VERSION));
try {
//Note the filename "CEDDINDEX" is used to differentiate where the index is
indexWriter = new IndexWriter(FSDirectory.open(new File(indexLoc)), conf);
System.out.println("created CEDD index");
} catch (IOException e) {
System.err.println("Could not create CEDD file indexer");
}
//Iterate through the images in the directory, building the CEDD features
for (Iterator<String> it = imagePaths.iterator(); it.hasNext(); ) {
String imageFilePath = it.next();
System.out.println("Indexing " + imageFilePath);
try {
//load the image as a buffered image (works multiple features from a single image)
BufferedImage img = ImageIO.read(new FileInputStream(imageFilePath));
//create the CEDD document using the document factory, then add to the index
Document document = builder.createDocument(img, imageFilePath);
indexWriter.addDocument(document);
} catch (Exception e) {
System.err.println("Error indexing images.");
}
}
//Close the writer
try {
indexWriter.close();
} catch (IOException e) {
System.err.println("Error closing CEDD image indexer.");
}
System.out.println("CEDD descriptor: Finished indexing.");
} |
e791bb03-7fda-4018-9b7c-680d0c4be9bf | 2 | public void draw(int x_offset, int y_offset, int width, int height, Graphics g) {
//int xleft = x_offset + 1 + (x * (width + 1));
//int ytop = y_offset + 1 + (y * (height + 1));
//g.drawImage(lab, xleft, ytop, width, height, null);
if(contains(Mho.class)) {
((Mho)occupant).draw(x_offset, y_offset, width, height, g);
}
else if(contains(Player.class)) {
((Player)occupant).draw(x_offset, y_offset, width, height, g);
}
} |
1db6c386-0581-4999-bb55-cae4213a3417 | 6 | private static int getFormat(AudioFormat streamFormat) {
int format = -1;
if (streamFormat.getChannels() == 1) {
if (streamFormat.getSampleSizeInBits() == 8) {
format = IAudioDevice.FORMAT_MONO_8;
} else if (streamFormat.getSampleSizeInBits() == 16) {
format = IAudioDevice.FORMAT_MONO_16;
}
} else if (streamFormat.getChannels() == 2) {
if (streamFormat.getSampleSizeInBits() == 8) {
format = IAudioDevice.FORMAT_STEREO_8;
} else if (streamFormat.getSampleSizeInBits() == 16) {
format = IAudioDevice.FORMAT_STEREO_16;
}
}
return format;
} |
509dbddf-a54c-45fd-85da-99dc609af4fa | 5 | public void moveOnFinalPath(int moveRemaning) {
System.out.println("Coin.moveOnFinalPath() " + this);
LudoRegion region = LudoRegion.values()[this.getBlockNo().getRegion() - 1];
System.out.println(this.getBlockNo().getRegion() + " Coin.moveOnFinalPath() region " + region);
if(moveRemaning > 6){
//invalid move
return;
}
int x = 0 , y = 0;
switch (this.getBlockNo().getRegion()) {
case 12:
x = region.getMinX() + moveRemaning;
y = region.getMaxY();
break;
case 3:
x = region.getMinX();
y = region.getMinY() + moveRemaning;
break;
case 6:
x = region.getMinX() - moveRemaning;
y = region.getMinY();
break;
case 9:
x = region.getMinX();
y = region.getMinY() - moveRemaning;
}
System.out.println("movesReamaning " + moveRemaning);
path.getElements().add(
new LineTo(x * xWidth + radius, y * yHeight + radius));
this.setBlockNo(new Cordenate(x, y));
} |
d9e134af-6647-45cf-9e95-9369ed2780d9 | 3 | public void vaikutaTilanteeseen(int poistetutRivit)
{
if(poistetutRivit > 0)
{
int edellisetPisteet = pelinTila.arvo(Pelitilanne.Tunniste.PISTEET);
int seuraavatPisteet = edellisetPisteet + 2 * (poistetutRivit - 1) + 1;
pelinTila.aseta(Pelitilanne.Tunniste.PISTEET, seuraavatPisteet);
pelinTila.aseta(Pelitilanne.Tunniste.RIVIT, pelinTila.arvo(Pelitilanne.Tunniste.RIVIT) + poistetutRivit);
if(poistetutRivit >= 8 || seuraavatPisteet % 8 <= edellisetPisteet % 8)
pelinTila.aseta(Pelitilanne.Tunniste.VAIKEUSTASO, pelinTila.arvo(Pelitilanne.Tunniste.VAIKEUSTASO) + 1);
}
} |
8f97e125-b59c-4f9e-b6d9-6759d865a43a | 9 | public IndexedModel toIndexedModel()
{
IndexedModel result = new IndexedModel();
IndexedModel normalModel = new IndexedModel();
HashMap<OBJIndex, Integer> resultIndexMap = new HashMap<OBJIndex, Integer>();
HashMap<Integer, Integer> normalIndexMap = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
for(int i = 0; i < indices.size(); i++)
{
OBJIndex currentIndex = indices.get(i);
Vector3f currentPosition = positions.get(currentIndex.vertexIndex);
Vector2f currentTexCoord;
Vector3f currentNormal;
if(hasTexCoords)
currentTexCoord = texCoords.get(currentIndex.texCoordIndex);
else
currentTexCoord = new Vector2f(0,0);
if(hasNormals)
currentNormal = normals.get(currentIndex.normalIndex);
else
currentNormal = new Vector3f(0,0,0);
Integer modelVertexIndex = resultIndexMap.get(currentIndex);
if(modelVertexIndex == null)
{
modelVertexIndex = result.getPositions().size();
resultIndexMap.put(currentIndex, modelVertexIndex);
result.getPositions().add(currentPosition);
result.getTexCoords().add(currentTexCoord);
if(hasNormals)
result.getNormals().add(currentNormal);
result.getTangents().add(new Vector3f(0,0,0));
}
Integer normalModelIndex = normalIndexMap.get(currentIndex.vertexIndex);
if(normalModelIndex == null)
{
normalModelIndex = normalModel.getPositions().size();
normalIndexMap.put(currentIndex.vertexIndex, normalModelIndex);
normalModel.getPositions().add(currentPosition);
normalModel.getTexCoords().add(currentTexCoord);
normalModel.getNormals().add(currentNormal);
normalModel.getTangents().add(new Vector3f(0,0,0));
}
result.getIndices().add(modelVertexIndex);
normalModel.getIndices().add(normalModelIndex);
indexMap.put(modelVertexIndex, normalModelIndex);
}
if(!hasNormals)
{
normalModel.calcNormals();
for(int i = 0; i < result.getPositions().size(); i++)
result.getNormals().add(normalModel.getNormals().get(indexMap.get(i)));
}
normalModel.calcTangents();
for(int i = 0; i < result.getPositions().size(); i++)
result.getTangents().add(normalModel.getTangents().get(indexMap.get(i)));
return result;
} |
655f1fad-554c-44b6-93e4-f41181c9d10e | 1 | public void removeNew(int where) throws CannotCompileException {
try {
byte[] data = new NewRemover(this.get(), where).doit();
this.set(data);
}
catch (BadBytecode e) {
throw new CannotCompileException("bad stack map table", e);
}
} |
19294c68-2bf4-4543-b9d9-0a7b49eb5736 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Servico other = (Servico) obj;
if (this.IdServico != other.IdServico && (this.IdServico == null || !this.IdServico.equals(other.IdServico))) {
return false;
}
return true;
} |
98b0a418-590c-4679-a5d8-f74b0f8a1dda | 7 | public void game() {
/* Update the game as long as it is running. */
while (canvas.isVisible() && !restart && !player.isLevelCompleted()) {
if (!pause) {
/*If the player have lives left and have not won*/
if((player.getNumLives() > 0) && !(player.getWon())) {
updateWorld(); // Update the world
}
}
paintWorld(); // Paint the game world
try {
Thread.sleep(BreakoutCanvas.FRAME_DELAY); // Wait a given interval.
} catch (InterruptedException e) {
// Ignore.
}
}
return;
} |
2dff79b9-be89-4ebf-8fbb-e69d1c204a98 | 3 | public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
} |
c4c6c9ac-c478-4058-b2f1-7b0b2750ad9d | 3 | private String constructPWhashForIPboard(String salt, String pw)
{
//$hash = md5( md5( $salt ) . md5( $cleaned_password ) );
/* this is how IPboard constructs the hash
$hash is the value stored in the database column members_pass_hash.
$salt is the value stored in the database column members_pass_salt.
$password is the plain text password. (but some chars are HTML-escaped decimally!!
see: http://www.invisionpower.com/support/guides/_/advanced-and-developers/integration/login-modules-r42)
*/
String hash = "";
String hashedPWhex = null;
String hashedSaltHex = null;
try
{
hashedPWhex = getMD5(escapeHTML(pw).getBytes("UTF-8")); // escapeHTML converts some special chars into HTML entities (see file: HtmlCharacterEntityReferencesForIPboard.properties)
if(RemoteQuery.debug){RemoteQuery.log.info("PLUGIN Hashed PW: " + hashedPWhex);}
hashedSaltHex = getMD5(salt.getBytes("UTF-8"));
if(RemoteQuery.debug){RemoteQuery.log.info("PLUGIN Hashed Salt: " + hashedSaltHex);}
String concatValue = hashedSaltHex.concat(hashedPWhex);
hash = getMD5(concatValue.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return hash;
} |
f3283e97-10c7-4c7e-86db-228a09ea8c87 | 1 | public void testForID_String_old() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("GMT", "UTC");
map.put("WET", "WET");
map.put("CET", "CET");
map.put("MET", "CET");
map.put("ECT", "CET");
map.put("EET", "EET");
map.put("MIT", "Pacific/Apia");
map.put("HST", "Pacific/Honolulu");
map.put("AST", "America/Anchorage");
map.put("PST", "America/Los_Angeles");
map.put("MST", "America/Denver");
map.put("PNT", "America/Phoenix");
map.put("CST", "America/Chicago");
map.put("EST", "America/New_York");
map.put("IET", "America/Indiana/Indianapolis");
map.put("PRT", "America/Puerto_Rico");
map.put("CNT", "America/St_Johns");
map.put("AGT", "America/Argentina/Buenos_Aires");
map.put("BET", "America/Sao_Paulo");
map.put("ART", "Africa/Cairo");
map.put("CAT", "Africa/Harare");
map.put("EAT", "Africa/Addis_Ababa");
map.put("NET", "Asia/Yerevan");
map.put("PLT", "Asia/Karachi");
map.put("IST", "Asia/Kolkata");
map.put("BST", "Asia/Dhaka");
map.put("VST", "Asia/Ho_Chi_Minh");
map.put("CTT", "Asia/Shanghai");
map.put("JST", "Asia/Tokyo");
map.put("ACT", "Australia/Darwin");
map.put("AET", "Australia/Sydney");
map.put("SST", "Pacific/Guadalcanal");
map.put("NST", "Pacific/Auckland");
for (String key : map.keySet()) {
String value = map.get(key);
TimeZone juZone = TimeZone.getTimeZone(key);
DateTimeZone zone = DateTimeZone.forTimeZone(juZone);
assertEquals(value, zone.getID());
// System.out.println(juZone);
// System.out.println(juZone.getDisplayName());
// System.out.println(zone);
// System.out.println("------");
}
} |
7c895b00-b13d-41c0-9cee-b501b0b07100 | 0 | public void setItemcode(String itemcode) {
this.itemcode = itemcode;
} |
75f5798c-7481-4b20-ad62-21e166112ccc | 9 | public int[][] combatBfs(List<Tile> queue, int[][] weights) {
// Initialize costMap array with 0's.
// 0 = unchecked tile.
// Anything above 0 = already checked tile
// (since cost has been assigned to it)
int[][] costMap = createEmptyCostMap();
// loop through open set and assign their positions
// in costMap a value of 1 (if they don't have a
// value assigned already). Since 0 = unchecked tile,
// assigning an initial value of 1 sets the
// initial queue to already be 'checked'.
for(Tile t : queue) {
costMap[t.getRow()][t.getCol()] = 1;
}
// initialize weights map to a bunch of 0's if it is null.
if(weights == null) {
weights = createEmptyCostMap();
}
// While there are still nodes left to be evaluated.
while(queue.size() > 0) {
Tile tile = queue.remove(0);
for(Aim direction : Aim.values()) {
Tile neighbor = getTile(tile, direction);
int currCost = costMap[neighbor.getRow()][neighbor.getCol()];
int newCost = costMap[tile.getRow()][tile.getCol()] + 1;
// Skip this tile if it already has a lower cost
// assigned to it.
if(currCost != 0 && currCost <= newCost)
continue;
// Skip tile if it isn't a walkable tile.
if(!getIlk(neighbor).isPassable())
continue;
// add cost of tile to costMap
costMap[neighbor.getRow()][neighbor.getCol()] = newCost;
// add weights!
costMap[neighbor.getRow()][neighbor.getCol()] += weights[neighbor.getRow()][neighbor.getCol()];
// clustering
if(getIlk(neighbor) == Ilk.MY_ANT) {
costMap[neighbor.getRow()][neighbor.getCol()] -= 2;
}
// add to queue
if(currCost == 0)
queue.add(neighbor);
}
}
return costMap;
} |
13ede6f1-b312-4d3a-a0ed-490d92660bda | 7 | @Test
public void testConnection() throws Throwable {
final String PIPE_NAME;
if (OS.startsWith("Windows")) {
PIPE_NAME = "\\\\.\\pipe\\libuv-java-pipe-handle-test-pipe";
} else {
PIPE_NAME = "/tmp/libuv-java-pipe-handle-test-pipe";
Files.deleteIfExists(FileSystems.getDefault().getPath(PIPE_NAME));
}
final AtomicInteger serverSendCount = new AtomicInteger(0);
final AtomicInteger clientSendCount = new AtomicInteger(0);
final AtomicInteger serverRecvCount = new AtomicInteger(0);
final AtomicInteger clientRecvCount = new AtomicInteger(0);
final AtomicBoolean serverDone = new AtomicBoolean(false);
final AtomicBoolean clientDone = new AtomicBoolean(false);
final Logger serverLoggingCallback = new Logger("S: ");
final Logger clientLoggingCallback = new Logger("C: ");
final LoopHandle loop = new LoopHandle();
final PipeHandle server = new PipeHandle(loop, false);
final PipeHandle peer = new PipeHandle(loop, false);
final PipeHandle client = new PipeHandle(loop, false);
peer.setReadCallback(new StreamReadCallback() {
@Override
public void onRead(final ByteBuffer data) throws Exception {
serverRecvCount.incrementAndGet();
if (data == null) {
peer.close();
} else {
final Object[] args = {data};
serverLoggingCallback.log(args);
if (serverSendCount.get() < TIMES) {
peer.write("PING " + serverSendCount.incrementAndGet());
} else {
peer.close();
}
}
}
});
peer.setCloseCallback(new StreamCloseCallback() {
@Override
public void onClose() throws Exception {
serverDone.set(true);
}
});
server.setConnectionCallback(new StreamConnectionCallback() {
@Override
public void onConnection(int status, Exception error) throws Exception {
serverLoggingCallback.log(status, error);
server.accept(peer);
peer.readStart();
peer.write("INIT " + serverSendCount.incrementAndGet());
server.close(); // not expecting any more connections
}
});
client.setConnectCallback(new StreamConnectCallback() {
@Override
public void onConnect(int status, Exception error) throws Exception {
clientLoggingCallback.log(status, error);
client.readStart();
}
});
client.setReadCallback(new StreamReadCallback() {
@Override
public void onRead(final ByteBuffer data) throws Exception {
clientRecvCount.incrementAndGet();
if (data == null) {
client.close();
} else {
final Object[] args = {data};
clientLoggingCallback.log(args);
if (clientSendCount.incrementAndGet() < TIMES) {
client.write("PONG " + clientSendCount.get());
} else {
client.close();
}
}
}
});
client.setCloseCallback(new StreamCloseCallback() {
@Override
public void onClose() throws Exception {
clientDone.set(true);
}
});
server.bind(PIPE_NAME);
server.listen(0);
client.connect(PIPE_NAME);
while (!serverDone.get() && !clientDone.get()) {
loop.run();
}
client.close();
server.close();
Assert.assertEquals(serverSendCount.get(), TIMES);
Assert.assertEquals(clientSendCount.get(), TIMES);
Assert.assertEquals(serverRecvCount.get(), TIMES);
Assert.assertEquals(clientRecvCount.get(), TIMES);
} |
bf597bd4-d41a-435e-a70f-33a32b764eb5 | 6 | public Server() throws HeadlessException, UnknownHostException {
super("A Hole In The Universe Server "
+ InetAddress.getLocalHost().getHostAddress());
setSize(1300, 700);
setLocationRelativeTo(null);
setLayout(new GridLayout(1, 2));
// The program will close when the window is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
uClearButton = new JButton("Clear");
uScrollPaneMsg = new JScrollPane(uTextAreaMsg);
uLabelConnections = new JLabel("Connections: 0");
uClearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
uTextAreaMsg.setText("");
}
});
// uPanelMsg.setPreferredSize();
uPanelMsg.setLayout(new BoxLayout(uPanelMsg, BoxLayout.Y_AXIS));
uPanelMsg.setBorder(new LineBorder(Color.BLACK));
uPanelMsg.add(uLabelConnections);
uPanelMsg.add(uScrollPaneMsg);
uPanelMsg.add(uClearButton);
uPanelDB.setLayout(new BoxLayout(uPanelDB, BoxLayout.Y_AXIS));
uPanelDB.add(new JLabel("XML Database:"));
uTextAreaDB.setTabSize(2);
uScrollPaneDB = new JScrollPane(uTextAreaDB);
uPanelDB.add(uScrollPaneDB);
this.add(uPanelMsg);
this.add(uPanelDB);
try {
ss = new ServerSocket(PORT_NUM); // bind to port
Thread uThread = new Thread(this);
uThread.start();
} catch (IOException ioe) {
System.out.println("ioe in Server: " + ioe.getMessage());
}
updateDBDisplay();
setVisible(true);
// set up XML Parsing
try {
db = dbf.newDocumentBuilder();
doc = db.parse(new File(DB));
doc.getDocumentElement().normalize();
new ActiveGameCountdown(doc);
new WaitPlayersReady(doc);
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
uTextAreaMsg.append("Error: Database not found. \n");
} catch (IOException e) {
e.printStackTrace();
}
} |
b0256fa5-0173-467c-8cc4-600ac4d0e690 | 8 | @Override
public String toString() {
return "Installation {"
+ (extReferences != null ? " extReferences [" + extReferences + "]" : "")
+ (cls != null ? " cls [" + cls + "]" : "")
+ (recommendedValue != null ? " recommendedValue [" + recommendedValue + "]" : "")
+ (quality != null ? " quality [" + quality + "]" : "")
+ (legacyReleasability != null ? " legacyReleasability [" + legacyReleasability + "]" : "")
+ (value != null ? " value [" + value + "]" : "")
+ (remarks != null ? " remarks [" + remarks + "]" : "")
+ (availability != null ? " availability [" + availability + "]" : "")
+ "}";
} |
46b73acb-b304-4ffb-9128-809223882e14 | 0 | private void centerScreen() {
int width = this.getWidth();
int height = this.getHeight();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width - width) / 2;
int y = (screen.height - height) / 2;
setBounds(x, y, width, height);
} |
3a048317-3eba-4f18-a654-8f45b7632293 | 3 | private static boolean isX86() {
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
boolean isX86;
if (arch.endsWith("64") || ((wow64Arch != null) && wow64Arch.endsWith("64"))) {
isX86 = false;
} else {
isX86 = true;
}
return isX86;
} |
ddc35179-0306-4671-9212-6f8ca56732d0 | 2 | public void omniData(Object m){
rover = head;
while(rover != null){
if(rover.status == 1){
rover.sendObject(m);
}
rover = rover.next;
}
} |
a8f09ce7-a36a-4f6f-93d5-551566c6c3db | 2 | public void run() {
String importantInfo[] = { "Mares eat oats", "Does eat oats",
"Little lambs eat ivy", "A kid will eat ivy too" };
try {
for (int i = 0; i < importantInfo.length; i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
} |
791a0b05-2220-4eef-8e3e-daadaf86a89d | 1 | private void updateWindow()
{
if (Mission.getLastInstance() != null) {
Mission.getLastInstance().emitUpdateWindowSignal(this);
}
} |
be1afbc2-088f-4346-b456-5d090ace723f | 4 | public List<String> anagrams(String[] strs) {
List<String> result = new ArrayList<String>();
Map<String,List<String>> map = new HashMap<String,List<String>>();
for (int i = 0; i < strs.length ;i++ ) {
char[] c = strs[i].toCharArray();
Arrays.sort(c);
List<String> list = map.get(new String(c));
if(list == null){
list = new ArrayList<String>();
list.add(strs[i]);
map.put(new String(c),list);
// System.out.println(new String(c)+" 100");
}
else
list.add(strs[i]);
}
for( String s : map.keySet()){
List<String> list = map.get(s);
// System.out.println(list.size());
if(list.size() > 1){
result.addAll(list);
}
}
// System.out.println(map.size());
return result;
} |
8a3af8ea-bfda-4c1b-ae71-2c0c543f482d | 6 | @EventHandler
public void PigZombieWither(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPigZombieConfig().getDouble("PigZombie.Wither.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getPigZombieConfig().getBoolean("PigZombie.Wither.Enabled", true) && damager instanceof PigZombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, plugin.getPigZombieConfig().getInt("PigZombie.Wither.Time"), plugin.getPigZombieConfig().getInt("PigZombie.Wither.Power")));
}
} |
3df91101-9e89-43b7-95f7-c0328ce18aa0 | 7 | private static void Move(IHIPathfinderValues values)
{
values.Tiles[values.X[values.BinaryHeap[1]]][values.Y[values.BinaryHeap[1]]] = 2;
values.BinaryHeap[1] = values.BinaryHeap[values.Count];
values.Count--;
short location = 1;
while (true)
{
short high = location;
if (2*high + 1 <= values.Count)
{
if (values.F[values.BinaryHeap[high]] >= values.F[values.BinaryHeap[2*high]])
location = (short) (2*high);
if (values.F[values.BinaryHeap[location]] >= values.F[values.BinaryHeap[2*high + 1]])
location = (short) (2*high + 1);
}
else if (2*high <= values.Count)
{
if (values.F[values.BinaryHeap[high]] >= values.F[values.BinaryHeap[2*high]])
location = (short) (2*high);
}
if (high == location)
break;
short temp = values.BinaryHeap[high];
values.BinaryHeap[high] = values.BinaryHeap[location];
values.BinaryHeap[location] = temp;
}
} |
138df0e8-6c36-44e5-ac3b-4301179c3b45 | 6 | public void mousePressed(MouseEvent e) {
buttonSelected = controller.buttonSelected;
if (buttonSelected == null)
return;
pointClicked = e.getPoint();
// MAKING A SELECTION
if (buttonSelected == ButtonSelected.SELECT) {
// a shape has already been selected and now the handles have been selected
if (handleManager.checkIfSelectedHandles(e.getX(), e.getY())) {
handlesSelected = true;
anchor = handleManager.getAnchorPoint();
}
else {
shapeSelected = shapeManager.select(e.getX(), e.getY());
shapeManager.setSelectedShape(shapeSelected);
handleManager.createOutline(shapeSelected);
}
GUIFunctions.refresh();
}
// DRAWING A TRIANGLE
else if (buttonSelected == ButtonSelected.DRAW_TRIANGLE) {
if (trianglePoints.size() < 3)
trianglePoints.add(e.getPoint());
if (trianglePoints.size() == 3) {
createOrUpdateShape(e, Action.STARTED_DRAWING, pointClicked);
trianglePoints.clear();
}
}
} |
ddf238b0-0bc4-48ba-b940-31911fbd1e87 | 9 | private void newChannelGroup(String args[]){
int i = 2;
String name = "";
if(args[i].startsWith("\"")){
while(!args[i].endsWith("\"") && i < args.length-1){
if(!name.isEmpty())
name += " ";
name += args[i];
i++;
}
if(!name.isEmpty())
name += " ";
name += args[i];
i++;
name=name.substring(1, name.length()-1);
if(args[i-1].endsWith("\"")){
if(args.length == i){
ctrl.newChannelGroup(name, 0);
}
else if(args.length == i+1)
try{
long parentId = Long.parseLong(args[i]);
ctrl.newChannelGroup(name, parentId);
}
catch(NumberFormatException e){
System.out.println("Argument "+i+" NaN.");
}
}
else
System.out.println("Invalid name for channelgroup. Has to be between quotes \"\".");
}
else
System.out.println("Invalid name for channelgroup. Has to be between quotes \"\".");
} |
8c5cef17-fabd-4122-b3e4-1d5653e8fc8e | 4 | public void stop(StageFlipper flipper) {
if (flipper.packageID == 102) {
if (flipper.jm.GameType.equals("TicTacToe")) {
this.lastMsg = flipper;
this.stage = 20;
} else if (flipper.jm.GameType.equals("Achtung Die Kurve")) {
this.lastMsg = flipper;
this.stage = 30;
}
} else if (flipper.packageID == 404) {
this.stage = 1;
} else {
System.out
.println("Unknown packageID for Monitor.stop(StageFlipper)");
}
} |
6eb42668-41c2-42a7-9e17-ecfa7a8bef4c | 6 | private void pressed(KeyEvent e, String text)
{
int key = e.getKeyCode();
//VK_SPACE = space bar
if(key == KeyEvent.VK_SPACE && !drawingLevel)
{
fired = true;
}
//VK_UP = Up arrow
if (key == KeyEvent.VK_UP)
{
upArrowPressed = true;
}
if (key== KeyEvent.VK_X)
{
superJumpPressed = true;
}
if (key== KeyEvent.VK_LEFT)
{runner.move2();}
if (key == KeyEvent.VK_RIGHT)
{runner.move1();}
} |
7deba770-9854-4d95-b813-5418509ef4e2 | 5 | public synchronized Client editClient(Client client) {
if (client != null) {
for (Client clientAux : listClient) {
if (clientAux.getMail().equals(client.getMail())) {
listClient.remove(clientAux);
try {
listClient.put(client);
} catch (InterruptedException e) {
e.getMessage();
} catch (NullPointerException e) {
e.getMessage();
}
logger.info("Client: " + client.getName() + " atualizado!");
return clientAux;
}
}
}
return null;
} |
8822a1db-d760-4244-a00b-3e80df2b8b48 | 4 | private BufferedYamlConfiguration loadConfig(final File base, final String world) {
BufferedYamlConfiguration config = this.configuration.get(world);
if (config != null) return config;
final File source = (world == null ? base : new File(base, world + ".yml"));
try {
config = new BufferedYamlConfiguration(this.plugin, source, this.minSave).load();
} catch (final FileNotFoundException e) {
} catch (final Exception e) {
throw new IllegalStateException("Unable to load region configuration file: " + source, e);
}
this.configuration.put(world, config);
return config;
} |
97aeeb75-f351-4e4e-914c-8be630fbf67d | 8 | @Override
public String getStat(String code)
{
if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0)
return CMLib.coffeeMaker().getGenItemStat(this,code);
switch(getCodeNum(code))
{
case 0:
return "" + powerCapacity();
case 1:
return "" + activated();
case 2:
return "" + powerRemaining();
case 3:
return "" + getManufacturerName();
case 4:
return "" + getClothingLayer();
case 5:
return "" + getLayerAttributes();
case 6:
return "" + techLevel();
default:
return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code);
}
} |
42f2b067-661e-48ca-bef0-74a3a88a7844 | 6 | public static EnumOs getPlatform()
{
String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
if(osName.contains("win"))
{
return EnumOs.WINDOWS;
}
if(osName.contains("mac"))
{
return EnumOs.MACOS;
}
if(osName.contains("solaris") || osName.contains("sunos") || osName.contains("linux") || osName.contains("unix"))
{
return EnumOs.UNIX;
}
return EnumOs.UNKNOWN;
} |
abe16752-663b-4c65-a3b2-21e8275b381e | 0 | public BallIterator(BallContainer ballContainer) {
this.ballContainer = ballContainer;// 将操作的“盆”传入,参考上面的代码
this.index = 0;
} |
0d112c30-f4dc-4598-8e1e-449bcc42955c | 1 | public String getParts(int index){
try{
return parts.get(index);
} catch (IndexOutOfBoundsException e){
}
return null;
} |
8c9b95c8-a8f7-4517-801e-6ea9aaa01035 | 6 | public Track(HtmlMidNode parent, HtmlAttributeToken[] attrs){
super(parent, attrs);
for(HtmlAttributeToken attr:attrs){
String v = attr.getAttrValue();
switch(attr.getAttrName()){
case "default":
defaultt = Default.parse(this, v);
break;
case "kind":
kind = Kind.parse(this, v);
break;
case "label":
label = Label.parse(this, v);
break;
case "src":
src = Src.parse(this, v);
break;
case "srclang":
srclang = Srclang.parse(this, v);
break;
}
}
} |
bfba6b0a-77aa-49d0-a022-abec760b883a | 5 | public static void main(String[] args) {
if (args.length == 0) {
UI.run(path);
} else if (args.length == 1) {
path = args[0];
UI.run(path);
} else if (args.length == 2) {
path = args[0];
tries = Integer.parseInt(args[1]);
Launcher.launchBatch(path, mode, tries);
}else if (args.length == 3) {
path = args[0];
tries = Integer.parseInt(args[1]);
mode = CoordinatorMode.ParseCoordinatorMode(args[2]);
Launcher.launchBatch(path, mode, tries);
} else if (args.length > 3) {
System.out.print(USAGE);
System.out.print(MODES);
}
} |
7153ba43-a297-40a2-b172-0afb02b3bcee | 5 | public void insertarCuenta(int numCuenta){
try {
r_con.Connection();
String fechaDesde=campoFecha.getText();
String fechaHasta=campoFecha1.getText();
int numAsiento=-1;
ResultSet rs=r_con.Consultar("select * from asientos,plan_cuentas where pc_nro_cuenta=as_nro_cuenta and as_nro_cuenta="+numCuenta);
BigDecimal d=new BigDecimal(0);
BigDecimal h=new BigDecimal(0);
BigDecimal saldo=new BigDecimal(0);
BigDecimal saldoInicial=new BigDecimal(0);
Fechas fecha=new Fechas();
String planCuenta="";
String nombreCuenta="";
boolean entre=false;
while(rs.next()){
entre=true;
planCuenta=rs.getString("pc_codigo_plan_cuenta");
nombreCuenta=rs.getString("pc_nombre_cuenta");
if(fecha.fechaEntreFechas(fecha.convertirBarras(rs.getDate("as_fecha_contabilidad")+"")+"",fechaInicio, fechaDesde+"")){
numAsiento=rs.getInt(1);
if(rs.getFloat("as_debe")!=0)
saldoInicial=sumarBigDecimal(saldoInicial+"",rs.getFloat("as_debe")+"");
else
saldoInicial=sumarBigDecimal(saldoInicial+"","-"+rs.getFloat("as_haber"));
}
else
{
saldo=sumarBigDecimal(saldo+"","-"+rs.getFloat("as_haber"));
saldo=sumarBigDecimal(saldo+"",+rs.getFloat("as_debe")+"");
d=sumarBigDecimal(d+"",rs.getFloat("as_debe")+"");
h=sumarBigDecimal(h+"",rs.getFloat("as_haber")+"");
}
}
if(entre){
BigDecimal diferencia=sumarBigDecimal(saldoInicial+"",saldo+"");
String cadena=numCuenta+",'"+planCuenta+"','"+nombreCuenta+"',"+saldoInicial+","+d+","+h+","+saldo+","+diferencia;
r_con.Insertar("insert into balance values("+cadena+")");
}
r_con.cierraConexion();
} catch (SQLException ex) {
r_con.cierraConexion();
Logger.getLogger(GUI_Imprimir_Mayor.class.getName()).log(Level.SEVERE, null, ex);
}
} |
f68c6bd0-4783-4665-8583-9490562cf49d | 1 | private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
JFileChooser chooser = new JFileChooser("/");
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
jTextField3.setText(chooser.getSelectedFile().getPath());
}
}//GEN-LAST:event_jMenuItem1ActionPerformed |
f628fe36-e8d2-46f4-9db2-27153f149105 | 8 | private void mergeArray(int start, int mid, int end) {
if(mid<start || end<mid+1) {
return;
}
int[] tmp = new int[end-start+1];
int tmpIdx=0;
int i = 0;
int j = 0;
while(i<mid-start+1&&j<end-mid) {
if(array[start+i]<array[mid+1+j]) {
tmp[tmpIdx++] = array[start+i];
i++;
} else {
tmp[tmpIdx++] = array[mid+1+j];
j++;
}
}
while(i<mid-start+1) {
tmp[tmpIdx++] = array[start+i++];
}
while(j<end-mid) {
tmp[tmpIdx++] = array[mid+1+j++];
}
for(tmpIdx=0;tmpIdx<end-start+1;tmpIdx++) {
array[start+tmpIdx] = tmp[tmpIdx];
}
} |
cb7b3248-e78a-4106-9790-dd232da1ebbf | 2 | public Fornecedor buscarFornecedor(String nome) {
for (Fornecedor f : fornecedores) {
if (f.getNome().compareToIgnoreCase(nome) == 0) {
return f;
}
}
return null;
} |
e77f0776-1917-4e62-8b2b-cf7603a9a756 | 0 | public boolean getIncludeSubDirs() {
return this.includeSubDirs;
} |
5e18929c-cdd4-4778-a9a5-5867be56ebbf | 7 | public AudioFormat[] getTargetFormats(final AudioFormat.Encoding targetEncoding,
final AudioFormat sourceFormat)
{
if (sourceFormat.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED) &&
targetEncoding instanceof SpeexEncoding) {
if (sourceFormat.getChannels() > 2 || sourceFormat.getChannels() <= 0 ||
sourceFormat.isBigEndian()) {
AudioFormat[] formats = {};
return formats;
}
else {
AudioFormat[] formats = {new AudioFormat(targetEncoding,
sourceFormat.getSampleRate(),
-1, // sample size in bits
sourceFormat.getChannels(),
-1, // frame size
-1, // frame rate
false)}; // little endian
return formats;
}
}
else if (sourceFormat.getEncoding() instanceof SpeexEncoding &&
targetEncoding.equals(AudioFormat.Encoding.PCM_SIGNED)) {
AudioFormat[] formats = {new AudioFormat(sourceFormat.getSampleRate(),
16, // sample size in bits
sourceFormat.getChannels(),
true, // signed
false)}; // little endian (for PCM wav)
return formats;
}
else {
AudioFormat[] formats = {};
return formats;
}
} |
8cd0974c-12e6-4282-9ee4-93cf6ecc6579 | 6 | public void promptMove(GoEngine g) {
List<Coord> moves = new ArrayList<Coord>();
g.board.calculateTerritory();
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(g.board.checkValid(i,j,piece)&&g.board.getTerritory(i, j)!=piece){
moves.add(new Coord(i,j));
}
}
}
if(moves.size()!=0){
Coord move = moves.get(rand.nextInt(moves.size()));
if(g.board.placePiece(move.row, move.col, piece)==false){
}
}else{
g.board.passTurn();
}
} |
b71bfee8-c21e-44ac-8c4a-365eb337ebb3 | 2 | public void testPropertyCompareToMonth() {
YearMonthDay test1 = new YearMonthDay(TEST_TIME1);
YearMonthDay test2 = new YearMonthDay(TEST_TIME2);
assertEquals(true, test1.monthOfYear().compareTo(test2) < 0);
assertEquals(true, test2.monthOfYear().compareTo(test1) > 0);
assertEquals(true, test1.monthOfYear().compareTo(test1) == 0);
try {
test1.monthOfYear().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0);
assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0);
assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0);
try {
test1.monthOfYear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
} |
d9312bbc-7042-4dd2-96db-dcf856c3ff0f | 0 | public Connection getConnection(){
return connection;
} |
82bbf000-a1bb-4832-9970-92a1c3c7616c | 2 | public int powerMod(String binaryKey, Integer caracter, Double n){
BigInteger a = BigInteger.valueOf(caracter);
BigInteger aux = BigInteger.valueOf((int)caracter);
for (int i=1;i<binaryKey.length();i++){
System.out.print( aux +" ");
if(binaryKey.charAt(i)=='1'){
aux = ((aux.pow(2)).multiply(a)).remainder(BigInteger.valueOf(n.longValue()));
}else{
aux = (aux.pow(2)).remainder(BigInteger.valueOf(n.longValue()));
}
}
System.out.print( aux +" = "+ aux.intValue());
System.out.println("");
// System.out.println("aux "+ aux);
return aux.intValue();
} |
26dcf2f7-ce49-4382-8527-3a88ee13df8d | 0 | public String getVisiteur() {
return visiteur;
} |
c605fafd-0ead-4e1b-a1c7-f8cb8b8271ab | 7 | public void saveSettings() {
FileWriter xmlfile;
String line;
// Open the default file settings //
try {
xmlfile=new FileWriter("rivet_settings.xml");
// Start the XML file //
line="<?xml version='1.0' encoding='utf-8' standalone='yes'?>\n<settings>\n";
xmlfile.write(line);
// Invert
line="<invert val='";
if (invertSignal==true) line=line+"TRUE";
else line=line+"FALSE";
line=line+"'/>\n";
xmlfile.write(line);
// Debug mode
line="<debug val='";
if (debug==true) line=line+"TRUE";
else line=line+"FALSE";
line=line+"'/>\n";
xmlfile.write(line);
// Mode
line="<mode val='"+Integer.toString(system)+"'/>\n";
xmlfile.write(line);
// CROWD36 sync tone
line="<c36tone val='"+Integer.toString(crowd36Handler.getSyncHighTone())+"'/>\n";
xmlfile.write(line);
// Soundcard Input Level
line="<soundcard_level val='"+Integer.toString(soundCardInputLevel)+"'/>\n";
xmlfile.write(line);
// Soundcard Input
if (soundCardInput==true) line="<soundcard_input val='1'/>\n";
else line="<soundcard_input val='0'/>\n";
xmlfile.write(line);
// View GW Free Channel Markers
if (viewGWChannelMarkers==true) line="<view_gw_markers val='1'/>\n";
else line="<view_gw_markers val='0'/>\n";
xmlfile.write(line);
// RTTY & FSK
// Baud
line="<rttybaud val='"+Double.toString(rttyHandler.getBaudRate())+"'/>\n";
xmlfile.write(line);
// Shift
line="<rttyshift val='"+Integer.toString(rttyHandler.getShift())+"'/>\n";
xmlfile.write(line);
// Stop bits
line="<rttystop val='"+Double.toString(rttyHandler.getStopBits())+"'/>\n";
xmlfile.write(line);
// Save the current audio source
line="<audioDevice val='"+inputThread.getMixerName()+"'/>\n";
xmlfile.write(line);
// Display bad packets
if (displayBadPackets==true) line="<display_bad_packets val='1'/>\n";
else line="<display_bad_packets val='0'/>\n";
xmlfile.write(line);
// Show UTC time
if (logInUTC==true) line="<UTC val='1'/>\n";
else line="<UTC val='0'/>\n";
xmlfile.write(line);
// CIS36-50 shift
line="<cis3650shift val='"+Integer.toString(cis3650Handler.getShift())+"'/>\n";
xmlfile.write(line);
// All done so close the root item //
line="</settings>";
xmlfile.write(line);
// Flush and close the file //
xmlfile.flush();
xmlfile.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error : Unable to create the file rivet_settings.xml\n"+e.toString(),"Rivet", JOptionPane.ERROR_MESSAGE);
}
return;
} |
354c4627-7bf7-4bf0-a5fd-43727192f518 | 9 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// consulta de la base de datos
try {
//Establece los valores para la sentencia SQL
Connection c=con.conectar();
PreparedStatement consultar = c.prepareStatement("SELECT clave_trabajador FROM historial group by clave_trabajador;");
//consultar.setString(1,camp_clave.getText());
HSSFWorkbook libro = new HSSFWorkbook();//creamos libro de exel
ResultSet rs = consultar.executeQuery();
if (rs.next()){//
//creacion del reporte en exel
int fil=1;
int cel=0;
do{
String clavet=rs.getString("clave_trabajador");
HSSFSheet hoja = libro.createSheet("Reporte de "+rs.getString("clave_trabajador"));//creamos una hoja
hoja.addMergedRegion(new Region(0, (short) 0, 0,(short) 1));
HSSFRow fila = hoja.createRow(0);//creamos la primera fila
HSSFCell celda = fila.createCell(0);//creamos una celda
HSSFRichTextString texto = new HSSFRichTextString("CENTRO DE BACHILLERATO AGROPECUARIO No 77");
celda.setCellValue(texto);
fila = hoja.createRow(fil);//creamos la primera fila
celda = fila.createCell(0);//creamos una celda
texto = new HSSFRichTextString("FECHA");
celda.setCellValue(texto);
celda = fila.createCell(1);//creamos una celda
texto = new HSSFRichTextString("ESTADO");
celda.setCellValue(texto);
Connection conect=con.conectar();
try{
PreparedStatement consulta_fechas = conect.prepareStatement("SELECT fecha, estado FROM historial where clave_trabajador='"+clavet+"';");
ResultSet rs_fechas = consulta_fechas.executeQuery();
if (rs_fechas.next()){
do{
fil=fil+1;
fila = hoja.createRow(fil);//creamos la siguiente fila
// Luego creamos el objeto que
HSSFCellStyle estiloCelda = libro.createCellStyle();
String estado= rs_fechas.getString("estado");
if(estado.equals("Retardo")){
estiloCelda.setFillForegroundColor((short)13);
estiloCelda.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
}
if(estado.equals("Falta")){
estiloCelda.setFillForegroundColor((short)10);
estiloCelda.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
}
celda = fila.createCell(0);//creamos una
String clave= rs_fechas.getString("fecha");
texto = new HSSFRichTextString(clave);
celda.setCellStyle(estiloCelda);
celda.setCellValue(texto);
cel=cel+1;
celda = fila.createCell(1);//creamos una
texto = new HSSFRichTextString(estado);
celda.setCellStyle(estiloCelda);
celda.setCellValue(texto);
}while(rs_fechas.next());
fil=1;
}
}catch(Exception e){
//
}finally{
con.desconectar();
}
}while(rs.next());
try {
FileOutputStream elFichero = new FileOutputStream("C:/Users/jesus/Desktop/Reportes.xls");
libro.write(elFichero);
elFichero.close();
mensajes.setText("El archivo se ha generado en:\nC:/Users/jesus/Desktop/Reportes.xls");
} catch (Exception e) {
e.printStackTrace();
}
} else {
mensajes.setText("No existe historial de ningun trabajador");
}
} catch (SQLException e) {
//Si ocurre un error lo indica en la consola
System.err.println("Error al verificar los datos del personal.");
}finally{
con.desconectar();
}
}//GEN-LAST:event_jButton1ActionPerformed |
6dc41e2e-d7d8-4ee6-8b1b-8b1445e8486f | 2 | public List<Disciplina> consultaDisciplinasPorPreferenciaPorProfessor(
String matriculaProfessor, int nivelPreferencia)
throws ProfessorInexistenteException, PreferenciaInvalidaException {
List<Disciplina> listaRetorno = new ArrayList<Disciplina>();
for (Professor p : professores) {
if (p.getMatricula().equals(matriculaProfessor)) {
listaRetorno = p
.getDisciplinasPreferidasComNivel(nivelPreferencia);
}
}
return listaRetorno;
} |
81ae24a2-5263-4e2b-acc5-f3b090fc69f6 | 0 | public AutomatonAction getRestoreAction() {
return restoreAction;
} |
e4108f7d-6cee-4aef-afb9-97f93a5f9221 | 6 | private static void tryDo(String s, int i, int j){
int len = j-i;
int sLen = s.length();
for(int k=0;k<len;k++){
if((j+k<allowed && j+k>=sLen) || (i+k<sLen && j+k<sLen && s.charAt(i+k)==s.charAt(j+k))){
continue;
} else {
return;
}
}
max = Math.max(len*2, max);
} |
21aa331c-fffc-42ac-9a2c-2d8837efe6f4 | 5 | private void processPlayers() {
for (HostedConnection each : getClients()) {
Boolean init = each.getAttribute(AttributeKey.INIT);
if(init==null) {
continue;
}
if (!init) {
//
Player p = pf.producePlayer();
each.setAttribute(AttributeKey.PLAYER, p);
each.setAttribute(AttributeKey.ANIMATION, Animation.IDLE);
//
getPhysicsSpace().add(p.getControl());
each.send(new InitPlayer(p.getId(), mapPath));
AddPlayer ap = new AddPlayer(p.getId());
for(HostedConnection others : getClients()) {
Player o = others.getAttribute(AttributeKey.PLAYER);
each.send(new AddPlayer(o.getId()));
others.send(ap);
}
each.setAttribute(AttributeKey.INIT, true);
// terrain stuff
DistanceLodCalculator lodcalc = new DistanceLodCalculator(33, 2.7f);
TerrainLodControl control = new TerrainGridLodControl(terrain, p.getCamera());
control.setLodCalculator(lodcalc); // patch size, and a multiplier
terrain.addControl(control);
// --
}
boolean connected = each.getAttribute(AttributeKey.CONNECTED);
if (!connected) {
continue;
}
//
Player p = each.getAttribute(AttributeKey.PLAYER);
float pitch = each.getAttribute(AttributeKey.PITCH);
float yaw = each.getAttribute(AttributeKey.YAW);
int keysPressed = each.getAttribute(AttributeKey.KEYSPRESSED);
p.setPitch(pitch);
p.setYaw(yaw);
p.setKeysPressed(keysPressed);
//
p.update();
}
} |
cdd18512-bd03-4cf8-b051-444670a10421 | 1 | private static String toString(ArrayList<String> al) {
String string = "";
for(String str : al) {
String build = string;
string = build + str;
}
return string;
} |
37425285-4ef2-4df2-8378-d1a2a1485c00 | 4 | private static Field findDeclaredField(Class<?> inClass, String fieldname)
throws NoSuchFieldException {
while (!Object.class.equals(inClass)) {
for (Field field : inClass.getDeclaredFields()) {
if (field.getName().equalsIgnoreCase(fieldname)) {
return field;
}
}
inClass = inClass.getSuperclass();
}
throw new NoSuchFieldException();
} |
561267b8-00fd-4279-816d-9decabc29780 | 3 | static Direction clockwise(Direction direction) {
if (direction == NORTH) return EAST;
if (direction == EAST) return SOUTH;
if (direction == SOUTH) return WEST;
return NORTH;
} |
7972b6b0-3416-4339-acb2-ffc12e9786c4 | 7 | private static BigInteger[] fraction(double val){
long bits = Double.doubleToLongBits(val);
int sign = ((bits >> 63) == 0) ? 1 : -1;
int exp = (int)((bits >> 52) & 0x7ffL);
if(exp == 2047){
throw new ArithmeticException("The double value "+val+" is Infinity or NaN, can't be represented as rational number");
}
long frac = bits & 0x000fffffffffffffL ;
if(exp!=0){//exp==0 for denormalized number
frac = frac | 0x0010000000000000L ;//add 1 here. 1.Signficant for normalized number
}
int numOfZeros = Math.min(Long.numberOfTrailingZeros(frac),52);//if significant are all zeros, 64 returned for numberofTrailingZeros() function.
frac = frac >>> numOfZeros;//remove zeros, unsigned shift
exp = Math.max(exp-BIAS,-BIAS+1);//biased exponent, -1022 for denormalized number
int numOfShifts = 52 - numOfZeros;//move the decimal point to make the maginitude a integer
int numerExp = exp-numOfShifts;//numerator is frac*2^numerExp
int denomExp = 0;//denominator is 1*2^0.
if(numerExp<0){
denomExp = - numerExp;//numerator is frac and denominator is 2^(-numerExp)
numerExp = 0;
}
//numerator is frac*2^numerExp
int n = numOfShifts+numerExp+1;//number of bits to store numerator
byte[] numer = new byte[n/8+(n%8==0?0:1)];
frac = frac<<numerExp%8; //numerator is frac*2^(numerExp%8)*2^(numerExp/8)
for(int i = numerExp/8; i<numer.length;i++){//big-endian
numer[numer.length-1-i] = (byte)(frac%256);
frac = frac>>8;
}
BigInteger numerator = new BigInteger(sign,numer);
//denominator is 2^denomExp
n = denomExp+1;//number of bits to store denominator
byte[] denom = new byte[n/8+(n%8==0?0:1)];
denom[0] |= 1<<(denomExp%8);//big-endian, 2^((denomExp%8)+(8*(denom.length-1)))=2^(deomExp/8+deomExp%8)
BigInteger denominator = new BigInteger(1,denom);
return new BigInteger[]{numerator,denominator};
} |
6e4f63b7-f981-4817-9060-fa9e944ae111 | 2 | @Override
public boolean free(ByteBuffer buffer)
{
boolean cached = false;
// If caching this buffer will go over the maximum allowable cached
// buffer memory then simply free the buffer and return the result.
if (usedMemory.get() + buffer.capacity() > maxMemory.get()) {
onFree(buffer);
}
// Try caching the buffer...
else {
cached = onCache(buffer);
// If cached update used memory.
if (cached) {
usedMemory.addAndGet(buffer.capacity());
}
// Else free the buffer from memory.
else {
onFree(buffer);
}
}
return cached;
} |
368c2524-4440-40ba-bc6b-f95571a52725 | 4 | public void rightClick(Tile tile, boolean shift, Point target, Point worldBound){
if(shift)
{
setCamera(target,worldBound);
}
else
{
if(selected == null || selected.getClass().getSuperclass() == Terrain.class)
{
setCamera(target,worldBound);
}
else if (selected != null)
{
AbstractMatterAction(tile);
}
}
} |
0c9fe196-e2bb-475a-ae08-435f752fafd5 | 7 | public DMemeGrid getRigorData() {
DMemeGrid dmg = new DMemeGrid();
String sql = "SELECT \n"
+ " BP.accountID, MSP.projectID, MSP.siteID, BP.name AS projectName\n"
+ ", BSite.disname AS districtName, BSite.schname AS schoolName\n"
+ ", MCSite.collectorID\n"
+ ", BC.subjectArea, BC.gradeLevel\n"
+ ", MSC.sampleID\n"
+ ", RD.groupingID, RD.dataName, RD.dataValue\n"
+ "FROM `bank_project` AS BP\n"
+ "LEFT JOIN map_site_project AS MSP ON MSP.projectID = BP.id\n"
+ "LEFT JOIN bank_site AS BSite ON BSite.id = MSP.siteID\n"
+ "LEFT JOIN map_collector_site AS MCSite ON MCSite.siteID = MSP.siteID\n"
+ "LEFT JOIN bank_collector AS BC ON BC.id = MCSite.collectorID\n"
+ "LEFT JOIN map_sample_collector AS MSC ON MSC.collectorID = MCSite.collectorID\n"
+ "LEFT JOIN review_data AS RD ON RD.sampleID = MSC.sampleID\n"
+ "WHERE MSP.projectID = 23401520791814151\n"
+ "AND MSP.active = 'y'\n"
+ "AND BSite.active = 'y'\n"
+ "AND MCSite.active = 'y'\n"
+ "AND BC.active = 'y'\n"
+ "AND MSC.active = 'y'\n"
+ "AND RD.active = 'y'\n"
+ "AND RD.dataName IN ('standard', 'dok', 'blm','counter')\n"
+ "AND RD.dataValue <> \"\"\n"
+ "AND BC.subjectArea = 'English'\n"
+ "AND BC.gradeLevel = 2\n"
+ "ORDER BY BP.name, BSite.disname, BSite.schname, \n"
+ "BC.gradeLevel, BC.subjectArea, MSC.sampleID, \n"
+ "RD.groupingID, RD.dataName, RD.dataValue ";
ResultSet rs = DM.Execute(sql);
try {
rs.beforeFirst();
String currentCollectorID = new String();
String currentSampleID = new String();
int currentGroupingID = 0;
String currentDOK = new String();
String currentBLM = new String();
Boolean jump = false;
Map<String, String> item = new HashMap<>();
Map<String, Integer> sample = new TreeMap<>();
dmg.setLabel("Cognitive Rigor: English Grade 2");
dmg.setColDescriptor("Bloom's Taxonomy (Revised)");
dmg.setRowDescriptor("Depth of Knowledge");
dmg.addRowLabel("4");
dmg.addRowLabel("3");
dmg.addRowLabel("2");
dmg.addRowLabel("1");
dmg.addColLabel("1");
dmg.addColLabel("2");
dmg.addColLabel("3");
dmg.addColLabel("4");
dmg.addColLabel("5");
dmg.addColLabel("6");
while (rs.next()) {
if (currentGroupingID > 0) {
if (rs.getInt("groupingID") != currentGroupingID) {
//currentGroupingID = rs.getString("groupingID");
jump = true;
}
}
if (jump == true) {
String CR = String.format("%s:%s", item.get("dok"), item.get("blm"));
String[] rigor = CR.split(":");
int dok = new Integer(rigor[0].replace("DOK-", ""));
int blm = new Integer(rigor[1].replace("BLM-", ""));
if (dmg.hasElement(4-dok, blm-1)) {
int c = new Integer(item.get("counter"));
int c2 = dmg.getItem(4-dok, blm-1).isNumeric()
? dmg.getItem(4-dok, blm-1).asInteger()
: 0;
dmg.addItem(4-dok, blm-1, new DataMeme(c+c2));
}
else {
dmg.addItem(4-dok, blm-1, new DataMeme(new Integer(item.get("counter"))));
}
item.clear();
jump = false;
}
item.put(rs.getString("dataName"), rs.getString("dataValue"));
currentCollectorID = rs.getString("collectorID");
currentSampleID = rs.getString("sampleID");
currentGroupingID = rs.getInt("groupingID");
}
} catch (SQLException ex) {
Logger.getLogger(CCSS_reporter.class.getName()).log(Level.SEVERE, null, ex);
}
return dmg;
} |
5b28afd7-be80-4e2f-b58c-b9f302063355 | 8 | private void setState(Request request, Response response, String status) {
for (String s : request.getValidStates()) {
if (status.equals(s)) {
response.setMatchOk(true);
break;
}
}
if (!response.isMatchOk() && request.getErrorStates() != null) {
for (String s : request.getErrorStates()) {
if (status.equals(s)) {
response.setMatchError(true);
break;
}
}
}
if (!response.isMatchOk() && !response.isMatchError()) {
throw new BeanstalkException(status);
}
} |
dfa1040a-4522-4ebf-8f23-43835bea6ece | 9 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(sprung)
return super.okMessage(myHost,msg);
if(!super.okMessage(myHost,msg))
return false;
if((msg.amITarget(affected))
||((msg.tool()!=null)&&(msg.tool()==affected)))
{
if((msg.targetMinor()==CMMsg.TYP_ENTER)
||(msg.targetMinor()==CMMsg.TYP_LEAVE)
||(msg.targetMinor()==CMMsg.TYP_FLEE))
{
if(msg.targetMinor()==CMMsg.TYP_LEAVE)
return true;
spring(msg.source());
return false;
}
}
return true;
} |
5d8a236b-bccc-4499-a5ba-4c807029b76b | 2 | @Override
protected void generateLevel() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
tilesInt[x + y * width] = random.nextInt(4);
}
}
} |
cb9c76cd-c7be-473c-a3bb-0f5ea6f1046d | 4 | public Component getListCellRendererComponent(
JList jlist,
Object e,
int index,
boolean isSelected,
boolean cellHasFocus)
{
this.viewer.setObject(e);
Color background;
Color foreground;
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = jlist.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
//background = Color.BLUE;
background = new Color(182, 171, 160);
foreground = Color.WHITE;
//background = UIManager.getColor("List.dropLineColor");
//foreground = UIManager.getColor("List.background");
// check if this cell is selected
} else if (isSelected) {
//background = Color.RED;
background = new Color(240, 119, 70);
foreground = Color.BLACK;
// unselected, and not the DnD drop location
} else {
//nao selecionado
background = Color.WHITE;
foreground = Color.BLACK;
//dependente do Look and Feel
// background = UIManager.getColor("List.background");
// foreground = UIManager.getColor("List.textForeground");
}
viewer.getView().setBackground(background);
viewer.getView().setForeground(foreground);
return viewer.getView();
} |
9267aea7-9fb3-4777-be10-1dcc9db3c0e8 | 5 | @Override
public void mouseDragged(MouseEvent event) {
if (isEnabled()) {
Row rollRow = null;
try {
int x = event.getX();
mSelectOnMouseUp = -1;
if (mDividerDrag != null && allowColumnResize()) {
dragColumnDivider(x);
JScrollPane scrollPane = UIUtilities.getAncestorOfType(this, JScrollPane.class);
if (scrollPane != null) {
Point pt = event.getPoint();
if (!(event.getSource() instanceof Outline)) {
// Column resizing is occurring in the header, most likely
pt.y = getVisibleRect().y + 1;
}
scrollRectToVisible(new Rectangle(pt.x, pt.y, 1, 1));
}
}
} finally {
repaintChangedRollRow(rollRow);
}
}
} |
158de135-946e-4416-84c5-6c11b087fdba | 8 | public Gleitpunktzahl add(Gleitpunktzahl r) {
/*
* TODO: hier ist die Operation add zu implementieren. Verwenden Sie die
* Funktionen normalisiere, denormalisiere und die Funktionen add/sub
* der BitFeldklasse. Achten Sie auf Sonderfaelle und die Einschraenkung
* der Funktion BitFeld.sub.
*/
if (this.isNaN() || r.isNaN())
return getNaN();
if (this.isInfinite() || r.isInfinite())
return getPosInfinite();
Gleitpunktzahl a = new Gleitpunktzahl(this);
Gleitpunktzahl b = new Gleitpunktzahl(r);
Gleitpunktzahl result = new Gleitpunktzahl();
if (a.vorzeichen && b.vorzeichen) {
a.vorzeichen = false;
b.vorzeichen = false;
result = a.add(b);
result.vorzeichen = true;
return result;
}
else if (a.vorzeichen){
a.vorzeichen = false;
return b.sub(a);
}
else if (b.vorzeichen) {
b.vorzeichen = false;
return a.sub(b);
}
denormalisiere(a, b);
result.exponent = a.exponent;
result.mantisse = a.mantisse.add(b.mantisse);
result.normalisiere(anzBitsMantisse-1);
return result;
} |
71acde98-38e9-42e4-9f52-bf92437b6955 | 8 | private RatingResult predictUserRating(DBObject reviewObject) {
if (reviewObject == null)
return null;
if (!reviewObject.containsField(CollectionReview.KEY_USER_ID)
|| !reviewObject
.containsField(CollectionReview.KEY_BUSINESS_ID)
|| !reviewObject.containsField(CollectionReview.KEY_STARS)) {
return null;
}
RatingResult ratingResult = new RatingResult();
/* user id of the (original) user */
ratingResult.userId = (String) reviewObject
.get(CollectionReview.KEY_USER_ID);
/* business id of the (original) business */
ratingResult.businessId = (String) reviewObject
.get(CollectionReview.KEY_BUSINESS_ID);
/*
* actual stars rating of the (original) review. The rest of the logic
* tries to use collaborative filtering to predict this values and then
* compares the prediction vs. the actual.
*/
ratingResult.stars = (Integer) reviewObject
.get(CollectionReview.KEY_STARS);
/* collect all reviews of the (original) user */
HashMap<String, DBObject> reviewArray = findUserReviews(reviewObject);
System.out.println("Try to predict user " + ratingResult.userId
+ " for business " + ratingResult.businessId);
/* search for all reviews for the same business */
DBCollection reviewCollection = db.getCollection(COLLECTION_REVIEW);
BasicDBObject filter = new BasicDBObject();
filter.put(CollectionReview.KEY_BUSINESS_ID, ratingResult.businessId);
DBCursor cursorReview2 = reviewCollection.find(filter);
/*
* comparableRatingArray contains the reviews by other users of the
* (original) business
*/
ArrayList<ComparableRating> comparableRatingArray = new ArrayList<ComparableRating>();
DBCollection userCollection = db.getCollection(COLLECTION_USER);
ensureCollectionUserIndex(userCollection);
int totalRatingCount = 0;
int totalRatingStars = 0;
/* for each review of the (original) business */
while (cursorReview2.hasNext()) {
DBObject reviewObject2 = cursorReview2.next();
String userId2 = (String) reviewObject2
.get(CollectionReview.KEY_USER_ID);
/* make sure to skip the review by the (original) business */
if (!userId2.equals(ratingResult.userId)) {
totalRatingCount++;
totalRatingStars += (Integer) reviewObject2
.get(CollectionReview.KEY_STARS);
/* collect all reviews of this other user */
HashMap<String, DBObject> reviewArray2 = findUserReviews(reviewObject2);
/*
* compute similarity between this other user and the (original)
* user
*/
SimilarityCoefficient coefficient = computeSimilarityCoefficient(
reviewArray, reviewArray2, ratingResult.businessId);
/* sometimes similarity cannot be computed so we need to check */
if (isCoefficientUsable(coefficient)) {
coefficient.sameGenderProbability = calculateSameGenderProbability(
userCollection, ratingResult.userId, userId2);
DBObject businessReview = reviewArray2
.get(ratingResult.businessId);
ComparableRating comparableRating = new ComparableRating();
comparableRating.originalUserId = ratingResult.userId;
comparableRating.userId = (String) businessReview
.get(CollectionReview.KEY_USER_ID);
comparableRating.stars = (Integer) businessReview
.get(CollectionReview.KEY_STARS);
comparableRating.coefficient = coefficient;
/*
* add an entry containing the other users' actual stars
* rating and the similarity of the other user vs. the
* (original) user
*/
comparableRatingArray.add(comparableRating);
System.out.println(comparableRating);
} // if
} // if
} // while
cursorReview2.close();
/*
* total number of reviews of the same business by other users where
* similarity can be computed
*/
ratingResult.totalUserCount = comparableRatingArray.size();
/* only use a subset of all other users' reviews */
ratingResult.actualUserCount = limitComparableRating(comparableRatingArray);
/* generate the prediction using the subset */
ratingResult.predictedStars = computeComparableRating(
comparableRatingArray, ratingResult.actualUserCount);
System.out.println(ratingResult);
if (ratingResult.predictedStars == null) {
System.out.println("Insufficient data to predict rating");
} else {
double error = ratingResult.predictedStars - ratingResult.stars;
System.out.println("error=" + error + " predictedStars="
+ ratingResult.predictedStars + " actualStars="
+ ratingResult.stars);
} // else
/* naive average rating of the (original) business by all other users */
ratingResult.averageRatingStars = (double) totalRatingStars
/ (double) totalRatingCount;
double arsError = ratingResult.averageRatingStars - ratingResult.stars;
System.out.println("averageRatingStars.error="
+ Double.toString(arsError) + " averageRatingStars="
+ Double.toString(ratingResult.averageRatingStars)
+ " actualStars=" + ratingResult.stars);
return ratingResult;
} // predictUserRating |
391a076c-47cf-45a5-853e-2364d6508da7 | 7 | public static void main( String[] args ) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, ClassNotFoundException, NoSuchFieldException
{
// 1 access static class
System.out.println( "directly " + StaticExample.class.getName() );
// 2 this throws an exception
try
{
Class<?> forname = Class.forName( "com.danibuiza.javacodegeeks.reflection.StaticReflection.StaticExample" );
System.out.println( "class for name " + forname.getName() );
}
catch( ClassNotFoundException ex )
{
System.err.println( "class not found " + ex.getMessage() );
}
// 3 this would work but is not that nice
try
{
Class<?> forname = Class.forName( "com.danibuiza.javacodegeeks.reflection.StaticReflection$StaticExample" );
System.out.println( "class for name " + forname.getName() );
}
catch( ClassNotFoundException ex )
{
System.err.println( "class not found " + ex.getMessage() );
}
// 4 another way iterating through all classes declared inside this class
Class<?>[] classes = StaticReflection.class.getDeclaredClasses();
for( Class<?> class1 : classes )
{
System.out.println( "iterating through declared classes " + class1.getName() );
}
// access static methods in the same way as instance ones
Method mathMethod = Math.class.getDeclaredMethod( "round", double.class );
// object can be null since method is static
Object result = mathMethod.invoke( null, new Double( 12.4 ) );
System.out.println( "result of calling Math.round using reflection for 12.4 " + result );
// static field access, instance can be null
Field counterField = Counter.class.getDeclaredField( "counter" );
System.out.println( counterField.get( null ) );
} |
Subsets and Splits