method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
b246a186-dbbd-427d-9dcf-11ed991d58af
| 3
|
@Override
public void remove() {
for (ForceFieldConnection forceFieldConnection : forceFieldConnections) {
for (ForceField forcefield : forceFieldConnection.getForceFieldsInConnection())
getGrid().removeElement(forcefield);
for (ForceFieldGenerator forceFieldGenerator : forceFieldConnection.getForceFieldGenerators())
forceFieldGenerator.removeForceFieldConnection(forceFieldConnection);
}
}
|
5102c143-7995-42b1-85c4-07d84e79ef78
| 5
|
public void handle(final Callback[] callbacks) throws UnsupportedCallbackException {
if (callbacks == null || callbacks.length == 0) {
return;
}
for (Callback cb : callbacks) {
if (cb instanceof NameCallback) {
NameCallback ncb = (NameCallback) cb;
ncb.setName(uname);
} else if (cb instanceof PasswordCallback) {
PasswordCallback pcb = (PasswordCallback) cb;
pcb.setPassword(pass.toCharArray());
}
}
}
|
a5462ad6-3e57-4113-8eac-ed65d3bc0f27
| 0
|
@Override
public void endElement(String namespaceURI, String localName, String qName) {
super.endElement(namespaceURI, localName, qName);
}
|
0244939d-80b8-4f8e-b0ae-6c7ad2f83c74
| 3
|
public static int getTreePointsSpent(String prestige){
for(ClassTree ct : takenPrestigeTrees){
if(ct.getPrestige().equalsIgnoreCase(prestige))
return ct.spentAp();
}
if(prestige.equalsIgnoreCase(characterRace))
return racialTree.spentAp();
return 0;//default
}
|
78a3653b-3b10-4d85-a6ea-8ffa1395a04d
| 3
|
private void loadAvaliblePlattformar() {
DefaultComboBoxModel<Plattform> dcbm = (DefaultComboBoxModel<Plattform>) cbAvaliblePlattformar.getModel();
ArrayList<String> tempal = new ArrayList<>();
ArrayList<Plattform> al = new ArrayList<>();
try {
String query = "select pid from plattform";
tempal = DB.fetchColumn(query);
} catch (InfException e) {
e.getMessage();
}
for (String st : tempal) {
al.add(new Plattform(Integer.parseInt(st)));
}
for (Plattform pt : al) {
dcbm.addElement(pt);
}
}
|
cb1739a3-ee42-4fa6-8f5e-cedb615f1431
| 0
|
public ArrayList<Integer> getLocalFolders()
{
_read.lock();
try
{
return _localFolders;
}
finally
{
_read.unlock();
}
}
|
666e977e-d9f6-4e2e-a1a5-1bf3a851b4d2
| 2
|
public long getUserCommentsCount(String userId) {
long result = 0L;
DBCursor cursor = database.getCollection(ACTIVITY_COLLECTION).find(new BasicDBObject("_id", Pattern.compile("^" + userId)), new BasicDBObject("comment", 1));
try {
while (cursor.hasNext()) {
DBObject activity = cursor.next();
if (activity.get("comment") != null) {
DBObject comments = (DBObject) activity.get("comment");
result += comments.keySet().size();
}
}
} finally {
cursor.close();
}
return result;
}
|
b890b8e7-ef51-4a68-babc-078faef5a8ce
| 6
|
private void retrievePublicKeys(List<String> list) {
String line;
boolean bNewKey = false;
String keyID = null;
for (String list1 : list) {
line = list1;
if (line.startsWith("pub")) {
Pattern p = Pattern.compile("^.*/([^\\s]+).*");
Matcher m = p.matcher(line);
if (m.matches()) {
String str = m.group(1);
keyID = str;
}
bNewKey = true;
}
else if (line.startsWith("uid")) {
if (bNewKey) {
Pattern p = Pattern.compile("uid\\s+(.+)");
Matcher m = p.matcher(line);
if (m.matches()) {
String str = m.group (1);
publicKeysMap.put(keyID, str);
}
}
bNewKey = false;
}
}
}
|
f161af67-7342-4e1e-a949-322d5877efa3
| 0
|
public static void println(Object s) {
System.out.println(s);
}
|
eafaf7e6-b878-4de8-b574-12aa246ef0af
| 1
|
public PosFuncEstado getPosFuncEstado(int idPos, long cedula){
Object o[] = {idPos, cedula};
List<PosFuncEstado> list = getHibernateTemplate().find(
"from PosFuncEstado where fesIdPos = ? and fesCedula = ?",
o
);
if (list.size()>0){
return list.get(0);
} else {
return null;
}
}
|
a8d8152b-46c9-4013-b110-8a110d2dce85
| 0
|
private AnimFrame getFrame(int i) {
return (AnimFrame)frames.get(i);
}
|
23fa9efa-ce47-45cd-9a90-da49952dc384
| 1
|
@Override
public void setEnabled( boolean enabled ) {
if( !enabled ){
closeMenu();
}
}
|
ff249711-cf78-4826-b6d1-4630eebb76ee
| 1
|
public void submit() {
// Get RMI data
RmiData socketData = new RmiData();
// Get list of problems
ArrayList<Problem> problems = socketData.getProblems();
ArrayList<Language> languages = socketData.getLanguages();
// Get selected problem and language
Problem problem = problems.get(problemComboBox.getSelectedIndex());
Language language = languages.get(languageComboBox.getSelectedIndex());
// Create a new submission object and set some values
Submission submission = new Submission();
submission.setProblem(problem);
submission.setLanguage(language);
submission.setSourceCode(textArea.getText()); // get data from text area
// Send to Client object
if (cv.getClient().submit(submission)) {
cv.submitMode(false);
}
}
|
f4722520-3887-4fc0-be1a-81a32ed31fab
| 3
|
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
if (!(sender instanceof Player)) {
Main.courier.send(sender, "messages.requiresPlayer", label);
return false;
}
final Player player = (Player) sender;
final Block target = player.getTargetBlock(null, 16);
if (!this.isKiosk(target)) {
Main.courier.send(sender, "messages.unknownKiosk");
return true;
}
final KioskRemove removal = new KioskRemove(target, player);
Bukkit.getPluginManager().callEvent(removal);
if (removal.isCancelled()) {
Main.courier.send(sender, "messages.removeCancel");
return true;
}
target.setType(Material.AIR);
target.getWorld().dropItemNaturally(target.getLocation(), new ItemStack(Material.SIGN));
return true;
}
|
bf92f7e1-bc12-4b99-81ba-6e17c2108c75
| 0
|
public void setDestinationStop(int value) {
this._destinationStop = value;
}
|
d85a4ad3-2eeb-4711-8856-41b6733ed04f
| 3
|
@Override
public void deserialize(Buffer buf) {
dungeonId = buf.readShort();
if (dungeonId < 0)
throw new RuntimeException("Forbidden value on dungeonId = " + dungeonId + ", it doesn't respect the following condition : dungeonId < 0");
int limit = buf.readUShort();
addedPlayers = new DungeonPartyFinderPlayer[limit];
for (int i = 0; i < limit; i++) {
addedPlayers[i] = new DungeonPartyFinderPlayer();
addedPlayers[i].deserialize(buf);
}
limit = buf.readUShort();
removedPlayersIds = new int[limit];
for (int i = 0; i < limit; i++) {
removedPlayersIds[i] = buf.readInt();
}
}
|
4b4f6f1a-6d09-4e5b-86ba-604b40f45bb4
| 4
|
@Override
protected byte[] load_from_current_position(String frameId, int dataLen,
RandomAccessFile openFile) throws IOException {
byte[] frameData=new byte[dataLen];
MediaFileUtil.read_sure(openFile,frameData);
int offs=0;
int pictureTypeId = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData);
offs+=4;
int stringLength = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
String mimeType = new String(Arrays.copyOfRange(frameData, offs, offs+stringLength),"US-ASCII");
offs+=stringLength;
stringLength = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
String description = new String(Arrays.copyOfRange(frameData, offs, offs+stringLength),"UTF-8");
offs+=stringLength;
int imgWidthPx = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
int imgHeightPx = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
int imgBitsPerPixel = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
int imgNumIndexedColors = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
int imgDataLen = (int)MediaFileUtil.convert32bitsToUnsignedInt(frameData,offs);
offs+=4;
byte[] imageData = Arrays.copyOfRange(frameData, offs, offs+imgDataLen);
this.setValue(new FileMetadata(this,null,mimeType,description,
Id3PictureType.getId3PictureType(pictureTypeId),imageData));
ImageAttributes scannedAttrs=this.embeddedImageLink.getImageAttributes();
if(imgWidthPx != scannedAttrs.getImgWidth()
|| imgHeightPx != scannedAttrs.getImgHeight()
|| imgBitsPerPixel != scannedAttrs.getImgBitsPerPixel()
|| imgNumIndexedColors != scannedAttrs.getImgIndexedColors()) {
this.log(Level.WARNING, "FLAC picture metadata disagrees with image data: ("
+imgHeightPx+"x"+imgWidthPx+"px, "+imgBitsPerPixel+"bpp, "+imgNumIndexedColors+"ixColors) != ("
+scannedAttrs.getImgWidth()+"x"+scannedAttrs.getImgHeight()+"px, "
+scannedAttrs.getImgBitsPerPixel()+"bpp, "+scannedAttrs.getImgIndexedColors()+"ixColors)");
// TODO: pick one?
}
return frameData;
}
|
2b4f97a6-b471-4360-b71e-c8e14d0c771a
| 8
|
@Override
public Value applyOperator(FunctionOperator op, List<Value> otherValues)
{
Value first = otherValues.get(0);
switch (op.toString()) // the two current operators aren't actually supported/ever used
{
case ".[]":
if (first instanceof IntValue)
{
int index = (int) ((IntValue) first).getValue();
if (index < 0 || index >= list.length)
throw new ambroscum.errors.NoSuchElementException("List index out of bounds: " + this + " has no element #" + index);
return list[index];
}
throw new FunctionNotFoundException("list's indexing expects an int");
case "[]=":
if (first instanceof IntValue)
{
int index = (int) ((IntValue) first).getValue();
if (index < 0 || index >= list.length)
throw new ambroscum.errors.NoSuchElementException("List index out of bounds: " + this + " has no element #" + index);
list[index] = otherValues.get(1);
return NullValue.NULL;
}
throw new FunctionNotFoundException("list's indexing expects an int");
}
return super.applyOperator(op, otherValues);
}
|
6b7d7d22-29c6-4163-bd7c-2cdabf744569
| 0
|
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
|
3de8e3ae-9032-4006-8a5b-54632cbce9e9
| 4
|
public ArrayList<Move> getRegularMoves(Board currentBoard, boolean onlyChainable, Checker checker) {
//List of possible moves.
ArrayList<Move> moves = new ArrayList<Move>();
//Add all regular moves to the list.
moves.add(new ForwardLeft(currentBoard, checker));
moves.add(new ForwardRight(currentBoard, checker));
moves.add(new BackwardLeft(currentBoard, checker));
moves.add(new BackwardRight(currentBoard, checker));
//Remove all moves that are not valid.
for (int i = moves.size() - 1; i >= 0; i--)
if (!moves.get(i).isLegal() || (onlyChainable && !moves.get(i).isChainable()))
moves.remove(i);
return moves;
}
|
13d878a8-dbc9-4e57-91d4-094b18815cc7
| 7
|
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 输入n
int n = Integer.parseInt(sc.nextLine());
// 创建ArrayList用于存放每一个十六进制字符串。将其容量设置为n,避免空间增长的时间消耗
ArrayList<char[]> list = new ArrayList<>(n);
// 将每个字符串的字母转换为大写后,将字符串转换成char数组并添加到ArrayList中
for (int i = 0; i < n; i++) {
String str = sc.nextLine().toUpperCase();
char[] c = str.toCharArray();
list.add(c);
}
// 遍历整个ArrayList
for (char[] i : list) {
// 十六进制转八进制,先将十六进制转换为二进制,在将二进制转换为八进制
// result数组用于存储八进制结果,结果的低位从0开始
int[] result = new int[i.length * 4 / 3 + 1];
// 表示result数组的下表
int index = 0;
// 临时字符串
String temp = "";
//从每个十六进制数字的最低位,即十六进制数字字符数组的最高位,开始转换。一个十六进制数转成4位二进制数,3位二进制数转成一个八进制
for (int j = i.length - 1; j >= 0; j--) {
// 将十六进制数转换为二进制字符串
String binstr = HexToBinary(i[j]);
temp = binstr + temp;
// 每三个二进制转换成一个八进制
while (temp.length() >= 3) {
char[] c = temp.toCharArray();
int k = c.length - 1;
result[index++] = (c[k - 2] - '0') * 4 + (c[k - 1] - '0')
* 2 + (c[k] - '0');
// 将传转换过的二进制数字去除
temp = temp.substring(0, temp.length() - 3);
}
}
// 处理剩余的小于三位的二进制数
if (temp.length() > 0) {
result[index] = Integer.parseInt(temp, 2);
}
// 去除八进制结果的前导0
while (result[index] == 0) {
index--;
}
// 输出结果
for (int j = index; j >= 0; j--) {
System.out.print(result[j]);
}
System.out.println();
}
}
|
931659bc-5614-4786-b6b3-51970417a50b
| 5
|
@SuppressWarnings("unchecked")
public static ViewMapper getView() {
// 根据请求地址映射到具体的视图控制器
HttpServletRequest req = WebContext.getRequest();
String uri = req.getServletPath().split("\\.")[0];
ViewMapper viewMapper = ContextConfig.getMapperCtrl().get(uri);
List<Object> params = new ArrayList<Object>();
// 如果视图控制器不为空,注入请求参数
if (viewMapper != null) {
MethodVO method = viewMapper.getMethod();
for (int i = 0; i < method.getParamNames().length; i++) {
String param = req.getParameter(method.getParamNames()[i]);
if (HttpServletRequest.class.isAssignableFrom(method
.getParamType()[i])) {
params.add(WebContext.getRequest());
} else if (HttpServletResponse.class.isAssignableFrom(method
.getParamType()[i])) {
params.add(WebContext.getResponse());
} else {
if (ValueUtil.isCustomDefinitionObject(method
.getParamType()[i]) == false) {
params.add(ValueUtil.castValue(param,
method.getParamType()[i]));
} else {
params.add(RequestUtil.paramsToBean(req,
method.getParamType()[i]));
}
}
}
viewMapper.setRequestParams(params);
}
return viewMapper;
}
|
f4e51740-056c-4a5a-b850-87cf9d54323c
| 7
|
private E getResult(boolean findMax) {
int index = 0;
Entry<Integer, Double> result = null;
if (findMax == true) {
Iterator<Entry<Integer, Double>> s = fitScores.entrySet().iterator();
for (; s.hasNext(); )
{
Entry<Integer, Double> curr = s.next();
if (result == null)
{
result = curr;
}
else if (curr.getValue() > result.getValue())
{
result = curr;
}
}
} else {
Iterator<Entry<Integer, Double>> s = fitScores.entrySet().iterator();
for (; s.hasNext(); )
{
Entry<Integer, Double> curr = s.next();
if (result == null)
{
result = curr;
}
else if (curr.getValue() < result.getValue())
{
result = curr;
}
}
}
bestFit = currGen.get(result.getKey());
return individual.decode(currGen.get(result.getKey()));
}
|
1b023058-0849-4ec1-affa-c92abb24a1d4
| 6
|
public Pair<Integer, TilesetRef> mapGidToFirstGidTilesetPair(int gid) {
if (gid == 0) {
return new Pair<Integer, TilesetRef>(0, null);
} else if (tilesets.containsKey(gid)) {
return new Pair<Integer, TilesetRef>(gid, tilesets.get(gid));
} else {
int last_key_gid = 0;
for(int current_key_gid : tilesets.keySet()) {
if (current_key_gid > last_key_gid && current_key_gid <= gid) {
last_key_gid = current_key_gid;
}
}
TilesetRef ret = tilesets.get(last_key_gid);
int offset = gid - last_key_gid;
if (offset < ret.getTileset().calcTileCount()) {
return new Pair<Integer, TilesetRef>(last_key_gid, ret);
} else {
return new Pair<Integer, TilesetRef>(0, null);
}
}
}
|
11954067-2915-4f27-900c-83ed5827b162
| 6
|
public boolean isOn() {
boolean hasStock = false;
outer:for (int i = 0; i < this.dispensers.size(); i++) {
if (!this.dispensers.get(i).getDispenserContents().isEmpty()) {
hasStock = true;
break outer;
}
}
if (!hasStock || !this.on) {
on = false;
return false;
}
Date temp = new Date();
if (temp.getHours() < this.startHour || temp.getHours() > this.endHour) {
this.on = false;
return false;
}
return on;
}
|
8762b7cd-9e05-4c20-b889-df5376c1c3e8
| 2
|
@Override
public Course unassignRoleSchoolFromCourse(long roleId, long courseId) {
// for(Person person : persons){
// List<RoleSchool> roles = (ArrayList<RoleSchool>)person.getRoles();
// for(RoleSchool role : roles){
// if(role.getId() == roleId){
// for(Course course : courses){
// for(RoleSchool coursesRole : course.getRoles()){
// course.removeRole(roleId);
// return person;
// }
// }
// }
// }
// }
// return null;
for(Course course : courses){
if(course.getId() == courseId){
course.removeRole(roleId);
return course;
}
}
return null;
}
|
cbc07e57-5eb2-4f3f-ad8f-297ac281af22
| 5
|
public final void method44(int i, AbstractToolkit var_ha) {
anInt9986++;
Object object = null;
r var_r;
if (aR9976 != null || !aBoolean9988) {
var_r = aR9976;
aR9976 = null;
} else {
Class2 class2 = method2401(var_ha, 262144, true, 22);
var_r = class2 == null ? null : ((Class2) class2).aR118;
}
if (var_r != null)
Class130.method1130(var_r, ((Class318_Sub1) this).mapHeightLevel,
((Class318_Sub1) this).xHash,
((Class318_Sub1) this).anInt6388, null);
if (i != 836)
aShort9991 = (short) 86;
}
|
359fde4d-dde0-4c0f-88d1-a6d2cf429e89
| 4
|
private void parse(String query) {
try {
// StringTokenizer is faster than split. http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml
StringTokenizer st = new StringTokenizer(query, "&");
while (st.hasMoreTokens()) {
String[] pair = st.nextToken().split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = pair.length == 1 ? null : URLDecoder.decode(pair[1], "UTF-8");
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Couldn't parse query string: " + query, e);
}
}
|
22ac5ee2-3813-486a-af92-46eb3fa8ca0f
| 1
|
public void uimsg(int id, String msg, Object... args) {
Widget w = widgets.get(id);
synchronized(robots) {
for(Robot r : robots)
r.uimsg(id, w, msg, args);
}
super.uimsg(id, msg, args);
}
|
aa724c13-0396-4256-a445-1e1bc3bc6591
| 6
|
public static void vendingMachine(char a, int n){
int price = 0;
if(a == 'w' || a == 'W') {
price = 10;
checkPayment(price, n, a);
} else if (a == 'j' || a == 'J') {
price = 15;
checkPayment(price, n, a);
} else if ( a == 'c' || a == 'C') {
price = 12;
checkPayment(price, n, a);
} else {
System.out.println("Wrong input");
}
}
|
7b7ddc1f-f930-4dcf-918f-ec194486f3f6
| 2
|
@Override
public void addTextBack() {
Element textBack = text.getOwnerDocument().createElement("path");
String d = "M";
for (Coordinate c : geometry.getCoordinates()) {
if(d.length()>1){
d=d+" L";
}
d = d + " " + c.x + "," + c.y;
}
textBack.setAttribute("d", d);
textBack.setAttribute("style", "fill:green;opacity:0.5;");
text.getParentNode().insertBefore(textBack, text);
}
|
819daba0-1fc9-4d51-8e89-069e7ad41925
| 4
|
public void mousePressed(MouseEvent e) {
if (!b.isEnabled()) return;
if (b instanceof javax.swing.JToggleButton) {
b.setBorder((b.isSelected() ? inactive : lowered));
b.setBorderPainted((b.isSelected() ? false : true));
} else {
b.setBorder(lowered);
b.setBorderPainted(true);
}
}
|
d0d45915-6adf-4afa-bbfb-25874898abe8
| 7
|
protected boolean controlThicknessInput(JTextField textfield, int maxLength, boolean negativeAllowed) {
boolean ret = true;
String tmp = textfield.getText();
if (negativeAllowed && tmp.matches("-")) {
ret = false;
} else if ((!negativeAllowed && !tmp.matches("[0-9]++")) || (negativeAllowed && !tmp.matches("-?[0-9]++"))) {
textfield.setText("");
ret = false;
} else {
if (tmp.length() > maxLength) {
textfield.setText(tmp.substring(0, maxLength));
ret = false;
}
}
return ret;
}
|
8f3f5d33-5aa5-441f-a5da-4cb4766f6431
| 4
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ArrayID other = (ArrayID) obj;
if (arrayId != other.arrayId)
return false;
return true;
}
|
11bb1c47-b97c-4f91-adca-b0b627cf761c
| 3
|
public void login()
{
if (!ValidationHelper.isNullOrEmpty(getLogin(),getPassword()))
{
setPassword(DigestUtils.md5Hex(getPassword()));
setUser(IndexedEntityService.em
.createNamedQuery("User.findByLogin", User.class)
.setParameter("login", getLogin()).getSingleResult());
if (user != null && user.getPassword().equals(getPassword())) {
RedirectHelper.redirectTo(Pages.HI);
}
}
}
|
3404b526-02fb-42c5-a84b-23cec95a641a
| 3
|
private boolean runSingleCycleAndContinue() {
if (checkReturnCode("Do you want to create a new Cell(Y/N)?"))
addLivingCellAndPrint();
if (checkReturnCode("Do you want to apply a tick (Y/N)?"))
applyTickAndPrint();
if (checkReturnCode("Do you want to quit (Y/N)?"))
return false;
return true;
}
|
0321e41a-dc21-4d51-a6fc-0724227ed6e3
| 8
|
final void method3049(ByteBuffer class348_sub49, int i, int i_0_) {
if (i_0_ != 31015)
method3049(null, 44, 80);
int i_1_ = i;
while_200_:
do {
while_199_:
do {
do {
if ((i_1_ ^ 0xffffffff) != -1) {
if (i_1_ != 1) {
if (i_1_ != 2) {
if ((i_1_ ^ 0xffffffff) != -4)
break while_200_;
} else
break;
break while_199_;
}
} else {
anInt9340 = class348_sub49.getShort();
break while_200_;
}
anInt9343 = class348_sub49.getShort();
break while_200_;
} while (false);
anInt9339 = class348_sub49.getShort();
break while_200_;
} while (false);
anInt9338 = class348_sub49.getShort();
} while (false);
anInt9337++;
}
|
6fb0597d-b9ac-4410-89d9-9d2c1a907dbe
| 7
|
public void paint(Graphics g_) {
super.paint(g_);
Graphics2D g = (Graphics2D) g_;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
if (socket.getGate() == null) return;
g.setColor(Color.BLACK);
switch (socket.getGate().type) {
case And:
g.drawLine(0, 0, 30, 0);
g.drawLine(0, 0, 0, 40);
g.drawLine(0, 40, 30, 40);
g.drawArc(10, 0, 40, 40, 270, 180);
break;
case Or:
g.drawArc(-10, 0, 20, 40, -90, 180);
g.drawLine(0, 0, 20, 0);
g.drawLine(0, 40, 20, 40);
g.drawArc(-10, 0, 60, 40, 270, 180);
break;
case Not:
g.drawLine(0, 0, 0, 40);
g.drawLine(0, 40, 43, 20);
g.drawLine(0, 0, 43, 20);
g.drawOval(43, 17, 7, 7);
break;
case Nand:
g.drawLine(0, 0, 21, 0);
g.drawLine(0, 0, 0, 40);
g.drawLine(0, 40, 21, 40);
g.drawArc(2, 0, 40, 40, 270, 180);
g.drawOval(43, 17, 7, 7);
break;
case Nor:
g.drawArc(-10, 0, 20, 40, -90, 180);
g.drawLine(0, 0, 15, 0);
g.drawLine(0, 40, 15, 40);
g.drawArc(-10, 0, 52, 40, 270, 180);
g.drawOval(43, 17, 7, 7);
break;
case Xor:
g.drawArc(-10, 0, 20, 40, -90, 180);
g.drawArc(-5, 0, 20, 40, -90, 180);
g.drawLine(8, 0, 15, 0);
g.drawLine(8, 40, 15, 40);
g.drawArc(-10, 0, 52, 40, 270, 180);
g.drawOval(43, 17, 7, 7);
break;
}
}
|
b622cf34-0e31-4f8b-8aa9-c458d452095e
| 3
|
public MySQLDataStorageImplementation(Decapitation decapitation, String url, String username, String password) throws SQLException {
plugin = decapitation;
connection = DriverManager.getConnection(url, username, password);
final ResultSet bansExists = connection.getMetaData().getTables(null, null, "bounties", null);
if (!bansExists.first()) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getResource("mysql.sql")));
final StringBuilder builder = new StringBuilder();
String next;
try {
while ((next = reader.readLine()) != null) {
builder.append(next);
}
getFreshPreparedStatementColdFromTheRefrigerator(builder.toString()).execute();
} catch (final IOException e) {
throw new SQLException("Could not load default table creation text", e);
}
}
}
|
27c768ac-8524-409e-9976-d75b13d60a9d
| 3
|
public static List<String> getResult() {
for (Thread t : threads) {
try {
if (!t.isInterrupted()) {
t.join();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
|
d2886132-da4a-4918-8c42-1ae1012c3998
| 4
|
public void stop() {
if(player != null) {
if(fadeTime == 0.0f || this != gamePlayList.getCurrentSong() || gamePlayList.getStopping()) {
stopFadeIn();
stopFadeOut();
// setVolume(getMinGain());
// if(playerThread != null) {
// playerThread.interrupt();
// playerThread = null;
// }
currentlyPlaying = false;
stopPlayer();
}
}
}
|
70a09e47-0057-47fa-b8bc-40fed8dd236b
| 1
|
public boolean hasPartName(String xpathExpression){
if (xpathExpression.contains("/")){
String varPart = xpathExpression.substring(0, xpathExpression.indexOf("/"));
return varPart.contains(".");
}else{
return xpathExpression.contains(".");
}
}
|
730b2d00-b5e5-43e6-acd2-10e9c441beff
| 6
|
private void handleDevices(AjaxRequest vars, HttpServletRequest request, HttpServletResponse response) {
EntityManager em = getEntityManager();
CommunicationDeviceDao dbDevice = new CommunicationDeviceDao(em);
CommunicationDeviceTypeDao dbType = new CommunicationDeviceTypeDao(em);
if (vars.getAction().equals("customerList")) {
List<CommunicationDevice> list = dbDevice.getListByCustomer(vars.getId());
writeResponse(response, list);
} else if (vars.getAction().equals("typeList")) {
writeResponse(response, dbType.getList());
} else if (vars.getAction().equals("update")) {
try {
em.getTransaction().begin();
HashMap a = (HashMap) new JSONDeserializer().deserialize(vars.getPayload());
if (a.get("o") instanceof CommunicationDevice) {
CommunicationDevice source = (CommunicationDevice) a.get("o");
CommunicationDevice target = dbDevice.getById(source.getId());
target.setType(source.getType());
target.setValueText(source.getValueText());
target.setOrderBy(source.getOrderBy());
em.persist(target);
} else if (a.get("o") instanceof HashMap) {
HashMap allItems = (HashMap) a.get("o");
String valueText = (String) allItems.get("valueText");
long orderBy = (long) allItems.get("orderBy");
long typeId = (long) ((HashMap) allItems.get("type")).get("id");
Object customerId = ((HashMap) allItems.get("customer")).get("id");
CustomerDao dbCustomer = new CustomerDao(em);
CommunicationDevice device = new CommunicationDevice();
device.setOrderBy(orderBy);
device.setValueText(valueText);
device.setCustomer(dbCustomer.getById(Long.parseLong((String) customerId)));
device.setType(dbType.getById(typeId));
Date date = new Date();
device.setCreated(new Timestamp(date.getDate()));
em.persist(device);
} else {
AjaxErrorResponse ajaxErrorResponse = new AjaxErrorResponse("");
writeResponse(response, ajaxErrorResponse);
}
em.getTransaction().commit();
AjaxErrorResponse ajaxErrorResponse = new AjaxErrorResponse("");
ajaxErrorResponse.isError = false;
writeResponse(response, ajaxErrorResponse);
} catch (Exception e) {
handleException(e, em, request, response);
}
}
em.close();
}
|
bf47af42-9dc2-49aa-929c-07e544c8a881
| 6
|
public Block getBlock(int x, int y, int z) {
if(x < 0 || x >= w_width || y < 0 || y >= w_height || z < 0 || z >= w_depth) return Block.air;
return Block.blocks[blocks[x][y][z]];
}
|
ef104be6-5608-44d8-8024-e892edb4a0df
| 4
|
public CuttingResult getReward(Tilia x){
ArrayList<Integer> pieces = new ArrayList<Integer>();
pieces.add(x.getSide());
// First two variables in CuttingResult are not used
CuttingResult best = new CuttingResult(0, 0, x.getReward(), pieces);
// Try possible cuts
for (int i =1 ; i < x.getSide() ; i++){
ArrayList<Integer> pieces_tmp = new ArrayList<Integer>();
long sum =0;
//Try different cuts
for (Tilia tilia : x.cut(i)){
//Process smaller pieces
CuttingResult temp = getReward(tilia);
for(int j=0; j < temp.getPieces().size();j++){
pieces_tmp.add(temp.getPieces().get(j));
}
sum+=temp.getReward();
}
//Select optimal result
if (sum > best.getReward()){
best.setPieces(pieces_tmp);
best.setReward(sum);
}
}
return best;
}
|
d9ace60c-a14d-4ae0-8a4e-22332b947a27
| 1
|
public void exception(){
long result = a.getTimeLeftInMillis();
if(result <= 0){
System.out.println("The bid for " + a.getName() + " has expired.");
}
}
|
f4cdcd41-2161-47b2-8983-a5c530b6fb68
| 3
|
public static void addAllCombos(String previous, int len) {
if (len == 0) {
if (checkHash(previous)) Solutions.add(previous);
// System.out.println(previous);
}else {
for (int i = 0; i < CHARS.length; i++) {
String next = previous + CHARS[i];
addAllCombos(next, len - 1);
}
}
}
|
589867bc-2947-4699-8f02-b6e2ef2a2229
| 9
|
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
if (cb_antialias.isSelected()) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
if (img!=null) {
//setSize(img.getWidth(null), img.getHeight(null));
g2.drawImage(img, 0, 0, this);
}
if (drawingHGuide>=0) {
g2.drawLine(0, drawingHGuide*zoomFactor, getWidth(), drawingHGuide*zoomFactor);
} else if (drawingVGuide>=0) {
g2.drawLine(drawingVGuide*zoomFactor, 0, drawingVGuide*zoomFactor, getHeight());
}
if (hGuides!=null)
for (int i=0; i<hGuides.size(); i++) {
Integer iy=(Integer)hGuides.get(i);
int y=iy.intValue()*zoomFactor;
g2.drawLine(0, y, getWidth(), y);
}
if (vGuides!=null)
for (int i=0; i<vGuides.size(); i++) {
Integer ix=(Integer)vGuides.get(i);
int x=ix.intValue()*zoomFactor;
g2.drawLine(x, 0, x, getHeight());
}
for (int i=0; i<shapeList.size(); i++)
shapeList.get_shape(i).draw(g2, zoomFactor);
}
|
657361dd-4246-407c-8a75-8da786a5b8b8
| 7
|
private void solve (int col, int row) throws Exception {
runCount++;
if (runCount>40000) {
System.out.println("Solution not found");
throw fail;
}
if (row>8) {
System.out.println("Solved");
throw new Exception("Solution succesful");
}
if (solutionArray[col][row] != 0) {
next(col,row);
} else {
for( int num = 1; num < 10; num++) {
if(checkRow(row,num)&&checkCol(col,num)&&checkBox(col,row,num)) {
solutionArray[col][row] = num;
next(col,row);
}
}
solutionArray[col][row] = 0;
}
}
|
8451ce19-872f-4481-8db8-5b8c1397ef34
| 3
|
private void update() {
long now = System.currentTimeMillis();
if (now - lastLine > lineDelay) {
if (!view.getGrid().newLine()) {
timer.cancel();
if (view.newGame()) {
init();
return;
} else {
System.exit(0);
}
}
lastLine = now;
lineDelay--;
}
}
|
d9932b86-eb6e-4308-a378-abd1312586bb
| 3
|
public static void main(String[] args) {
// TODO code application logic here
int i = 1;
int count = 0;
boolean s = true;
while (s) {
i++;
if (Prime(i)) {
count++;
}
if (count == 10001) {
s = false;
}
}
System.out.println(i);
/*int[] Pros = new int[10001];
int k=0;
boolean kon=true;
for(int i=2;kon;i++)
{
boolean sign=true;
for(int j=2;j<i;j++)
{
int z=i%j;
if(z==0)
{
sign = false;
}
}
if(sign)
{
Pros[k]=i;
k++;
}
if(k==10001)
{
kon=false;
}
}
System.out.println(Pros[10000]);*/
}
|
f425d7ac-05b3-4d53-961b-1b90ea63c4a6
| 8
|
@Override
public void run() {
while (true) {
try {
// Wait for an event one of the registered channels
this.selector.select();
// Iterate over the set of keys for which events are available
Iterator<?> selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
// Check what event is available and deal with it
if (key.isConnectable()) {
this.finishConnection(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
0e3618bd-6898-496b-964f-1662f7728c2c
| 0
|
@Override
public String toString() {
return "CallType is " + remoteCallObjectType + "\n" +
"Command is " + execCommand;
}
|
3ab84aff-a721-4dfc-bc89-9224e0e7857d
| 6
|
private String getFieldName(ExtendedField field) {
try {
if (field.hasDBMapping()) {
return field.getDBColumnNameWithoutEscape();
}
if (field.hasEntityMapping()
&& MappingType.MANY_TO_ONE.equals(field.getEntityMapping())) {
return field.getTableName() + "_UUID";
}
if (field.hasEntityMapping()
&& MappingType.ONE_TO_MANY.equals(field.getEntityMapping())) {
return DaoUtils.getTableName(field.getMappedType()) + "_UUID";
}
} catch (NullPointerException e) {
throw new DBException("cant get FieldName for field: "
+ field.getName() + " in class "
+ field.getMainObjectClass().getCanonicalName(), e);
}
throw new IllegalArgumentException("should never occure");
}
|
026174bf-271e-4e78-b844-8f02d77b6310
| 2
|
public String getShortDateUS(){
this.shortDateUS = (new Integer(this.getMonthAsInteger())).toString();
if(this.shortDateUS.length()<2)this.shortDateUS = "0" + this.shortDateUS;
int dayI = this.getDayOfTheMonth();
if(dayI<10){
this.shortDateUS += "/0" + dayI;
}
else{
this.shortDateUS += "/" + dayI;
}
String yearS = (new Integer(this.getYear())).toString();
this.shortDateUS+= "/" + yearS.substring(2);
return this.shortDateUS;
}
|
25236d08-18e6-4e89-a5c0-a586e58a7a26
| 7
|
private void handleMousePressed(int x, int y) {
x -= 50;
y -= 50;
x /= 16;
y /= 16;
if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
return;
}
if (map.getUnit(x, y) != 0) {
selectedx = x;
selectedy = y;
lastFindX = -1;
} else {
if (selectedx != -1) {
map.clearVisited();
path = finder.findPath(new UnitMover(map.getUnit(selectedx, selectedy)), selectedx, selectedy, x, y);
if (path != null) {
path = null;
int unit = map.getUnit(selectedx, selectedy);
map.setUnit(selectedx, selectedy, 0);
map.setUnit(x, y, unit);
selectedx = x;
selectedy = y;
lastFindX = -1;
}
}
}
repaint(0);
}
|
52156636-e08a-4e85-8912-88fe9908ca8b
| 8
|
public int flags(int x, int y) // get the number of surrounding flags
{
int surFlags = 0;
for (int q = x - 1; q <= x + 1; q++) {
for (int w = y - 1; w <= y + 1; w++) {
while (true) {
if (q < 0 || w < 0 || q >= row || w >= col) // makes sure
// that it wont
// have an error
// for buttons
// next to the
// wall
break;
if (flag[q][w] == true) {
surFlags++;
}
break;
}
}
}
return surFlags;
}
|
9a353550-956f-4e3e-8fae-af6e6b08b314
| 4
|
@Override
protected void generateLevel()
{
// Grass = 0xFF00;
// Flower = 0xFFFF00;
// Rock = 0x7F7F00;
for (int i = 0; i < levelpixels.length; i++) {
if (levelpixels[i] == 0xff00) {
tiles[i] = Tile.grass;
}
if (levelpixels[i] == 0xffff00) {
tiles[i] = Tile.flower1;
}
if (levelpixels[i] == 0x7f7f00) {
tiles[i] = Tile.rock;
}
}
}
|
c11e8cfd-3045-4d5c-b083-a39bab5b5057
| 8
|
@Override
public void quickPlay( boolean priority, boolean toStream, boolean toLoop,
String sourcename, FilenameURL filenameURL, float x,
float y, float z, int attModel, float distOrRoll,
boolean temporary )
{
IntBuffer myBuffer = null;
if( !toStream )
{
// Grab the sound buffer for this file:
myBuffer = ALBufferMap.get( filenameURL.getFilename() );
// if not found, try loading it:
if( myBuffer == null )
loadSound( filenameURL );
// try and grab the sound buffer again:
myBuffer = ALBufferMap.get( filenameURL.getFilename() );
// see if it was there this time:
if( myBuffer == null )
{
errorMessage( "Sound buffer was not created for " +
filenameURL.getFilename() );
return;
}
}
SoundBuffer buffer = null;
if( !toStream )
{
// Grab the sound buffer for this file:
buffer = bufferMap.get( filenameURL.getFilename() );
// if not found, try loading it:
if( buffer == null )
{
if( !loadSound( filenameURL ) )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because an error occurred while loading "
+ filenameURL.getFilename() );
return;
}
}
// try and grab the sound buffer again:
buffer = bufferMap.get( filenameURL.getFilename() );
// see if it was there this time:
if( buffer == null )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because audio data was not found for "
+ filenameURL.getFilename() );
return;
}
}
SourceLWJGLOpenAL s = new SourceLWJGLOpenAL( listenerPositionAL,
myBuffer, priority,
toStream, toLoop,
sourcename, filenameURL,
buffer, x, y, z,
attModel, distOrRoll,
false );
sourceMap.put( sourcename, s );
play( s );
if( temporary )
s.setTemporary( true );
}
|
eab737f9-b64b-4b2e-815a-9af5870fc705
| 6
|
private void dealDamage(GridSpace target, Weapon weapon, Point targetLocation) {
ArrayList<LivingThing> livingThings = target.returnLivingThings();
Character c = (grid.get(getCharacterLocation())).returnCharacter();
if (livingThings == null || livingThings.size() == 0) {
return;
} else {
for (LivingThing livingThing : livingThings) {
if (livingThing instanceof Character) {
return;
} else {
int hp = livingThing.getHp();
int enemyType = livingThing.getDexterity() / 10;
hp -= weapon.getDamage().getBaseHpDamage();
if (weapon.getDamage().isFreeze()) {
livingThing.setFrozen(true);
}
livingThing.setDot(weapon.getDamage().getDot());
if (hp <= 0) {
target.remove(livingThing);
removeEnemy(targetLocation);
c.addXp(500 * enemyType);
c.levelUp();
numKilled++;
c.addMoney(10 * enemyType);
} else {
livingThing.setHp(hp);
}
}
}
}
target.sortArrayOfThings();
}
|
fbf12a8c-836c-476d-8b14-9b5557efa6bc
| 0
|
public void chercher() {
String nom = (String) this.vue.getjComboBoxSearch().getSelectedItem();
String[] libelle = nom.split(" ", 0);
System.out.println(libelle[0] + " " + libelle[1]);
Praticien unPraticien = DaoPraticienJPA.selectOneByNomPrenom(em, libelle[0], libelle[1]);
afficherPraticien(unPraticien);
}
|
c2796e24-912b-4d45-b395-7230e688698f
| 4
|
public static void quickSort(int[] array, int lowIndex, int highIndex) {
// this.printArray();
// System.out.println("low:high="+lowIndex+":"+highIndex);
if (lowIndex >= highIndex)
return;
count2 += (highIndex - lowIndex);
int i = lowIndex + 1;
int pivot = choosePivot(array, lowIndex, highIndex);
int tmp = 0;
for (int j = lowIndex + 1; j <= highIndex; j++) {
count++;
// compare array[j] and pivot, see if needs swap
if (array[j] < pivot) {
// if there is nothing <p yet, then just move i forward;
if (i != j) {
// swap array[j] and array[i] unless there is nothing
// smaller than pivot yet
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
i++;
}
}
// swap pivot and array[i-1]
tmp = array[i - 1];
array[i - 1] = pivot;
array[lowIndex] = tmp;
// element i-1 is the pivot, doesn't need to sort.
quickSort(array, lowIndex, i - 2);
quickSort(array, i, highIndex);
}
|
4bacf179-7a79-4032-b3fc-bb4983ac4b35
| 4
|
private static final List<Integer[]> drawCircle(Graphics graphics,
int xc, int yc, int radius) {
/*
* Declare and initialise local variables.
* The origin is base on positive y-axis at (0,r)
*
* int x and y - Circle coordinates use
* to draw the pixels of circle's 8 arcs.
* int p - A computed variable responsible for determining
* which pixels to draw.
*/
int x, y, p;
Integer[] coordinate;
List<Integer[]> edges1stOctant = new ArrayList<>();
x = 0;
y = radius;
// Initialises first points of the 8 arcs.
for (int i = 1; i <= 8; i++) {
drawCircleArcs(graphics, x, y, xc, yc, i);
}
// Initialise the value of P, base on the Bresenham's algorithm.
p = 3 - 2 * radius;
while (x <= y) {
// Increments x at each iteration regardless the value of p.
x++;
// If the value of P is negative then choose (x, y)
// as the next pixel to draw
// Then calculate the next value of p
if (p < 0) {
p += (4 * x) + 6;
} // Else choose the pixel (x, y-1) to draw
// Then calculate the next value of p
else {
y--;
p += (4 * (x - y)) + 10;
}
// Records all pixel drawn, later use to as limit in filling circle
coordinate = new Integer[2];
coordinate[0] = x;
coordinate[1] = y;
edges1stOctant.add(coordinate);
// Draws the 8 pixels for each octant of the circle through symmetry;
// by calling the drawTheCircle method which takes
// circle parameters as method arguments.
for (int i = 1; i <= 8; i++) {
drawCircleArcs(graphics, x, y, xc, yc, i);
}
}
return edges1stOctant;
}
|
9b2d40e1-5876-44c7-84ee-304e76271fbb
| 5
|
@Override
public boolean retiro(int codigo, double m) {
try{
boolean seRetiro = false;
double saldo = 0;
if( buscarCuenta(codigo) ){
TipoCuenta tc = TipoCuenta.valueOf(rCuentas.readUTF());
rCuentas.readUTF();
saldo = rCuentas.readDouble();
if( tc == TipoCuenta.PLAZOFIJO ){
rCuentas.readLong();
rCuentas.readLong();
saldo = rCuentas.readDouble();
}
if( saldo > m ){
rCuentas.seek(rCuentas.getFilePointer()-8);
rCuentas.writeDouble(saldo - m);
seRetiro = true;
registrarTransaccion(codigo, TipoTransaccion.RETIRO, m);
}
if( tc == TipoCuenta.CHEQUE ){
agregarCheque(codigo, m, seRetiro);
}
return seRetiro;
}
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
return false;
}
|
5c338a9f-d6f1-4dd4-abef-177efed12d71
| 9
|
Point3f getFaceCenter(byte face) {
if (faceCenter == null)
faceCenter = new Point3f();
switch (face) {
case TOP:
switch (axis) {
case 'x':
faceCenter.set(center.x + 0.5f * height, center.y, center.z);
break;
case 'y':
faceCenter.set(center.x, center.y + 0.5f * height, center.z);
break;
case 'z':
faceCenter.set(center.x, center.y, center.z + 0.5f * height);
break;
}
return faceCenter;
case BOTTOM:
switch (axis) {
case 'x':
faceCenter.set(center.x - 0.5f * height, center.y, center.z);
break;
case 'y':
faceCenter.set(center.x, center.y - 0.5f * height, center.z);
break;
case 'z':
faceCenter.set(center.x, center.y, center.z - 0.5f * height);
break;
}
return faceCenter;
}
return null;
}
|
387af50e-6623-4640-9af9-af37b1c23f30
| 9
|
private void setStatus(int status)
{
if ((status & 128) == 128)
FIN = true;
if ((status & 64) == 64)
RSV1 = true;
if ((status & 32) == 32)
RSV2 = true;
if ((status & 16) == 16)
RSV3 = true;
// if the opcode is 8, then we're closing
opcode = (byte) (status & (15)); // lower 4 bits = 1+2+4+8 = 15
if (opcode == WSRequest.OPCODE_CONNECTION_CLOSE)
{
System.out.println("Received request to close the connection. Returning closing frame");
closing = true;
try {
response = new WSResponse(WSRequest.OPCODE_CONNECTION_CLOSE, "");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (opcode >= 8)
{
controlFrame = true;
if (opcode == 0xF) {
closing = true;
try {
response = new WSResponse(WSRequest.OPCODE_CONNECTION_CLOSE, "");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
controlFrame = false;
}
System.out.println("Opcode: "+opcode);
}
|
8c73d7e3-6eb5-4866-834b-82d4abe52dc8
| 3
|
public int execute() {
// The LOGLEVEL command is described as follows:
// LOGLEVEL [<level>]
if( this.getParamCount() == 0 ) {
// this.getFactory().getServer().performLogLevel( null );
this.getFactory().getServer().getLogger().log( Level.INFO,
"Current log level is: " + this.getFactory().getServer().getLogger().getLevel() );
return 0; // implies success
} else {
String str_level = this.getParamAt(0).getString();
try {
Level level = Level.parse( str_level.toUpperCase() );
this.getFactory().getServer().getLogger().setLevel( level );
this.getFactory().getServer().getLogger().log( Level.INFO,
"Log level set to: " + level );
return 0; // implies success
} catch( BasicTypeException e ) {
this.getFactory().getServer().getLogger().log( Level.SEVERE,
"[Type error] " + e.getMessage() );
return 101; // implies error
} catch( IllegalArgumentException e ) {
this.getFactory().getServer().getLogger().log( Level.SEVERE,
"Illegal log level " + str_level );
return 101; // implies error
}
}
}
|
152d9823-6546-48b2-885e-e10dead65642
| 9
|
public static int howManySundays0(){
int sundays = 0;
//first pass
int day = 1;
int year = 1900;
for(; year < 1901; year++)
for(int month = 1; month <= 12; month++)
for(int date = 1; date <= daysInMonth(month, year); date++, day++){
if(day % 7 == 0)day = 0;
}
for(; year <= 2000; year++){
for(int month = 1; month <= 12; month++){
int limit = daysInMonth(month, year);
for(int date = 1; date <= limit; date++, day++){
if(day % 7 == 0){
if(date == 1) sundays++;
day = 0;
}
}
}
}
return sundays;
}
|
a2b60e17-7cb2-43df-a7d7-771540b2965e
| 5
|
public static ArrayList<Entity> getEntitiesWithinRange(Point location, double maxRange, Team entityTeam) {
ArrayList<Entity> entitiesWithinRange = new ArrayList<Entity>();
if (entityTeam == Team.EVIL) {
for (Enemy enemy : enemies) {
if (enemy.isLocationWithinDistance(location, maxRange)) {
entitiesWithinRange.add(enemy);
}
}
} else {
if (HeroInfo.INSTANCE.isHeroAlive() && HeroInfo.INSTANCE.getHero().isLocationWithinDistance(location, maxRange)) {
entitiesWithinRange.add(HeroInfo.INSTANCE.getHero());
}
}
return entitiesWithinRange;
}
|
0d032467-26ff-4fdd-ab49-5203d2ef80b4
| 7
|
public SecureChannel (byte[] secret, String algs)
throws NoSuchAlgorithmException
{
// reset counters
countIn = countOut = 0;
String digAlg = null;
String encAlg = null;
pending = null;
// parse definition string
int pos = algs.indexOf ('/');
if (pos < 0) {
// we have only one algorithm: find out
// whether it is a digest or encryption alg.
if (ChannelDigester.isSupported (algs))
// we have a digester but no cipher
digAlg = algs;
else if (ChannelCipher.isSupported (algs)) {
// we have a cipher but no digester
encAlg = algs;
}
} else {
// split the definition string
digAlg = algs.substring (0, pos);
if (!ChannelDigester.isSupported(digAlg))
throw new NoSuchAlgorithmException (digAlg);
encAlg = algs.substring (pos+1);
if (!ChannelCipher.isSupported(encAlg))
throw new NoSuchAlgorithmException (encAlg);
}
// instantiate worker objects
if (digAlg != null)
hasher = new ChannelDigester (digAlg, secret);
if (encAlg != null) {
encrypter = new ChannelCipher (encAlg, secret, true);
decrypter = new ChannelCipher (encAlg, secret, false);
}
}
|
636cff2e-497b-4032-a8fb-58f4e98c3298
| 6
|
public static String convertId(Object value){
if(value != null && String.class.isAssignableFrom(value.getClass())){
return value.toString();
}
else if (value != null && Double.class.isAssignableFrom(value.getClass())) {
StringBuilder sb = new StringBuilder();
String text = value.toString();
if(text.contains(".")){
String[] parts = text.split("\\.");
sb.append(parts[0]);
if(text.contains("E")){
String lastPart = parts[1].substring(0, (parts[1]).indexOf("E"));
sb.append(lastPart);
}
}
return sb.toString();
}
return "";
}
|
7f34aad4-69f5-4a78-83fe-533f1e3856bb
| 9
|
public List<Action> selectActions(boolean units, boolean buildings, boolean research, boolean upgrades) {
List<Action> actions = new ArrayList<Action>();
for(Action action : this.actions){
if (action.type == Type.Building && buildings)
actions.add(action);
if (action.type == Type.Unit && units)
actions.add(action);
if (action.type == Type.Research && research)
actions.add(action);
if (action.type == Type.Upgrade && upgrades)
actions.add(action);
}
return actions;
}
|
7a58e417-5a28-46f4-9d5b-7d693b28750f
| 8
|
public TypeBinding postConversionType(Scope scope) {
TypeBinding convertedType = this.resolvedType;
// if (this.genericCast != null)
// convertedType = this.genericCast;
int runtimeType = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4;
switch (runtimeType) {
case T_boolean :
convertedType = TypeBinding.BOOLEAN;
break;
case T_short :
convertedType = TypeBinding.SHORT;
break;
case T_char :
convertedType = TypeBinding.CHAR;
break;
case T_int :
convertedType = TypeBinding.INT;
break;
case T_float :
convertedType = TypeBinding.FLOAT;
break;
case T_long :
convertedType = TypeBinding.LONG;
break;
case T_double :
convertedType = TypeBinding.DOUBLE;
break;
default :
}
if ((this.implicitConversion & BOXING) != 0) {
convertedType = scope.environment().computeBoxingType(convertedType);
}
return convertedType;
}
|
1f9a7de5-bd45-45ba-ba42-db8e2f1b1ddd
| 0
|
@Override
public double getArea() {
return _width * _height;
}
|
9d7fa60d-5de2-48f2-9737-dcb62244f85f
| 5
|
public void run() {
try {
boolean work = true;
while (work) {
String str = in.readLine().replace(";;", "\n");
GUI.memo.append( "Server recived message:" );
GUI.println( str );
if (str == "END") {
socket.close();
UserList.user_list.remove(port);
work = false;
break;
} else {
Map<String, String> response;
response = (HashMap<String, String>) yaml.load(str);
Analizer.analize(response, this);
}
}
} catch (IOException e) {
System.err.println("IO Exception");
} catch(ClassCastException e){
System.out.println("Cannot get response");
}finally {
try {
socket.close();
UserList.user_list.remove(port);
} catch (IOException e) {
System.err.println("Socket not closed");
}
}
}
|
d14038d2-9d56-4b70-bc22-9de4223435b3
| 0
|
public String toCSV() {
return super.toCSV();
}
|
be0bb0b4-d47f-4c05-a993-a79768837f77
| 3
|
public void act() {
move();
Vector players = find("players");
if (players.size() > 0) {
for (int p = 0; p < players.size(); p++) {
Agent other = (Agent) players.elementAt(p);
//The agents only play when *both* have moved.
if (other.hasMoved) {
play(other);
}
}
}
}
|
d9b53acc-f681-447d-983b-5b8ab26ca1f0
| 6
|
@Override
public void run() {
if (Updater.this.url != null) {
// Obtain the results of the project's file feed
if (Updater.this.read()) {
if (Updater.this.versionCheck(Updater.this.versionName)) {
if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) {
String name = Updater.this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (Updater.this.versionLink.endsWith(".zip")) {
final String[] split = Updater.this.versionLink.split("/");
name = split[split.length - 1];
}
Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink);
} else {
Updater.this.result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
}
}
|
44b5a7a1-e0c6-44a5-ac8b-5b97fb652eee
| 1
|
static CursorContext getNepticalContext(NepticalContext nepticalContext) {
if (nepticalContext.getContextKey() == null) {
ContextKey contextKey = CONTEXT_KEY_FACTORY.createContextPartitionKey("UNSAFE".hashCode(),
nepticalContext.getIdentity().toString(), Location.class);
nepticalContext.setContextKey(contextKey);
LOGGER.warn(
"Attempted to set a context that has never been inialized with a context key. Creating a cursor context unique to context: "
+ nepticalContext);
return manifestCursorContext(contextKey);
}
return lookupContext(nepticalContext.getContextKey());
}
|
9591c47c-365f-4e29-b9e3-9039ac8905b1
| 4
|
public static void main(String[] args) throws IOException,
ParserConfigurationException, SAXException {
String path = "BIGxml.xml";
boolean error = false;
try {
if (args.length > 0) {
if (isValidXML(args[0])) {
path = args[0];
}
else {
System.out
.println("Invalid file path. Path must be to a valid XML file");
error = true;
}
}
if (!error) {
startRobot(path);
}
} catch (Exception exp) {
logger.log(Level.SEVERE, "Error starting robot with log", exp);
}
}
|
1574ab23-b2ef-42d6-9292-f662091c09e4
| 2
|
public void updateCustomer(boolean equal) {
Database db = dbconnect();
try {
StringBuilder query = new StringBuilder ();
query.append("UPDATE customer SET firstname = ?, "
+ "lastname = ?, username = ?");
if (!equal) {
query.append(",password = hash_pw(?),");
} else {
query.append(",password = ?,");
}
query.append("telephone = ?, email = ? WHERE CID = ? AND bDeleted = 0");
db.prepare(query.toString());
db.bind_param(1, this.c_firstname);
db.bind_param(2, this.c_lastname);
db.bind_param(3, this.c_username);
db.bind_param(4, this.c_pw);
db.bind_param(5, this.c_tel);
db.bind_param(6, this.c_email);
db.bind_param(7, this.CID.toString());
db.executeUpdate();
db.close();
} catch(SQLException e){
Error_Frame.Error(e.toString());
}
}
|
b39c98df-b57c-4752-af1d-0fd3440444be
| 4
|
public static void giveFlag(Cuboid c, String player, Flag flag) {
if (c == null || player == null || flag == null) return;
if (c.getFlags().get(flag).contains(player)) return;
c.getFlags().get(flag).add(player);
}
|
891cff73-5916-4e98-a843-30630d4093f0
| 5
|
public static List<Trends> constructTrendsList(Response res)
throws WeiboException {
JSONObject json = res.asJSONObject();
List<Trends> trends;
try {
Date asOf = parseDate(json.getString("as_of"));
JSONObject trendsJson = json.getJSONObject("trends");
trends = new ArrayList<Trends>(trendsJson.length());
Iterator ite = trendsJson.keys();
while (ite.hasNext()) {
String key = (String) ite.next();
JSONArray array = trendsJson.getJSONArray(key);
Trend[] trendsArray = jsonArrayToTrendArray(array);
if (key.length() == 19) {
// current trends
trends.add(new Trends(res, asOf, parseDate(key,
"yyyy-MM-dd HH:mm:ss"), trendsArray));
} else if (key.length() == 16) {
// daily trends
trends.add(new Trends(res, asOf, parseDate(key,
"yyyy-MM-dd HH:mm"), trendsArray));
} else if (key.length() == 10) {
// weekly trends
trends.add(new Trends(res, asOf, parseDate(key,
"yyyy-MM-dd"), trendsArray));
}
}
Collections.sort(trends);
return trends;
} catch (JSONException jsone) {
throw new WeiboException(jsone.getMessage() + ":" + res.asString(),
jsone);
}
}
|
376d4943-3fc7-41d4-a326-849379de4062
| 4
|
private static void findAllMaps(List<String> allMaps) {
try {
File[] folderFiles = MAP_FOLDER.listFiles();
assert folderFiles != null;
for (File fileEntry : folderFiles) {
if (fileEntry.isDirectory()) {
findAllMaps(allMaps);
} else {
String name = fileEntry.getName();
if (name.endsWith(".txt")) {
int indexOfFileExtension = name.indexOf('.', 0); //We only want the name of map, so we remove .txt in filename
allMaps.add(name.substring(0,indexOfFileExtension));
}
}
}
}catch (RuntimeException e){
e.printStackTrace();
}
}
|
640497d1-1584-4cb0-af05-231713afb7d0
| 1
|
@Override
public void update() {
Background background = null;
for (int i = 0; i < backgrounds.size(); i++) {
background = backgrounds.get(i);
background.update();
}
super.update();
}
|
994bb16a-90f0-4152-bb6c-ec7f66026fe9
| 7
|
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
// when this spell is on a MOBs Affected list,
// it should consistantly prevent the mob
// from trying to do ANYTHING except sleep
if(msg.amISource(mob))
{
if((!msg.sourceMajor(CMMsg.MASK_ALWAYS))
&&((msg.sourceMajor(CMMsg.MASK_HANDS))
||(msg.sourceMajor(CMMsg.MASK_MOVE))))
{
if(mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> struggle(s) against the web.")))
{
amountRemaining-=(mob.charStats().getStat(CharStats.STAT_STRENGTH)+mob.phyStats().level());
if(amountRemaining<0)
unInvoke();
}
return false;
}
}
return super.okMessage(myHost,msg);
}
|
48220b70-c7c5-4f08-9cec-81b07b8fab8b
| 2
|
public void InsertarVideo(ArrayList datos)
{
// Cambiamos todos los datos, que se puedan cambiar, a minúsculas
for(int i = 0 ; i < datos.size() ; i++)
{
try{datos.set(i, datos.get(i).toString().toLowerCase());}
catch(Exception e){}
}
biblioteca.insertarRegistros("video", datos);
}
|
21c6435f-b2df-49d8-8892-d6caa0349e64
| 6
|
static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
|
3abdfac4-bda3-4963-a52b-4bcf260baffc
| 2
|
public int getCoverage() {
int coverage = 0;
if (evalFalse > 0)
coverage += 50;
if (evalTrue > 0)
coverage += 50;
return coverage;
}
|
0b0da476-9cf2-49be-80b8-23deb5bef881
| 6
|
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
// g.drawImage(skybg, 0, 0);
g.setBackground(new Color(61, 52, 73, 1));
level.map.render(0,0);
if(player.alive)
g.drawAnimation(player.animation , player.x, player.y);
g.drawImage(levelText[0], 370, 10);
g.drawImage(levelText[currentLevel], 370 + levelText[0].getWidth() + 10, 10);
if(currentLevel == 1){
g.drawImage(arrows, 12 * TILESIZE, 16 * TILESIZE);
}
else if(currentLevel == 2){
g.drawImage(space, 4 * TILESIZE, 19 * TILESIZE);
}
// loop and render mobs
for (Iterator<Mob> iterator = mobs.iterator(); iterator.hasNext(); ) {
Mob m = iterator.next();
if(m.alive)
g.drawAnimation(m.animation, m.x, m.y);
else
iterator.remove();
}
// loop and render picakbles
for (Iterator<Pickable> iterator = pickables.iterator(); iterator.hasNext(); ) {
Pickable p = iterator.next();
g.drawAnimation(p.animation, p.x, p.y);
}
}
|
e19d69e0-0881-4419-bb14-1b72eb6ccad9
| 8
|
@Override
public Vector2f getHitSideVector(Entity entity) {
Shape[] skeleton = getSkeleton();
Vector2f vector = new Vector2f();
float ex = entity.getBBCentre().getX();
float ey = entity.getBBCentre().getY();
float cx = getBBCentre().getX();
float cy = getBBCentre().getY();
if (cx > ex && cy > ey) {
// 1
vector.x = skeleton[0].getPoint(1)[0] - skeleton[0].getPoint(0)[0];
vector.y = skeleton[0].getPoint(1)[1] - skeleton[0].getPoint(0)[1];
} else if (cx > ex && cy < ey) {
// 4
vector.x = skeleton[1].getPoint(0)[0] - skeleton[1].getPoint(2)[0];
vector.y = skeleton[1].getPoint(0)[1] - skeleton[1].getPoint(2)[1];
} else if (cx < ex && cy > ey) {
// 2
vector.x = skeleton[0].getPoint(2)[0] - skeleton[0].getPoint(1)[0];
vector.y = skeleton[0].getPoint(2)[1] - skeleton[0].getPoint(1)[1];
} else if (cx < ex && cy < ey) {
// 3
vector.x = skeleton[1].getPoint(2)[0] - skeleton[1].getPoint(1)[0];
vector.y = skeleton[1].getPoint(2)[1] - skeleton[1].getPoint(1)[1];
}
return vector;
}
|
40264c3c-03d4-4c32-93e4-989a9a0ba717
| 2
|
private MapPortal getMapPortal(Point location){
for (MapPortal portal : getPortals()){
if (portal.getLocation().equals(location)){
return portal;
}
}
return null;
}
|
482c9bc1-4cc3-4b98-9fa9-255e59a0fd50
| 6
|
@Override
public Stream resolveStreamUrl(final String url, boolean skipLogging) throws IOException {
HttpResponse resp = head(Request.to(url));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
Header location = resp.getFirstHeader("Location");
if (location != null && location.getValue() != null) {
final String headRedirect = location.getValue();
resp = safeExecute(null, new HttpHead(headRedirect));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Stream stream = new Stream(url, headRedirect, resp);
// need to do another GET request to have a URL ready for client usage
Request req = Request.to(url);
if (skipLogging) {
// skip logging
req.with("skip_logging", "1");
}
resp = get(req);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
return stream.withNewStreamUrl(resp.getFirstHeader("Location").getValue());
} else {
throw new ResolverException("Unexpected response code", resp);
}
} else {
throw new ResolverException("Unexpected response code", resp);
}
} else {
throw new ResolverException("Location header not set", resp);
}
} else {
throw new ResolverException("Unexpected response code", resp);
}
}
|
a6eb0fd7-0e78-4a68-9f20-e5966521fbea
| 4
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Room other = (Room) obj;
if (uid != other.uid)
return false;
return true;
}
|
2d2bc271-0a2c-420f-8e71-11e099d693b9
| 9
|
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((affected!=null)&&(affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
final MOB mob=(MOB)affected;
if((buildingI==null)
||((fireRequired)&&(getRequiredFire(mob,0)==null))
||(theSpell==null))
{
aborted=true;
unInvoke();
}
else
if(tickUp==0)
{
if((theSpell.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER)
{
commonEmote(mob,L("<S-NAME> start(s) praying for @x1.",buildingI.name()));
displayText=L("You are praying for @x1",buildingI.name());
verb=L("praying for @x1",buildingI.name());
}
else
{
commonEmote(mob,L("<S-NAME> start(s) brewing @x1.",buildingI.name()));
displayText=L("You are brewing @x1",buildingI.name());
verb=L("brewing @x1",buildingI.name());
playSound="hotspring.wav";
}
}
}
return super.tick(ticking,tickID);
}
|
8bd1563c-95e7-4bf0-b73b-3a954cf9f39c
| 1
|
public Graph createGraph(final String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
final Graph graph = new Graph(name);
// Now we can add our graph
graphs.add(graph);
// and return back
return graph;
}
|
def7ddb2-696b-4fb7-9589-f96defa9f3be
| 7
|
public final String method1(int i, int j, int ai[], long l) {
if (j != -8945) {
method1(-60, -74, null, -72L);
}
if (i == 0) {
Class142_Sub27_Sub14 class142_sub27_sub14 = Animation.method962(ai[0], -2882);
return class142_sub27_sub14.method1887((int) l, (byte) 1);
}
if (i == 1 || i == 10) {
ItemDefinition itemDefinition = NPC.itemDefinitionForID((int) l);
return itemDefinition.name;
}
if (i == 6 || i == 7 || i == 11) {
return Animation.method962(ai[0], -2882).method1887((int) l, (byte) 1);
} else {
return null;
}
}
|
04cdce72-e276-415a-af82-b512f8ed0943
| 3
|
private String getRightStringResult(String step, int pos, char value) {
String result = "";
pos++; // the initial position is already taken care of
int max = step.length();
for (; pos < max; pos++) {
if (step.charAt(pos) != '0' && step.charAt(pos) != '1') {
break;
}
result += value;
}
return result;
}
|
6f0f028a-ebc7-4931-b7d7-47ad80060805
| 2
|
public SQLite_helper() throws Throwable {
// load driver; connect to DB
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection(urlToDb);
// test if Tables have already been set up; initialize if not
try {
pst = con.prepareStatement("SELECT * FROM users;");
rs = pst.executeQuery();
if(!rs.next()) init_db();
rs.close();
pst.close();
} catch(SQLException k) {
init_db();
}
}
|
ec2eaf45-9012-4a47-8d09-4343fed6cb99
| 3
|
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof ActorModel)
{
ActorModel currentActor = (ActorModel) obj;
if (currentActor.id == this.id)
{
return true;
}
}
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.