method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
d110f072-bbf7-4f89-b9d8-a9239944415c | 2 | public boolean registraEquipo(HttpServletRequest request, HttpServletResponse response) throws IOException {
ConexionBD bd = new ConexionBD();
request.setCharacterEncoding("UTF-8");
String activoFijo = (String) request.getParameter("activoFijo");
int actFijo = (activoFijo.equals("")) ? 0 : Integer.parseInt(activoFijo);
String numInvUNAM = (String) request.getParameter("descripcion");
int numInv = (numInvUNAM.equals("")) ? 0 : Integer.parseInt(numInvUNAM);
String descripcion = request.getParameter("descripcionExtendida");
String modelo = request.getParameter("modelo");
String marca = request.getParameter("marca");
String numSerie = request.getParameter("numeroSerie");
String familia = request.getParameter("familia");
String tipoActivoFijo = request.getParameter("tipoActivoFijo");
String proveedor = request.getParameter("proveedor");
String clase = request.getParameter("clase");
String uso = request.getParameter("uso");
String nivelObsolencia = request.getParameter("nivelObsolencia");
String estadoFisico = request.getParameter("estadoFisico");
String ubicacion = request.getParameter("ubicacion");
String centroCosto = request.getParameter("centroCosto");
String fechaResguardo = request.getParameter("fechaResguardo");
String responsable = request.getParameter("responsable");
return bd.insertaEquipo(actFijo, numInv, descripcion, modelo, marca, numSerie, familia, tipoActivoFijo, proveedor, clase, uso, nivelObsolencia, estadoFisico, ubicacion, centroCosto, fechaResguardo, responsable);
} |
a75bb4be-9406-4130-97a4-74990eef5129 | 0 | public void addChatGuiListener(ChatGuiListener listener) {
chatGuiListener.add(listener);
} |
56418554-3865-45ba-9af6-2ab144ff6eb2 | 1 | public T pop() {
int length = size();
if (length == 0) {
throw new EmptyStackException();
}
return remove(length - 1);
} |
482cf3f5-4b12-4305-8e7b-ddc5170c6b55 | 9 | private void process_bmpcache2(RdpPacket_Localised data, int flags,
boolean compressed) throws RdesktopException, IOException {
Bitmap bitmap;
int y;
int cache_id, cache_idx_low, width, height, Bpp;
int cache_idx, bufsize;
byte[] bmpdata, bitmap_id;
bitmap_id = new byte[8]; /* prevent compiler warning */
cache_id = flags & ID_MASK;
Bpp = ((flags & MODE_MASK) >> MODE_SHIFT) - 2;
Bpp = Options.Bpp;
if ((flags & PERSIST) != 0) {
bitmap_id = new byte[8];
data.copyToByteArray(bitmap_id, 0, data.getPosition(), 8);
}
if ((flags & SQUARE) != 0) {
width = data.get8(); // in_uint8(s, width);
height = width;
} else {
width = data.get8(); // in_uint8(s, width);
height = data.get8(); // in_uint8(s, height);
}
bufsize = data.getBigEndian16(); // in_uint16_be(s, bufsize);
bufsize &= BUFSIZE_MASK;
cache_idx = data.get8(); // in_uint8(s, cache_idx);
if ((cache_idx & LONG_FORMAT) != 0) {
cache_idx_low = data.get8(); // in_uint8(s, cache_idx_low);
cache_idx = ((cache_idx ^ LONG_FORMAT) << 8) + cache_idx_low;
}
// in_uint8p(s, data, bufsize);
logger.info("BMPCACHE2(compr=" + compressed + ",flags=" + flags
+ ",cx=" + width + ",cy=" + height + ",id=" + cache_id
+ ",idx=" + cache_idx + ",Bpp=" + Bpp + ",bs=" + bufsize + ")");
bmpdata = new byte[width * height * Bpp];
int[] bmpdataInt = new int[width * height];
if (compressed) {
if (Bpp == 1)
bmpdataInt = Bitmap.convertImage(Bitmap.decompress(width,
height, bufsize, data, Bpp), Bpp);
else
bmpdataInt = Bitmap.decompressInt(width, height, bufsize, data,
Bpp);
if (bmpdataInt == null) {
logger.debug("Failed to decompress bitmap data");
// xfree(bmpdata);
return;
}
bitmap = new Bitmap(bmpdataInt, width, height, 0, 0);
} else {
for (y = 0; y < height; y++)
data.copyToByteArray(bmpdata, y * (width * Bpp),
(height - y - 1) * (width * Bpp), width * Bpp); // memcpy(&bmpdata[(height
// - y -
// 1) *
// (width
// *
// Bpp)],
// &data[y
// *
// (width
// *
// Bpp)],
// width
// *
// Bpp);
bitmap = new Bitmap(Bitmap.convertImage(bmpdata, Bpp), width,
height, 0, 0);
}
// bitmap = ui_create_bitmap(width, height, bmpdata);
if (bitmap != null) {
cache.putBitmap(cache_id, cache_idx, bitmap, 0);
// cache_put_bitmap(cache_id, cache_idx, bitmap, 0);
if ((flags & PERSIST) != 0)
PstCache.pstcache_put_bitmap(cache_id, cache_idx, bitmap_id,
width, height, width * height * Bpp, bmpdata);
} else {
logger.debug("process_bmpcache2: ui_create_bitmap failed");
}
// xfree(bmpdata);
} |
d17c3e5c-d45a-43da-bf20-2508258161d6 | 1 | private KeyEventHandler() {
registeredListeningObjects = new SynchronisedGameQueue<IKeyboardEventable>();
waitingEventLists = new ConcurrentHashMap<KeyEventType, Collection<EventHolder>>();
for (KeyEventType eventType : KeyEventType.values()) {
waitingEventLists.put(eventType, Collections.synchronizedList(new ArrayList<EventHolder>()));
}
currentlyDownKeys = new ArrayList<Integer>(10);
} |
51d427fa-e608-4814-99a0-385735e3e7a3 | 2 | public Animation getAnimationLeft(){
if(dead){
return death;
}
if (type == Type.CAT){
return catAnimLeftWalking;
} else {
return dogAnimLeftWalking;
}
} |
77b9fa25-50a8-4f4a-bd2b-a3283fc99fb4 | 5 | public static String stripLeading(final String string, final char ch) {
//// Preconditons
if (string == null)
throw new InvalidParameterException("string cannot be null");
int index = 0;
final int string_length = string.length();
if (string_length == 0)
return string;
while (true) {
if (string.charAt(index) != ch)
break;
else if (++index >= string_length)
break;
}
return string.substring(index);
} |
fb8364d5-493b-46de-b6f4-67f2dd616a78 | 8 | public static byte[] decodeBase64(byte[] base64Data) {
// RFC 2045 requires that we discard ALL non-Base64 characters
base64Data = discardNonBase64(base64Data);
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0) {
return new byte[0];
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex = 0;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD) {
if (--lastData == 0) {
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++) {
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD) {
//No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
} else if (marker0 == PAD) {
//Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
} else if (marker1 == PAD) {
//One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
} |
df9a2a91-ed9a-45b5-af94-07fd74d37508 | 3 | public void actionPerformed (ActionEvent e)
{
if (e.getSource() instanceof JButton)
{
//make new jframe asking "are you sure"
//if yes, client.disconnect
//if no, kill jframe and do nothing
JOptionPane sure = new JOptionPane ("Exit audiochat", JOptionPane.INFORMATION_MESSAGE);
int dave = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit audiochat?", "Exit Audiochat", JOptionPane.YES_NO_OPTION);
if (dave==0)
{
stopRunning();
}
else if (dave==1)
{
}
}
} |
191ee778-3ea4-4faf-b2e5-a0931e931c28 | 9 | private static void doCrypt(String in, String out, String pass, boolean encrypt, String encoding) throws IOException, InvalidEncodingException {
Cryptographer crypt = new CBCCryptographer();
CryptographerHandler bm = new CryptographerHandler(crypt);
verbosePrint("Using "+bm.getCryptoMode());
CryptStatus result = null;
verbosePrint("Opening file: " + in);
try {
bm.openFile(new File(in));
}
catch (OutOfMemoryError oome) {
System.err.println("Error: Out Of Memory! File too large");
System.exit(1);
}
Encoding enc = Encoding.toEnum(encoding);
if(!encoding.equals("default")) {
if(enc == null) {
throw new InvalidEncodingException("Invalid encoding: " + encoding);
}
else {
verbosePrint("Setting encoding to: "+enc.toString());
bm.setEncoding(enc);
}
}
if (pass == null) {
System.out.print("Enter password: ");
//Attempt to hide password input. Only works if the program is run from a true console
//Running from an IDE won't return a Console object, use Scanner in this case.
Console c = System.console();
try {
pass = new String(c.readPassword());
} catch (NullPointerException npe) {
pass = new Scanner(System.in).nextLine();
}
}
try {
if (encrypt) {
verbosePrint("Encrypting...");
result = bm.encrypt(pass);
} else {
verbosePrint("Decrypting...");
result = bm.decrypt(pass);
}
}
catch (OutOfMemoryError oome) {
System.err.println("Error: Out Of Memory! File too large");
System.exit(1);
}
if(result.equals(CryptStatus.DECRYPT_SUCCESS) || result.equals(CryptStatus.ENCRYPT_SUCCESS)) {
verbosePrint("Saving to: "+out);
bm.saveFile(new File(out));
}
System.out.println(result.toString());
} |
16d18052-66a4-4a0d-8822-73780270d7b2 | 1 | @Override
public void run() {
arr_data = History.showHistory();
data = new Object[arr_data.size()][];
for (int i = 0; i < arr_data.size(); i++) {
data[i] = arr_data.get(i).Array();
}
this.fireTableDataChanged();
} |
74213e9c-09d2-4139-9a2f-c92b2fb96e6d | 8 | private static String maskPassword(String proxyString) {
String retVal = proxyString;
if (proxyString != null && !"".equals(proxyString.trim())) {
boolean hasSchemeDefined = proxyString.contains("http:") || proxyString.contains("https:");
boolean hasProtocolDefined = proxyString.contains(DS);
boolean hasAtCharacterDefined = proxyString.contains(AT);
if (hasSchemeDefined && hasProtocolDefined && hasAtCharacterDefined) {
final int firstDoubleSlashIndex = proxyString.indexOf(DS);
final int lastAtCharIndex = proxyString.lastIndexOf(AT);
boolean hasPossibleURIUserInfo = firstDoubleSlashIndex < lastAtCharIndex;
if (hasPossibleURIUserInfo) {
final String userInfo =
proxyString.substring(firstDoubleSlashIndex + DS.length(), lastAtCharIndex);
final String[] userParts = userInfo.split(":");
if (userParts.length > 0) {
final int startOfUserNameIndex = firstDoubleSlashIndex + DS.length();
final int firstColonInUsernameOrEndOfUserNameIndex =
startOfUserNameIndex + userParts[0].length();
final String leftPart =
proxyString.substring(0, firstColonInUsernameOrEndOfUserNameIndex);
final String rightPart = proxyString.substring(lastAtCharIndex);
retVal = leftPart + ":***" + rightPart;
}
}
}
}
return retVal;
} |
331f09d8-289e-4a1f-a76d-905cf4be1cf1 | 7 | public void shootArrow(char x) {
if (running) {
if (x == 'A' || x == 'D') {
if (hunterLocation.y == wumpusLocation.y) {
hitWumpus = true;
}
} else if (x == 'W' || x == 'S') {
if (hunterLocation.x == wumpusLocation.x) {
hitWumpus = true;
}
}
hitSelf = true;
updateCurrentState();
}
} |
47279841-e0d2-4d3b-9fa6-453947b3655f | 7 | public Ticket in(Car car) {
if(isFull()) {
throw new ParkException("停车场已满,不能停车了。");
}
int num = this.parkBoyList.size();
if(this.park != null) {
num += 1;
}
Random random = new Random();
while(true) {
int i = random.nextInt(num);
if(i == 0 && !this.park.isFull()) {
return park.in(car);
} else if(i > 0) {
ParkBoy boy = this.parkBoyList.get(i - 1);
if(!boy.isFull()) {
return boy.in(car);
} else {
continue;
}
} else {
continue;
}
}
} |
39989c7e-1052-4c17-85b2-4e67f100cf39 | 0 | public TextFieldListener(JTextField field, Preference pref) {
setTextField(field);
setPreference(pref);
} |
99b81d52-bcc9-4f57-806e-46fe9d2fd9b4 | 6 | private void Load(String file)
{
BufferedReader reader;
try
{
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null)
{
if (!line.equalsIgnoreCase(""))
{
String[] p = line.split(" ");
Waypoint w = new Waypoint(Integer.valueOf(p[0]), Integer.valueOf(p[1]));
line = reader.readLine();
if (line != null && !line.equalsIgnoreCase(""))
{
p = line.split(" ");
for (String s : p)
w.addLink(Integer.valueOf(s));
}
waypoints.add(w);
}
}
reader.close();
}
catch (IOException ioe)
{
System.out.print("Erreur : ");
ioe.printStackTrace();
}
} |
dc5116e7-8f1d-4068-8768-d540696156ca | 3 | private List<String> GetZipNames(String projectName){
String zipArray="";
List<String> zipNames=new ArrayList<String>();
@SuppressWarnings("unchecked")
List<HierarchicalConfiguration> appList = SystemConfig.getInstance().configurationsAt("apps.app");
for (Iterator<HierarchicalConfiguration> iterator = appList.iterator(); iterator.hasNext();) {
HierarchicalConfiguration hierarchicalConfiguration = iterator.next();
zipArray = hierarchicalConfiguration.getString(projectName);
}
zipNameList=new ArrayList<String>();
zipNames=Arrays.asList(zipArray.split(" "));
for(String item : zipNames){ //加后缀
if(item.indexOf(".zip")==-1){
item+=".zip";
}
zipNameList.add(item);
}
return zipNameList;
} |
1bb7c456-c58d-4da3-859d-4ae0ea1fa58e | 4 | public void drawNewPoints() {
if (imageGfx == null) {
imageGfx = image.getGraphics();
}
if (activeTool == Tool.ERASER) {
imageGfx.setColor(Color.white);
} else {
if (color == null) imageGfx.setColor(Color.black);
else imageGfx.setColor(color);
}
for (Point p : pointsToDraw) {
imageGfx.fillOval(p.x - toolRadius, p.y - toolRadius, toolRadius, toolRadius);
}
} |
0697b593-1007-455a-9388-f3b4e47d4c7c | 0 | public int getX() {
return this.x;
} |
eaeed3e6-1320-4f53-b0da-4f97d95b65d0 | 3 | @Override
public void handleEvent(Event event) {
if (event.getType() == EventType.END_ACTION)
endActionUpdate();
else if (event.getType() == EventType.END_EFFECT)
if (isValidEndEffectEvent(event))
removeEffect();
} |
556fa186-0114-40bd-8df0-eb965903e72c | 8 | public boolean moveDown() {
// Block invalid moves
if (!canMoveDown)
return false;
boolean result = false;
for (int j = 0; j < dim; j++) {
for (int i = dim-2; i >= 0; i--) { // Can skip the bottom most row
// Skip empty tiles
if (isTileEmpty(i, j))
continue;
// Stepping indices
int k = i;
// Slide this value as far down as it will go
while (isValidLocation(k + 1, j) && isTileEmpty(k + 1, j) && moveTileDown(k, j)) {
k++;
result = true;
}
// If the tile came to rest above a tile with the
// same value, nullify it
if (canTilesMerge(k, j, k + 1, j)) {
mergeDown(k, j);
result = true;
}
}
}
return result;
} |
468a273d-17c6-4e0b-8640-18f74915aecd | 0 | public JustShoot() {
// addSequential(new Command() {
// public void initialize() {
// new SetColor(new Color(0,0,255)).start();
// }
// protected void execute() {}
// protected boolean isFinished() {
// return true;
// }
// protected void end() {}
// protected void interrupted() {}
// });
addSequential(new TiltSetDistance(Tilter.SPEED_DEFAULT, Vision.Distance.NEAR));
// Align the tilter with the target
// addSequential(new TargetPIDTilt(Target.ThreePT, 1.0, false));
// Shoot repeatedly (in case of jams)
addSequential(new Shoot());
addSequential(new Shoot());
addSequential(new Shoot());
addSequential(new Shoot());
addSequential(new Shoot());
addSequential(new Shoot());
// Stop shooting (not entirely necessary -- disabled mode would spin it
// down anyway)
addSequential(new SpinDown());
} |
70d36165-f8a6-422e-beed-8410a4afd337 | 9 | @Override
public short[] getTerrainData(int px, int pz, int sx, int sz)
{
short[] res = base.getTerrainData(px, pz, sx, sz);
for (int x = 0; x < sx; x++)
for (int z = 0; z < sz; z++)
{
int y;
int d = depth;
boolean paint = false;
for (y = Chunk.MAP_HEIGHT - 1; y >= 0; y--)
{
int i = z + sz * (x + sx * y);
if (res[i] == 0)
{
d = depth;
paint = y <= maxHeight && y >= minHeight;
}
else
{
if (d > 0 && (surfaceBlock == 0 || res[i] == surfaceBlock) && paint)
res[i] = overlayBlock;
d--;
}
}
}
return res;
} |
366513cd-8f05-43b0-b778-29d8b900d16c | 5 | public static void saveLifestone(String bWorld, int bX, int bY, int bZ) throws SQLException {// Block
// block
// String bWorld = block.getWorld().getName();
// int bX, bY, bZ;
// bX = block.getX();
// bY = block.getY();
// bZ = block.getZ();
String table = "Lifestones";
Connection con = getConnection();
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from `" + table + "` where `world` LIKE '" + bWorld + "' AND `x` LIKE " + bX + " AND `y` LIKE " + bY
+ " AND `z` LIKE " + bZ);
while (rs.next()) {
if (rs.getString("world").equalsIgnoreCase(bWorld)) {
if (rs.getInt("x") == bX && rs.getInt("y") == bY && rs.getInt("z") == bZ) {
// System.out.println("Lifestone already in DB!");
rs.close();
stat.close();
con.close();
return;
}
}
}
PreparedStatement prep = con.prepareStatement("insert into `" + table + "` (world, x, y, z) values (?, ?, ?, ?)");
prep.setString(1, bWorld);
prep.setInt(2, bX);
prep.setInt(3, bY);
prep.setInt(4, bZ);
prep.execute();
rs.close();
stat.close();
con.close();
} |
610900a7-7997-4a6b-aef7-e69d9079da84 | 6 | private void close(Connection conn, PreparedStatement stmt,
ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Exception ex) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception ex) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception ex) {
}
}
} |
d050cd4b-a215-4040-93ad-97162ae5cdca | 8 | public void load() {
try {
BufferedReader br = new BufferedReader(new FileReader("src/save.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.equals("max")) {
this.setMaxLevel(Integer.parseInt(br.readLine()));
}
if (line.equals("current")) {
this.setCurrentLevel(Integer.parseInt(br.readLine()));
}
if (line.equals("settings")) {
this.setSettings(Integer.parseInt(br.readLine()));
}
if (line.equals("screen")) {
this.setScreen(
new Vector2f(Float.parseFloat(br.readLine()), Float.parseFloat(br.readLine())));
}
if (line.equals("times")) {
this.setTimes(new ArrayList<>());
for (int i = 0; i < this.getMaxLevel(); i++) {
br.readLine();
this.getTimes().add(Float.parseFloat(br.readLine()));
}
}
}
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
} |
302b8092-26a4-46a2-a860-8a6dd454f557 | 6 | public void optField() {
Class<?> clazz;
try {
clazz = Class.forName("com.rock.reflect.User");
User u = (User) clazz.newInstance();
Field f = clazz.getDeclaredField("userName");
f.setAccessible(true);//设置为true后,可访问私有变量
System.out.println(f);
f.set(u, "rock");
System.out.println(u.getUserName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
} |
961b5159-5067-43c7-a3ca-d162656542e8 | 2 | public int getButton(int index) {
try {
if (buttonState[index])
return 255;
else
return 0;
} catch (Exception e) {
// this index doesn't exist, return 0;
return 0;
}
} |
f34dea67-a0be-4a70-bcec-4e1885463a1f | 1 | private Reader[] open(String... f) throws FileNotFoundException {
Reader[] r = new Reader[f.length];
for (int i = 0; i < r.length; i++) {
r[i] = new FileReader(this.getClass().getResource(f[i]).getFile());
}
return r;
} |
f4714284-b32b-4bbd-a9d4-80358a37dd38 | 3 | public Expression getValueBySlot(int slot) {
slot--; // skip this parameter (not an outer value)
for (int i = 0; i < headCount; i++) {
if (slot == 0) {
Expression expr = head[i];
if (i >= headMinCount)
headMinCount = i;
return expr;
}
slot -= head[i].getType().stackSize();
}
return null;
} |
4283ba4c-175a-4fe7-9f71-d5c884f65043 | 1 | @Override
public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException {
List paramList1 = new ArrayList<>();
List paramList2 = new ArrayList<>();
StringBuilder sb = new StringBuilder(UPDATE_QUERY);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_HOTEL_NAME, DB_HOTEL_NAME, criteria, paramList1, sb, COMMA);
Appender.append(DAO_HOTEL_STATUS, DB_HOTEL_STATUS, criteria, paramList1, sb, COMMA);
Appender.append(DAO_HOTEL_STARS, DB_HOTEL_STARS, criteria, paramList1, sb, COMMA);
Appender.append(DAO_HOTEL_PICTURE, DB_HOTEL_PICTURE, criteria, paramList1, sb, COMMA);
Appender.append(DAO_ID_DESCRIPTION, DB_HOTEL_ID_DESCRIPTION, criteria, paramList1, sb, COMMA);
Appender.append(DAO_ID_CITY, DB_HOTEL_ID_CITY, criteria, paramList1, sb, COMMA);
Appender.append(DAO_HOTEL_STATUS, DB_HOTEL_STATUS, criteria, paramList1, sb, COMMA);
sb.append(WHERE);
Appender.append(DAO_ID_HOTEL, DB_HOTEL_ID_HOTEL, beans, paramList2, sb, AND);
Appender.append(DAO_HOTEL_NAME, DB_HOTEL_NAME, beans, paramList2, sb, AND);
Appender.append(DAO_HOTEL_STATUS, DB_HOTEL_STATUS, beans, paramList2, sb, AND);
Appender.append(DAO_HOTEL_STARS, DB_HOTEL_STARS, beans, paramList2, sb, AND);
Appender.append(DAO_HOTEL_PICTURE, DB_HOTEL_PICTURE, beans, paramList2, sb, AND);
Appender.append(DAO_ID_DESCRIPTION, DB_HOTEL_ID_DESCRIPTION, beans, paramList2, sb, AND);
Appender.append(DAO_ID_CITY, DB_HOTEL_ID_CITY, beans, paramList2, sb, AND);
return sb.toString();
}
}.mapQuery();
paramList1.addAll(paramList2);
try {
return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn);
} catch (DaoException ex) {
throw new DaoQueryException(ERR_HOTEL_UPDATE, ex);
}
} |
4e4d9e5e-ae87-47e0-9fa3-22c5b152a046 | 6 | public String addBinary(String a, String b) {
int aLast = a.length() - 1;
int bLast = b.length() - 1;
String result = "";
int carry = 0;
while (aLast >= 0 || bLast >= 0) {
int aNum = 0, bNum = 0;
if(aLast >= 0) aNum = Character.getNumericValue(a.charAt(aLast));
if(bLast >= 0) bNum = Character.getNumericValue(b.charAt(bLast));
result = "" + (aNum + bNum + carry) % 2 + result;
if (aNum + bNum + carry > 1)
carry = 1;
else
carry = 0;
aLast--;
bLast--;
}
if(carry != 0){
result = "" + carry + result;
}
return result;
} |
9edbd3a7-052d-4ae5-b4c9-c29efece55bb | 0 | public int CalculateOffset(int oldaddress,int newaddress){
//Calculates offset in case of labels
int x=0;
x=(newaddress-oldaddress)/2-1;
return x;
} |
ae7a10f7-14ef-451a-a229-de4fa6d2715f | 2 | public static void loadProperties(String configPath) throws IOException {
properties = new Properties();
String path = (configPath == null) ? Constants.PROP_FILENAME : configPath;
try {
properties.load(new FileInputStream(path));
validateProperties();
logger.info("config.properties file loaded.");
} catch (IOException e) {
// properties file does not exist
Logger.getLogger(Properties.class.getName()).warn("Properties file not found.");
validateProperties();
properties.store(new FileOutputStream(path), null);
Logger.getLogger(Properties.class.getName()).info("New properties file created with default values.");
}
displayConfiguration();
} |
b6473096-bbb9-4cff-97e9-3a361f7e16cb | 1 | public void mouseMove(MouseEvent e)
{
for(UIContent content : Contents)
{
content.contentMouseMove(e);
}
} |
5c851d43-72a3-42d7-aa26-8437860cf39d | 7 | public static MoodleGroupUser[] getMembersFromGroupIds(long[] groupids) throws MoodleRestGroupException, UnsupportedEncodingException, MoodleRestException {
Vector v=new Vector();
MoodleGroupUser user=null;
StringBuilder data=new StringBuilder();
String functionCall=MoodleCallRestWebService.isLegacy()?MoodleServices.MOODLE_GROUP_GET_GROUP_MEMBERS:MoodleServices.CORE_GROUP_GET_GROUP_MEMBERS;
if (MoodleCallRestWebService.getAuth()==null)
throw new MoodleRestGroupException();
else
data.append(MoodleCallRestWebService.getAuth());
data.append("&").append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING)).append("=").append(URLEncoder.encode(functionCall, MoodleServices.ENCODING));
for (int i=0;i<groupids.length;i++) {
if (groupids[i]<1) throw new MoodleRestGroupException(); data.append("&").append(URLEncoder.encode("groupids["+i+"]", MoodleServices.ENCODING)).append("=").append(groupids[i]);
}
data.trimToSize();
NodeList elements=MoodleCallRestWebService.call(data.toString());
user=null;
for (int j=0;j<elements.getLength();j+=2) {
String content1=elements.item(j).getTextContent();
String content2=elements.item(j+1).getTextContent();
user=new MoodleGroupUser(Long.parseLong(content1),Long.parseLong(content2));
v.add(user);
}
if (user!=null)
v.add(user);
MoodleGroupUser[] users=new MoodleGroupUser[v.size()];
for (int i=0;i<v.size();i++) {
users[i]=(MoodleGroupUser)v.get(i);
}
v.removeAllElements();
return users;
} |
707b6272-cda2-4306-a185-091e3b7a036d | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
6958b37c-c220-4cf5-806e-87983f7ff93b | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
boolean isWateryEnough = CMLib.flags().isWateryRoom(mob.location());
if(!isWateryEnough)
{
if(mob.location().resourceChoices().contains(Integer.valueOf(RawMaterial.RESOURCE_FISH)))
isWateryEnough = true;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final String msgStr = isWateryEnough ?
L("^S<S-NAME> chant(s) and gaze(s) upon the waters.^?")
:L("^S<S-NAME> chant(s) and gaze(s) toward the distant waters.^?");
final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":msgStr);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.tell(mob.location().getArea().getTimeObj().getTidePhase(mob.location()).getDesc());
}
}
else
{
final String msgStr = isWateryEnough ?
L("^S<S-NAME> chant(s) and gaze(s) upon the waters, but the magic fizzles.^?")
:L("^S<S-NAME> chant(s) and gaze(s) toward the distant waters, but the magic fizzles.^?");
beneficialVisualFizzle(mob,null,msgStr);
}
return success;
} |
0f110caa-d7f1-498a-9677-4d6053226a6f | 0 | @Test(expected=IllegalArgumentException.class)
public void testGcdInvalidInput() {
// Integers must be non-negative
int q = 1;
int p = -5;
BasicMath.gcd(p, q);
} |
f4f4b367-0124-4566-9bb3-6eb94eb8c1f2 | 0 | public Client(){
} |
708c9211-e72e-40e8-bad5-b06871380840 | 3 | public void startDataConnection(Client c, String device) {
if ((activeClient != null) && (activeDevice != null)) {
stopDataConnection(activeClient, activeDevice);
}
c.startDataConnection(device);
activeClient = c;
activeDevice = device;
List<ClientChangedListener> copy = new ArrayList<ClientChangedListener>();
copy.addAll(listeners);
for (ClientChangedListener listener : copy) {
listener.deviceConnected(c, device);
}
} |
953913f6-a734-4a00-a01b-82b684961748 | 2 | public void mapSize() {
carte = new Map();
JLabel labels[] = new JLabel[(19 * 49)];
String bufferMap = carte.lire("./ressources/map.txt");
for (int i = 0, j = 0; i < bufferMap.length(); i++) {
if (bufferMap.charAt(i) != '\n') {
colonne = i;
}
ligne++;
}
} |
702a6697-fa60-43ec-a729-8a2e08ad8885 | 8 | public void drawWindow(RenderEngine renderEngine, FontRenderer fontRenderer) {
if (!(this instanceof SceneScreen)) {
if (this instanceof IRendersEventProvider) {
IRendersEventProvider provider = (IRendersEventProvider) this;
provider.preRenderScreen(renderEngine, fontRenderer);
} else {
renderEngine.bindMaterial(backgroundImage);
renderEngine.renderQuad(10, 10, GameApplication.getScreenWidth() - 20, GameApplication.getScreenHeight() - 20);
}
}
renderScreen(renderEngine, fontRenderer);
for (IScreenComponent g : screenComponents) {
if (g != null)
g.renderComponent(renderEngine, fontRenderer);
}
if (theGame.gameSettings.showFPS) {
fontRenderer.setRenderingSize(4);
fontRenderer.setRenderingColor(ColorHelper.RED);
fontRenderer.renderString("FPS : " + theGame.getGameFPS(), 0, 50);
}
if (displayedMessage != null) {
displayedMessage.renderMessage(renderEngine, fontRenderer);
}
if (!(this instanceof SceneScreen)) {
if (this instanceof IRendersEventProvider) {
IRendersEventProvider provider = (IRendersEventProvider) this;
provider.postRenderScreen(renderEngine, fontRenderer);
}
}
} |
d1954bb8-3f12-4223-ae1f-fea5e9f1c43f | 5 | @Override
public void paintComponent(Graphics G){
super.paintComponent(G);
if(started){
//button building
G.drawImage(BuildImages[0], 578, 0, null);
G.drawImage(BuildImages[1], 578, 80, null);
//G.drawImage(BuildImages[2], 578, 498, null);
G.drawString("", 646, 505);
//selected image and button drawing
if(!terrainFlag)
G.drawImage(GameImages[6], mouseX*24, mouseY*24, null);
if(buttonSelected){
if(selection.equals("MG"))
G.drawImage(BuildImages[2], 578, 0, null);
else if (selection.equals("LA"))
G.drawImage(BuildImages[2], 578, 80, null);
}
this.repaint();
}//end if(started)
}//end paintComponent |
881af849-1725-4ab7-8015-fa69c7eb8d74 | 6 | public static void main(String[] args) {
try {
ConfigManager configManager = new ConfigManager();
Map<String, ConfigEntry> config = new HashMap<>();
if (!configManager.loadConfig(config)) {
System.out.println("Invalid configuration file!");
return;
}
if (args.length == 0) {
System.out.println("Database name expected!");
return;
}
boolean found = false;
for (int i = 0; i < args.length; ++i) {
String dbName = args[i].toUpperCase();
ConfigEntry configEntry = config.get(dbName);
if (configEntry != null) {
found = true;
process(dbName, configEntry);
}
}
if (!found) {
System.out.println("Configuration not found, for specified database name!");
}
} catch (Exception ex) {
LOGGER.error("main", ex);
}
} |
c3279624-4e3d-406e-ba2a-e74d45b97716 | 5 | public int[] getComplexErrorCodes() {
Map<String, String> allFields = getFields();
List<Integer> errorCodeList = new ArrayList<Integer>();
for (Entry<String, String> field : allFields.entrySet()) {
String fieldKey = field.getKey();
if (fieldKey.startsWith("Errors.")) {
int nextDot = fieldKey.indexOf('.', 7);
if (nextDot > -1) {
int errorCode = FcpUtils.safeParseInt(fieldKey.substring(7, nextDot));
if (errorCode != -1) {
errorCodeList.add(errorCode);
}
}
}
}
int[] errorCodes = new int[errorCodeList.size()];
int errorIndex = 0;
for (int errorCode : errorCodeList) {
errorCodes[errorIndex++] = errorCode;
}
return errorCodes;
} |
c6b04bbe-50c2-4b4b-8f6d-30bec246f2c7 | 0 | public String getPhone() {
return Phone;
} |
405d1d6a-2f8d-42e3-8c83-beaa3e86891e | 3 | public void run() {
System.out.println("Enter Portal");
if(Util.WalkToAndClick("Enter", Util.portals)) {
int time = 0;
while(validate() && time <= 5000) {
time += 50;
Time.sleep(50);
}
}
} |
c200bf26-1852-4df8-b41d-dd4e8b36c822 | 0 | public Command(String _name, String _command, int _numParams, String _help) {
this.name = _name;
this.command = _command;
this.numParameters = _numParams;
this.helpMessage = _help;
} |
d02a3ed1-7b36-47e9-b8fa-ed582261e725 | 8 | public static WordLocation parseWordLocation(String obj) {
WordLocation wl = new WordLocation();
String data[] = obj.split("\n");
if( data.length != 2)
return null;
String tokens[] = data[0].split("[=]|[\\{]|[\\}]|[,]");
try {
if(data[0].indexOf("WordLocation") != -1 || tokens.length > 0) {
for( int i = 0; i<tokens.length; i++ ) {
if(tokens[i].indexOf("word")!=-1)
wl.setWord(tokens[i+1].trim());
else if(tokens[i].indexOf("fileName")!=-1)
wl.setFileName(tokens[i+1].trim());
else if(tokens[i].indexOf("location")!=-1)
wl.setLocations(parseLocation(tokens[i+1]));
}
wl.setBook(Book.parseBook(data[1]));
wl.setCount(wl.getLocations().size());
}
else {
logger.warn("WordLocation:Invalid Record read " + data);
}
}
catch(Exception ex)
{
logger.error("WordLocation: Error Record read " + data);
ex.printStackTrace();
}
return wl;
} |
59f223c1-58ec-4af7-ac06-ebc8c99e5143 | 4 | public void setInfo(String info) {
// レコード情報設定
this.info = info;
String[] tmp = info.split(";");
// 化合物名設定
this.name = tmp[0].trim();
// ソート用化合物名設定
this.sortName = tmp[0].trim();
// 付加情報設定
StringBuffer addition = new StringBuffer();
for (int i=0; i<tmp.length; i++) {
if (i==0) {
continue;
}
addition.append(tmp[i].trim());
if (i != (tmp.length-1)) {
addition.append("; ");
}
}
this.addition = addition.toString();
// ソート用付加情報設定
this.sortAddition = addition.toString();
// リンク用親ノード名設定
final int maxLinkStr = 50;
if (tmp[0].trim().length() > maxLinkStr) {
StringBuffer parentLink = new StringBuffer();
parentLink.append(tmp[0].trim().substring(0, maxLinkStr));
parentLink.append("...");
this.parentLink = sanitize(parentLink.toString());
}
else {
this.parentLink = sanitize(tmp[0].trim());
}
// リンク用子ノード名設定
this.childLink = sanitize(addition.toString());
} |
8653623c-67de-4f95-b348-84bdc1ebf1af | 5 | public void actionPerformed(java.awt.event.ActionEvent event)
{
Object object = event.getSource();
if (object == JButton_Exit)
JButtonExit_actionPerformed(event);
else if (object == JButton_NewCCAccount)
JButtonNewCCAC_actionPerformed(event);
else if (object == JButton_GenBill)
JButtonGenerateBill_actionPerformed(event);
else if (object == JButton_Deposit)
JButtonDeposit_actionPerformed(event);
else if (object == JButton_Withdraw)
JButtonWithdraw_actionPerformed(event);
} |
59ba4e3d-e9a8-4e7f-9e3d-b3accbeacad8 | 0 | public String getTitle() {
return title;
} |
423210e0-bb01-4779-84b1-79d8132d5356 | 1 | public void addTreasureChest(TreasureChest chest)
{
if(possibleTreasures.contains(chest)) return;
possibleTreasures.add(chest);
} |
0ee59f62-240c-4b9d-8766-9ea5a94b9752 | 3 | @Test
public void testRunStartServerInvalidSpot()throws Exception{
AccessControlServer server = new AccessControlServer(1930);
server.start();
SpotStub spot = new SpotStub("999",1930);
spot.start();
sleep(1000);
String ans = "";
int x = 0;
while(x != -1 && x<=50){ //if no response is recieved in 10 seconds, test is deemed failed.
x++;
ans = spot.getAnswer();
sleep(100);
if(ans != ""){
x = -1;
}
}
assertNotEquals("",ans);
} |
583622db-955c-4200-b537-d7e1940696e2 | 2 | int nextDescriptorOffset (int offset)
{
if (data.length < offset)
return -1;
offset += 0xff & data [offset];
if (data.length <= (offset + 2))
return -2;
return offset;
} |
24be8369-b801-4dc3-a19b-6ac437f80499 | 1 | public void testLeapYearRulesConstructionInvalid() {
// 1500 not leap in Gregorian, but is leap in Julian
try {
new DateMidnight(1500, 2, 30, GJChronology.getInstanceUTC());
fail();
} catch (IllegalFieldValueException ex) {
// good
}
} |
8de34469-c092-40b3-a77c-26edbc60a4cd | 7 | @Override
public void run() {
try{
_user = new ClientUDP();
_user.sendToServer(new MessageUDP(_CSName, _CSPort, Protocol.LIST + "\n"));
System.out.println(">> Sent list");
_bufferUDP = _user.receiveFromServer();
_arguments = _bufferUDP.getMessage().split(" ");
if(_arguments[0].equals(Protocol.LIST_RESPONSE)){
if(_arguments.length > 4){
User.setSS(_arguments[1], Integer.parseInt(_arguments[2]));
int numFiles = Integer.parseInt(_arguments[3]);
System.out.println("Available files for download:");
for(int i = 1; i <= numFiles; i++){
System.out.println(i + " " + _arguments[3+i]);
}
}
}
else if(_arguments[0].startsWith(Protocol.ERROR)){
System.out.println(Errors.INVALID_PROTOCOL);
System.exit(-1);
}
else if(_arguments[0].startsWith(Protocol.EOF)){
System.out.println(Errors.SERVER_BUSY);
}
else{
System.out.println(Errors.INVALID_COMMAND);
}
} catch (IOException e){
e.printStackTrace();
System.err.println(Errors.IO_PROBLEM);
System.exit(-1);
} finally{
try {
_user.close();
} catch (IOException e) {
System.err.println(Errors.IO_PROBLEM);
System.exit(-1);
}
}
} |
70301275-370d-46f3-a28a-6f8cdebcc6d8 | 0 | public void setjLabelBilan(JLabel jLabelBilan) {
this.jLabelBilan = jLabelBilan;
} |
ff996d02-0430-43e8-b8d4-fc685bade12e | 6 | public String getLyricsWebPage(String artistName,String songName){
try {
if (artistName.equals(null) || artistName.equals("") || songName.equals(null) || songName.equals(""))
return null;
String url = buildUrl(artistName,songName);
Document document = reader.read(url);
// XMLUtil.writeToFile(document, artistName + " - " + songName + ".xml");
Element root = document.getRootElement(); //LyricsResult element
Element pageIdElement = root.element("page_id"); // page_id element
String pageId = pageIdElement.getText();
if(pageId.equals("")){ //there is NOT lyrics page
System.out.println("No lyrics page.");
return null;
}
else
return root.element("url").getText();
} catch (Exception e) {
return null;
//e.printStackTrace();
}
} |
6c5d30ae-16dc-4486-8c8b-fb7e12578442 | 9 | public void readParams() throws IOException {
Set<String> allParams = paramsSet();
// Read normal non-multipart params.
for (String name : allParams) {
if (!mParent.isParameterSet(name)) {
continue;
}
mParamTable.put(name, mParent.getParam(name).getBytes(IOUtil.UTF8));
//System.err.println("Set Param: " + name + " : " + mParamTable.get(name));
}
// Then read multipart params if there are any.
try {
for (String part : mParent.getParts()) {
if (!allParams.contains(part)) {
continue;
}
// Special case file posts.
if (part.equals("upload")) {
HTTPUploadedFile uploadedFile = mParent.getUploadedFile(part);
Bucket bucket = uploadedFile.getData();
try {
byte[] data = IOUtil.readAndClose(bucket.getInputStream());
if (data == null) {
throw new IOException("Couldn't read uploaded file data from bucket.");
}
if (data.length > WikiApp.MAX_POST_LENGTH) {
throw new IOException("Uploaded file too big.");
}
mParamTable.put(part, data);
mParamTable.put(part + ".filename", uploadedFile.getFilename().getBytes(IOUtil.UTF8));
} finally {
bucket.free();
}
} else {
byte[] value = mParent.getPartAsBytesFailsafe(part, 128 * 1024);
mParamTable.put(part, value);
}
// Can fail if value isn't utf-8
// System.err.println("Set multipart Param: " + part + " : " +
// mParamTable.get(part));
}
if (!mParamTable.containsKey("action")) {
//System.err.println("Forced default action to view");
mParamTable.put("action", "view".getBytes(IOUtil.UTF8));
}
if (!mParamTable.containsKey("title")) {
mParamTable.put("title", mPath.getBytes(IOUtil.UTF8));
}
} finally {
mParent.freeParts();
}
} |
a7b39e4f-e56b-4c34-9074-3fd87cb92b37 | 7 | Photon emit(Atom atom) {
Electron e = atom.getElectron(0);
if (e == null)
return null;
ElectronicStructure es = model.getElement(atom.id).getElectronicStructure();
int m = es.indexOf(e.getEnergyLevel());
if (m == 0)
return null; // electron already in the ground state
if (!e.readyToGo(model.getModelTime())) // the electron is just excited
return null;
// assume that the probability for the electron to transition to any lower state is equal
float prob = 1.0f / m;
double r1 = Math.random(); // the random number used to select a lower state
double r2 = Math.random(); // the random number used to select a transition mechanism
EnergyLevel level;
float excess;
for (int i = 0; i < m; i++) {
if (r1 >= i * prob && r1 < (i + 1) * prob) {
level = es.getEnergyLevel(i);
excess = e.getEnergyLevel().getEnergy() - level.getEnergy();
/* emit a photon */
if (r2 > model.quantumRule.getProbability(QuantumRule.RADIATIONLESS_TRANSITION)) {
e.setEnergyLevel(level);
return new Photon((float) atom.rx, (float) atom.ry, excess / MDModel.PLANCK_CONSTANT);
}
break;
}
}
return null;
} |
e1d30736-f83b-4e21-9b56-5adbf2543211 | 1 | public int unwrapInteger() {
if (!isInteger) { //If not integer, return floatingPointOperand cast to int (fraction part lost)
int castIntOperand = (int) floatingPointOperand; //Create temporary value so as not to overwrite true value
return castIntOperand;
}
return intOperand;
} |
015b0354-0bbf-44fa-ab5a-2574ffde27fb | 3 | public Key keyOf(int i) {
if (i < 0 || i >= NMAX) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
else return keys[i];
} |
28116d55-fd98-4ae6-8b11-baac7e36d850 | 5 | @Override public boolean getOption(String opname){
if(opname == "Ages"){ return ages;}
if(opname == "Fades"){ return fades;}
if(opname == "Any"){return any;}
if(opname == "All"){return all;}
if(opname == "Mirror"){ return mirror;}
return false;} |
8273f78e-7614-453f-9296-dd256412ca98 | 5 | public final void update(Level level, int x, int y, int z, Random rand) {
int var6 = level.getTile(x, y - 1, z);
if(level.isLit(x, y, z) && (var6 == DIRT.id || var6 == GRASS.id)) {
if(rand.nextInt(5) == 0) {
level.setTileNoUpdate(x, y, z, 0);
if(!level.maybeGrowTree(x, y, z)) {
level.setTileNoUpdate(x, y, z, this.id);
}
}
} else {
level.setTile(x, y, z, 0);
}
} |
57abfd99-9af0-42ad-809e-4c105b6f84a5 | 4 | protected Constructor<? extends T> getCtor() {
if(ctor == null)
try {
ctor = projectileType.getDeclaredConstructor(actor.Actor.class);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return ctor;
} |
53541928-5cf3-45b9-946c-71eefd75e6de | 7 | @Override
public boolean okMessage(Environmental host, CMMsg msg)
{
if((msg.source()!=affected)
&&((msg.target()==pocket)||(msg.tool()==pocket))
&&(CMath.bset(msg.sourceMajor(),CMMsg.MASK_HANDS)
||CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOVE)
||CMath.bset(msg.sourceMajor(),CMMsg.MASK_DELICATE)
||CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOUTH)))
{
msg.source().tell(L("The dark pocket draws away from you, preventing your action."));
return false;
}
return true;
} |
64c428f8-9407-4095-a98f-fba531d03205 | 1 | public JSONObject getJSONObject(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a JSONObject.");
} |
1c6a75e8-ff00-42de-b178-04c29e223870 | 5 | public void reloadConfig() {
if (configFile == null) {
configFile = new File(master.getDataFolder(), configFileName);
}
config = YamlConfiguration.loadConfiguration(configFile);
if (configFileName.equals("localization.yml")) {
InputStream defDataConfigStream = master.getResource("localization.yml");
if (defDataConfigStream != null) {
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defDataConfigStream);
try {
defConfig.save(configFile);
config.load(configFile);
config.save(configFile);
} catch (IOException e1) {
e1.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
} |
71a1c637-62ed-4ae0-880e-5ae63d001c56 | 3 | static int getFactor(final double d, final int max)
{
if (d == 0)
{
return 0;
}
int factor = 0;
do
{
final double scale = getDScale(factor);
final double scaled = d * scale;
if (scaled == (long) scaled)
{
return factor;
}
else
{
factor++;
}
}
while (factor < max);
return max;
} |
e8b21217-c27e-4391-a278-18528a4d0a17 | 8 | public void testValidityOfRanks() {
FiveEval fiveEval = new FiveEval();
System.out.println("testing ranks...\n");
for (int i = 6; i < 52; i++) {
for (int j = 5; j < i; j++) {
for (int k = 4; k < j; k++) {
System.out.println("" + i + "_" + j + "_" + k + "\n");
for (int l = 3; l < k; l++) {
for (int m = 2; m < l; m++) {
for (int p = 1; p < m; p++) {
for (int q = 0; q < p; q++) {
int rankOne = fiveEval.getBestRankOf(i, j,
k, l, m, p, q);
int rankTwo = this.getRankOf(i, j, k, l, m,
p, q);
if (rankOne != rankTwo) {
System.out.println("\n" + rankOne + "_"
+ rankTwo + "::" + i + "_"
+ "_" + j + "_" + k + "_" + l
+ "_" + m + "_" + p + "_" + q);
return;
}
}
}
}
}
}
}
}
System.out.println("SevenEval and FiveEval agree everywhere.");
} |
f90851b6-2792-48ac-befc-2f77ca7b9d78 | 1 | public static void isNull(Object object, String message) {
if (object != null) {
throw new IllegalArgumentException(message);
}
} |
bad480c8-804b-4537-8830-28948e306e87 | 5 | final String _readValue_() throws IOException, IllegalArgumentException {
final Reader source = this._reader_;
final StringBuilder result = this._builder_;
result.setLength(0);
while (true) {
int symbol = source.read();
switch (symbol) {
case -1:
case '\r':
case '\n':
return result.toString();
case '\\':
symbol = this._readSymbol_(source.read());
}
result.append((char)symbol);
}
} |
1b5a5411-2b5a-4314-abb6-0052cf97bfa6 | 0 | public void listRoot() throws IOException {
this.list("/");
} |
71a1aad6-4cc5-4926-8476-e39ac510b3b4 | 2 | public static boolean isHighScore(int score){
Integer scorez = 0;
for(int i = 0; i < 5; i++){
scorez = Integer.parseInt(topScores[i][1]);
if(score > scorez){
return true;
}
}
return false;
} |
99b9a84c-f8cc-446f-baff-d81d56751fc4 | 8 | public Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
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 = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} |
68cd49df-4d16-4897-b90c-e47ebf721ffc | 5 | public void mouseExited(MouseEvent paramMouseEvent) {
if (ImageButton.this.Enabled)
{
if (ImageButton.this.MouseOverImage != null)
{
if ((ImageButton.this.On) && (ImageButton.this.OnImage != null))
ImageButton.this.rawSetImage(ImageButton.this.OnImage);
else {
ImageButton.this.rawSetImage(ImageButton.this.NormalImage);
}
}
if (ImageButton.this.VerboseEvents)
ImageButton.this.event(paramMouseEvent);
}
} |
9d5e1d00-44fc-4b65-beb7-27a2e62d5e99 | 4 | private boolean winCheck() {
String winner = Resolution.resolutionWinCheck();
if(winner.equals("X")){
JOptionPane.showMessageDialog(null, "X wins the game!", "Winner", 0);
return true;
}
else if(winner.equals("O")){
JOptionPane.showMessageDialog(null, "O wins the game!", "Winner", 0);
return true;
}
else{
for(int i = 0; i < playedNodes.length; i++){
if(playedNodes[i] == null){
return false;
}
}
JOptionPane.showMessageDialog(null, "It's a cat game!", "Tie", 0);
}
return true;
} |
b31cddd6-d7e4-4c88-b1a5-b3eb5b59b31e | 4 | private void neuMalen(Graphics2D g) {
g.setColor(Color.WHITE);
g.scale(zoom, zoom);
g.fillRect(0, 0, (int) (rahmen.getWidth() / zoom),
(int) (rahmen.getHeight() / zoom));
g.setColor(Color.BLACK);
try {
for (Geo geo : statisch) {
geo.zeichnen(g);
}
} catch (Exception e) { // u. a.
// ConcurrentModificationException
}
try {
for (Geo geo : beweglicheObjekte.values()) {
geo.zeichnen(g);
}
} catch (Exception e) { // u. a.
// ConcurrentModificationException
}
brett.requestFocus(); // damit immer auf Tasten reagiert
// wird
} |
85b41c7a-4e11-4059-9084-dad83bcb88e8 | 7 | public static int findFloor(int[] input, int start, int end, int k) {
if(k < input[start]){
return -1;
}
if(k > input[end]){
return input[end];
}
int mid = (start +end)/2;
if(input[mid]<=k && input[mid+1] > k){
return input[mid];
}
if(input[mid] > k ){
return findFloor(input,start,mid-1,k);
}
if(input[mid]<k && input[mid+1] < k) {
return findFloor(input,mid+1,end,k);
}
return -1;
} |
6c2b4285-a5ef-4e23-a694-1fd48050d672 | 2 | private void deleteCard(){
int i;
System.out.println("----------- Delete a Card -----------");
System.out.print("Enter the index of the card you want to delete (start at 0): ");
i = sc.nextInt();
sc.nextLine();
if(i >= 0 && i <= this.deck.numberOfCards() - 1){
this.deck.deleteCard(i);
System.out.println("Card deleted !\n");
}
} |
cead1a99-4bbd-41ce-acee-980f4c8fcb05 | 2 | public ZFrame pop() {
if (frames == null)
frames = new ArrayDeque<ZFrame>();
try {
return frames.pop();
} catch (NoSuchElementException e) {
return null;
}
} |
91c47a55-6333-4313-bb6d-5082a89b8409 | 3 | private String stackTraceString(Exception e){
StringWriter stackString = new StringWriter();
int depth = 0;
for(StackTraceElement element : e.getStackTrace()){
stackString.write("\t");
for (int i = 0 ; i <= depth ; i++){
stackString.write(" ");
}
stackString.write(element.getClassName() + ":" + element.getMethodName());
if (element.getFileName() != null){
stackString.write(" - in file " + element.getFileName());
}
stackString.write("\n");
depth++;
}
return stackString.toString();
} |
e0567eeb-9157-4276-ad65-2fffe74a8288 | 0 | public void setVerdes(int verdes) {
this.verdes = verdes;
} |
a6e4f133-9daf-4f0b-9ebe-b0ef11cb4c1e | 3 | static double[][] inverse(double[][] A){
double[][] B;
double detA = det(A);
if(A.length == 1){
B = new double[1][1];
B[0][0] = 1/detA;
}else{
B = new double[A.length][A.length];
B = transpose(cofactor(A));
for(int i = 0; i < B.length; i++){
for(int j = 0; j < B.length; j++){
B[i][j] = B[i][j]/detA;
}
}
}
return B;
} |
38fe65bc-bc41-4d14-b2de-5ad5e633608c | 9 | public void cambiarCasilla(Casilla casilla, int type){
if(type != 7 && type != 5 && type != 6)
porcentajeObstaculos = (float) (porcentajeObstaculos + (100.0 / ((float) size_tablero_F * (float) size_tablero_C)));
if( (type == 7 || type == 5 || type == 6) && casilla.get_type() != 7 && casilla.get_type() != 5 && casilla.get_type() != 6)
porcentajeObstaculos = (float) (porcentajeObstaculos - (100.0 / ((float) size_tablero_F * (float) size_tablero_C)));
casilla.set_type(type, WIDTH/size_tablero_F,HEIGHT/size_tablero_C);
} |
e7625b8d-520d-4b47-8e29-32a14c1ba845 | 2 | @Override
public void show_PortA(Integer value) {
PIC_Logger.logger.info("Showing Port A");
int x=7;
for(int i = 0; i < 8; i++){
if( (value & (int)Math.pow(2, i)) == (int)Math.pow(2, i)){
regA.setValueAt(1, 1, x+1);
}
else{
regA.setValueAt(0, 1, x+1);
}
x--;
}
} |
8619a934-d244-4fb0-8595-38d03864e9a8 | 3 | void createChildWidgets() {
/* Add common controls */
super.createChildWidgets();
/* Add TableEditors */
comboEditor = new TableEditor(table);
nameEditor = new TableEditor(table);
table.addMouseListener (new MouseAdapter() {
public void mouseDown(MouseEvent e) {
resetEditors();
index = table.getSelectionIndex();
if (index == -1) return;
//set top layer of stack to the selected item
setTopControl (index);
TableItem oldItem = comboEditor.getItem();
newItem = table.getItem(index);
if (newItem == oldItem || newItem != lastSelected) {
lastSelected = newItem;
return;
}
table.showSelection();
combo = new CCombo(table, SWT.READ_ONLY);
createComboEditor(combo, comboEditor);
nameText = new Text(table, SWT.SINGLE);
nameText.setText(((String[])data.elementAt(index))[NAME_COL]);
createTextEditor(nameText, nameEditor, NAME_COL);
}
});
} |
ce4b1f30-ade1-40cb-ac4f-5663452cbff2 | 6 | public List<String> anagrams(String[] strs) {
List<String> result = new ArrayList<String>();
if (strs == null || strs.length == 0)
return result;
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String str : strs) {
char[] strChars = str.toCharArray();
Arrays.sort(strChars);
String tmp = new String(strChars);
if(map.containsKey(tmp)){
map.get(tmp).add(str);
}else{
List<String> list = new ArrayList<String>();
list.add(str);
map.put(tmp, list);
}
}
for(java.util.Map.Entry<String, List<String>> entry : map.entrySet()){
if(entry.getValue().size()>1){
result.addAll(entry.getValue());
}
}
return result;
} |
55f44b11-621f-43d0-9c64-b125985121db | 7 | private JPopupMenu getTabsPopupMenu() {
JPopupMenu popup = new JPopupMenu("Tabs");
// Tabs -> Part
JMenuItem menuItemPart = new JMenuItem("Part");
menuItemPart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = getSelectedComponent();
if (!(component instanceof ConsolePanel)) {
String chan = ((PanelTemplate)component).getWindowName();
if (isConnected() && component instanceof ChanPanel)
conn.doPart(chan);
else if (component instanceof QueryPanel)
closePanel(chan);
}
}
} );
popup.add(menuItemPart);
// Tabs -> Close (Force)
JMenuItem menuItemClose = new JMenuItem("Force Close");
menuItemClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = getSelectedComponent();
if (!(component instanceof ConsolePanel)) {
String chan = ((PanelTemplate)component).getWindowName();
if (isConnected() && component instanceof ChanPanel)
conn.doPart(chan);
closePanel(chan);
}
}
} );
popup.add(menuItemClose);
return popup;
} |
34bbac6d-3ea8-496b-889d-9661d03b8feb | 9 | private int validateInsert()
{
try
{
int receiptID;
int upc;
int quantity;
if (returnID.getText().trim().length() != 0 && isNumeric(returnID.getText().trim()))
{
receiptID = Integer.valueOf(returnID.getText().trim()).intValue();
} else {
return VALIDATIONERROR;
}
if (itemUPC.getText().trim().length() != 0 && isNumeric(itemUPC.getText().trim()))
{
upc = Integer.valueOf(itemUPC.getText().trim()).intValue();
// check for duplicates
if (returnItem.findReturnItem(receiptID, upc))
{
Toolkit.getDefaultToolkit().beep();
mvb.updateStatusBar("ReturnItem (" + receiptID + "," + upc + ") already exists!");
return OPERATIONFAILED;
}
}
else
{
return VALIDATIONERROR;
}
if (itemQuantity.getText().trim().length() != 0 && isNumeric(itemQuantity.getText().trim()))
{
quantity = Integer.valueOf(itemQuantity.getText().trim()).intValue();
}
else
{
return VALIDATIONERROR;
}
mvb.updateStatusBar("Inserting returnItem...");
if (returnItem.insertReturnItem(receiptID, upc, quantity))
{
mvb.updateStatusBar("Operation successful.");
showAllReturnItems();
return OPERATIONSUCCESS;
}
else
{
Toolkit.getDefaultToolkit().beep();
mvb.updateStatusBar("Operation failed.");
return OPERATIONFAILED;
}
}
catch (NumberFormatException ex)
{
// this exception is thrown when a string
// cannot be converted to a number
return VALIDATIONERROR;
}
} |
8a59c8a5-b72f-41ec-b05d-b5e2b580a7b9 | 3 | public Boolean readBit() throws IOException{
if(buffer==-1)
return null;
if(bufferFilled==0){
buffer = in.read();
if(buffer==-1)
return null;
bufferFilled = 7;
}
else
bufferFilled--;
boolean ret = (buffer&128)>0;
buffer<<=1;
return ret;
} |
a8a0eed7-1b66-43b1-8a19-e2742e7eb030 | 3 | protected void buildIntervals(IntervalsBuilder<T> builder) {
// go throug map and create intervals as numbers goes
for (Iterator<Map.Entry<T, Boolean>> it = setMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<T, Boolean> object = it.next();
// start
if (object.getValue() && it.hasNext()) {
Map.Entry<T, Boolean> end = it.next();
builder.add(object.getKey(), end.getKey());
}
}
} |
f3014ac2-26a7-4f36-9ec0-20ded65896fe | 5 | @EventHandler(priority = EventPriority.LOWEST)
public void onEnchantAttempt(PrepareItemEnchantEvent e) {
final World world = e.getEnchantBlock().getWorld();
for (String worldname : WorldSettings.worlds) {
if (Settings.world || world.getName() == worldname) {
if (Settings.totalenchant
&& !PermissionHandler.has(e.getEnchanter(),
PermissionNode.ALLOW_ENCHANTING)) {
e.setCancelled(true);
e.getEnchanter()
.sendMessage(
ChatColor.GREEN
+ "[EM]"
+ ChatColor.RED
+ " You dont have permission to enchant items!");
alert(e);
}
}
}
} |
b3954998-62cb-4f74-b296-5d350c9eb76a | 8 | public byte[] CreateAnswerPacket(byte[] Qpacket,String adrr){
System.out.println("Le packet QUERY recu");
for(int i = 0;i < Qpacket.length;i++){
if(i%16 == 0){
System.out.println("\r");
}
System.out.print(Integer.toHexString(Qpacket[i] & 0xff).toString() + " ");
}
System.out.println("\r");
//copie les informations dans un tableau qui est utilis� de buffer
//durant la modification du packet
byte[] Querypacket = new byte[1024];
for(int i = 0; i < Qpacket.length; i++){
Querypacket[i] = Qpacket[i];
}
//Conversion de l'adresse IP de String � byte
adrr = adrr.replace("."," ");
String[] adr = adrr.split(" ");
byte part1 = 0;
byte part2 = 0;
byte part3 = 0;
byte part4 = 0;
part1 = (byte)(Integer.parseInt(adr[0]) & 0xff);
part2 = (byte)(Integer.parseInt(adr[1]) & 0xff);
part3 = (byte)(Integer.parseInt(adr[2]) & 0xff);
part4 = (byte)(Integer.parseInt(adr[3]) & 0xff);
System.out.println("Construction du packet ANSWER");
//modification de l'identifiant
Querypacket[0] = (byte)Qpacket[0];
Querypacket[1] = (byte)Qpacket[1];
//modification des param�tres
//Active le champ reponse dans l'en-t�te
Querypacket[2] = (byte) 0x81;
Querypacket[3] = (byte) 0x80;
Querypacket[4] = (byte) 0x00;
Querypacket[5] = (byte) 0x01;
Querypacket[6] = (byte) 0x00;
Querypacket[7] = (byte) 0x01;
Querypacket[8] = (byte) 0x00;
//Serveur authority --> 0 il n'y a pas de serveur d'autorit�
Querypacket[9] = (byte) 0x00;
Querypacket[10] = (byte) 0x00;
Querypacket[11] = (byte) 0x00;
//Lecture de l'hostname
//ici comme on ne connait pas la grandeur que occupe le nom de domaine
//nous devons rechercher l'index pour pouvoir placer l'adresse IP � la bonne endroit
//dans le packet
int nbchar = Querypacket[12];
String hostName = "";
int index = 13;
while(nbchar != 0){
while(nbchar > 0) {
hostName = hostName + String.valueOf(Character.toChars(Querypacket[index]));
index++;
nbchar--;
}
hostName = hostName + ".";
nbchar = Querypacket[index];
index++;
}
//System.out.println(hostName);
index = index - 1;
//Identification de la class
Querypacket[index + 1] = (byte)0x00;
Querypacket[index + 2] = (byte)0x01;
Querypacket[index + 3] = (byte)0x00;
Querypacket[index + 4] = (byte)0x01;
Querypacket[index + 5] = (byte) (0xC0);
Querypacket[index + 6] = (byte) (0x0C);
Querypacket[index + 7] = (byte) (0x00);
Querypacket[index + 8] = (byte) 0x01;
Querypacket[index + 9] = (byte) 0x00;
Querypacket[index + 10] = (byte) 0x01;
Querypacket[index + 11] = (byte) 0x00;
Querypacket[index + 12] = (byte) 0x01;
//time to life
Querypacket[index + 13] = (byte)0x1a;
Querypacket[index + 14] = (byte) (0x6c);
Querypacket[index + 15] = (byte) (0x00);
//Grace a l'index de possion, nous somme en mesure
//de faire l'injection de l'adresse IP dans le packet
//et ce � la bonne endroit
Querypacket[index + 16] = 0x04;
Querypacket[index + 17] = (byte) (part1 & 0xff);
Querypacket[index + 18] = (byte) (part2 & 0xff);
Querypacket[index + 19] = (byte) (part3 & 0xff);
Querypacket[index + 20] = (byte) (part4 & 0xff);
longueur = index + 20 + 1;
Answerpacket = new byte[this.longueur];
for(int i = 0; i < Answerpacket.length; i++){
Answerpacket[i] = Querypacket[i];
}
System.out.println("Identifiant: 0x" + Integer.toHexString(Answerpacket[0] & 0xff) + Integer.toHexString(Answerpacket[1] & 0xff));
System.out.println("parametre: 0x" + Integer.toHexString(Answerpacket[2] & 0xff) + Integer.toHexString(Answerpacket[3] & 0xff));
System.out.println("question: 0x" + Integer.toHexString(Answerpacket[4] & 0xff) + Integer.toHexString(Answerpacket[5] & 0xff));
System.out.println("reponse: 0x" + Integer.toHexString(Answerpacket[6] & 0xff) + Integer.toHexString(Answerpacket[7] & 0xff));
System.out.println("autorite: 0x" + Integer.toHexString(Answerpacket[8] & 0xff) + Integer.toHexString(Answerpacket[9] & 0xff));
System.out.println("info complementaire: 0x" + Integer.toHexString(Answerpacket[10] & 0xff) + Integer.toHexString(Answerpacket[11] & 0xff));
for(int i = 0;i < Answerpacket.length;i++){
if(i%16 == 0){
System.out.println("\r");
}
System.out.print(Integer.toHexString(Answerpacket[i] & 0xff).toString() + " ");
}
System.out.println("\r");
return Answerpacket;
} |
c1600326-14c0-4110-beb8-54e88b0cb419 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final XML other = (XML) obj;
if (this.document != other.document && (this.document == null || !this.document.equals(other.document))) {
return false;
}
return true;
} |
ca2dacc8-1477-4bb0-b14d-e8a8c04a5650 | 1 | public void unlockProgrammProcess() {
try {
programLocker.close();
new File(VCNConstants.LOCK_FILE_PATH).delete();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Program lock released");
} |
8acc2065-e139-4777-98e9-c0080062f01e | 1 | private boolean isFirst(){ //todo 2 regime
if (gameRegime != TWO_PLAYERS_ONLINE_GAME_REGIME){
return true;
} else {
System.out.println("Are you first to play?");
//2 потока - сообщение, ввод с клавы
} return true;
} |
085e0421-dc9f-4bc8-af23-7e49b390ef3d | 6 | private void randomSolve()
{
Log.log("RandomSolve <Start>");
collectAreas(true);
if ( !mAreas.isEmpty())
{
double prop = 0;
Area maxArea = null;
for (Area area : mAreas)
if ( !area.isToRemove() && (maxArea == null || area.getProbability() > prop))
{
maxArea = area;
prop = maxArea.getProbability();
}
for (int tile : maxArea.getTiles())
{
final int x = Tile.getX(tile), y = Tile.getY(tile);
Log.log("Opening: " + x + " " + y);
mAnalyzer.userOpenTile(x, y);
mChanged = true;
break;
}
}
Log.log("RandomSolve <End>");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.