method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
e86fdd8d-8d26-4e9e-886a-2818f1e84b86 | 7 | private Method returnTypeMethod(String name, Class<?> returnType, Class<?>... argTypes) {
try {
Method method = method(name, argTypes);
Ghost<?> ghost = Ghost.me(method.getReturnType());
if (ghost.openEyes().isPrimitive()) {
if (Ghost.me(returnType).openEyes().wrapperClass() == ghost.openEyes().wrapperClass()) {
return method;
}
}
if (ghost.openEyes().isOf(returnType)) {
return method;
}
throw new NoSuchMethodException();
} catch (Exception e) {
throw Lang.uncheck(e);
}
} |
c88b4f52-4024-4384-81b3-331ad7de16f8 | 0 | @Basic
@Column(name = "PRP_FORMA_PAGO")
public String getPrpFormaPago() {
return prpFormaPago;
} |
c36bee33-ad4d-416f-97a9-f1c3fc1e60e7 | 4 | public void set_side_info(FrameData fd){
for(int ch = 0; ch < channels; ch++)
side_info.set_scfsi(fd.si.scfsi[ch], ch);
for(int gr = 0; gr < max_gr; gr++)
for(int ch = 0; ch < channels; ch++){
Channel gi = fd.si.gr[gr].ch[ch];
if(gi.window_switching_flag != 0)
side_info.set_granule_info(ch, gr, fd.getBigValues(ch, gr),
fd.getCount1TableSelect(ch, gr), fd.getGlobalGain(ch, gr),
fd.getPart23Length(ch, gr), 0, fd.getPreflag(ch, gr),
fd.getBlockType(ch, gr), fd.getScalefactCompress(ch, gr),
fd.getTableSelect(ch, gr), fd.getMixedBlockFlag(ch, gr),
fd.getScalefacScale(ch, gr), fd.getSubblockGain(ch, gr));
else side_info.set_granule_info(ch, gr, gi.big_values,
gi.count1table_select, gi.global_gain, gi.part2_3_length,
0, gi.preflag, gi.region0_count, gi.region1_count,
gi.scalefac_compress, gi.table_select, gi.block_type,
gi.scalefac_scale);
}
} |
9c2ebb4e-ddd0-45e4-b640-70dfd149bd6f | 0 | public void addContaCorrente(ContaCorrente conta)
{
//this.aContas.incluir(conta);
this.aContas.incluirNoFim(conta);
} |
a432f12c-e762-4409-b3e8-e469d2855196 | 9 | @Override
public void update(Observable o, Object arg) {
if (o instanceof MP3Model) {
if (arg instanceof List) {
List<?> list = (List<?>) arg;
if(list.get(0).getClass().equals(TrackBean.class)) {
// If the list is full of tracks then we need to update the playlist
view.setDisplayedPlaylist(model.getPlaylist());
} else if (list.get(0).getClass().equals(File.class)) {
// Display an error message to the user
view.displayErrorMessage("Unable to add " + list.size() + " files. Please check the log.");
} else {
// Update the displayed artists
view.updateArtists(model.getArtists());
}
} else if (arg instanceof TrackBean) {
view.updatePlayingTrack((TrackBean) arg);
} else if (arg == null) {
view.stopPlayingTrack();
} else if (arg instanceof String) {
System.out.println("Update lastfm here!");
}
}
} |
b246ead0-06f6-40ea-acd4-33b0de0edf96 | 7 | public void addModule(String policy,String subjectInput,String resourceInput, String actionInput, String environmentInput) {
FilePolicyModule policyModule = new FilePolicyModule();
String policyname=Log4jInit.prefix+"/"+policy;
System.out.println(policy);
policyModule
.addPolicy(policyname);
CurrentEnvModule envModule = new CurrentEnvModule();
PolicyFinder policyFinder = new PolicyFinder();
Set<FilePolicyModule> policyModules = new HashSet<FilePolicyModule>();
policyModules.add(policyModule);
policyFinder.setModules(policyModules);
AttributeFinder attrFinder = new AttributeFinder();
ArrayList<CurrentEnvModule> attrModules = new ArrayList<CurrentEnvModule>();
attrModules.add(envModule);
attrFinder.setModules(attrModules);
PDP pdp = new PDP(new PDPConfig(attrFinder, policyFinder, null));
try {
try {
RequestCtx req= new RequestCtx(SetupAttributes.setupSubjects(subjectInput), SetupAttributes.setupResource(resourceInput), SetupAttributes.setupAction(actionInput), SetupAttributes.setupEnvironment(environmentInput));
ResponseCtx response = pdp.evaluate(req);
System.out.println("");
response.encode(System.out);
//ResponseCtx response = response.
Iterator<Result> it=response.getResults().iterator();
//response.getInstance(input);
Map<String, Result> resultMap=new HashMap<String, Result>();
while(it.hasNext()){
Result res=it.next();
resultMap.put(res.getResource(), res);
if(res.getDecision()==0)
log.info("Decision: DECISION_PERMIT");
else if(res.getDecision()==1)
log.info("Decision: DECISION_DENY");
else if(res.getDecision()==2)
log.info("Decision: DECISION_INDETERMINATE");
else if(res.getDecision()==3)
log.info("Decision: DECISION_NOT_APPLICABLE");
log.info("Status: "+res.getStatus().getCode());
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
69b9ba02-cdaf-4b3c-879f-613601407987 | 7 | private Object findGetMethodInvoke(MBeanAttributeInfo[] attInfos, String attribute)
throws AttributeNotFoundException, MBeanException, ReflectionException{
Object value = null;
for (MBeanAttributeInfo beanAttributeInfo : attInfos) {
if (attribute.equals(beanAttributeInfo.getName())) {
try {
Method method = findGetMethod(attribute);
if (null == method) {
throw new AttributeNotFoundException("Attribute " + attribute + "has no getter method");
}
value = method.invoke(_mbeanImpl, (Object[]) null);
} catch (IllegalAccessException e) {
throw new ReflectionException(e);
} catch (InvocationTargetException e) {
throw new ReflectionException(e);
} catch (Exception e) {
throw new MBeanException(e);
}
break;
}
}
if (null == value) {
throw new AttributeNotFoundException("Attribute " + attribute + "not found");
}
return value;
} |
df281b5b-0f16-4faf-b892-a6883bc4bfe1 | 4 | public LinkedList<String> operatePhoenix(String runParse, int extractFlag, File compile) {
LinkedList<String> phoenixOutput = new LinkedList<String>();
try {
//compile grammar
compile(compile);
//run parse for file input
ProcessBuilder phoenixBuilder = new ProcessBuilder("/bin/tcsh", runParse);
phoenixBuilder.directory(new File("resources/nlu/Phoenix/TalkingRobot"));
phoenixBuilder.redirectInput(new File("resources/nlu/Phoenix/TalkingRobot/input"));
Process phoenix = phoenixBuilder.start();
BufferedReader stdin2 = new BufferedReader(new InputStreamReader(phoenix.getInputStream()));
BufferedReader stderr2 = new BufferedReader(new InputStreamReader(phoenix.getErrorStream()));
String phoenixLine2 = null;
while ((phoenixLine2 = stderr2.readLine()) != null && (!phoenixLine2.equals("READY"))) {
stdin2.close();
stderr2.close();
phoenix.destroy();
compile(compile);
return operatePhoenix(runParse, extractFlag, compile);
}
while ((phoenixLine2 = stdin2.readLine()) != null) {
phoenixOutput = insertWords(extractFlag, phoenixOutput, phoenixLine2);
}
} catch (IOException e) {
e.printStackTrace();
}
return phoenixOutput;
} |
086f5d17-9ead-4f89-abc3-136c1066fffa | 1 | @Override
public void rotate180(Board board) {
int rot = (getRotation()+2) % 4;
if (rotateAlgorithm(board, Point.translate(getBase(), BASES[rot]), RELS[rot], getKicks()[(getRotation()+1)%4])) {
addRotation(2);
}
} |
7bcc561a-250e-4dff-9f86-8a0d379dd62a | 7 | private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
467beb1e-0897-4a13-a940-053fff3fb68c | 2 | private static void registrarVinilo()
{
boolean salir;
String nombre, codigo;
float precio;
Vinilo vinilo;
do
{
try
{
System.out.print( "Introduce el nombre del Vinilo: ");
nombre = scanner.nextLine();
System.out.print( "Introduce el cdigo del Vinilo: ");
codigo = scanner.nextLine();
System.out.print( "Introduce el precio base oficial del Vinilo: ");
precio = (float)Double.parseDouble( scanner.nextLine());
vinilo = Vinilo.registrar( nombre, codigo, precio);
System.out.println( "- Vinilo registrado con id " + vinilo.getId() + " -");
salir = true;
}
catch (Exception e)
{
System.out.println( e.getMessage());
salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?");
}
} while (!salir);
} |
914f37db-b5cf-4ee3-a014-2f44ff1b35aa | 0 | static void actionLikeB(B b) {
b.action();
} |
66e6e27a-6a75-4629-bcdb-b55f8af65d76 | 9 | int checkBlockLine(int par1ArrayOfInteger[], int par2ArrayOfInteger[])
{
int ai[] =
{
0, 0, 0
};
byte byte0 = 0;
int i = 0;
for (; byte0 < 3; byte0++)
{
ai[byte0] = par2ArrayOfInteger[byte0] - par1ArrayOfInteger[byte0];
if (Math.abs(ai[byte0]) > Math.abs(ai[i]))
{
i = byte0;
}
}
if (ai[i] == 0)
{
return -1;
}
byte byte1 = otherCoordPairs[i];
byte byte2 = otherCoordPairs[i + 3];
byte byte3;
if (ai[i] > 0)
{
byte3 = 1;
}
else
{
byte3 = -1;
}
double d = (double)ai[byte1] / (double)ai[i];
double d1 = (double)ai[byte2] / (double)ai[i];
int ai1[] =
{
0, 0, 0
};
int j = 0;
int k = ai[i] + byte3;
do
{
if (j == k)
{
break;
}
ai1[i] = par1ArrayOfInteger[i] + j;
ai1[byte1] = MathHelper.floor_double((double)par1ArrayOfInteger[byte1] + (double)j * d);
ai1[byte2] = MathHelper.floor_double((double)par1ArrayOfInteger[byte2] + (double)j * d1);
int l = worldObj.getBlockId(ai1[0], ai1[1], ai1[2]);
if (l != 0 && l != 18)
{
break;
}
j += byte3;
}
while (true);
if (j == k)
{
return -1;
}
else
{
return Math.abs(j);
}
} |
1caba292-dd38-48bf-b088-d60bd0cff41a | 0 | public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
game.getCurrentScreen().onKey(e.getKeyCode());
} |
e6bdbe92-b91d-436c-babd-635a6efca632 | 3 | @Override
public void ParseIn(Connection Main, Server Environment)
{
Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom);
if (Room == null)
{
return;
}
if (!Room.CheckRights(Main.Data, true))
{
return;
}
if (Room.State != 0)
{
Environment.InitPacket(367, Main.ClientMessage);
Environment.Append(false, Main.ClientMessage);
Environment.Append(3, Main.ClientMessage);
Environment.EndPacket(Main.Socket, Main.ClientMessage);
return;
}
Environment.InitPacket(367, Main.ClientMessage);
Environment.Append(true, Main.ClientMessage);
Environment.EndPacket(Main.Socket, Main.ClientMessage);
} |
a57ac897-87a9-490e-a734-66e801e6afac | 9 | public List<Message<?>> purge(MessageSelector selector) {
if (selector == null) {
return this.clear();
}
List<Message<?>> purgedMessages = new ArrayList<Message<?>>();
Object[] array = this.queue.toArray();
for (Object o : array) {
Message<?> message = (Message<?>) o;
if (!selector.accept(message) && this.queue.remove(message)) {
purgedMessages.add(message);
}
}
return purgedMessages;
} |
daf4437f-7b3f-475c-9c19-1cde55d1d1db | 4 | public FieldPainter (int winWidth, int winHeight) {
super();
setSize(winWidth, winHeight);
fieldWidth = (getWidth() - 200) / cellSize;
fieldHeight = (getHeight() - 40) / cellSize;
alg = new AStar(fieldWidth, fieldHeight, Integer.valueOf(dTextField.getText()));
alg.setDelay(600000);
lengthFromStartToEnd = getLength(alg.getStartCell(), alg.getEndCell());
setLayout(null);
setFocusable(true);
requestFocus();
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(new KeyAdapter() {
@Override
public void keyReleased (KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
startSolution();
} else if (e.getKeyChar() == KeyEvent.VK_SPACE) {
alg.reset();
}
}
});
int textX = winWidth - 180;
JLabel dLabel = new JLabel("Weight:");
dLabel.setLocation(textX, 130);
dLabel.setSize(45, 20);
add(dLabel);
dTextField.setLocation(textX + dLabel.getWidth() + 5, 130);
dTextField.setSize(60, 20);
dTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
startSolution();
grabFocus();
} else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
dTextField.setText(dTextField.getText().replace(" ", ""));
alg.reset();
grabFocus();
}
}
});
add(dTextField);
initPainter();
} |
e483faa3-1816-47e6-b708-7639ff05c21a | 1 | public int getMinimumWidth(TreePanel panel) {
int width = TextDrawing.getPreferredSize(getHeaderFont(), getName()).width;
if (panel.isUserSortable()) {
width += SORTER_WIDTH;
}
return width;
} |
9cf77c0a-8a94-4ed4-a1a0-c56fa0848f4a | 3 | @Override
public void putAll(Map<? extends K, ? extends V> m) {
for (K k : m.keySet()) {
keys.add(k);
values.add(m.get(k));
}
} |
9a65f863-b49f-4699-ad61-9d730220453b | 9 | public void move(int dir) {
direction = dir;
setImage(dir);
if (dir == def.Frame.UP) {
GoingUp = true;
GoingDown = false;
beStoped();
if (canMoveUp) {
dy = -def.Frame.SPEED;
}
}
if (dir == def.Frame.DOWN) {
GoingDown = true;
GoingUp = false;
beStoped();
if (canMoveDown) {
dy = def.Frame.SPEED;
}
}
if (dir == def.Frame.LEFT) {
GoingLeft = true;
GoingRight = false;
beStoped();
if (canMoveLeft) {
dx = -def.Frame.SPEED;
}
}
if (dir == def.Frame.RIGHT) {
GoingRight = true;
GoingLeft = false;
beStoped();
if (canMoveRight) {
dx = def.Frame.SPEED;
}
}
if (dir == def.Frame.STILL) {
dx = 0;
dy = 0;
canMoveLeft = true;
canMoveRight = true;
canMoveUp = true;
canMoveDown = true;
}
} |
0eaca6ba-0cff-4232-9460-17f5851ecf52 | 6 | @BeforeTest
@Test(groups = { "MaxHeapIntegers" })
public void testMaxHeapIntPushPop() {
Reporter.log("[ ** MaxHeap Integer Push ** ]\n");
testQueueInt = new MaxPriorityQueue<>(new Integer[seed], true);
try {
Reporter.log("Insertion : \n");
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
testQueueInt.push(shuffledArrayWithDuplicatesInt[i]);
}
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
} catch (CollectionOverflowException e) {
throw new TestException("MaxHeap Insertion Failed!!!");
}
try {
testQueueInt.push(1);
} catch (CollectionOverflowException e) {
Reporter.log("**Overflow Exception caught -- Passed.\n");
}
Reporter.log("[ ** MaxHeap Integer Pop ** ]\n");
try {
Reporter.log("Deletion : \n");
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
testQueueInt.pop();
}
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
} catch (EmptyCollectionException e) {
throw new TestException("MaxHeap Removal Failed!!!");
}
try {
testQueueInt.pop();
} catch (EmptyCollectionException e) {
Reporter.log("**Empty Exception caught -- Passed.\n");
}
} |
70a7132a-e2d8-446c-86f4-ea908d6ee9ff | 0 | public Piece getPiece() {
return this.placedPiece;
} |
12967c93-0462-4374-8d17-508c96672948 | 5 | public static Rate getRateByID(int rateID){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Rate r = null;
try {
Statement stmnt = conn.createStatement();
String sql = "SELECT * FROM Rates where rate_id = " + rateID;
ResultSet res = stmnt.executeQuery(sql);
if(res.next()) {
r = new Rate(res.getInt("rate_id"), res.getString("description"), res.getFloat("rate"));
}
}
catch(SQLException e) {
System.out.println("PROBLEM");
e.printStackTrace();
}
return r;
} |
f79ddfdb-47b0-4f2b-8e9e-ba2680925a46 | 0 | User(String prefix, String nick) {
_prefix = prefix;
_nick = nick;
_lowerNick = nick.toLowerCase();
} |
a6fafb8b-6caf-41cb-8a2d-ef2a21134828 | 1 | public LimitedSkiPass(int id, String type, Date activationDate, Date expirationDate,
int numPassages) {
super(id, type, activationDate, expirationDate);
if (numPassages <= 0) {
throw new IllegalArgumentException(
"Non-positive number of passages is not allowed");
}
this.numPassages = numPassages;
} |
ae2f8283-5b5a-4e15-acc6-05ce5faab8e1 | 5 | public synchronized String getRawData() throws IOException {
byte[] input; //temporary holder
if (m_connected) {
m_os.write('G'); //request Data
System.out.println("Requested Data");
if (m_is.available() <= bufferSize) {
input = new byte[m_is.available()]; //storage space sized to fit!
m_receivedData = new byte[m_is.available()]; //using stream to simply null detection
m_is.read(input); //Read in data from Pi
for (int i = 0; (input != null) && (i < input.length); i++) {
m_receivedData[i] = input[i]; //transfer input to full size storage
}
} else {
System.out.println("PI OVERFLOW");
m_is.skip(m_is.available()); //reset if more is stored than buffer
return null;
}
m_rawData = ""; //String to transfer received data to
System.out.println("Raw Data: " + m_receivedData.length);
for (int i = 0; i < m_receivedData.length; i++) {
m_rawData += (char) m_receivedData[i]; //Cast bytes to chars and concatinate them to the String
}
System.out.println(m_rawData);
return m_rawData;
} else {
connect();
return null;
}
} |
ea17d269-fd70-4370-a067-5e2747f0bb36 | 9 | public Matrix solve (Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
throw new RuntimeException("Matrix is singular.");
}
// Copy right hand side with pivoting
int nx = B.getColumnDimension();
Matrix Xmat = B.getMatrix(piv,0,nx-1);
double[][] X = Xmat.getArray();
// Solve L*Y = B(piv,:)
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
// Solve U*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
return Xmat;
} |
26eaa6d2-120a-4ea8-91e8-24b08b382e94 | 8 | public void setProporties(int type) {
this.type = type;
switch(type) {
case PLAYER:
health = 100;
damage = -1;
points = -1;
hitLevel = 2;
break;
case INVADER1:
health = 100;
damage = -1;
points = 10;
hitLevel = 1;
break;
case INVADER2:
health = 100;
damage = -1;
points = 20;
hitLevel = 1;
break;
case INVADER3:
health = 100;
damage = -1;
points = 30;
hitLevel = 1;
break;
case INVADER4:
health = 100;
damage = -1;
points = 999;
hitLevel = 1;
break;
case BARRICADE: break;
case PLAYER_PROJECTILE:
health = -1;
damage = 100;
points = -1;
hitLevel = 3.1;
break;
case INVADER_PROJECTILE:
health = -1;
damage = 100;
points = -1;
hitLevel = 3.2;
break;
}
} |
15ef17bd-50cd-4ddd-a1f4-a5d862568af9 | 9 | public Integer getByeWeekValue(Schedule evolvable) {
Integer value = 0;
List<Week> weeks = evolvable.getWeeks();
for(int i = 0; i < weeks.size(); i++) {
Week w = weeks.get(i);
if(i >= 4 && i <= 11) {
int byeCount = 0;
for(int j = 0; j < Week.DAYS_PER_WEEK; j++) {
Day day = w.getDay(j);
List<NFLEvent> events = day.getEvents();
for(NFLEvent event : events) {
if(this.isByeEvent(event)) {
byeCount += 1;
}
}
}
/* there should be as close to 4 team bye weeks during weeks 4-11 */
value += Math.abs(4 - byeCount);
} else {
for(int j = 0; j < Week.DAYS_PER_WEEK; j++) {
Day day = w.getDay(j);
List<NFLEvent> events = day.getEvents();
for(NFLEvent event : events) {
if(this.isByeEvent(event)) {
value += 1;
}
}
}
}
}
return value;
} |
09440afb-aacb-43d8-97af-5fabee262847 | 0 | public String getRoadHaul() {
return roadHaul;
} |
5a3029e0-ff9c-4f88-959e-7c81f0fe2d7d | 4 | public void setBoardValue(int i,int j,int token) {
if(i < 0 || i >= 3) return;
if(j < 0 || j >= 3) return;
board[i][j] = token;
} |
96d7123b-215a-4891-96b8-d5884e3a0f45 | 0 | public static void changeSelectionToNode(JoeTree tree, OutlineLayoutManager layout) {
Node selectedNode = tree.getYoungestInSelection();
// Update Selection
tree.clearSelection();
tree.addNodeToSelection(selectedNode);
// Record State
tree.setEditingNode(selectedNode);
tree.setCursorPosition(0);
tree.getDocument().setPreferredCaretPosition(0);
// Redraw and Set Focus
layout.draw(selectedNode, OutlineLayoutManager.ICON);
} |
66322b91-6d35-48cd-8235-d9495b1c53b9 | 3 | @Override
public Cliente salvar(Cliente entidade) throws ValidacaoException {
if (entidade == null)
throw new IllegalArgumentException("'entidade' não pode ser nula");
if (!cnpjEstaValido(entidade.getCNPJ()))
throw new ValidacaoException(
String.format("CNPJ '%s' não é válido",
entidade.getCNPJ()));
if (!emailEstaValido(entidade.getEmail()))
throw new ValidacaoException(
String.format("Email '%s' não é um email válido",
entidade.getEmail()));
return super.salvar(entidade);
} |
148d6218-9953-40e8-9d8e-5c09de1a8cc5 | 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(ContactUs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ContactUs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ContactUs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ContactUs.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 ContactUs().setVisible(true);
}
});
} |
cad6bb33-b55f-478a-be69-7693ecc19ffa | 0 | public synchronized int getInt(ConfigValues path) {
return this.yaml.getInt(path.getPath());
} |
99870523-da04-4939-97d1-3dfc500d9ba7 | 1 | public boolean contains(E e) {
if (search(e) != null) {
return true;
}
return false;
} |
3f312222-e747-4cf5-a497-974473357d75 | 8 | protected int[] filterPixels( int width, int height, int[] inPixels, Rectangle transformedSpace ) {
int index = 0;
int[] outPixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = 0xffffffff;
for (int dy = -1; dy <= 1; dy++) {
int iy = y+dy;
int ioffset;
if (0 <= iy && iy < height) {
ioffset = iy*width;
for (int dx = -1; dx <= 1; dx++) {
int ix = x+dx;
if (0 <= ix && ix < width) {
pixel = PixelUtils.combinePixels(pixel, inPixels[ioffset+ix], PixelUtils.MIN);
}
}
}
}
outPixels[index++] = pixel;
}
}
return outPixels;
} |
85c2b405-2d4d-4500-b8f8-5f9bcd6895dc | 1 | void move(int delta) {
try {
DateFormat df = new SimpleDateFormat("yyyy/MM");
Date d = df.parse(currentMonth);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.MONTH, delta);
DateFormat df2 = new SimpleDateFormat("yyyy/MM");
currentMonth = df2.format(calendar.getTime());
lblDate.setText(currentMonth);
} catch (ParseException e) {
throw new RuntimeException(e);
}
} |
9adbf883-e940-4664-9629-279403845e8f | 7 | private void createNetwork(ArrayList<Road> roads, ArrayList<RoadLink> roadLinks){
// initialization
int totalRoads = roads.size();
network = new int[totalRoads*2][totalRoads*2][NUMBER_OF_ARC_ATTRIBUTES];
// set up road to node relation - needed for adding road links
HashMap<Integer, Integer> roadIdToNode = new HashMap<Integer, Integer>();
// Add the roads themselves to network
int index = 0;
for (Road road : roads) {
roadIdToNode.put(road.getId(), index);
// Add road to network as long as not closed
if(road.getStatus() != RoadStatus.Closed){
network[index][index+totalRoads] = new int[]{1,road.getLength(), road.getRiskLevel()};
if(LabelRerouter.ASSUME_SYMMETRIC){
network[index+totalRoads][index] = new int[]{1,road.getLength(), road.getRiskLevel()};
}
}
index++;
}
// Add links between roads
for (RoadLink roadLink : roadLinks) {
Road fromRoad = roadLink.getFromRoad();
Road toRoad = roadLink.getToRoad();
int startNodeIndex = roadLink.getFrom() == RoadPart.Start ? roadIdToNode.get(fromRoad.getId())
: roadIdToNode.get(fromRoad.getId()) + totalRoads;
int endNodeIndex = roadLink.getTo() == RoadPart.Start ? roadIdToNode.get(toRoad.getId())
: roadIdToNode.get(toRoad.getId()) + totalRoads;
network[startNodeIndex][endNodeIndex] = new int[]{1,roadLink.getDistance(), 0};
if(LabelRerouter.ASSUME_SYMMETRIC){
network[endNodeIndex][startNodeIndex] = new int[]{1,roadLink.getDistance(), 0};
}
}
} |
db161014-9869-4986-adb7-3aff09e95ad5 | 3 | public String solve(){
if(status != NOT_SOLVED){
return status;
}
double p0 = initAprox;
double p = p0;
for(int i = 0; i < MAX_ITER; i++){
p = p0 - (f.at(p0) / fp.at(p0));
if( Math.abs(p - p0) < TOLERANCE){ // we're done
solution = p;
iterations = i;
solutionEval = f.at(p);
status = SUCCESS;
return SUCCESS;
}
p0 = p;
}
System.out.println("Finished computaiton in MAX iterations");
solution = p;
iterations = MAX_ITER;
solutionEval = f.at(p);
status = FAIL_MAX_ITER;
return status;
} |
2fe94d02-66da-45d9-ae19-07f790738a06 | 9 | private void addCardImageToLabel(int position, boolean naMao, Carta carta) {
String caminhoCarta = null;
if(carta.isVirada()){
caminhoCarta = "resources/images/" + carta.getNumero() + carta.getNaipe() + ".png";
}
if(carta.isFechada()){
caminhoCarta = "resources/images/verso.png";
}
try
{
BufferedImage card = ImageIO.read(new File(caminhoCarta));
switch(position)
{
case 1:
jLabel1.setIcon(new ImageIcon(card));
jLabel10.setIcon(new ImageIcon(card));
jLabel1.setVisible(naMao);
jLabel10.setVisible(!naMao);
break;
case 2:
jLabel2.setIcon(new ImageIcon(card));
jLabel11.setIcon(new ImageIcon(card));
jLabel2.setVisible(naMao);
jLabel11.setVisible(!naMao);
break;
case 3:
jLabel3.setIcon(new ImageIcon(card));
jLabel12.setIcon(new ImageIcon(card));
jLabel3.setVisible(naMao);
jLabel12.setVisible(!naMao);
break;
case 4:
jLabel4.setIcon(new ImageIcon(card));
jLabel7.setIcon(new ImageIcon(card));
jLabel4.setVisible(naMao);
jLabel7.setVisible(!naMao);
break;
case 5:
jLabel5.setIcon(new ImageIcon(card));
jLabel8.setIcon(new ImageIcon(card));
jLabel5.setVisible(naMao);
jLabel8.setVisible(!naMao);
break;
case 6:
jLabel6.setIcon(new ImageIcon(card));
jLabel9.setIcon(new ImageIcon(card));
jLabel6.setVisible(naMao);
jLabel9.setVisible(!naMao);
break;
}
}
catch (IOException ex) {
Logger.getLogger(JanelaConfiguracaoView.class.getName()).log(Level.SEVERE, null, ex);
}
} |
fb83b568-7d78-496d-9314-13a78400f46f | 4 | public int compareTo(Instruction instr) {
if (addr != instr.addr)
return addr - instr.addr;
if (this == instr)
return 0;
do {
instr = instr.nextByAddr;
if (instr.addr > addr)
return -1;
} while (instr != this);
return 1;
} |
83c4245f-98b2-4eb8-a132-272d676d01fd | 8 | public String translate(final String text) {
final StringBuffer rv = new StringBuffer();
Element temp = null;
char current;
boolean match = false;
for (int x = 0; x < text.length(); x++) {
current = text.charAt(x);
temp = pattern;
match = false;
while(temp != null) {
if (isMatch(current, temp)) {
if (temp.replacement != CharacterIterator.DONE) {
rv.append(temp.replacement);
}
// perform our squeeze :)
while((options & Transliteration.OPTION_SQUEEZE) == Transliteration.OPTION_SQUEEZE && x + 1 < text.length() && text.charAt(x + 1) == current) {
x++;
}
match = true;
break;
}
temp = temp.next;
}
if (!match) {
rv.append(current);
}
}
return rv.toString();
} |
bcb0f401-6375-4d22-8d46-ea30465dddaf | 3 | public void initTermList(ResultSet rs) {
try {
while (rs.next()) {
String term = rs.getString("term");
if (!termList.contains(term)) {
termList.add(term);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} |
c99d23d5-9d32-4d0c-90a4-5fb0b6e8d6a1 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ThreeDimCoordinate other = (ThreeDimCoordinate) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
if (z != other.z)
return false;
return true;
} |
62030910-902f-46df-b42c-058f6630e8f5 | 6 | public static void main(String[] varArgs) {
int rows;
String option;
Pset2Mario m = new Pset2Mario();
do {
Console c = System.console();
out.print("How many rows high would you like the pyramid to be? (The number must be between 0 and 23, inclusive.) ");
rows = Integer.parseInt(System.console().readLine());
} while (rows < 0 || rows > 23);
do {
Console c = System.console();
out.print("Press 'c' to print the pyramid on the console, or 'f' to send it to a text file.");
option = System.console().readLine();
} while ((!option.equals("c")) && (!option.equals("f")));
m.pyramidBuilder(rows);
if (option.equals("c")) {
out.print(m.pyramid);
} else {
try {
writeFile(m.pyramid);
} catch (IOException e) {
out.print("Caught IOException" + e.getMessage());
}
}
} |
73ce6555-fecd-448c-a6fa-1d9c83db9be6 | 3 | public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String shortStr, longStr;
int count = 0;
int seriesCount = 0;
System.out.print("Please enter a short string: ");
shortStr = s.nextLine();
System.out.print("Now please enter a long string: ");
longStr = s.nextLine();
for(int i = 0; i < longStr.length(); i++){
if(longStr.charAt(i) == shortStr.charAt(seriesCount)){
seriesCount++;
if(seriesCount == shortStr.length()){
count++;
seriesCount = 0;
}
}
}
System.out.println("The short string appears " + count + " times in the long string.");
} |
d26d2513-811a-4d26-96c8-a831cc323795 | 0 | @Override
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
String key = (String) node.getUserObject();
JScrollPane jsp = (JScrollPane) panelJspMap.get(key);
jsp.getVerticalScrollBar().setValue(0); // Scrolls the right panel back to the top whenever we change cards.
CARD_LAYOUT.show(RIGHT_PANEL, key);
} |
2ffbff0d-16f2-460e-ab96-96b70a83b4c4 | 8 | @Override
public void actionPerformed(ActionEvent e)
{
Reference.lastActionMinute = new DateTime().getMinuteOfDay();
if (e.getSource() == overviewButton)
{
Reference.overPanel = new OverPanel();
Reference.saveAndChangePanel(Reference.overPanel, Reference.bankAccountPanel, Reference.BANK_ACCOUNT);
}
else if (e.getSource() == debtButton)
Reference.saveAndChangePanel(Reference.debtAccountPanel, Reference.bankAccountPanel, Reference.BANK_ACCOUNT);
else if (e.getSource() == billButton)
Reference.saveAndChangePanel(Reference.billAccountPanel, Reference.bankAccountPanel, Reference.BANK_ACCOUNT);
else if (e.getSource() == logoutButton)
{
Reference.loginPanel = new LoginPanel();
Reference.ex.shutdownNow();
Reference.saveAndChangePanel(Reference.loginPanel, Reference.bankAccountPanel, Reference.BANK_ACCOUNT);
}
else if (e.getSource() == saveButton)
Reference.saveAccounts(Reference.BANKACCOUNT_DATABASE_FILE.toString(), Reference.BANK_ACCOUNT);
else if (e.getSource() == newButton)
accountTableModel.addNewAccount();
else if (e.getSource() == delButton)
{
if ( Reference.bankAccountTable.getSelectedRow() == -1)
{
JOptionPane
.showMessageDialog(
getRootPane(),
"No account selected: Please click on an account to highlight it and then click the Remove account button.",
"No account selected",
JOptionPane.INFORMATION_MESSAGE);
}else
accountTableModel.removeAccount(Reference.bankAccountTable.getSelectedRow());
}
} |
48897302-7bbf-468b-a7f0-9182008cc3d0 | 7 | protected void updateText(
final BaseUI UI, Text headerText, Text detailText
) {
detailText.setText("") ;
headerText.setText("") ;
final String name = category.name ;//.toUpperCase() ;
headerText.setText(name+" structures:") ;
for (final InstallType type : category.types) {
final Composite icon = type.sample.portrait(UI) ;
final String typeName = type.sample.fullName() ;
final String typeDesc = type.sample.helpInfo() ;
final int buildCost = type.sample.buildCost() ;
detailText.insert(icon, 40) ;
detailText.append(" "+typeName) ;
detailText.append("\n Cost: "+buildCost+" Credits") ;
//TODO: List construction materials too.
detailText.append(new Text.Clickable() {
public void whenClicked() { initInstallTask(UI, type) ; }
public String fullName() { return "\n (BUILD)" ; }
}) ;
detailText.append(new Text.Clickable() {
public void whenClicked() {
listShown = (type == listShown) ? null : type ;
helpShown = null ;
}
public String fullName() { return " (LIST)" ; }
}) ;
detailText.append(new Text.Clickable() {
public void whenClicked() {
helpShown = (type == helpShown) ? null : type ;
listShown = null ;
}
public String fullName() { return " (INFO)" ; }
}) ;
if (helpShown == type) {
detailText.append("\n") ;
detailText.append(typeDesc) ;
detailText.append("\n") ;
}
if (listShown == type) {
final Batch <Installation> installed = listInstalled(UI, type) ;
int ID = 0 ;
if (installed.size() == 0) {
detailText.append("\n (no current installations)") ;
}
else for (Installation i : installed) {
detailText.append("\n ") ;
final String label = i.fullName()+" No. "+(++ID) ;
detailText.append(label, (Text.Clickable) i) ;
// You might also list location.
}
detailText.append("\n") ;
}
detailText.append("\n\n") ;
}
} |
577af883-f668-4640-8c37-11249aab0a45 | 6 | public static double wordDifference(Map<String, Integer> t1, Map<String, Integer> t2) {
// construct total word counts
int totes1 = 0;
int totes2 = 0;
for (String s : t1.keySet()) {
totes1 += t1.get(s);
}
for (String s : t2.keySet()) {
totes2 += t2.get(s);
}
// construct return value for first author
double val = 0;
// goes through everything in t1
for (String s : t1.keySet()) {
Integer temp = t2.get(s); //we cannot use int here! get may return null
if (temp == null) {
temp = 0;
}
double freq1 = ((double) t1.get(s))/totes1;
double freq2 = ((double) temp)/totes2;
val += Math.abs(freq1 - freq2);
}
// goes through everything in t2 that is NOT in t1
for (String s : t2.keySet()) {
if (!t1.containsKey(s)) {
val += ((double) t2.get(s))/totes2;
}
}
return val;
} |
07680f5c-23b3-47dd-91ce-1e468781a1ee | 8 | public static String getTypeName(Type type) {
if (type == null)
return "null";
if (! (type instanceof Class<?>))
return type.toString();
Class<?> cls = (Class<?>) type;
if (cls.isArray()) {
// ??? in Field.getTypeName, this block was wrapped with a try block
// which allowed a Throwable to simply fall through. Why?
Class<?> cl = cls;
StringBuilder rank = new StringBuilder();
while (cl.isArray()) {
rank.append("[]");
cl = cl.getComponentType();
}
return new StringBuilder(cl.getName()).append(rank.toString()).toString();
}
return cls.getName();
} |
cf7e730f-bcd1-41e9-bad0-2a686060a23d | 0 | public String getSavePath() {
return savePath;
} |
5cd379d8-64c1-490c-b1de-45161a4ebca2 | 1 | * @param beep true if the clock should beep
*/
public void start(int interval, final boolean beep)
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval, listener);
t.start();
} |
f3a5f127-6b41-4c8c-90da-8f667055963d | 5 | public Writer openSource( JPackage pkg, String fileName ) throws IOException {
final OutputStreamWriter bw = encoding != null
? new OutputStreamWriter(openBinary(pkg,fileName), encoding)
: new OutputStreamWriter(openBinary(pkg,fileName));
// create writer
try {
return new UnicodeEscapeWriter(bw) {
// can't change this signature to Encoder because
// we can't have Encoder in method signature
private final CharsetEncoder encoder = EncoderFactory.createEncoder(bw.getEncoding());
@Override
protected boolean requireEscaping(int ch) {
// control characters
if( ch<0x20 && " \t\r\n".indexOf(ch)==-1 ) return true;
// check ASCII chars, for better performance
if( ch<0x80 ) return false;
return !encoder.canEncode((char)ch);
}
};
} catch( Throwable t ) {
return new UnicodeEscapeWriter(bw);
}
} |
aebb349f-e905-48e0-b897-a469505d5849 | 2 | public void actionPerformed(ActionEvent e) {
if (automaton.getInitialState() == null) {
JOptionPane.showMessageDialog(Universe
.frameForEnvironment(environment),
"The automaton should have " + "an initial state.");
return;
}
AutomatonChecker ac = new AutomatonChecker();
if (ac.isNFA(automaton)) {
JOptionPane.showMessageDialog(Universe
.frameForEnvironment(environment), "This isn't a DFA!");
return;
}
// Show the new environs pane.
FiniteStateAutomaton minimized = (FiniteStateAutomaton) automaton
.clone();
MinimizePane minPane = new MinimizePane(minimized, environment);
environment.add(minPane, "Minimization", new CriticalTag() {
});
environment.setActive(minPane);
} |
be2efafa-d558-4070-8861-ba045bf9f196 | 1 | boolean inSubroutine(final long id) {
if ((status & Label.VISITED) != 0) {
return (srcAndRefPositions[(int) (id >>> 32)] & (int) id) != 0;
}
return false;
} |
e11b4f79-765c-40fa-80bc-5e4c52b395c8 | 5 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String activateString = request.getParameter("activate");
if (activateString != null && !activateString.trim().isEmpty()) {
Boolean activate = Boolean.valueOf(activateString);
if (activate != null && activate && !ParkingOrderEmulatorClient.isActive) {
ParkingOrderEmulatorClient.isActive = true;
new ParkingOrderEmulatorClient().startEmulation();
} else {
ParkingOrderEmulatorClient.isActive = false;
}
}
response.getWriter().write(String.valueOf(ParkingOrderEmulatorClient.isActive));
} |
ffed5757-46bc-45dc-9bfe-a9b3ee75aebf | 2 | public boolean increment(T myKey,double increment) {
boolean newObject=false;
Double myValue=get(myKey);
if (myValue==0) {
myValue=new Double(increment);
if (increment>0) {
newObject=true;
}
}
else {
myValue=new Double(myValue.doubleValue()+increment);
}
put(myKey,myValue);
return newObject;
} |
e5117b9a-2633-45aa-ae5e-9b4de6558faf | 3 | private Mnemonic getMnemData(String assemblyLine) throws AssemblerException {
String[] assemblyLineSplit = assemblyLine.split("\\s+");
ArrayList<String> assemblyTermList = new ArrayList<String>();
for (String assemblyTerm : assemblyLineSplit) {
assemblyTerm = assemblyTerm.replaceAll("^,+", "");
assemblyTerm = assemblyTerm.replaceAll(",+$", "");
assemblyTermList.add(assemblyTerm);
}
Mnemonic mnemData = null;
for (String assemblyTerm : assemblyTermList) {
if (data.getMnemonicTable().get(assemblyTerm) != null) {
mnemData = data.getMnemonicTable().get(assemblyTerm);
break;
}
}
return mnemData;
} |
741153a3-63b7-4142-acd0-0bf5a644157d | 3 | @Override
public int getChildCount ( Object parent ) {
Value<?> vprt = ( (BencodeTreeNode) parent ).getValue();
if ( vprt instanceof ListValue ) {
return ( (ListValue) vprt ).getSize();
} else if ( vprt instanceof DictionaryValue ) {
return ( (DictionaryValue) vprt ).getSize();
} else {
return 0;
}
} |
83b03265-58e2-4b25-a030-6828c36ba27f | 5 | private boolean camposCompletos (){
if((combo_tipo.getSelectedIndex()>=0)&&
(fecha.isFechaValida(field_desdee.getText()))&&
(fecha.isFechaValida(field_hasta.getText()))&&
(!field_tasa.getText().equals(""))&&
(!field_sobretasa.getText().equals(""))
){
return true;
}
else{
return false;
}
} |
15131437-43b8-4f1f-a0ea-f6e6bc381a05 | 4 | public static int reverse(int x) {
int sign = x < 0 ? -1 : 1;
int raw = x < 0 ? -1 * x : x;
long res = 0;
do {
res = res * 10L + raw % 10L;
raw = raw / 10;
} while (raw != 0);
if (res > Integer.MAX_VALUE) return 0;
else return (int) (sign * res);
} |
987955b4-a1a6-40ca-98d5-5f04ea803d40 | 1 | @Before
public void setUp() {
try {
tiedosto = new File("JapanimaatinTiedostot/testi.txt");
PrintWriter kirjoitin = new PrintWriter(tiedosto);
kirjoitin.print(""); //tyhjennetään tiedosto edellisten testien tms jäljiltä
kirjoitin.close();
lukija = new Scanner(tiedosto);
} catch (Exception e){
System.out.println("Tiedostoa ei löydy");
}
kertain = new Kertausmaatti();
kertain.setTiedosto("JapanimaatinTiedostot/testi.txt");
} |
72aea229-a4a8-45b8-9a90-21f4f0e1ccdd | 7 | public static void setAssets(String serverID, String assetID) {
List baskets = Basket.getBasketList(serverID, null);
if (baskets != null && baskets.size() > 0 && !"Popup Dialog".equalsIgnoreCase(((String[]) baskets.get(0))[0])) {
((BasketTableModel) jTable19.getModel()).setValue(baskets);
}
refreshAssetContractList();
if (Utility.VerifyStringVal(assetID)) {
for (int i = 0; i < jTable19.getRowCount(); i++) {
String id = (String) jTable19.getModel().getValueAt(i, 1);
if (!Utility.VerifyStringVal(id)) {
continue;
}
if (assetID.equals(id)) {
jTable19.setRowSelectionInterval(i, i);
break;
}
}
}
} |
94b94eee-382a-498b-8936-e152207d8071 | 2 | public void setPosition(float[] position) {
if (Float.isNaN(position[0]) || Float.isNaN(position[1])) {
throw new RuntimeException("Position is NaN");
}
this.position = position;
} |
707a75cf-8114-4640-be7e-18d013b6533c | 0 | @Test
public void testFindByPrimaryKey() {
fail("Not yet implemented");
} |
ec6382be-03da-478b-8039-1c13cb64622c | 3 | private void validateEvaluateStack(){
if(isStackEmpty()) throw new EmptyStackEvaluationException();
if( !( operandStack.size() == operatorStack.size()+1 && operandStack.size() > 1) ) throw new IllegalNumberOfOperandsException();
} |
fcfe6223-8a60-400d-bebd-050e8fd73d2f | 7 | public double[][] rankedAttributes ()
throws Exception {
int i, j;
if (m_attributeList == null || m_attributeMerit == null) {
throw new Exception("Search must be performed before a ranked "
+ "attribute list can be obtained");
}
int[] ranked = Utils.sort(m_attributeMerit);
// reverse the order of the ranked indexes
double[][] bestToWorst = new double[ranked.length][2];
for (i = ranked.length - 1, j = 0; i >= 0; i--) {
bestToWorst[j++][0] = ranked[i];
}
// convert the indexes to attribute indexes
for (i = 0; i < bestToWorst.length; i++) {
int temp = ((int)bestToWorst[i][0]);
bestToWorst[i][0] = m_attributeList[temp];
bestToWorst[i][1] = m_attributeMerit[temp];
}
if (m_numToSelect > bestToWorst.length) {
throw new Exception("More attributes requested than exist in the data");
}
if (m_numToSelect <= 0) {
if (m_threshold == -Double.MAX_VALUE) {
m_calculatedNumToSelect = bestToWorst.length;
} else {
determineNumToSelectFromThreshold(bestToWorst);
}
}
/* if (m_numToSelect > 0) {
determineThreshFromNumToSelect(bestToWorst);
} */
return bestToWorst;
} |
b6269c9d-34e4-486e-a6da-bba23f389bc7 | 5 | public boolean searchMatrix(int[][] matrix, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (matrix == null || matrix.length == 0)
return false;
int m = matrix.length;
int n = matrix[0].length;
int s = 0;
int e = m * n - 1;
while (s <= e) {
int mid = (s + e) >> 1;
int x = mid / n;
int y = mid % n;
if (matrix[x][y] == target) {
return true;
} else if (matrix[x][y] > target) {
e = mid - 1;
} else {
s = mid + 1;
}
}
return false;
} |
9e9d904e-7b24-4837-bc22-e474cdd84632 | 1 | protected CycFormulaSentence loadKBQSentence(CycAccess access, CycDenotationalTerm kbq)
throws CycApiException, IOException {
try {
final String command = SubLAPIHelper.makeSubLStmt(KBQ_SENTENCE, kbq);
return access.converseSentence(command);
} catch (CycApiException xcpt) {
throw new CycApiException("Could not load query sentence for KBQ " + kbq.cyclify(), xcpt);
}
} |
9738e799-c1a0-456c-becf-8b12b8f34d03 | 5 | private Tree conditionalExpressionPro(){
Tree conditionalExpression = null, truePart = null, falsePart = null;
if((conditionalExpression = orExpressionPro()) != null){
if((accept(Symbol.Id.PUNCTUATORS,"\\?")) != null){
if((truePart = expressionPro()) != null){
if((accept(Symbol.Id.PUNCTUATORS,":")) != null){
if((falsePart = expressionPro()) != null){
return new TernaryExpression(conditionalExpression, truePart, falsePart);
}
}
}
return null;
}
return conditionalExpression;
}
return null;
} |
0b980316-9b35-4b3f-a20a-accdaf7ef28d | 5 | public void writeTypes(Vector vector) {
// A big ol' case statement in a for loop -- what's polymorphism mean, again?
// I really wish I could extend the base classes!
Enumeration enm = vector.elements();
Object nextObject;
while (enm.hasMoreElements()) {
nextObject = enm.nextElement();
if (null == nextObject)
continue;
// if the array at i is a type of array write a [
// This is used for nested arguments
if (nextObject.getClass().isArray()) {
stream.write('[');
// fill the [] with the SuperCollider types corresponding to the object
// (e.g., Object of type String needs -s).
writeTypesArray((Object[]) nextObject);
// close the array
stream.write(']');
continue;
}
// Create a way to deal with Boolean type objects
if (Boolean.TRUE.equals(nextObject)) {
stream.write('T');
continue;
}
if (Boolean.FALSE.equals(nextObject)) {
stream.write('F');
continue;
}
// go through the array and write the superCollider types as shown in the
// above method. the Classes derived here are used as the arg to the above method
writeType(nextObject.getClass());
}
// align the stream with padded bytes
appendNullCharToAlignStream();
} |
fdc6a3eb-a901-41b3-87e6-663956c1417e | 6 | public static void main(String[] args) {
try {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File(ClassLoader.getSystemResource(runXMLAUTHORITY).getFile());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
for (String warning : warnings) {
System.out.println("Warning:" + warning);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMLParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
d7ca1343-1b13-40b6-aed5-24ba5d46a606 | 8 | protected static boolean chantAlignmentCheck(StdAbility A, MOB mob, boolean renderedMundane, boolean auto)
{
if((!auto)
&&(!mob.isMonster())
&&(!A.disregardsArmorCheck(mob))
&&(mob.isMine(A))
&&(!renderedMundane)
&&(CMLib.dice().rollPercentage()<50))
{
if(!A.appropriateToMyFactions(mob))
{
mob.tell(A.L("Extreme emotions disrupt your chant."));
return false;
}
else
if(!CMLib.utensils().armorCheck(mob,CharClass.ARMOR_LEATHER))
{
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,A.L("<S-NAME> watch(es) <S-HIS-HER> armor absorb <S-HIS-HER> magical energy!"));
return false;
}
}
return true;
} |
69de9741-34d7-4186-8528-e451d488764c | 1 | public String toString()
{
String s = "";
for (int amount = totalAmount; amount > 0; amount -= coin[amount])
s += coin[amount] + " ";
return s;
} |
6d664159-fddc-4469-b83e-edfb4041fba5 | 4 | public CreditCard() {
setTitle("Credit Card Application");
JButton_PerAC.setText("Add Credit-card account");
JButton_Withdraw.setText("Charge");
JButton_CompAC.setText("Generate Monthly bills");
//remove all listener that we have first
for (ActionListener al : JButton_PerAC.getActionListeners()) {
JButton_PerAC.removeActionListener(al);
}
for (ActionListener al : JButton_CompAC.getActionListeners()) {
JButton_CompAC.removeActionListener(al);
}
for (ActionListener al : JButton_Deposit.getActionListeners()) {
JButton_Deposit.removeActionListener(al);
}
for (ActionListener al : JButton_Withdraw.getActionListeners()) {
JButton_Withdraw.removeActionListener(al);
}
JButton_CompAC.addActionListener(new BillController());
JButton_PerAC.addActionListener(new AddCreditCardController());
JButton_Deposit.addActionListener(new DepositController());
JButton_Withdraw.addActionListener(new WithdrawController());
} |
b32e886b-fc0c-401f-baa0-a2ce2aaeed55 | 3 | @Override
public void sort(T[] comparables) {
for (int i = 0; i < comparables.length; i++) {
for (int j = i + 1; j < comparables.length; j++) {
if (comparables[i].compareTo(comparables[j]) > 0) {
swat(comparables, i, j);
}
}
}
} |
119d8e2e-bcca-4bf5-9f08-58ca0f2d8017 | 5 | @Override
public DataTable generateDataTable (Query query, HttpServletRequest request) throws DataSourceException
{
DataTable dataTable = null;
try (final Reader reader = new FilterCsv (new BufferedReader (new InputStreamReader (new URL (this.urlYahoo).openStream()))))
{
TableRow row = new TableRow ();
dataTable = CsvDataSourceHelper.read(reader, this.column, false);
dataTable.addColumn(new ColumnDescription (FieldIndice.NASDAQ.toString(), ValueType.TEXT, FieldIndice.NASDAQ.toString()));
dataTable.addColumn(new ColumnDescription (FieldIndice.SP500.toString(), ValueType.TEXT, FieldIndice.SP500.toString()));
dataTable.addColumn(new ColumnDescription (FieldIndice.TSX100.toString(), ValueType.TEXT, FieldIndice.TSX100.toString()));
row.addCell(this.getTime());
row.addCell(this.getDowJones());
for (int i = 0; i < dataTable.getNumberOfRows(); i++)
{
String lastPriceDataTable = dataTable.getCell(i, 0).toString();
String changePercentDataTable = dataTable.getCell(i, 1).toString();
if (! lastPriceDataTable.matches(".*\\d.*"))
lastPriceDataTable = "0";
if (! changePercentDataTable.matches(".*\\d.*"))
changePercentDataTable = "0";
String lastPriceString = this.formatter.format(Double.parseDouble(lastPriceDataTable));
String changePercentString = this.formatter.format(Double.parseDouble(changePercentDataTable));
row.addCell(lastPriceString + " (" + changePercentString + "%)");
}
dataTable.addRow(row);
}
catch (MalformedURLException e)
{
System.out.println("TableIndiceUS generateDataTable() MalformedURLException " + "URL : " + this.urlYahoo + " " + e);
}
catch (IOException e)
{
System.out.println("TableIndiceUS generateDataTable() IOException " + e);
}
return dataTable;
} |
7dd538f9-d19d-4b93-9b0d-ef21ae36c0d4 | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (;;) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
3b6d4dd9-bdd5-4300-a8f1-6dcbe806f0fb | 9 | @SuppressWarnings("empty-statement")
private static <T extends Comparable<? super T>> void quickSort(T[] a, int low, int high) {
if (low + CUTOFF >= high) {
insertionSort(a, low, high);
} else {
int middle = (low + high) / 2;
// Sort low, middle, high
if (compare(a[middle], a[low]) < 0) {
swapReferences(a, low, middle);
}
if (compare(a[high], a[low]) < 0) {
swapReferences(a, low, high);
}
if (compare(a[high], a[middle]) < 0) {
swapReferences(a, middle, high);
}
swapReferences(a, middle, high - 1);
T pivot = a[high - 1];
// Begin partitioning
int i, j;
for (i = low, j = high - 1;;) {
// Start at position i+1 since low has already been sorted correctly
// i.e. a[low] < pivot
//while ( a[++i].compareTo(pivot) < 0 )
while (compare(a[++i], pivot) < 0)
;
// Start at position j-1 since high has already been sorted correctly
// i.e. a[high-1] = pivot
//while ( a[--j].compareTo(pivot) > 0 )
while (compare(a[--j], pivot) > 0)
;
if (i >= j) {
break;
}
swapReferences(a, i, j);
}
// Restore the pivot
swapReferences(a, i, high - 1);
quickSort(a, low, i - 1); // Sort small elements
quickSort(a, i + 1, high); // Sort large elements
}
} |
0e04c5ff-0c71-4b92-897d-2f12406b0358 | 5 | public void setPitch( float pitch )
{
if ( pitch < 0 )
{
pitch += 360f; // unnegativize(TM) the number
}
pitch %= 360; // get the number within 0-359
// the pitch is out of range
if ( ( pitch > minPitch ) && ( pitch < maxPitch ) )
{
// set the pitch to the nearest boundary
if ( pitch >= 180 )
{
pitch = maxPitch;
}
if ( pitch < 180 )
{
pitch = minPitch;
}
}
this.pitch = pitch;
} |
753b50e5-3e22-4627-bdbb-22a3a380469b | 8 | private static boolean checkEdges(ConnectedGraph G1, ConnectedGraph G2, Map map, int n) {
// Check edges in the forward direction.
for (int i = 0; i < n; i++) {
int key = map.getKey(i);
int value = map.getValue(i);
if (G1.V[key].children.length != G2.V[value].children.length) {
System.out.println("Error. Map sets correspondence between nodes with different number of children! ");
return true;
}
for (int j = 0; j < G1.V[key].children.length; j++) {
int key1 = G1.V[key].children[j].data;
for (int l = 0; l < G1.V.length; l++){
if (G1.V[l].data == key1){
key1 = l;
break;
}
}
int value1 = map.mapKey(key1);
value1 = G2.V[value1].data;
boolean flag = false;
for (int k = 0; k < G2.V[value].children.length; k++) {
if (G2.V[value].children[k].data == value1) {
flag = true;
break;
}
}
if (flag == false) {
System.out.println("Error. An edge was not mapped! ");
return true;
}
}
}
return false;
} |
6745a841-c6cb-4745-b9c1-80a1d70c421b | 5 | public void writeWritingAccesses() {
String path = output.toString() + "/" + measurementName
+ "_writingAccesses.txt";
writingAccesses = new File(path);
if (writingAccesses.exists()) {
try {
fr = new FileReader(path);
br = new BufferedReader(fr);
StringBuffer buffer = new StringBuffer();
for (int value : sortStat.getWriteAccesses()) {
buffer.append(br.readLine().concat(" ")
.concat(Integer.toString(value)));
buffer.append(System.getProperty("line.separator"));
}
writer = new FileWriter(writingAccesses, false);
writer.write(buffer.toString());
writer.close();
br.close();
fr.close();
} catch (Exception ex) {
}
} else {
try {
writer = new FileWriter(writingAccesses, false);
for (int value : sortStat.getWriteAccesses()) {
writer.write(Integer.toString(value));
writer.write(System.getProperty("line.separator"));
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
86322bc9-521c-4e19-8fc6-47bbff4021e7 | 7 | private final boolean cons(int i) {
switch (b[i]) {
case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
} |
d7c212dc-52d0-43bd-81ae-0b4fb2f0edad | 4 | protected void fileScan(File f) throws FileNotFoundException{
//Do not consider the size of pkgs
String key=null;
boolean chunkEncoding=false;
boolean emptyPkg=false;
InfoItemSlot item = new InfoItemSlot(null,0,1);
// System.out.println("File name: "+f.getName());
FileInputStream fin = new FileInputStream(f);
Scanner in = new Scanner(fin);
while(in.hasNextLine()){
/*Process the header*/
// System.out.println("This line has : "+line.length+" parts");
String[] line;
String l=null;
if(!(l=in.nextLine().trim()).isEmpty()){
line=l.split(" ");
if(line.length>2 && line[2].contains("HTTP/1")){
// System.out.println("Type: "+line[0]);
item.typeUpdate(line[0]);
// System.out.println("Type: "+item.returnType());
key=line[1];
updateDataTable(key,item);
// System.out.println("URL: "+key);
}
// if(line[0].contains("Content-Length") && line.length>1){
// //we record the length
//// System.out.println("lentgh: "+line[1]);
// item.sizeUpdate(line[1]);
// }else if(line[0].contains("Transfer-Encoding")){
// //transfer-encoding used, we need to extract length from the message body
// chunkEncoding=true;
// }
// }else{
//// System.out.println("Should be an empty line: "+l); //jump the blank line
// /*Process the messagebody*/
// StringBuilder s = new StringBuilder();
// int sizeCount=0;
// if(chunkEncoding==true){
//// System.out.println("chunkencoding!");
//// System.out.println("The size is: "+String.valueOf(Integer.parseInt(in.nextLine().trim(), 16)));
// item.sizeUpdate(String.valueOf(Integer.parseInt(in.nextLine().trim(), 16)));//file length
// while(in.hasNextLine() && !in.nextLine().trim().equals("0")){
// String thisLine=in.nextLine();
// s.append(thisLine.trim());
// sizeCount+=thisLine.length();
// }
// item=updateDataTable(emptyPkg, key,s,item);
// break;
// }else{
//// System.out.println("No chunkencoding!");
// String thisLine=null;
// while(in.hasNextLine()){
// thisLine=in.nextLine();
//// System.out.println("1st line of content is: "+thisLine);
// if(!thisLine.isEmpty() && sizeCount+thisLine.length()>=item.returnSize()){
//// System.out.println("Last line length: "+thisLine.length());
// int i=0;
// for(;i<(item.returnSize()-sizeCount);i++){
// s.append(thisLine.charAt(i));
// }
// sizeCount+=i;
//
//// httpPackageDetect(fin,skipByte);
// item=updateDataTable(emptyPkg, key,s,item);
// break;
// }else{
//
// s.append(thisLine.trim());
//// System.out.println("CUrrent line length: "+thisLine.length());
// sizeCount+=thisLine.length();
// }
// }
// item=updateDataTable(emptyPkg, key,s,item);
// }
//
}
}
} |
4a991ccb-e489-4cba-a352-83846d7b9e56 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Passage other = (Passage) obj;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
return true;
} |
f005a89e-6d36-4c8e-ba3c-667023e96527 | 4 | String ToStringOnlyBorderInformation(int mark) {
String retVal = "";
if (!comparisonResult.numberGenesOnBorderIntervalAllSide.isEmpty()) {
for (String gene : comparisonResult.numberGenesOnBorderIntervalAllSide.keySet()) {
if (comparisonResult.numberGenesOnBorderIntervalAllSide.get(gene) == 5 || comparisonResult.numberGenesOnBorderIntervalAllSide.get(gene) == 7)
retVal += gene + "\n";
}
}
return retVal + "";
} |
5e6725c8-e4b7-4c16-932b-39f822017f46 | 2 | @Override
public void load(FileInputStream in) throws IOException{
int c = in.read();
if (c != -1){
for (int i = 0; i < contains.length; i++){
setItemInSlot(i, new Item(in.read()));
}
}
} |
a298b329-b502-4358-8e14-9e1c2acbefd1 | 7 | *@param nivel
* @return descuento
**/
public long devolverPorcentaje(long valor, int nivel){
long descuento = 0;
if(nivel == 1){
descuento = (valor * 2)/100;
}else if(nivel == 2){
descuento = (valor * 25)/100;
}else if(nivel == 3){
descuento = (valor * 6)/100;
}else if(nivel >= 4 && nivel <= 5){
descuento = (valor * 3)/100;
}else if(nivel >= 6 && nivel <= 10){
descuento = (valor * 2)/100;
}
return descuento;
} |
16413b4b-b84c-4eff-ab1b-2e7c792e18e7 | 3 | public void trajectory(int time){
int activity;
for(int i=0; i<time; i++){
for(int j=0;j<numNodes;j++){
System.out.printf(""+(nodes.get(j).getState()? " ":"█") );
}
activity = 0;
activity = update(activity);
System.out.printf("\t%d\t%d\n", activity, state);
}
} |
7b10cf25-f8ef-4f31-9f98-35628597574f | 5 | @Override
public String getColumnName(int column){
String name = "??";
switch (column){
case 0:
name ="RaavareId";
break;
case 1:
name ="Raavare Navn";
break;
case 2:
name ="LeverandoerId";
break;
case 3:
name ="Raavare Kost Pris";
break;
case 4:
name ="Raavare Vaegt";
break;
}
return name;
} |
a77e31e5-5cca-41b1-bd5a-b09b8adca8b7 | 4 | @Override
public void tileFocusChangedAt(Position p) {
// check if a tile was clicked
Unit u = game.getUnitAt(p);
City c = game.getCityAt(p);
if (c != null) {
CleanCityUI();
ImageFigure productionFig = new ImageFigure(c.getWorkforceFocus(),
new Point(GfxConstants.WORKFORCEFOCUS_X,
GfxConstants.WORKFORCEFOCUS_Y));
ImageFigure shieldFig = new ImageFigure(
c.getOwner() == Player.RED ? GfxConstants.RED_SHIELD
: GfxConstants.BLUE_SHIELD, new Point(
GfxConstants.CITY_SHIELD_X,
GfxConstants.CITY_SHIELD_Y));
ImageFigure prodFig = new ImageFigure(c.getProduction(), new Point(
GfxConstants.CITY_PRODUCTION_X,
GfxConstants.CITY_PRODUCTION_Y));
add(productionFig);
add(shieldFig);
add(prodFig);
} else if (u != null) {
CleanUnitUI();
ImageFigure shieldFig = new ImageFigure(
u.getOwner() == Player.RED ? GfxConstants.RED_SHIELD
: GfxConstants.BLUE_SHIELD, new Point(
GfxConstants.UNIT_SHIELD_X,
GfxConstants.UNIT_SHIELD_Y));
TextFigure movesFig = new TextFigure(u.getMoveCount() + "", new Point(GfxConstants.UNIT_COUNT_X, GfxConstants.UNIT_COUNT_Y));
add(shieldFig);
add(movesFig);
} else {
CleanCityUI();
CleanUnitUI();
}
} |
33bb840e-dd82-4f94-a264-dfa1b515e22b | 1 | public void removeMouseMotionListener(MouseMotionListener l) {
if(l == null) {
return;
}
this.mouseMotionListener = null;
} |
a3df2e70-de91-4e67-882e-784803a40a57 | 2 | @Override
public void onEnable()
{
plugin = this;
cmdManager = new CommandManager(this);
listenerManager = new ListenerManager(this);
loadKits = new LoadKits(this);
configFile = new File(getDataFolder().getAbsolutePath()+"/config.yml");
voteKits = new File(getDataFolder().getAbsolutePath()+"/kits.yml");
if(!configFile.exists())
{
firstRun();
}
YamlConfiguration pluginYML = YamlConfiguration.loadConfiguration(this.getResource("plugin.yml"));
if(!pluginYML.getString("config-version").equals(getConfig().getString("config-version")))
{
logger.warning("[Vote Redeemer] Config Version does not match.");
}
cmdManager.initCommands();
listenerManager.initListeners();
loadKits.load();
PluginDescriptionFile pdfFile = this.getDescription();
this.logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled.");
} |
6b5aeaf0-0cf7-4b1c-b5e7-329355280fbf | 0 | public void start_logging() {
synchronized(logging_enabled) {
logging_enabled = true;
}
} |
9cac1b9a-3430-46b0-a9b3-a4585cd58580 | 4 | private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
int lastItem = jComboBox1.getItemCount()-1;
if(loaded && jComboBox1.getSelectedIndex()==lastItem) {
String input = JOptionPane.showInputDialog("Enter the application's ID:");
jComboBox1.setSelectedIndex(0);
if(input != null) {
if(input.trim().length()>0) {
jComboBox1.removeItemAt(lastItem);
jComboBox1.addItem(input.trim());
jComboBox1.addItem("<Other...>");
jComboBox1.setSelectedIndex(lastItem);
}
}
}
}//GEN-LAST:event_jComboBox1ActionPerformed |
74bb4863-970f-47f6-a9d3-17d2bce758c6 | 9 | private void updateRanking(int clan) throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT c.id, ");
sb.append(clan != -1 ? "c.jobRank, c.jobRankMove" : "c.rank, c.rankMove");
sb.append(", a.lastlogin AS lastlogin, a.loggedin FROM characters AS c LEFT JOIN accounts AS a ON c.accountid = a.id WHERE a.gm < 3 AND a.banned < 1 AND c.reborns > 10 ");
if (clan != -1) {
sb.append("AND c.clan = ? ");
}
sb.append("ORDER BY c.reborns DESC , c.level DESC , c.exp DESC ");
PreparedStatement charSelect = con.prepareStatement(sb.toString());
if (clan != -1) {
charSelect.setInt(1, clan);
}
ResultSet rs = charSelect.executeQuery();
PreparedStatement ps = con.prepareStatement("UPDATE characters SET " + (clan != -1 ? "jobRank = ?, jobRankMove = ? " : "rank = ?, rankMove = ? ") + "WHERE id = ?");
int rank = 0;
while (rs.next()) {
int rankMove = 0;
rank++;
if (rs.getLong("lastlogin") < lastUpdate || rs.getInt("loggedin") > 0) {
rankMove = rs.getInt((clan != -1 ? "jobRankMove" : "rankMove"));
}
rankMove += rs.getInt((clan != -1 ? "jobRank" : "rank")) - rank;
ps.setInt(1, rank);
ps.setInt(2, rankMove);
ps.setInt(3, rs.getInt("id"));
ps.addBatch();
}
ps.executeBatch();
rs.close();
charSelect.close();
ps.close();
} |
90727150-158f-434c-822e-944e364ca7f5 | 3 | @Override
public void onSpawnTick(SinglePlayerGame game) {
Set<Location> entityLocations = game.getEntityLocations(this);
for (Location loc : entityLocations) {
Set<Location> emptyLocations = game.getEmptyLocations(loc.x, loc.y, 1);
for (Location empty : emptyLocations) {
if (filterByID(game.getSquareNeighbors(empty.x, empty.y, 1), id).size() == 3) {
game.spawnEntity(empty.x, empty.y, spawn());
}
}
}
} |
c609b5be-516b-4bdf-8f2e-2e2c9abda9ac | 3 | public static List<Car> loadData(String datafile)
throws NumberFormatException, IOException {
List<Car> cars = new LinkedList<Car>();
int nextuid = 0;
//open file from jar
BufferedReader in = new BufferedReader(new InputStreamReader(RentalStore.class.getClassLoader().getResourceAsStream(datafile)));
//while next line exists
while (in.ready()) {
//read line
String line = in.readLine();
//if comment: skip
if (line.startsWith("#")) {
continue;
}
//tokenize on ,
StringTokenizer csvReader = new StringTokenizer(line, ",");
//create new car type from first 5 fields
CarType type = new CarType(csvReader.nextToken(),
Integer.parseInt(csvReader.nextToken()),
Float.parseFloat(csvReader.nextToken()),
Double.parseDouble(csvReader.nextToken()),
Boolean.parseBoolean(csvReader.nextToken()));
//create N new cars with given type, where N is the 5th field
for (int i = Integer.parseInt(csvReader.nextToken()); i > 0; i--) {
cars.add(new Car(nextuid++, type));
}
}
return cars;
} |
Subsets and Splits