method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
3a429f5e-1a3d-4503-941b-b6775c012776 | 5 | public static void main(String[] args) {
final int NOMBRE = 5;
findNumero();
String numero;
int i;
int j;
for(i = 0; i < NOMBRE; i++) {
numero = genNumero();
for(j = 0; j < TAILLE; j++) {
System.out.print(numero.charAt(j));
if(j == 2 || j == 5)
System.out.print(" ");
}
System.out.print(" -> "+(isNumero(numero)==true?"valide":"non-valide")+"\n");
}
System.exit(0);
} |
6e512b39-845c-4c75-a5c8-801c61d44d2b | 4 | public void framerateManager()
{
if( lastFPS <=System.currentTimeMillis() )
{
fps=""+frames;
//System.out.println(fps);
lastFPS = System.currentTimeMillis() + 1000;
if(frames<80&&slp>0)
slp--;
else if(frames>110)
slp++;
frames=0;
}
} |
9e6f9e00-6071-4e36-8f4c-df10c33bac04 | 6 | @Override
public int compareTo(PacketEntry that) {
// compare type first
if (this.underlyingPacket.getPacketType().getTypePriority() > that.underlyingPacket
.getPacketType().getTypePriority()) {
return -1;
} else if (this.underlyingPacket.getPacketType().getTypePriority() < that.underlyingPacket
.getPacketType().getTypePriority()) {
return 1;
}
// type is same, now compare size
if (this.underlyingPacket.getPacketSize().getSizePriority() > that.underlyingPacket
.getPacketSize().getSizePriority()) {
return -1;
} else if (this.underlyingPacket.getPacketSize().getSizePriority() < that.underlyingPacket
.getPacketSize().getSizePriority()) {
return 1;
}
// size and type are both same - use entry time as tiebreaker
if (this.queueEntryTime < that.queueEntryTime) {
// packet with lower entry time should go to the
// head of the queue so return -1
return -1;
} else if (this.queueEntryTime > that.queueEntryTime) {
return 1;
}
// everything is equal so return 0.
return 0;
} |
1305c84f-0b4a-4766-babd-054c2891a904 | 5 | public static void decode(final String password, final String codeImagePath, final boolean useOTP, final String otpImagePath, final IDECoderInterface coderInterface) {
Thread t = new Thread() {
@Override
public void run() {
byte[] data = null;
String error = "";
boolean success = false;
try {
File codeImage = new File(codeImagePath);
if (codeImage.exists() && codeImage.canRead()) {
BufferedImage code = ImageIO.read(codeImage);
BufferedImage otp = null;
if (useOTP) {
otp = ImageIO.read(new File(otpImagePath));
}
data = decodeData(password, code, otp);
success = true;
}
} catch (Exception ex) {
error = ex.getMessage();
success = false;
}
if (success) {
coderInterface.dataSuccessfullyDecoded(codeImagePath, data);
} else {
coderInterface.decodingError(codeImagePath, error);
}
}
};
t.start();
} |
077dc0a8-ebbb-4771-8679-f8f2effacb5a | 2 | public void padr()
{
if (("MI").indexOf(ftype)>=0) {/*do nothing */}
else if (("CLD").indexOf(ftype)>=0) addc(false," ");
else addc(false,"\0");
} |
847592d6-6b2e-47ba-a70c-792e7748df5d | 9 | @Override
public Object execute(Object obj, Object[] args) {
// 获取Mongo查询中需要用到的查询shell和参数
Method[] getterMethods = definition.getGetterMethods();
Integer[] parameterIndexes = definition.getParameterIndexes();
BeanMapper<?> beanMapper = definition.getBeanMapper();
int batchSize = definition.getBatchSize();
String actualShell = definition.getShellWithToken();
List<String> parameterNames = definition.getParsedShell().getParameterNames();
Object[] paramArray = ReflectionUtils.fetchValues(getterMethods, parameterIndexes, args, parameterNames);
String collectionName = definition.getCollectionName(args);
MongoQuery query = new MongoQuery(actualShell, paramArray);
query.setBatchSize(batchSize);
DBObject sort = definition.getSortObject();
query.setSort(sort);
// 判断是否为分页查询,如果是则进行分页查询
Page page = definition.getPageArgument(args);
if (page != null) {
return dataAccessor.findPage(collectionName, query, beanMapper, page);
}
LOGGER.info("Mongo查询操作Shell(带Token)[" + actualShell + "]");
// 不是分页,进行普通查询
Integer skip = definition.getSkip(args);
if (skip == null) {
skip = -1;
}
query.setSkip(skip);
Integer limit = definition.getLimit(args);
if (limit == null) {
limit = -1;
}
query.setLimit(limit);
List<?> result = dataAccessor.find(collectionName, query, beanMapper);
if (definition.isUnique()) {
if (result == null || result.isEmpty()) {
return null;
}
if (result.size() > 1) {
LOGGER.debug("返回记录数 >1,默认获取第一条记录");
}
return result.get(0);
} else {
return result;
}
} |
6f834f57-c0a1-4647-a4c5-0a72ab59ee4d | 2 | public void insertDates() throws ParseException{
// http://docs.oracle.com/javase/tutorial/essential/io/file.html
// http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
//
Path file = Paths.get("/home/mark/0-prj/bible/bookchap-v3.csv");
Charset charset = Charset.forName("US-ASCII");
//
// http://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java
//
String dt = "2013-03-08"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
String WEEKDAY_CHINESE="日一二三四五六";
int id=0;
for (int ww = 1; ww <= 52; ww++) {
for (int dd = 0; dd < 7; dd++) {
id++;
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
System.out.printf("INSERT INTO `bible`.`dates` ( `ID` , `DATE` , `WEEKNUM` ,`WEEKDAY` ) VALUES (");
System.out.printf("'%s', ", id);
System.out.printf("'%s', ", dt);
System.out.printf("'%s', ", ww);
System.out.printf("'%s' ", WEEKDAY_CHINESE.charAt(dd));
System.out.printf("); %n");
}
}
} |
5122aa8a-9c62-4f9f-92f7-ab5b0d0132fc | 9 | public void applyPositionChange(Vector3d[] linearChange,
Vector3d[] angularChange, double max) {
double[] angularMove = new double[2];
double[] linearMove = new double[2];
double totalInertia = 0.0d;
double[] linearInertia = new double[2];
double[] angularInertia = new double[2];
for (int i = 0; i < 2; i++)
{
if (body[i] != null)
{
Matrix3d inverseInertiaTensor = new Matrix3d();
inverseInertiaTensor = body[i].getInverseInertiaTensorWorld();
Vector3d angularInertiaWorld = new Vector3d(relativeContactPosition[i]);
angularInertiaWorld = angularInertiaWorld.CrossProduct(contactNormal);
angularInertiaWorld = inverseInertiaTensor.Transform(angularInertiaWorld);
angularInertiaWorld = angularInertiaWorld.CrossProduct(relativeContactPosition[i]);
angularInertia[i] = angularInertiaWorld.ScalarProduct(contactNormal);
linearInertia[i] = body[i].getInverseMass();
totalInertia += linearInertia[i] + angularInertia[i];
}
}
for (int i = 0; i < 2; i++)
{
if (body[i] != null)
{
double sign = (i == 0) ? 1.0d : -1.0d;
angularMove[i] = sign * penetration * (angularInertia[i]/totalInertia);
linearMove[i] = sign * penetration * (linearInertia[i]/totalInertia);
Vector3d projection = new Vector3d(relativeContactPosition[i]);
projection.addScaledVector(contactNormal, -relativeContactPosition[i].ScalarProduct(contactNormal));
double maxMagnitude = angularLimit * projection.Magnitude();
if (angularMove[i] < -maxMagnitude)
{
double totalMove = angularMove[i] + linearMove[i];
angularMove[i] = -maxMagnitude;
linearMove[i] = totalMove - angularMove[i];
}
else if (angularMove[i] > maxMagnitude)
{
double totalMove = angularMove[i] + linearMove[i];
angularMove[i] = maxMagnitude;
linearMove[i] = totalMove - angularMove[i];
}
if (angularMove[i] == 0.0d)
{
angularChange[i].clear();
}
else
{
Vector3d targetAngularDirection = relativeContactPosition[i].CrossProduct(contactNormal);
Matrix3d inverseInertiaTensor = new Matrix3d();
inverseInertiaTensor = body[i].getInverseInertiaTensorWorld();
Vector3d transform = new Vector3d(inverseInertiaTensor.Transform(targetAngularDirection));
transform.Multiply(angularMove[i]/angularInertia[i]);
angularChange[i] = new Vector3d(transform);
}
linearChange[i] = contactNormal.NewVectorMultiply(linearMove[i]);
Vector3d pos = new Vector3d(body[i].getPosition());
pos.addScaledVector(contactNormal, linearMove[i]);
body[i].setPosition(pos);
Quaternion q = new Quaternion(body[i].getOrientation());
q.AddScaledVector(angularChange[i], 1.0d);
body[i].setOrientation(q);
if (!body[i].getAwake()) body[i].CalculateDerivedData();
}
}
} |
e56f9ca0-978a-4fe1-a516-b25884bccc7c | 3 | public static String getMaxCategoryID(){
try {
ResultSet rs=DB.myConnection().createStatement().executeQuery("select max(CategoryID) from category");
while(rs.next()){
max_category_id=Integer.toString(rs.getInt(1)+1);
}
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Error @ LoadCategoryID class not found exception");
}catch(SQLException e2){
JOptionPane.showMessageDialog(null, "Error @ LoadCategoryID SQL exception");
}
return max_category_id;
} |
5a9bb9d4-0f88-4e76-a1f8-d40384451700 | 7 | private void calculate_amplitude() {
int envelope_volume, tremolo_volume, amplitude;
int envelope_panning, mixer_panning, panning_range;
Envelope envelope;
envelope_volume = 0;
if( instrument.volume_envelope_active ) {
envelope = instrument.get_volume_envelope();
envelope_volume = envelope.calculate_ampl( volume_envelope_tick );
} else {
if( key_on ) {
envelope_volume = 64;
}
}
tremolo_volume = volume + tremolo_add;
if( tremolo_volume < 0 ) {
tremolo_volume = 0;
}
if( tremolo_volume > 64 ) {
tremolo_volume = 64;
}
amplitude = tremolo_volume << IBXM.FP_SHIFT - 6;
amplitude = amplitude * envelope_volume >> 6;
amplitude = amplitude * fade_out_volume >> 15;
amplitude = amplitude * global_volume[ 0 ] >> 6;
amplitude = amplitude * module.channel_gain >> IBXM.FP_SHIFT;
silent = sample.has_finished( sample_idx );
if( amplitude <= 0 ) {
silent = true;
} else {
envelope_panning = 32;
if( instrument.panning_envelope_active ) {
envelope = instrument.get_panning_envelope();
envelope_panning = envelope.calculate_ampl( panning_envelope_tick );
}
mixer_panning = ( panning & 0xFF ) << IBXM.FP_SHIFT - 8;
panning_range = IBXM.FP_ONE - mixer_panning;
if( panning_range > mixer_panning ) {
panning_range = mixer_panning;
}
mixer_panning = mixer_panning + ( panning_range * ( envelope_panning - 32 ) >> 5 );
left_gain = amplitude * ( IBXM.FP_ONE - mixer_panning ) >> IBXM.FP_SHIFT;
right_gain = amplitude * mixer_panning >> IBXM.FP_SHIFT;
}
} |
c09f268d-8944-420d-ac58-e92b46119137 | 8 | public void visit_astore(final Instruction inst) {
final int index = ((LocalVariable) inst.operand()).index();
if (index + 1 > maxLocals) {
maxLocals = index + 1;
}
if (inst.useSlow()) {
if (index < 256) {
addOpcode(Opcode.opc_astore);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_astore);
addShort(index);
}
stackHeight--;
return;
}
switch (index) {
case 0:
addOpcode(Opcode.opc_astore_0);
break;
case 1:
addOpcode(Opcode.opc_astore_1);
break;
case 2:
addOpcode(Opcode.opc_astore_2);
break;
case 3:
addOpcode(Opcode.opc_astore_3);
break;
default:
if (index < 256) {
addOpcode(Opcode.opc_astore);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_astore);
addShort(index);
}
break;
}
stackHeight--;
} |
f47386d6-21cd-41c6-8d20-7d48a62b1407 | 9 | public void roll(int pinDown) {
System.out.println(currentFrame + "프레임 " + currentRoll + "번째 투구");
System.out.println("공을 굴립니다! 데구르르르....");
totalRoll++;
currentPin = currentPin - pinDown;
System.out.println(pinDown + "핀을 쳤습니다!");
if (currentRoll == 1 && pinDown == 10) {
System.out.println("대단해요! 스트라이크입니다!");
Frames.add(currentFrame, frame.generateStrike());
goNextFrame();
}
else if (currentRoll == 2 && currentPin == 0) {
System.out.println("멋진 스페어처리군요.");
putScoreTable('/');
goNextFrame();
}
else if (currentRoll == 1 && pinDown == 0) {
System.out.println("초구부터 거터라니ㅠ");
putScoreTable('-');
goNextRoll();
}
else if (currentRoll == 2 && pinDown == 0) {
System.out.println("두번째가 거터라니. 슬프네요.");
putScoreTable('-');
goNextFrame();
}
else if (currentRoll == 2) {
putScoreTable((char) pinDown);
goNextFrame();
}
else {
goNextRoll();
}
} |
fc25ec4a-b476-4860-a9f0-bac4406efb80 | 4 | @SuppressWarnings("unchecked")
@Override
public String displayQuestionWithAnswer(int position, Object userAnswer) {
String questionStr = (String) question;
ArrayList<String> answerList = (ArrayList<String>) answer;
String userAnswerStr = (String) userAnswer;
boolean correct = false;
if (getScore(userAnswer) == score)
correct = true;
StringBuilder sb = new StringBuilder();
sb.append("<span class=\"dominant_text\">Feedback for Question " + position + " (Score: " + Math.round(getScore(userAnswer)*100)/100.0 + "/" + Math.round(score*100)/100.0 + ")" + ":</span><br /><br />\n");
sb.append("<span class=\"quiz_title\">\n");
sb.append(questionStr + "\n");
sb.append("</span><br /><br />\n");
sb.append("<p class=\"answer\">Your answer is :\n");
if (correct) {
sb.append("<span class=\"correct answer\">" + userAnswerStr + "  </span>");
sb.append("<img class=\"small\" src=\"images/right.png\"></p><br /><br />");
} else {
sb.append("<span class=\"wrong answer\">" + userAnswerStr + "  </span>");
sb.append("<img class=\"small\" src=\"images/wrong.png\"><span class=\"wrong\">incorrect</span></p><br />\n");
sb.append("<p class=\"answer\">Correct answer : <span class=\"correct answer\">");
for (int i = 0; i < answerList.size(); i++) {
sb.append(answerList.get(i));
if (i < answerList.size() - 1)
sb.append(" OR ");
}
sb.append("</span></p>\n");
}
return sb.toString();
} |
4a944b86-2ea5-469b-846e-0d6554efd9e7 | 1 | public static List<String> getStrings() {
ArrayList<String> strings = new ArrayList<>();
for (DataType dataType : DataType.values()) {
strings.add(dataType.toString());
}
return strings;
} |
d1d06979-8251-4e6b-ac08-1a301fec13bd | 5 | public int neighbors(){
// Requires indexes of array
int countLiveNeighbors = 0;
for (int offsetY = -1; offsetY <= 1; offsetY++){
for(int offsetX = -1; offsetX <= 1; offsetX++){
if (0 != offsetX || 0 != offsetY) {
int altRow = mod(positionY+offsetY, this.height);
int altCol = mod(positionX+offsetX, this.width);
countLiveNeighbors += (petriDish[altRow][altCol]) ? 1 : 0;
}
}
}
return countLiveNeighbors;
} |
47b6b393-47f1-413e-8b37-6c0628c99273 | 9 | public String run(File f) throws IOException, JAXBException{
if(isUniconvertoInstalled() && isImageMagickInstalled()){
List<String> command = new ArrayList<String>(Arrays.asList("identify", "-verbose",f.getPath()));
String identifyOutput = CommandLine.exec(command, null);
Result res = new Result();
res.setValid(false);
res.setFeatures(new Hashtable<String, String>());
try{
Map<String,String> properties = extractMetadata(identifyOutput);
if(properties.containsKey("Format") && properties.get("Format").equalsIgnoreCase("cdr")){
res.setValid(true);
}
if(res.isValid()){
res.setFeatures(properties);
}
}catch(Exception e){
}
try{
if(isCdrToolsInstalled()){
List<String> cdr2rawCommand = new ArrayList<String>(Arrays.asList("cdr2raw",f.getPath()));
String cdr2rawOutput = CommandLine.exec(cdr2rawCommand, null);
if(!cdr2rawOutput.toUpperCase().contains("ERROR:")){
res.setValid(true);
}
}
}catch(Exception e){
//e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JAXBContext jaxbContext = JAXBContext.newInstance(Result.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(res, bos);
return bos.toString("UTF-8");
}
return null;
} |
b56f3c93-e561-4234-83c0-1341c191a506 | 9 | public boolean blockCheck() {
for (int k = 0; k < blockX.size(); k++) {
for (int i = 0; i < cb.length; i++) {
for (int j = 0; j < cb.length; j++) {
if (cb[i][j] % 2 != 0 && cb[i][j] != 0) {
if (checkBlackAttack(cb, cb[i][j], j, i, blockX.get(k), blockY.get(k))) {
return true;
}
}
if (cb[i][j] % 2 == 0 && cb[i][j] != 0) {
if (checkWhiteAttack(cb, cb[i][j], j, i,blockX.get(k), blockY.get(k))) {
return true;
}
}
}
}
}
return false;
} |
31a286c0-0ff3-47a3-9a83-d25f62cb405d | 2 | @OnLoad
public void onLoad() {
UserModel user = DataStore.getUser(getParis_userId());
if(user!=null) this.paris_user = user;
ScheduleModel sched = DataStore.getSchedule(getParis_schedId());
if(sched!=null) this.paris_sched = sched;
} |
65cb7060-4808-44d3-93b3-2ca68862abb1 | 7 | @Override
public void run(){
Exception invocationError = null;
setResponse(null);
try {
if (false) throw new Exception("");
// It's a synchronized sectiondue the fact is not guaranteed that the proxy object
// hasn't been shared along different threads
synchronized(serviceProxy){
setResponse(getMethod().invoke(getServiceProxy(), getParams()));
}
}
catch (IllegalAccessException ex) {
invocationError = new ServiceDefinitionException(getServiceCode(), ex);
}
catch (IllegalArgumentException ex) {
invocationError = new ServiceDefinitionException(getServiceCode(), ex);
}
catch (InvocationTargetException ex) {
invocationError = new ServiceDefinitionException(getServiceCode(), ex);
}
catch (Exception ex){
invocationError = ex;
}
if ( this.listener != null ){
if (invocationError == null){
// success
this.listener.successAction(getServiceCode(), getResponse(), getParams(), getExtraData());
}
else {
// error
this.listener.errorAction(getServiceCode(), invocationError, getParams(), getExtraData());
}
}
} |
78539b48-a43b-4b73-b98f-6943f68df7f2 | 3 | public static String[][] getLinks(String webpage) throws IOException, BadLocationException {
doc = new HTMLDocument();
InputStream in = new URL(webpage).openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(in,"ISO-8859-1");
String[][] matrix = new String[50][50];
int i = 0;
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
try {
new HTMLEditorKit().read(reader, doc, 0);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
while (it.isValid()) {
StringBuffer text = new StringBuffer();
int start = it.getStartOffset();
int end = it.getEndOffset();
int length = end - start;
text.append(doc.getText(start, length));
String url = it.getAttributes().toString().split("=")[1];
String[] matrix2 = { text.toString(), url };
if (i < 50) {
matrix[i] = matrix2;
i++;
it.next();
} else {
break;
}
}
return matrix;
} |
b48669a6-d050-40e0-97f8-c5fc00c6f50b | 0 | public void setPrice(float price) {
this.price = price;
} |
45191e11-8dc1-4bb2-be5f-d9bcaba786a0 | 7 | @Override
public void init() {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PokemonMoveset.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PokemonMoveset.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PokemonMoveset.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PokemonMoveset.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the applet
*/
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
} |
1aabad8b-49f9-45f4-9e58-c331a9574861 | 8 | public void visitBaseType(final char descriptor) {
switch (descriptor) {
case 'V':
declaration.append("void");
break;
case 'B':
declaration.append("byte");
break;
case 'J':
declaration.append("long");
break;
case 'Z':
declaration.append("boolean");
break;
case 'I':
declaration.append("int");
break;
case 'S':
declaration.append("short");
break;
case 'C':
declaration.append("char");
break;
case 'F':
declaration.append("float");
break;
// case 'D':
default:
declaration.append("double");
break;
}
endType();
} |
6ec474af-f0e9-4869-8f9c-c7724bc5a36d | 3 | public void disableServiceMode(Player player)
{
if(null != player)
{
if(playersInSM.contains(player.getName()))
{
playersInSM.remove(player.getName());
if(player.isOnline())
{
player.sendMessage(ChatColor.RED + "Service-Modus AUS");
}
}
}
} |
cc3af1e3-648b-4584-9af9-15672c40aeff | 1 | private static void displaySchedules(ResultSet rs)throws SQLException{
StringBuffer bf = new StringBuffer();
while (rs.next()){
bf.append(rs.getDate("work_day")+", ");
bf.append(rs.getTime("work_from")+", ");
bf.append(rs.getTime("work_till")+", ");
bf.append(rs.getBigDecimal("hourly_rate")+", ");
bf.append(rs.getInt("vac_days")+", ");
bf.append(rs.getString("username"));
System.out.println(bf.toString());
bf.delete(0, bf.length());
}
} |
4534a19c-1769-457b-98d3-2a6f1180c647 | 0 | private void loginPage(){
loginPane = new JPanel();
loginPane.setBackground(SystemColor.activeCaption);
loginPane.setLayout(null);
//Title Image, CareMRS
ImageIcon image_title;
JLabel label1;
image_title = new ImageIcon(getClass().getResource("CareMRS.png"));
label1 = new JLabel(image_title);
label1.setBounds(51,32,871,196);
loginPane.add(label1);
//Button, Login
JButton B_login = new JButton("Login");
B_login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
login(L_userNameField.getText(),L_passwordField.getPassword());
L_userNameField.setText(null);
L_passwordField.setText(null);
}
});
B_login.setFont(new Font("Arial", Font.PLAIN, 20));
B_login.setBounds(327, 452, 110, 60);
loginPane.add(B_login);
//Button, Exit
JButton B_exit = new JButton("Exit");
B_exit.setBackground(new Color(255, 192, 203));
B_exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
B_exit.setFont(new Font("Arial", Font.PLAIN, 20));
B_exit.setBounds(547, 452, 110, 60);
loginPane.add(B_exit);
//Label, User name
JLabel lblNewLabel = new JLabel("User Name :");
lblNewLabel.setFont(new Font("Arial", Font.PLAIN, 20));
lblNewLabel.setBounds(285, 265, 120, 30);
loginPane.add(lblNewLabel);
//Label, Password
JLabel lblPassword = new JLabel("Password :");
lblPassword.setFont(new Font("Arial", Font.PLAIN, 20));
lblPassword.setBounds(285, 342, 120, 30);
loginPane.add(lblPassword);
} |
6d37f07f-36b2-416d-bad3-692bcdceeacb | 5 | private void setData( TLanguageFile langFile, TProject pProject )
{
project = pProject ;
if ( langFile != null )
{
mode = EDIT_MODE ;
filenameField.setText( langFile.getFileName() ) ;
String dummy = langFile.getLanguageCode() ;
if ( ( dummy != null ) && ( dummy.length() > 0 ) )
{
fullLangField.setText( TLanguageNames.runtime.getLanguageName( dummy ) ) ;
}
else
{
fullLangField.setText( "" ) ;
}
encCombo.setSelectedItem( langFile.getDefaultEncoding() );
langField.setText( dummy ) ;
dummy = langFile.getCountryCode() ;
if ( dummy != null )
{
fullCountryField.setText( TCountryNames.runtime.getCountryName( dummy ) ) ;
}
else
{
fullCountryField.setText( "" ) ;
}
countryField.setText( langFile.getCountryCode() ) ;
variantField.setText( langFile.getVariantCode() ) ;
escapeCB.setSelected( langFile.isSaveWithEscapeSequence() );
}
else
{
mode = ADD_MODE ;
filenameField.setText( "" ) ;
langField.setText( "" ) ;
fullLangField.setText( "" ) ;
countryField.setText( "" ) ;
fullCountryField.setText( "" ) ;
variantField.setText( "" ) ;
encCombo.setSelectedIndex(0);
escapeCB.setSelected(true);
}
if ( project != null )
{
dirChooser.setSelectedFile( new File( project.getWorkingDirectory() ) ) ;
checkEncoding();
}
} |
04ad9727-2b68-4767-b737-15c2b97225d7 | 3 | public void draw() {
Graphics.setColour(192, 192, 255);
for (int i = 0; i < body.size(); i ++) {
Cell c = body.get(i);
if (i >= bullets) Graphics.setColour(255, 255, 255);
Graphics.rectangle(true, c.x * Map.TILE_SIZE, c.y * Map.TILE_SIZE, Map.TILE_SIZE, Map.TILE_SIZE);
}
for (Pellet p : pelletsEating) {
Graphics.setColour(128, 255, 128, 128);
Graphics.rectangle(true, p.x * Map.TILE_SIZE, p.y * Map.TILE_SIZE, Map.TILE_SIZE, Map.TILE_SIZE);
}
Graphics.setColour(255, 255, 255);
} |
68aa29df-42b9-46d3-b8e5-a04563d66d94 | 5 | @EventHandler
public void onPlayerQuit(PlayerQuitEvent event){
final Player p = event.getPlayer();
final String pname = p.getName();
if(plugin.getArena(p)!= null){
a = plugin.getArena(p);
plugin.Out.get(a).add(pname);
plugin.Playing.get(a).remove(pname);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ // Jeppa: how long is this delay?
public void run(){
if(plugin.Out.get(a).contains(pname)){
plugin.Quit.get(a).add(pname);
plugin.Out.get(a).remove(pname); //Jeppa: fix
p.getScoreboard().clearSlot(DisplaySlot.SIDEBAR);
if(plugin.scoreboards.containsKey(p.getName()))
plugin.scoreboards.remove(p.getName());
if(plugin.Kills.containsKey(p.getName()))
plugin.Kills.remove(p.getName());
plugin.winner(a);
plugin.inArena.get(a).add(pname); //Jeppa: add him to Quit and to inArena ?
}else if(plugin.getArena(p)== null){
plugin.Quit.get(a).add(pname);
}
}
}, 1200L);
}
} |
2ed63384-5318-4ed1-a9b4-eca143184e2a | 9 | public final void setTeacher(final Unit newTeacher) {
Unit oldTeacher = this.teacher;
if(newTeacher == oldTeacher){
return;
}
if (newTeacher == null) {
this.teacher = null;
if(oldTeacher != null && oldTeacher.getStudent() == this){
oldTeacher.setStudent(null);
}
} else {
UnitType skillTaught = newTeacher.getType().getSkillTaught();
if (newTeacher.getColony() != null &&
newTeacher.getColony() == getColony() &&
getColony().canTrain(skillTaught)) {
if(oldTeacher != null && oldTeacher.getStudent() == this){
oldTeacher.setStudent(null);
}
this.teacher = newTeacher;
this.teacher.setStudent(this);
} else {
throw new IllegalStateException("unit can not be teacher: " + newTeacher);
}
}
} |
075caccf-5e5a-4038-9b06-22eb6437ddbe | 3 | public void paintComponent(Graphics g) {
setScale(); //makes the grid scale according to panel size
if(!background) {
g.drawImage(Player.getImage(), 25, 35, (cellWidth+1)*this.width+1, (cellHeight+1)*this.height+1, null);
background = trace;
}
g.setColor(Color.CYAN);
drawCells(g);
if(gui.getLose()) { //if lose displays a GAME OVER message
g.setFont(g.getFont().deriveFont(100f).deriveFont(Font.BOLD));
g.setColor(Color.RED);
g.drawString("GAME OVER", 25 + ((cellWidth+1)*this.width+1 - g.getFontMetrics().stringWidth("GAME OVER"))/2,
25 + (int) (((cellHeight+1)*this.height+1 - g.getFontMetrics().getStringBounds("GAME OVER", g).getHeight())/2));
}
if(gui.getWin()) { //if win displays a YOU WIN message
g.setFont(g.getFont().deriveFont(100f).deriveFont(Font.BOLD));
g.setColor(Color.GREEN);
g.drawString("YOU WIN", 25 + ((cellWidth+1)*this.width+1 - g.getFontMetrics().stringWidth("YOU WIN"))/2,
25 + (int) (((cellHeight+1)*this.height+1 - g.getFontMetrics().getStringBounds("YOU WIN", g).getHeight())/2));
}
} |
5004434c-5084-463b-a04b-d0f16772977f | 1 | public void loadUsers(){
table=new DefaultTableModel();
table.addColumn("Usuarios");
table.addColumn("Contraseñas");
this.tableUsers.setModel(table);
String[][] user=con.leerDatos("usuarios","user,pass", null);
for(int i=0;i<user.length;i++){
String[] data=new String[2];
data[0]=user[i][0];data[1]=user[i][1];
table.addRow(data);
}
} |
7e8dd95d-c1f5-4409-ada1-d114b74569cc | 1 | public void setPWResetFonttype(Fonttype fonttype) {
if (fonttype == null) {
this.pwResetFontType = UIFontInits.PWRESET.getType();
} else {
this.pwResetFontType = fonttype;
}
somethingChanged();
} |
c60554a5-cd75-4dc9-bf83-4a1ca335431c | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaCadastroPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaCadastroPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaCadastroPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaCadastroPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaCadastroPessoa().setVisible(true);
}
});
} |
bf9c8b76-e9cd-4f8a-ae8b-a44fea72de6f | 8 | public String alignment(ErrorStream obostream) {
String str = "";
int i = 0;
for(WeightedError err : obostream) {
if (err.max() != null && i < size()) {
if(!(ignore_noerr && (err.max().getType() == ErrorTypes.UNC_NO_ERR ||
err.max().getType() == ErrorTypes.OBO_NOERR))) {
if (err.max().getIs() == get(i).getTyped() || err.max().getShould() == get(i).getTyped()) {
str += err.max() + " " + get(i) + " " + get(i).getAcceleration() + "\n";
i++;
} else {
str += err.max() + "\n";
}
}
}
}
return str;
} |
1e15fb2e-40e2-4169-a568-4891dd567e7e | 9 | public void loadConfig(String config)
throws IOException
{
Properties properties = new Properties();
Resource resource=Resource.newResource(config);
properties.load(resource.getInputStream());
_jdbcDriver = properties.getProperty("jdbcdriver");
_url = properties.getProperty("url");
_userName = properties.getProperty("username");
_password = properties.getProperty("password");
_userTable = properties.getProperty("usertable");
_userTableKey = properties.getProperty("usertablekey");
_userTableUserField = properties.getProperty("usertableuserfield");
_userTablePasswordField = properties.getProperty("usertablepasswordfield");
_roleTable = properties.getProperty("roletable");
_roleTableKey = properties.getProperty("roletablekey");
_roleTableRoleField = properties.getProperty("roletablerolefield");
_userRoleTable = properties.getProperty("userroletable");
_userRoleTableUserKey = properties.getProperty("userroletableuserkey");
_userRoleTableRoleKey = properties.getProperty("userroletablerolekey");
_cacheTime = new Integer(properties.getProperty("cachetime")).intValue();
if (_jdbcDriver == null || _jdbcDriver.equals("")
|| _url == null || _url.equals("")
|| _userName == null || _userName.equals("")
|| _password == null
|| _cacheTime < 0)
{
if(log.isDebugEnabled())log.debug("UserRealm " + getName()
+ " has not been properly configured");
}
_cacheTime *= 1000;
_lastHashPurge = 0;
_userSql = "select " + _userTableKey + ","
+ _userTablePasswordField + " from "
+ _userTable + " where "
+ _userTableUserField + " = ?";
_roleSql = "select r." + _roleTableRoleField
+ " from " + _roleTable + " r, "
+ _userRoleTable + " u where u."
+ _userRoleTableUserKey + " = ?"
+ " and r." + _roleTableKey + " = u."
+ _userRoleTableRoleKey;
} |
c4b1683f-6529-4028-9717-3199ed12e7e0 | 7 | public static void main(String[] args) throws FileNotFoundException, IOException {
if(args.length < 2){
System.out.println("One or more argument(s) missing.");
System.out.println("EXAMPLE: java -jar JCEPIT.jar -R RabinExampleAutomata.txt");
System.out.println("EXAMPLE: java -jar JCEPIT.jar -B BuchiExampleAutomata.txt");
return;
}
if (args[0].matches("-B|-b")) {
Buchi BTA = Buchi.fromFile(args[1]);
Buchi tmpBTA = BTA.recognizeEmptyLanguage();
System.out.println("Language recognized by automata " + (tmpBTA.states.isEmpty() ? "is " : "isn't ") + "empty.");
if (!tmpBTA.states.isEmpty()) {
tmpBTA.toImageFile(args[1].substring(0, args[1].lastIndexOf('.')) + ".png");
}
} else if (args[0].matches("-R|-r")) {
Rabin RA = Rabin.fromFile(args[1]);
Rabin tmpRA = RA.recognizeEmptyLanguage();
System.out.println("Language recognized by automata " + (tmpRA.states.isEmpty() ? "is " : "isn't ") + "empty.");
if (!tmpRA.states.isEmpty()) {
tmpRA.toImageFile(args[1].substring(0, args[1].lastIndexOf('.')) + ".png");
}
} else {
System.out.println("Unknow option: " + args[0]);
}
} |
a9bd4b9c-1ed2-4e61-b826-b43767fc9af3 | 7 | public void setOptions(String[] options) throws Exception {
String tableString, inputString, tmpStr;
resetOptions();
tmpStr = Utils.getOption("url", options);
if (tmpStr.length() != 0)
setUrl(tmpStr);
tmpStr = Utils.getOption("user", options);
if (tmpStr.length() != 0)
setUser(tmpStr);
tmpStr = Utils.getOption("password", options);
if (tmpStr.length() != 0)
setPassword(tmpStr);
tableString = Utils.getOption('T', options);
inputString = Utils.getOption('i', options);
if(tableString.length() != 0){
m_tableName = tableString;
m_tabName = false;
}
m_id = Utils.getFlag('P', options);
if(inputString.length() != 0){
try{
m_inputFile = inputString;
ArffLoader al = new ArffLoader();
File inputFile = new File(inputString);
al.setSource(inputFile);
setInstances(al.getDataSet());
//System.out.println(getInstances());
if(tableString.length() == 0)
m_tableName = getInstances().relationName();
}catch(Exception ex) {
printException(ex);
ex.printStackTrace();
}
}
} |
650d0ab0-04c3-448a-b350-7a5ead53ee5b | 4 | public static BufferedImage setBlackAndWhiteNonStrict(BufferedImage img) {
for (int i = 0; i < img.getWidth() - 1; i++) {
for (int j = 0; j < img.getHeight() - 1; j++) {
if (img.getRGB(i, j) != -1 && img.getRGB(i, j) != -16777216) {
img.setRGB(i, j, -1);
}
}
}
return img;
} |
766108be-6cdd-4dda-b6f1-3be7a326aaf6 | 1 | public void actionPerformed(ActionEvent ae) {
if (((MenuItem)ae.getSource()).equals(aboutMenuItem)) {
textArea.setText(aboutText());
setVisible(true);
} else {
textArea.setText(helpText());
setVisible(true);
}
} |
801aadf7-e5fb-43d2-9633-95af5716bdff | 5 | public void drawNode(Graphics g) {
g.setColor(Color.BLACK);
if (start) {
// if user denotes node to be start
g.setColor(Color.RED);
g.fillRect(x, y, w, w);
} else if (dest) {
//user denoted destination
g.setColor(Color.BLUE);
g.fillRect(x, y, w, w);
} else if (inPath) {
//A* denotes part of shortest path
g.setColor(Color.BLACK);
g.fillRect(x, y, w, w);
}else if (visited) {
//A* has visited this node
g.setColor(Color.GREEN);
g.fillRect(x, y, w, w);
} else if (accessible) {
// Node can be visited
g.drawRect(x, y, w, w);
} else {
//user denoted inaccessible node
g.setColor(new Color (34, 138, 93));
g.fillRect(x, y, w, w);
}
} |
33a69e0e-43c8-40d8-9ed4-aafd02ba4a9e | 4 | @Override
public void collide(Entity entity) {
if(entity instanceof Hero) {
Hero hero = (Hero)entity;
if(!hero.getTeam().equals(owner)) {
capture(hero.getTeam());
}
} else if(entity instanceof Explosion) {
if(entity != lastExplosion) {
takeDamage();
lastExplosion = (Explosion)entity;
}
}
} |
fca3f20a-f311-4e56-a686-26abb9d7c9c4 | 1 | private DalcPlaylist() {
try {
mConnection = DBConnection.getConnection();
} catch (SQLServerException ex) {
}
} |
8e78e865-4e65-4b4c-8b48-6ef15d6f495f | 3 | private static void blankField(Class<?> enumClass, String fieldName) throws Exception
{
for (final Field field : Class.class.getDeclaredFields())
if (field.getName().contains(fieldName))
{
field.setAccessible(true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
} |
0829cb0a-570e-470f-9e27-1abbe637213d | 6 | @EventHandler
public void GiantPoison(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getGiantConfig().getDouble("Giant.Poison.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getGiantConfig().getBoolean("Giant.Poison.Enabled", true) && damager instanceof Giant && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getGiantConfig().getInt("Giant.Poison.Time"), plugin.getGiantConfig().getInt("Giant.Poison.Power")));
}
} |
7e7003b8-6e5b-4965-be97-be0d6ab3f184 | 7 | @Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Type)) {
return false;
}
Type t = (Type) o;
if (sort != t.sort) {
return false;
}
if (sort >= ARRAY) {
if (len != t.len) {
return false;
}
for (int i = off, j = t.off, end = i + len; i < end; i++, j++) {
if (buf[i] != t.buf[j]) {
return false;
}
}
}
return true;
} |
ea589ce7-a38c-4de4-b7b7-ec011185adc1 | 7 | @SuppressWarnings("unchecked")
public synchronized void init(Properties props)
throws BadRealmException, NoSuchRealmException {
super.init(props);
String jaasCtx = props.getProperty(IASRealm.JAAS_CONTEXT_PARAM);
String digestAlgorithm = props.getProperty(PARAM_DIGEST_ALGORITHM,
getDefaultDigestAlgorithm());
String encoding = props.getProperty(PARAM_ENCODING, NONE);
String charset = props.getProperty(PARAM_CHARSET, "UTF-8");
serviceURI = props.getProperty(PARAM_SERVICE_URI);
cr = (ActiveDescriptor<ConnectorRuntime>) Util.getDefaultHabitat().getBestDescriptor(BuilderHelper.createContractFilter(ConnectorRuntime.class.getName()));
if (jaasCtx == null) {
String msg = sm.getString(
"realm.missingprop", IASRealm.JAAS_CONTEXT_PARAM, "RestRealm");
throw new BadRealmException(msg);
}
if (serviceURI == null) {
String msg = sm.getString(
"realm.missingprop", PARAM_SERVICE_URI, "RestRealm");
throw new BadRealmException(msg);
}
if (!NONE.equalsIgnoreCase(digestAlgorithm)) {
try {
md = MessageDigest.getInstance(digestAlgorithm);
} catch (NoSuchAlgorithmException e) {
String msg = sm.getString("restrealm.notsupportdigestalg",
digestAlgorithm);
throw new BadRealmException(msg);
}
}
this.setProperty(IASRealm.JAAS_CONTEXT_PARAM, jaasCtx);
this.setProperty(PARAM_DIGEST_ALGORITHM, digestAlgorithm);
if (encoding != null) {
this.setProperty(PARAM_ENCODING, encoding);
}
if (charset != null) {
this.setProperty(PARAM_CHARSET, charset);
}
if (_logger.isLoggable(Level.FINEST)) {
_logger.finest("RealmRealm : "
+ IASRealm.JAAS_CONTEXT_PARAM + "= " + jaasCtx + ", "
+ PARAM_SERVICE_URI + "= " + serviceURI + ", "
+ PARAM_DIGEST_ALGORITHM + " = " + digestAlgorithm + ", "
+ PARAM_ENCODING + " = " + encoding + ", "
+ PARAM_CHARSET + " = " + charset);
}
groupCache = new HashMap<String, Vector>();
emptyVector = new Vector<String>();
modelCache = new HashMap<String, AuthenticationDescriptor>();
} |
55280630-44b8-4561-adda-0eb79f74ee76 | 0 | @Override
public void setCity(String city) {
super.setCity(city);
} |
442554b9-638b-4701-896d-741af5d02709 | 1 | final int getNextChar() {
int next = -1;
if (writeIndex != readIndex) {
next = charQueue[readIndex];
readIndex = readIndex + 1 & 0x7f;
}
return next;
} |
3b04c3ba-a5ae-4d99-8672-17218235c516 | 8 | public static Proposition findMatchingConceivedProposition(Proposition goal) {
{ Keyword testValue000 = goal.kind;
if ((testValue000 == Logic.KWD_PREDICATE) ||
((testValue000 == Logic.KWD_FUNCTION) ||
((testValue000 == Logic.KWD_ISA) ||
(testValue000 == Logic.KWD_EQUIVALENT)))) {
{ Stella_Object backlinkedargument = Proposition.selectArgumentWithBacklinks(goal, new Object[1]);
if (backlinkedargument == null) {
return (null);
}
{ Proposition value000 = null;
{ Proposition p = null;
Iterator iter000 = Logic.unfilteredDependentPropositions(backlinkedargument, ((Surrogate)(goal.operator))).allocateIterator();
loop000 : while (iter000.nextP()) {
p = ((Proposition)(iter000.value));
if ((((Surrogate)(p.operator)) == goal.operator) &&
Proposition.argumentsMatchArgumentsP(p, goal)) {
value000 = p;
break loop000;
}
}
}
{ Proposition value001 = value000;
return (value001);
}
}
}
}
else {
return (goal);
}
}
} |
7a4dc501-bde0-4a7d-b762-c95bec1a88f3 | 9 | public void addLine(double pXFrom, double pYFrom, double pXTo, double pYTo)
{
int lYFrom;
int lYTo;
// Do some rounding (but not in the way we expect it), limit values
if(pYFrom < pYTo)
{
// Round lYFrom (but .5 is handled oddly)
// 1.5001 - 2.5 -> 1.0001 - 2.0 -> 2
lYFrom = (int)Math.ceil(pYFrom - 0.5);
// Round lYTo, substract 1
// 1.5 - 2.4999 -> 1.0 - 1.9999 -> 1
lYTo = (int)Math.floor(pYTo - 0.5);
/**
* I don't know if this is intended, but in Java 3 == 3.001 is false
* (the left arg is converted to double), so the expr is true only when
* pYTo - 0.5 is exactly lYTo
*/
if(lYTo == pYTo - 0.5)
{
lYTo--;
}
} else
{
lYFrom = (int)Math.ceil(pYTo - 0.5);
lYTo = (int)Math.floor(pYFrom - 0.5);
if(lYTo == pYFrom - 0.5)
{
lYTo--;
}
}
// Limit y to size of image
if(lYFrom < 0)
{
lYFrom = 0;
}
if(lYTo >= fLines)
{
lYTo = fLines - 1;
}
if(lYFrom > lYTo)
{
// No lines crossed.
return;
}
// Note min/max settings so far
if(lYFrom < fLineMin)
{
fLineMin = lYFrom;
}
if(lYTo > fLineMax)
{
fLineMax = lYTo;
}
// todo Curious: What happens if yFrom and yTo are equal? Shit? Or can't they be?
double lDx = (pXTo - pXFrom) / (pYTo - pYFrom);
double lX = pXFrom + lDx * ((lYFrom + 0.5) - pYFrom);
// Record the x value for every line (y).
for(int lLineNo = lYFrom; lLineNo <= lYTo; lLineNo++)
{
fScanbuf[lLineNo].add(new Double(lX));
lX += lDx;
}
fScanBufsAdded = true;
} |
6950eef0-5134-425d-a8ba-9a680ec9af31 | 8 | @EventHandler(priority = EventPriority.LOW)
public void onDiabloMonsterDamageEvent(final EntityDamageEvent event) {
if (event.getEntity() instanceof Monster) {
if (plugin.getSetAPI().wearingSet((LivingEntity) event.getEntity())) {
String sName = plugin.getSetAPI().getNameOfSet(
(LivingEntity) event.getEntity());
ArmorSet aSet = plugin.getSetAPI().getArmorSet(sName);
if (aSet != null) {
List<String> effects = aSet.getBonuses();
for (String s : effects) {
EffectsAPI.addEffect((LivingEntity) event.getEntity(),
null, s, event);
}
}
}
} else if (event.getEntity() instanceof Player) {
if (plugin.getSetAPI().wearingSet((Player) event.getEntity())) {
String sName = plugin.getSetAPI().getNameOfSet(
(Player) event.getEntity());
ArmorSet aSet = plugin.getSetAPI().getArmorSet(sName);
if (aSet != null) {
List<String> effects = aSet.getBonuses();
for (String s : effects) {
EffectsAPI.addEffect((Player) event.getEntity(), null,
s, event);
}
}
}
}
} |
6c037f17-66d7-41d0-b6d1-03e8440e8613 | 4 | public void wearAsBackpack(Backpack b)
{
//Take off previous backpack
if(getBackpack() != null) {getBackpack().setWearer(null);}
//If putting on backpack
if(b != null)
{
if(b.getWearer() != null) {b.getWearer().wearAsBackpack(null);}
b.moveToContainer(null); //remove from any container or grid
b.setWearer(this); //update backpack's knowledge of its wearer
}
setBackpack(b); //update knowledge of backpack
System.out.print(getName() + " is now wearing ");
if(b != null)
{
System.out.println(b.getName() + " as its backpack.");
b.setName(getName() + "'s backpack"); //change name of backpack to "<Name>'s backpack"
}
else
System.out.println("no backpack.");
} |
4300547e-26fb-4b1a-a1b3-0565a4d5225c | 6 | @Override
public void execute(TransitionEvent event) throws Exception {
if(this.out == null) {
this.out = this.bean.getOut();
}
if(!this.rxModeAck) {
send(Statics.RX_HELI_ACK);
this.rxModeAck = true;
}
if(this.sender == null) {
initializeDataSender();
}
if(Statics.ACK.equals(event.getIdentifier())) {
Object parameter = event.getParameter(Statics.TRAMSITION_ID);
if(parameter != null && parameter instanceof Long) {
this.dataset.remove(parameter);
}
}
} |
82c1c8ce-8ad5-4b23-a338-f4e762575352 | 8 | @Override
public Order getOrderByID(final Integer id) {
Connection conn = null;
PreparedStatement stmt=null;
Order order=null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement("SELECT ORDER_ID, ORDER_DATE, USER_ID FROM \"ORDER\" WHERE ORDER_ID=?");
stmt.setInt(1, id);
rs = stmt.executeQuery();
while(rs.next()){//必須要有游標next才取的到值
order = new Order(rs.getInt("ORDER_ID"),rs.getTimestamp("ORDER_DATE"),rs.getString("USER_ID"));
}
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex1) {
Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex1) {
Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex1) {
Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
return order;
} |
02adc169-9a60-4487-91f4-bc69085d34e4 | 0 | public DocumentManager(int sizeOfDocSet) {
// call on the ancestors
super();
// set up the data arrays
docOpenStates = new boolean[sizeOfDocSet] ;
docPaths = new String[sizeOfDocSet] ;
docAlfaOrder = new int[sizeOfDocSet] ;
Outliner.documents.addDocumentRepositoryListener(this);
} |
6fe707dd-d2a2-4b6e-a983-d893ceee7a76 | 5 | public String toString() {
String out = "";
for (int i = (height - 1); i >= 0; i--) {
for (int z = 0; z < width; z++) {
if (z == (width - 1)) {
if (board[z][i] == ' ') {
out = out + "*" + System.getProperty("line.separator");
}
else {
out = out + board[z][i] +
System.getProperty("line.separator");
}
}
else {
if (board[z][i] == ' ') {
out = out + "*";
}
else {
out = out + board[z][i];
}
}
}
}
return out;
} |
0f3e4a04-00cc-4fef-94a7-5ba74dc6257a | 6 | public void run(){
try {
Socket socket = new Socket(ip, Integer.parseInt(port));
output = socket.getOutputStream();
output.flush();
ooutput = new ObjectOutputStream(socket.getOutputStream());
if(command != null){
FileInputStream finput = new FileInputStream(command);
Integer size = finput.available();
ooutput.writeObject(size);
ooutput.flush();
byte [] buffer = new byte[32 * 1024];
int read = 0;
while((read = finput.read(buffer)) != -1){
if(read > 0){
output.write(buffer, 0, read);
}
}
finput.close();
output.close();
ooutput.close();
}
}
catch(NumberFormatException e){}
catch(UnknownHostException e){}
catch(IOException e){}
} |
6573a8b0-f5d0-41d8-bca0-f2e03866b49e | 0 | public void go() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Being child = being.bear();
Supervisor.getSupervisor().registerBeing(child);
} |
ec6c5baf-3367-484c-9113-a82720f48ce9 | 6 | @Override
public Object receiveData(final Identifiable data) {
Object result = GenericResponses.ILLEGAL_DATA;
if (data instanceof JobTask) {
result = GenericResponses.ILLEGAL_HEADER;
final JobTask jt = (JobTask) data;
final UUID id = jt.getJobId();
final String descr = jt.getTaskDescription();
if (descr != null) {
if (descr.equals(JobConstants.JOB_TASK)) {
if (assignmentListener != null) {
if (runningJobs.size() < maxJobCount) {
final ClientSideJob job = new ClientSideJob(jt.getTask(), id, this);
jobs.put(job.getId(), job);
exec.execute(new Runnable() {
@Override
public void run() {
assignmentListener.receiveTask(job);
}
});
result = GenericResponses.OK;
} else {
result = GenericResponses.CANCEL;
}
} else {
result = GenericResponses.GENERAL_ERROR;
}
} else if (descr.equals(JobConstants.JOB_CANCEL)) {
jobs.remove(id);
exec.execute(new Runnable() {
@Override
public void run() {
assignmentListener.cancelTask(jobs.get(id));
}
});
result = GenericResponses.OK;
}
}
}
return result;
} |
e36e9882-c354-4bee-9ead-f4e938570c04 | 9 | public void markSolidOccupant(int x, int y, int width, int height,
int orientation, boolean impenetrable) {
int occupied = 256;
if (impenetrable)
occupied += 0x20000;
x -= insetX;
y -= insetY;
if (orientation == 1 || orientation == 3) {
int temp = width;
width = height;
height = temp;
}
for (int _x = x; _x < x + width; _x++)
if (_x >= 0 && _x < this.width) {
for (int _y = y; _y < y + height; _y++)
if (_y >= 0 && _y < this.height)
set(_x, _y, occupied);
}
} |
1ad15ab3-db63-4d25-ac4f-ef4beabc29f7 | 1 | public void addAccount(BankAccount account) throws IllegalArgumentException {
if (! canHaveAsAccount(account))
throw new IllegalArgumentException();
accounts.add(account);
} |
9eb1e3af-8c09-4a48-adb2-e23187bc6930 | 6 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
boolean verifie = true;
if(jTxtCreateNom.getText().equals("")){
jTxtCreateNom.setBackground(Color.gray);
verifie = false;
}
if(jTxtCreatePrenom.getText().equals("")){
jTxtCreatePrenom.setBackground(Color.gray);
verifie = false;
}
if(jTxtCreateMail.getText().equals("")){
jTxtCreateMail.setBackground(Color.gray);
verifie = false;
}
if(jTxtCreateLogin.getText().equals("")){
jTxtCreateLogin.setBackground(Color.gray);
verifie = false;
}
if(jTxtCreateMdp.getText().equals("")){
jTxtCreateMdp.setBackground(Color.gray);
verifie = false;
}
if(!verifie){
String info = "Certains champs nécessaires ne sont pas renseignés";
javax.swing.JOptionPane.showMessageDialog(null,info);
}else{
String nom = jTxtCreateNom.getText();
String prenom = jTxtCreatePrenom.getText();
String adresse = jTxtCreateAdresse.getText();
String mail = jTxtCreateMail.getText();
String login = jTxtCreateLogin.getText();
String mdp = jTxtCreateMdp.getText();
String situation = jCmbSituation.getSelectedItem().toString();
int role = jCmbSituation.getSelectedIndex()+1;
enregistrerPersonne(nom,prenom,adresse,mail,login,mdp,situation,role);
}
}//GEN-LAST:event_jButton1ActionPerformed |
9e97b303-944e-4d2c-85dc-482278b15bf9 | 9 | public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int startRange = 0;
int endRange = 0;
try {
startRange = scanner.nextInt();
endRange = scanner.nextInt();
} catch (NumberFormatException nfex) {
System.err.println("Invalid input " + nfex);
}
String output = "";
for (int i = startRange; i <= endRange; i++) {
if (i < 10) {
output += Integer.toString(i);
output += " ";
}
else if (i > 10 && i < 100 && i % 11 == 0) {
output += Integer.toString(i);
output += " ";
}
else if (i > 100 && i <= 999) {
int firstDigit = i / 100 % 100;
int lastDigit = i % 10;
if (firstDigit == lastDigit) {
output += Integer.toString(i);
output += " ";
}
}
}
System.out.println(output);
} |
9ac7ec73-bc46-42f7-801d-3309a3bb0b20 | 3 | public static String get(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
String cookieName = GetterUtil.getString(cookie.getName());
if (cookieName.equalsIgnoreCase(name)) {
return cookie.getValue();
}
}
return null;
} |
b2c835c3-7ee3-47e0-b906-0321e4a49634 | 0 | public static byte[] decrypt(byte[] data, String publicKey,
String privateKey) throws Exception {
// 生成本地密钥
SecretKey secretKey = getSecretKey(publicKey, privateKey);
// 数据解密
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} |
27f35d49-a612-4a0d-954f-68f34b0e3aa8 | 4 | public Matrix times(Matrix B) {
Matrix A = this;
if (A.N != B.M) throw new RuntimeException("Illegal matrix dimensions.");
Matrix C = new Matrix(A.M, B.N);
for (int i = 0; i < C.M; i++)
for (int j = 0; j < C.N; j++)
for (int k = 0; k < A.N; k++)
C.data[i][j] += (A.data[i][k] * B.data[k][j]);
return C;
} |
f00bf0e9-2e48-47a9-815d-68e1c757bc7d | 5 | static String findFile(File root, String name) {
// Cleans the results list at the beginning
List<File> results = new ArrayList<File>();
if (!root.isDirectory()) {
throw new IllegalArgumentException("File root is not a directory");
}
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
// if is directory, it starts to search in this directory
if (file.isDirectory()) {
findFile(file, name);
}
// It compares to the file's name
if (file.getName().matches(name)) {
addResult(file, results);
return results.get(0).getAbsolutePath();
}
}
if (!results.isEmpty()) {
return results.get(0).getAbsolutePath();
}
return "End of search";
} |
a3368023-d91e-4e69-9551-944d59586d20 | 5 | public EasySolve solve()
{
EasySolve ret = null;
List<Row> solverows = new ArrayList<Row>();
solverows.addAll(rows);
debugRows("Initial rows", solverows, modulus);
for (int workrowindex = 0, maxindex = solverows.size(); workrowindex < maxindex; workrowindex++)
{
Row otherrow = solverows.get(workrowindex);
for (int fixindex = workrowindex + 1; fixindex < maxindex; fixindex++)
{
int columnIndexToCancel = workrowindex + 1;
Row cancelrowr = solverows.get(fixindex).cancelColumn(columnIndexToCancel,
otherrow,
modulus);
solverows.set(fixindex, cancelrowr);
}
debugRows("after workrowindex=" + workrowindex + " finished", solverows, modulus);
}
debugRows("after all loops", solverows, modulus);
//
// the matrix should look like this now:
//
// 33 a b c
// -51 0 d e
// -13 0 0 f
// so, start at the bottom, and solve and cancel the other direction:
for (int workrowindex = solverows.size() - 1; workrowindex >= 0; workrowindex--)
{
Row reducedToOne = solverows.get(workrowindex).solveThisRow(modulus);
logger.fine("reverse, index=" + workrowindex + " is " + reducedToOne.debugRow());
solverows.set(workrowindex, reducedToOne);
for (int fixindex = workrowindex - 1; fixindex >= 0; fixindex--)
{
int columnIndexToCancel = workrowindex + 1;
logger.finer(" going to cancel fixindex=" + fixindex + " is " +
solverows.get(fixindex).debugRow() + " using row " +
reducedToOne.debugRow());
Row cancelrowr = solverows.get(fixindex).cancelColumn(columnIndexToCancel,
reducedToOne,
modulus);
solverows.set(fixindex, cancelrowr);
}
debugRows("After reverse loopindex=" + workrowindex + " finished", solverows, modulus);
}
//
// the matrix should look like this now:
//
// 3 1 0 0
// -5 0 1 0
// -3 0 0 1
BigInteger[] answers = new BigInteger[solverows.size() + 1];
answers[0] = null;
for (int i = 1, n = answers.length; i < n; i++)
{
answers[i] = solverows.get(i - 1).getColumn(0);
}
ret = new EasySolve(answers);
return ret;
} |
f9e9d8de-8585-42c1-a39c-afb3f892f320 | 4 | public boolean accept(File pathName) {
try {
String path = pathName.getCanonicalPath();
if (path.endsWith(".tmx") || path.endsWith(".tsx") ||
path.endsWith(".tmx.gz")) {
return true;
}
} catch (IOException e) {}
return false;
} |
b24e5e42-7961-410d-b5a1-ec8c4d9f2563 | 8 | @Override
public void insertUpdate(DocumentEvent ev) {
if (ev.getLength() != 1)
return;
int pos = ev.getOffset();
String content = null;
try {
content = textField.getText(0, pos + 1);
} catch (BadLocationException e) {
e.printStackTrace();
}
//Find where the word starts
int w;
for (w = pos; w >= 0; w--) {
if (!Character.isLetter((content.charAt(w)))) {
break;
}
}
//Too few chars
if (pos - w < 1)
return;
String prefix = content.substring(w + 1).toLowerCase();
int n = Collections.binarySearch(keywords, prefix);
if (n < 0 && -n <= keywords.size()) {
String match = keywords.get(-n - 1);
if (match.startsWith(prefix)) {
String completion = match.substring(pos - w);
suggest(match);
// We cannot modify Document from within notification,
// so we submit a task that does the change later
SwingUtilities.invokeLater(new CompletionTask(completion, pos + 1));
}
} else {
//Found Nothing
mode = Mode.INSERT;
}
} |
cd955659-650f-4067-80b4-83d16df0c7af | 0 | public Set<Integer> getVisited() {
return visited;
} |
2dceb995-4e81-4f27-8712-7a13d3e2e7f4 | 0 | public String getTableFiledName() {
return tableFiledName;
} |
4cd45ae3-82e6-4df0-b116-4f0b0d6712af | 8 | @Override
public Object getValueAt(final int rowIndex, int columnIndex) {
switch (columnIndex){
case 0: return sorok.get(rowIndex).tipus;
case 1: return sorok.get(rowIndex).sor;
case 2:
final JButton torlesGomb = new JButton(oszlopNevek[columnIndex]);
torlesGomb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int i = rowIndex;
if(sorok.get(rowIndex).tipus.equals("Válasz")){
sorok.remove(rowIndex);
} else {
sorok.remove(rowIndex);
while(rowIndex < sorok.size() && sorok.get(rowIndex).tipus.equals("Válasz")){
sorok.remove(rowIndex);
i++;
}
}
fireTableDataChanged();
}
});
return torlesGomb;
case 3:
if(sorok.get(rowIndex).tipus.equals("Válasz")) {
JButton button = new JButton();
return button;
}
final JButton hozzaadasGomb = new JButton(oszlopNevek[columnIndex]);
hozzaadasGomb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
sorok.add(rowIndex + 1, new Sor("Válasz", ""));
fireTableDataChanged();
}
});
return hozzaadasGomb;
default: return null;
}
} |
70112eaf-52c1-4fbb-9880-d62017004fa6 | 6 | public static SceneNode trace(SpaceRegion region, Vec3 position,
Vec3 direction) {
SceneNode returned;
if ( region instanceof SpaceRegion && collidesWithRegion( region, position, direction ) ) {
if ( region instanceof GroupSector ) {
for ( SceneNode sn : ((GroupSector)region).getSons()) {
if ( sn instanceof SpaceRegion ) {
//please notice we're bringing the position vector into the region's subspace.
returned = trace( ((SpaceRegion)sn), position.sub( region.localPosition ), direction );
if ( returned != null ) {
return returned;
}
}
}
}
return region;
}
return null;
} |
d50385c4-2793-434b-8fa7-2490ec564966 | 5 | public void copyStateTo(RrdUpdater other) throws IOException, RrdException {
if(!(other instanceof Archive)) {
throw new RrdException(
"Cannot copy Archive object to " + other.getClass().getName());
}
Archive arc = (Archive) other;
if(!arc.consolFun.get().equals(consolFun.get())) {
throw new RrdException("Incompatible consolidation functions");
}
if(arc.steps.get() != steps.get()) {
throw new RrdException("Incompatible number of steps");
}
int count = parentDb.getHeader().getDsCount();
for(int i = 0; i < count; i++) {
int j = Util.getMatchingDatasourceIndex(parentDb, i, arc.parentDb);
if(j >= 0) {
states[i].copyStateTo(arc.states[j]);
robins[i].copyStateTo(arc.robins[j]);
}
}
} |
5d585d90-2544-4e67-8986-abe95b9cd853 | 1 | public boolean getLinhaVenda(int id) throws ExceptionGerenteVendas {
if (atual.getLinhaVenda(id)) {
return true;
}
throw new ExceptionGerenteVendas("Nenhuma venda encontrada nesta data");
} |
1ce49e2f-d939-4c69-97fb-29d5f54ed69a | 9 | private void newMethod(GameBoardMark playerMark, int[] tempRowForChecks, int sign, int foo, int bar, int baz) {
for (int b1 = 0; b1 < 5; b1++) {
for (int b2 = 0; b2 < 5; b2++) {
int positionB = b1 * GameBoard.SQUARES_PER_SIDE + b2;
if (gameBoard.hasEmptyValueAt(GameBoard.indexOfBoardTwo, positionB + foo) && gameBoard.hasEmptyValueAt(GameBoard.indexOfBoardTwo, positionB + bar + 5)) {
marksByAxis.setPositionsToZero(0, 1);
for (int b3 = 1; b3 < 5; b3++) {
positionB = gameBoard.getValueAt(GameBoard.indexOfBoardTwo, b1 * GameBoard.SQUARES_PER_SIDE + b2 + sign * b3 * baz + foo).index;
if (positionB == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0);
if (positionB == GameBoardMark.EMPTY.index) {
tempRowForChecks[marksByAxis.getValueAtPosition(1)] = b1 * GameBoard.SQUARES_PER_SIDE + b2 + sign * b3 * baz + foo;
marksByAxis.incrementValueAtPositionAndReturnValue(1);
}
}
if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 2), new MarksByAxisPositionPair(1, 2))) for (int b4 = 0; b4 < 2; b4++)
StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[b4]);
}
}
}
} |
78ba66a3-46ed-4430-943a-ca9515343b08 | 8 | public static <T extends NucleotideFasta>NCBI_Q_TBLASTN newDefaultInstance(List<T> query,
List<String> query_IDs) {
return new NCBI_Q_TBLASTN<T>(query, query_IDs) {
/**
* Combines the formQuery() sendBLASTRequest() extractRID() and
* retrieveResult() in order to finish the Q_BLAST with ncbi
*/
@Override
public void run() {
try {
this.BLAST();
this.retrieveResult();
} catch (IOException e) {
e.printStackTrace();
} catch (Bad_Q_BLAST_RequestException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
this.BLASTed = true;
this.notifyListeners();
}
/**
* Retrieves the blast output from the ncbi server and stores it in
* the blastOutput private field
*
* @throws JAXBException
* in case a JAXB parser error
* @throws SAXException
* in case an XML error occurs
* @throws IOException
* in case an error in connection occurs
*/
@Override
protected void retrieveResult() throws SAXException, JAXBException,
IOException {
String retreiveRequest = NCBI_Q_BLAST.QBLAST_SERVICE_URL
+ NCBI_Q_BLAST_Parameter.CMD(
NCBI_Q_BLAST_Parameter.CMD_PARAM.Get)
.toString()
+ NCBI_Q_BLAST_ParameterSet.ampersand
+ NCBI_Q_BLAST_Parameter.RID(this.BLAST_RID).toString()
+ NCBI_Q_BLAST_ParameterSet.ampersand
+ NCBI_Q_BLAST_Parameter.FORMAT_TYPE(
NCBI_Q_BLAST_Parameter.FORMAT_TYPE_PARAM.XML)
.toString();
// On a laggy network might be useful to prevent looping through
// failed
// attempts
// to catch the output
int retreiveAttempts = 0;
try {
// Generates a status request
URL request = new URL(retreiveRequest);
// Opens a connection
URLConnection connection = request.openConnection();
// Gets InputStream and redirects to the helper,
// sets blastoutPut field
this.blastOutput = NCBI_BLAST_OutputHelper
.catchBLASTOutput(connection.getInputStream());
} catch (IOException ioe) {
throw new IOException("A connection error has occurred: "
+ ioe.getMessage(), ioe);
} catch (UnmarshalException ue) {
// Retry opening connection and retrieving the output
retreiveAttempts++;
if (retreiveAttempts < 4) {
URL request = new URL(retreiveRequest);
URLConnection connection = request.openConnection();
this.blastOutput = NCBI_BLAST_OutputHelper
.catchBLASTOutput(connection.getInputStream());
} else {
throw new IOException("Failed to retreive the output: "
+ ue.getMessage(), ue);
}
}
}
};
} |
0a3ac1cc-48c4-48ea-9ee1-d0483a6c7696 | 7 | private boolean checkValidPosition(int positionX, int positionY) {
boolean ret;
boolean xOutOfBounds = positionX > getPlatformSizeX() || positionX < 0;
boolean yOutOfBounds = positionY > getPlatformSizeY() || positionY < 0;
boolean collision = false;
ArrayList<Rover> otherRovers = getBase().getRovers();
//check we aren't going to hit another rover
for (int i = 0; i < otherRovers.size(); i++) {
if (positionX == otherRovers.get(i).getPositionX()
&& positionY == otherRovers.get(i).getPositionY()) {
collision = true;
break;
}
}
//all three failure conditions should be false for the position to be valid
ret = !(xOutOfBounds || yOutOfBounds || collision);
return ret;
} |
2e0dfeb1-b897-4bb7-9fd2-9e9294ecaa32 | 3 | public static int binarySearch(int key, int[] list){//二分查找,返回key的索引。或者若无key,该key应该在位置(负数)
int low = 0;
int high = list.length - 1;
int middle = 0;
while(low <= high){
middle = low + (high - low)/2;
if(key < list[middle]) high = middle - 1;
else if(key > list[middle]) low = middle + 1;
else return middle;
}
return low*(-1);
} |
1de67e12-91a2-41ea-b415-9f7cb491e97b | 4 | @Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null
|| (object instanceof String && ((String) object).length() == 0)) {
return null;
}
if (object instanceof Usuario) {
Usuario o = (Usuario) object;
return getStringKey(o.getIdUsuario());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Usuario.class.getName()});
return null;
}
} |
cd68fc34-342e-4113-b954-2ce5a074ca27 | 3 | @Override
public void move(Excel start, Excel finish) {
for(Excel ex: coloredEx)
{
if (ex.getX() == start.getX() && ex.getY() == start.getY())
{
Dx += finish.getX() - start.getX();
Dy += finish.getY() - start.getY();
setColoredExes();
return;
}
}
} |
3bd97cf7-d655-41d7-b07f-8a13ad430f8d | 1 | public void visitInstanceOfExpr(final InstanceOfExpr expr) {
if (previous == expr.expr()) {
previous = expr;
expr.parent.visit(this);
}
} |
6db63a09-b437-4a9e-a28f-7fd8d60d7482 | 5 | @Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args){
if(commandLabel.compareToIgnoreCase("gelplacement") == 0){
if(sender.hasPermission("portalgel.gelplacement")){
if(args.length == 1){
if(args[0].compareToIgnoreCase("on") == 0){
plugin.setPlacing(true);
sender.sendMessage("Gel placement is turned on");
}
else if(args[0].compareToIgnoreCase("off") == 0){
plugin.setPlacing(false);
sender.sendMessage("Gel placement is turned off");
}
}
else
sender.sendMessage("Correct format for command is: /gelplacement <on|off>");
}
else
sender.sendMessage("You don't have sufficient permissions");
}
else
return false;
return true;
} |
022325c8-e641-4872-bab0-504c43611c55 | 8 | protected boolean disconnectInput(NeuralConnection i, int n) {
int loc = -1;
boolean removed = false;
do {
loc = -1;
for (int noa = 0; noa < m_numInputs; noa++) {
if (i == m_inputList[noa] && (n == -1 || n == m_inputNums[noa])) {
loc = noa;
break;
}
}
if (loc >= 0) {
for (int noa = loc+1; noa < m_numInputs; noa++) {
m_inputList[noa-1] = m_inputList[noa];
m_inputNums[noa-1] = m_inputNums[noa];
//set the other end to have the right connection number.
m_inputList[noa-1].changeOutputNum(m_inputNums[noa-1], noa-1);
}
m_numInputs--;
removed = true;
}
} while (n == -1 && loc != -1);
return removed;
} |
78f1e0a2-5821-45e0-adb6-1931a7d2a576 | 2 | protected void logRequest( Class<? extends HttpRequestBase> reqType, Request request) {
if (debugRequests) System.err.println(reqType.getSimpleName()+" "+request);
} |
e3d99559-2c25-4b11-933b-b2e87204a6f5 | 7 | public boolean checkAccusation(Card person, Card room, Card weapon){
ArrayList<Card> accusation = new ArrayList<Card>();
boolean personMatch = false, roomMatch = false, weaponMatch = false;
accusation.add(person);
accusation.add(room);
accusation.add(weapon);
for(Card temp : solution){
if(person.name.equalsIgnoreCase(temp.name))
personMatch = true;
else if(room.name.equalsIgnoreCase(temp.name))
roomMatch = true;
else if(weapon.name.equalsIgnoreCase(temp.name))
weaponMatch = true;
}
if (personMatch && roomMatch && weaponMatch) return true;
else return false;
} |
be9c2d3a-3a9a-4cb3-af4e-c64178170ec4 | 4 | public <T extends ElementType<E>> boolean positiveLookaheadBefore(ElementType<E> before,
T... expected) {
E lookahead;
for (int i = 1; i <= elements.length; i++) {
lookahead = lookahead(i);
if (before.isMatchedBy(lookahead)) {
break;
}
for (ElementType<E> type : expected) {
if (type.isMatchedBy(lookahead)) {
return true;
}
}
}
return false;
} |
15d100f6-a2c0-4f82-9a67-efa6b7fecef5 | 3 | protected void processKeyEvent(KeyEvent e) {
if (e.getID() == e.KEY_PRESSED) {
// if backspace is pressed, clear the map
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE &&
inputManager.getMaps(action).size() > 0)
{
inputManager.clearMap(action);
setText("");
screen.getFullScreenWindow().requestFocus();
}
else {
mapGameAction(e.getKeyCode(), false);
}
}
e.consume();
} |
9db752d7-e567-4b42-a5c1-fbbfd3ab40df | 7 | public Atividade SelectATividadePorNome(String NomeAtividade) throws SQLException {
Connection conexao = null;
PreparedStatement comando = null;
ResultSet resultado = null;
Atividade atividade = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_SELECT_ATIVIDADE);
comando.setString(1, NomeAtividade);
resultado = comando.executeQuery();
if (resultado.next()) {
atividade = new Atividade();
atividade.setNome(resultado.getString("NOME"));
atividade.setDuracao(resultado.getFloat("DURACAO"));
atividade.setIdAtividade(resultado.getInt("ID_ATIVIDADE"));
}
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
return atividade;
} |
21ae10bb-3e41-4366-bc35-dd5fca2cdd72 | 3 | @Override
public void run() {
while(true){
// isIdle = false;
if (serverHandler!=null) {
serverHandler.run(); //core service
}
// isIdle = true;
thrdPlInst.returnThread(this);
synchronized(this) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.err.println(e.getMessage());
System.exit(1);
}
}
}
} |
f25dae75-f8b9-460b-a7d7-197937d613c8 | 8 | public void rekenAf(Persoon pers){
hoeveelheidPersonen += 1;
double totaalPrijs=0.00;
boolean kkh=false; //kkh=kortingskaarthouder
double kortingspercentage=0.00;
boolean kortingMax=false;
double maxKorting=0.00;
double korting=0.00;
//als de persoon een kortingskaarthouder is, controleer zijn 'kortingsstatus'
if (pers instanceof KortingskaartHouder){
kkh=true;
//haal percentage op
kortingspercentage=pers.geefKortingsPercentage();
maxKorting=0.00;
//als hij/zij een maximumkortingspercentage heeft, haal deze dan op
if (pers.heeftMaximum()){
kortingMax=true;
maxKorting=pers.geefMaximum();
}
else kortingMax=false;
}
//haal de Iterator van het dienblad op
Iterator<Artikel> itr=getIteratorDienblad();
//zolang er nog artikelen aanwezig zijn, ga door met afrekenen
while(itr.hasNext()){
//pak eerstvolgende artikel
this.art=itr.next();
double prijs = this.art.getArtikelPrice();
//als de persoon een kortingskaarthouder is, bereken de korting en sla op in een aparte variabele
if (kkh){
korting+=(prijs*(1-kortingspercentage));
}
//tel de prijs bij de totaalprijs op
totaalPrijs+=prijs;
}
//haal de korting van de totaalprijs af
if (kkh){
//controle op maximumkorting(overschrijding)
if (kortingMax && korting>maxKorting){
//als de korting hoger is dan het maximum, veranderd de korting in het maximumbedrag
korting=maxKorting;
}
totaalPrijs-=korting;
}
//haal de pinpas van de persoon op
Pinpas pinpas=pers.getPinpas();
//als de betaling geslaagd is, tel de totaalprijs bij het 'kassageld' op.
//Bij te weinig saldo, wordt er een TeWeinigGeldException gegooid.
try{
pinpas.betaal(totaalPrijs);
hoeveelheidGeld += totaalPrijs;
}
catch(Exception e){
System.out.println("##########ERROR##########");
System.out.println();
System.out.println(pers);
System.out.println(e);
System.out.println();
System.out.println("-------------------------");
System.out.println();
}
} |
923838ee-7a75-4b5e-b155-eb9eec1fd285 | 5 | public void move() {
if (!inPlay)
return;
pos.x += dx;
pos.y += dy;
if (pos.x < xrangemin) {
pos.x = xrangemin;
dx = -dx;
}
if (pos.x > xrangemax) {
pos.x = xrangemax;
dx = -dx;
}
if (pos.y < yrangemin) {
inPlay = false;
game.updateScore(0);
}
if (pos.y > yrangemax) {
inPlay = false;
game.updateScore(1);
}
} |
462895e7-eb8d-42fb-88cb-5ca90f8bc063 | 8 | */
private void positionMap(Tile pos) {
Game gameData = freeColClient.getGame();
int x = pos.getX(),
y = pos.getY();
int leftColumns = getLeftColumns(),
rightColumns = getRightColumns();
/*
PART 1
======
Calculate: bottomRow, topRow, bottomRowY, topRowY
This will tell us which rows need to be drawn on the screen (from
bottomRow until and including topRow).
bottomRowY will tell us at which height the bottom row needs to be
drawn.
*/
if (y < topRows) {
// We are at the top of the map
bottomRow = (size.height / (halfHeight)) - 1;
if ((size.height % (halfHeight)) != 0) {
bottomRow++;
}
topRow = 0;
bottomRowY = bottomRow * (halfHeight);
topRowY = 0;
} else if (y >= (gameData.getMap().getHeight() - bottomRows)) {
// We are at the bottom of the map
bottomRow = gameData.getMap().getHeight() - 1;
topRow = size.height / (halfHeight);
if ((size.height % (halfHeight)) > 0) {
topRow++;
}
topRow = gameData.getMap().getHeight() - topRow;
bottomRowY = size.height - tileHeight;
topRowY = bottomRowY - (bottomRow - topRow) * (halfHeight);
} else {
// We are not at the top of the map and not at the bottom
bottomRow = y + bottomRows;
topRow = y - topRows;
bottomRowY = topSpace + (halfHeight) * bottomRows;
topRowY = topSpace - topRows * (halfHeight);
}
/*
PART 2
======
Calculate: leftColumn, rightColumn, leftColumnX
This will tell us which columns need to be drawn on the screen (from
leftColumn until and including rightColumn).
leftColumnX will tell us at which x-coordinate the left column needs
to be drawn (this is for the Tiles where y%2==0; the others should be
halfWidth more to the right).
*/
if (x < leftColumns) {
// We are at the left side of the map
leftColumn = 0;
rightColumn = size.width / tileWidth - 1;
if ((size.width % tileWidth) > 0) {
rightColumn++;
}
leftColumnX = 0;
} else if (x >= (gameData.getMap().getWidth() - rightColumns)) {
// We are at the right side of the map
rightColumn = gameData.getMap().getWidth() - 1;
leftColumn = size.width / tileWidth;
if ((size.width % tileWidth) > 0) {
leftColumn++;
}
leftColumnX = size.width - tileWidth - halfWidth -
leftColumn * tileWidth;
leftColumn = rightColumn - leftColumn;
} else {
// We are not at the left side of the map and not at the right side
leftColumn = x - leftColumns;
rightColumn = x + rightColumns;
leftColumnX = (size.width - tileWidth) / 2 - leftColumns * tileWidth;
}
} |
c285cdf7-b54b-41ab-9dd2-8bf07934793b | 4 | public static boolean listaHasonlo( LinkedList<Integer[]> lista, Integer[] parok )
{
for( Integer[] i : lista )
{
int j=0;
for( j=0; j<6; j++ )
{
if( i[j] != parok[j] )
break;
}
if(j == 6)
return true;
}
return false;
} |
dcf4fc16-4be8-47aa-9b6e-c98f0282f5d9 | 2 | static Map<String, Integer> getMethods(final String program) {
char[] chars = program.toCharArray();
Map<String, Integer> methodMap = new HashMap<String, Integer>();
int methodCount = 0;
for (int p = 0; p < chars.length; p++) {
char c = chars[p];
if (c == '[') {
int end = findEndBracket(p, program);
String body = program.substring(p + 1, end);
methodMap.put(body, methodCount++);
}
}
return methodMap;
} |
b3482d5d-1361-4a52-8e6e-65a0eec2c81d | 0 | @Test
public void verifyMethodAnnotationsFound()
{
assert this.foundMethodAnnotation;
} |
37192071-accd-481b-aeb7-b6592d7535bf | 0 | public AbstractPlay get(int number) {
return everyPlay.get(number);
} |
389d6099-8de7-4283-b788-26d4feabc69b | 4 | public LinkedList<Node> allNeighbours(int x, int y) {
LinkedList<Node> neighbours = new LinkedList<Node>();
int thisX = x - 1;
int thisY = y - 1;
// Prevent Nodes on the edge of the map from being added as neighbours.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
continue;
}
neighbours.add(getNode(thisX + i, thisY + j));
}
}
return neighbours;
} |
Subsets and Splits