text stringlengths 14 410k | label int32 0 9 |
|---|---|
public boolean matchesSub(Identifier ident, String name) {
for (int i = 0; i < matchers.length; i++) {
if (matchers[i].matchesSub(ident, name) == isOr)
return isOr;
}
return !isOr;
} | 2 |
public int trap1(int[] height) {
int N=height.length;
int water=0;
for (int i=0;i<N-1;){
if(height[i]==0){
i++;
continue;
}
// System.out.println("i "+i);
int maxIndex=i+1;
for (int j=i+1;j<N;j++){
if(height[j]>height[maxIndex]){
maxIndex=j;
}
if(height[j]>=height[i]){
break;
}
}
// System.out.println("maxIndex "+maxIndex);
int min=height[i]<height[maxIndex]?height[i]:height[maxIndex];
// System.out.println("min "+min);
//{1,5,4,3,2,1,2};
for (int k=i+1;k<maxIndex;k++){
int tmp = min-height[k];
// System.out.println("tmp "+tmp);
water+=tmp;
}
i=maxIndex;
}
return water;
} | 7 |
private Move(int col0, int row0, int col1, int row1) {
assert ((col0 > 0) && (col0 < 8)) && ((col1 > 0) && (col0 < 1))
&& ((row0 > 0) && (row0 < 8)) && ((row1 > 0) && (row1 < 8));
_col0 = col0;
_row0 = row0;
_col1 = col1;
_row1 = row1;
} | 7 |
public static String[] getDecoderNames(SeekableStream src) {
if (!src.canSeekBackwards() && !src.markSupported()) {
throw new IllegalArgumentException(JaiI18N.getString("ImageCodec2"));
}
Enumeration enumeration = codecs.elements();
Vector nameVec = new Vector();
String opName = null;
while (enumeration.hasMoreElements()) {
ImageCodec codec = (ImageCodec)enumeration.nextElement();
int bytesNeeded = codec.getNumHeaderBytes();
if ((bytesNeeded == 0) && !src.canSeekBackwards()) {
continue;
}
try {
if (bytesNeeded > 0) {
src.mark(bytesNeeded);
byte[] header = new byte[bytesNeeded];
src.readFully(header);
src.reset();
if (codec.isFormatRecognized(header)) {
nameVec.add(codec.getFormatName());
}
} else {
long pointer = src.getFilePointer();
src.seek(0L);
if (codec.isFormatRecognized(src)) {
nameVec.add(codec.getFormatName());
}
src.seek(pointer);
}
} catch (IOException e) {
ImagingListenerProxy.errorOccurred(JaiI18N.getString("ImageCodec3"),
e, ImageCodec.class, false);
// e.printStackTrace();
}
}
return vectorToStrings(nameVec);
} | 9 |
private void btn_SubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_SubmitActionPerformed
//Checking for missing details
if ( !txt_Name.getText().equals("")
&& cmbbx_DOBDate.getSelectedIndex() != 0
&& cmbbx_DOBMonth.getSelectedIndex() != 0
&& ( !txt_DOBYear.getText().equals("") || !txt_DOBYear.getText().equals("Year...") )
)
{
pName = txt_Name.getText();
String temp1 = cmbbx_DOBDate.getSelectedItem().toString();
pDOBDate = Integer.parseInt(temp1);
pDOBMonth = cmbbx_DOBMonth.getSelectedIndex();
try
{
pDOBYear = Integer.parseInt(txt_DOBYear.getText());
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(rootPane, "Please Re-check entered 'YEAR'!", "Error", 0);
// --submitCount;
error = true;
}
if(!error)
{
//Creating a Person Object
Date bdate;
Calendar cal = Calendar.getInstance();
cal.set(pDOBYear, pDOBMonth-1, pDOBDate,0,0,0);
bdate = cal.getTime();
Person p = new Person(pName, bdate);
sendingList.add(p);
//Setting the CheckButton Enabled
++submitCount;
lbl_People.setText(submitCount.toString());
if (submitCount >= 3)
{
btn_Check.setEnabled(true);
}
}
}
else
{
JOptionPane.showMessageDialog(rootPane,
"Please provide both 'Name' and your 'Date Of Birth' properly to submit!",
"Missing Details",0);
}
}//GEN-LAST:event_btn_SubmitActionPerformed | 8 |
public static int trap3(int[] a) {
int l = a.length;
int[] before = new int[l];
int[] after = new int[l];
int max = 0;
for (int i = 0 ; i < l ; i++) {
before[i] = max;
max = max > a[i] ? max : a[i];
}
max = 0;
for (int i = l-1 ; i >= 0 ; i--) {
after[i] = max;
max = max > a[i] ? max : a[i];
}
int sum = 0;
for (int i = 0 ; i < l; i++) {
int lv = after[i] > before[i] ? before[i] : after[i];
if (a[i] >= lv)
continue;
sum = sum + lv - a[i];
}
return sum;
} | 7 |
private Client getClientByName(String name) {
for (Client client : clients) {
if (client.getName().equals(name)) {
return client;
}
}
return null;
} | 2 |
public boolean canPlaceBlockAt(World par1World, int par2, int par3, int par4)
{
int var5 = 0;
if (par1World.getBlockId(par2 - 1, par3, par4) == this.blockID)
{
++var5;
}
if (par1World.getBlockId(par2 + 1, par3, par4) == this.blockID)
{
++var5;
}
if (par1World.getBlockId(par2, par3, par4 - 1) == this.blockID)
{
++var5;
}
if (par1World.getBlockId(par2, par3, par4 + 1) == this.blockID)
{
++var5;
}
return var5 > 1 ? false : (this.isThereANeighborChest(par1World, par2 - 1, par3, par4) ? false : (this.isThereANeighborChest(par1World, par2 + 1, par3, par4) ? false : (this.isThereANeighborChest(par1World, par2, par3, par4 - 1) ? false : !this.isThereANeighborChest(par1World, par2, par3, par4 + 1))));
} | 8 |
private void debugAddGoodsToUnit(final Game serverGame, Unit unit) {
Specification spec = serverGame.getSpecification();
List<ChoiceItem<GoodsType>> gtl
= new ArrayList<ChoiceItem<GoodsType>>();
for (GoodsType t : spec.getGoodsTypeList()) {
if (t.isFoodType() && t != spec.getPrimaryFoodType()) continue;
gtl.add(new ChoiceItem<GoodsType>(Messages.message(t.toString() + ".name"),
t));
}
GoodsType goodsType = gui.showChoiceDialog(null, "Select Goods Type", "Cancel", gtl);
if (goodsType == null) return;
String amount = gui.showInputDialog(null,
StringTemplate.name("Select Goods Amount"), "20",
"ok", "cancel", true);
if (amount == null) return;
int a;
try {
a = Integer.parseInt(amount);
} catch (NumberFormatException nfe) {
return;
}
GoodsType sGoodsType = spec.getGoodsType(goodsType.getId());
GoodsContainer ugc = unit.getGoodsContainer();
GoodsContainer sgc = serverGame.getFreeColGameObject(ugc.getId(),
GoodsContainer.class);
ugc.setAmount(goodsType, a);
sgc.setAmount(sGoodsType, a);
} | 6 |
@Override
public void windowDeactivated(WindowEvent arg0)
{
} | 0 |
public static Object getAnnotatedFieldValue(Object source, Class<? extends Annotation> annotation){
Class<?> clazz = source.getClass();
try {
for(Field field:clazz.getDeclaredFields()){
field.setAccessible(true);
if(field.getAnnotation(Id.class) != null)
return field.get(source);
}
return null;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
} | 6 |
public Object getObjectPosition(int x, int y) {
for (int i = 0; i < getNumPlace(); i++) {
PlaceUI p = (PlaceUI) getPlace(i);
if (p.inPlace(x, y)) {
selectedPlace = i;
return p;
}
}
for (int i = 0; i < getNumTransition(); i++) {
TransitionUI t = (TransitionUI) getTransition(i);
if (t.inTransition(x, y)) {
selectedTrans = i;
return t;
}
}
for (int i = 0; i < getNumArc(); i++) {
ArcUI a = (ArcUI) getArc(i);
if (a.inArc(x, y)) {
selectedArc = i;
return a;
}
}
for (int i = 0; i < getNumMarker(); i++) {
Marker l = getMarker(i);
if (l.inLabel(x, y)) {
selectedLabel = i;
return l;
}
}
return null;
} | 8 |
public void actionPerformed( ActionEvent e ) {
if( e.getSource() == this.buttonOK ) {
InetAddress address = this.addressComboBoxModel.getSelectedAddress();
int port = this.portSpinnerModel.getNumber().intValue();
String protocol;
if( this.radioTCP.isSelected() ) protocol = "TCP";
else protocol = "UDP";
int backlog = this.backlogSpinnerModel.getNumber().intValue();
//Collator caseInsensitive = Collator.getInstance();
//caseInsensitive.setStrength( Collator.PRIMARY );
// Map<String,BasicType> bindSettings = new TreeMap<String,BasicType>( caseInsensitive );
java.util.Comparator<String> caseInsensitiveComparator = ikrs.util.CaseInsensitiveComparator.sharedInstance;
Environment<String,BasicType> bindSettings =
new DefaultEnvironment<String,BasicType>( new ikrs.util.TreeMapFactory<String,BasicType>(caseInsensitiveComparator) );
bindSettings.put( Constants.CONFIG_SERVER_PROTOCOL, new BasicStringType(protocol) );
bindSettings.put( Constants.CONFIG_SERVER_BACKLOG, new BasicNumberType(backlog) );
bindSettings.put( Constants.CONFIG_SERVER_ADDRESS, new BasicStringType(address.toString()) );
bindSettings.put( Constants.CONFIG_SERVER_PORT, new BasicNumberType(port) );
setStatus( "Starting server: { "+
"address: "+address+", "+
"port: "+port+", "+
"protocol: "+protocol+", "+
"backlog: "+backlog+" } ...",
true );
boolean started = this.serverManagerDialog.performStartServer( address, port, bindSettings );
if( started ) {
this.setVisible( false );
}
} else if( e.getSource() == this.buttonCancel ) {
this.setVisible( false );
}
} | 4 |
public static int min3(int a, int b, int c) {
if( a > b )
return (( c > b) ? b : c);
else
return (( c > a) ? a : c);
} | 3 |
public static String encodeFromFile( String filename )
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile | 3 |
@Override
public void actionPerformed(ActionEvent e) {
JCheckBox source = (JCheckBox) e.getSource();
boolean state = source.isSelected();
if (state) {
this.setTitle("JCheckbox example");
} else {
this.setTitle("");
}
} | 1 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String page=request.getParameter("page");
HttpSession session=request.getSession(false);
String role=(String)session.getAttribute("role");
String id=(String)session.getAttribute("userid");
if(page.equals("profilepage")){
if(role.equals("Admin")){
ArrayList<AdminBean> adminList=AdminDao.viewAdminId(id);
request.setAttribute("result", adminList);
RequestDispatcher rd=request.getRequestDispatcher("Other/"+role+"ProfilePage.jsp");
rd.forward(request, response);
}
if(role.equals("Teacher")){
ArrayList<TeacherBean> List=TeacherDao.viewTeacherId(id);
request.setAttribute("result", List);
RequestDispatcher rd=request.getRequestDispatcher("Other/"+role+"ProfilePage.jsp");
rd.forward(request, response);
}
}
} | 3 |
@Deprecated
protected static Iterator<IPluggable> getIteratorFromComplexMap(Map<PlugMode, TreeSet<IPluggable>> map) {
Iterator<IPluggable> it;
PlugMode[] modes = PlugMode.getAllModes();
Set<IPluggable> set = new HashSet<IPluggable>();
for(PlugMode mode : modes) {
it = map.get(mode).iterator();
while(it.hasNext()) {
IPluggable plug = it.next();
if(!set.contains(plug)) set.add(plug);
}
}
return set.iterator();
} | 3 |
public static void main(String[] args) {
File file = new File("breast-cancer-wisconsin.data");
List<Point> data = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
String[] values = new String[11];
double[] attributes = new double[9];
boolean valid = true;
// read lines from file
while ((line = br.readLine()) != null) {
values = line.split(",");
// start at 1 because the 0 attribute is useless id number
for (int i = 1; i < 10; i++) {
if (values[i].equals("?")) { // do not add this data point if it is missing any field
valid = false;
break;
}
attributes[i-1] = Double.parseDouble(values[i]);
}
if (valid) {
int classification = Integer.parseInt(values[10]);
// change the value, 2 to 1 and 4 to -1
if (classification == 2) {
classification = 1;
} else {
classification = -1;
}
data.add(new Point(attributes, classification));
}
valid = true;
}
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
PocketPerceptron perceptron = new PocketPerceptron(9);
perceptron.train(data, 1000);
} | 6 |
private boolean isSymmetricAux(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (left.getVal() != right.getVal()) {
return false;
}
return isSymmetricAux(left.getLeft(), right.getRight()) && isSymmetricAux(left.getRight(), right.getLeft());
} | 6 |
private Canvas()
{
if (System.getProperty("com.horstmann.codecheck") == null)
{
frame = new JFrame();
if (!System.getProperty("java.class.path").contains("bluej"))
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(component);
frame.pack();
frame.setLocation(LOCATION_OFFSET, LOCATION_OFFSET);
frame.setVisible(true);
}
else
{
final String SAVEFILE ="canvas.png";
final Thread currentThread = Thread.currentThread();
Thread watcherThread = new Thread()
{
public void run()
{
try
{
final int DELAY = 10;
while (currentThread.getState() != Thread.State.TERMINATED)
{
Thread.sleep(DELAY);
}
saveToDisk(SAVEFILE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
};
watcherThread.start();
}
} | 4 |
public static String[] trimArrayElements(String[] array) {
if (isEmpty(array)) {
return new String[0];
}
String[] result = new String[array.length];
for (int i = 0; i < array.length; i++) {
String element = array[i];
result[i] = (element != null ? element.trim() : null);
}
return result;
} | 3 |
public void update(String line, LineStatus status, Scanner fileScan) throws IOException
{
ArrayList<UrlCard> allUrls = UrlCard.getAllUrls();
boolean isUrlObjectComplete = false;
do {
switch (status)
{
case BlankLine: {
isUrlObjectComplete = true;
}
break;
case TitleLine: {
allUrls.add(new UrlCard(line)); //invokes new object (should it be 'invoke' method)
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case UrlLine: {
int i = allUrls.size() - 1;
UrlCard url = allUrls.get(i);
url.setUrl(line);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case CategoryLine: {
int i = allUrls.size() - 1;
UrlCard url = allUrls.get(i);
url.setCategory(CategoryParser.clean(line));
Parser category = new CategoryParser();
category.update(line, status, fileScan);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case TodoLine: {
int i = allUrls.size() - 1;
UrlCard url = allUrls.get(i);
url.setTodo(TodoParser.clean(line));
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case NoteLine: {
int i = allUrls.size() - 1;
UrlCard url = allUrls.get(i);
url.setNotes(NoteParser.clean(line));
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case OtherLine: {
Ui userInterface = new UiCli();
userInterface.warningMessage(MessageType.ProblemParsingManifest);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
}
} while(isUrlObjectComplete==false);
//--> concider adding variable here to feed a progress bar or increment to show how many have been entered into main memory
} | 8 |
public static void main(String[] args) {
new Test().howdy();
} | 0 |
@Override
public String toString()
{
return "isAbstract()";
} | 0 |
public void parseExpressions(String expressions, Handler handler) {
for(String expression : expressions.split("[\n\r]+")) {
parseExpression(expression, handler);
}
} | 1 |
protected Object getDefault(String path) {
Configuration root = getRoot();
Configuration defaults = root == null ? null : root.getDefaults();
return (defaults == null) ? null : defaults.get(createPath(this, path));
} | 2 |
static void rellenarBlancos(int[][] mat, int posI, int posJ){
LinkedList<int[]> cola = new LinkedList<int[]>();
mat[posI][posJ]=3;
cola.add(new int[]{posI,posJ});
while(!cola.isEmpty()){
int[] pos=cola.removeFirst();
if(pos[0]<mat.length-1&&mat[pos[0]+1][pos[1]]==0){
cola.add(new int[]{pos[0]+1,pos[1]});
mat[pos[0]+1][pos[1]]=3;
}
if(pos[0]>0&&mat[pos[0]-1][pos[1]]==0){
cola.add(new int[]{pos[0]-1,pos[1]});
mat[pos[0]-1][pos[1]]=3;
}
if(pos[1]<mat[pos[0]].length-1&&mat[pos[0]][pos[1]+1]==0){
cola.add(new int[]{pos[0],pos[1]+1});
mat[pos[0]][pos[1]+1]=3;
}
if(pos[1]>0&&mat[pos[0]][pos[1]-1]==0){
cola.add(new int[]{pos[0],pos[1]-1});
mat[pos[0]][pos[1]-1]=3;
}
}
} | 9 |
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
} | 3 |
public ParkingPlace getParkingPlace(long maxWaitMillis)
throws ParkingException {
try {
if (SEMAPHORE.tryAcquire(maxWaitMillis, TimeUnit.MILLISECONDS)) {
return pollParkingPlace();
}
} catch (InterruptedException e) {
throw new ParkingException(e);
}
throw new ParkingException("Timeout");
} | 2 |
public void removeSolutions(int[] sol, int index)
{
ArrayList<PossibleSol> temp = new ArrayList<PossibleSol>();
for (int i= 0; i < sol.length; i++)
{
System.out.print(sol[i] + " ");
}
System.out.println();
for (PossibleSol current: this.possibleSol)
{
boolean found = true;
for (int j = 0; j < index; j++)
{
if (current.obj[j] != sol[j])
{
found = false;
break;
}
}
if (found)
{
if (current.obj[index] > sol[index])
{
System.out.println(current);
temp.add(current);
}
}
}
this.possibleSol.removeAll(temp);
System.out.println("Done");
} | 6 |
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new RuntimeException("half width can't be negative");
if (halfHeight < 0) throw new RuntimeException("half height can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
} | 4 |
@Override
public HallEventType getTypeByName(final String name) throws WrongTypeNameException {
if (name == null) {
throw new WrongTypeNameException("Type name is empty");
}
switch (name) {
case CONFERENCE_TYPE_NAME:
case HACKATHON_TYPE_NAME:
return new HallEventType(name);
default: throw new WrongTypeNameException("Type name is wrong");
}
} | 3 |
private void drawHeatFluxSensors(Graphics2D g) {
List<HeatFluxSensor> heatFluxSensors = model.getHeatFluxSensors();
if (heatFluxSensors.isEmpty())
return;
g.setStroke(thinStroke);
Symbol.HeatFluxSensor s = new Symbol.HeatFluxSensor(false);
float w = HeatFluxSensor.RELATIVE_WIDTH * model.getLx();
float h = HeatFluxSensor.RELATIVE_HEIGHT * model.getLy();
s.setIconWidth((int) (w * getHeight() / (xmax - xmin))); // use view height to set icon dimension so that the sensor doesn't get distorted
s.setIconHeight((int) (h * getHeight() / (ymax - ymin)));
float iconW2 = s.getIconWidth() * 0.5f;
float iconH2 = s.getIconHeight() * 0.5f;
g.setFont(sensorReadingFont);
int x, y;
float rx, ry;
String str;
synchronized (heatFluxSensors) {
for (HeatFluxSensor f : heatFluxSensors) {
Rectangle2D.Float r = (Rectangle2D.Float) f.getShape();
r.width = w;
r.height = h;
rx = (f.getX() - xmin) / (xmax - xmin);
ry = (f.getY() - ymin) / (ymax - ymin);
if (rx >= 0 && rx < 1 && ry >= 0 && ry < 1) {
x = (int) (rx * getWidth() - iconW2);
y = (int) (ry * getHeight() - iconH2);
str = HEAT_FLUX_FORMAT.format(f.getValue()) + "W/m" + '\u00B2';
if (f.getAngle() != 0)
g.rotate(-f.getAngle(), x + s.wSymbol / 2, y + s.hSymbol / 2);
centerString(str, g, (int) (x + iconW2), y - 5, true);
if (f.getLabel() != null)
centerString(f.getLabel(), g, (int) (x + iconW2), y + s.getIconHeight() + 12, false);
s.paintIcon(this, g, x, y);
if (f.getAngle() != 0)
g.rotate(f.getAngle(), x + s.wSymbol / 2, y + s.hSymbol / 2);
}
}
}
} | 9 |
private void collectTypeHierarchy(Set<Class<?>> typeHierarchy, Class<?> type) {
if (type != null && !IGNORED_CLASSES.contains(type)) {
if (typeHierarchy.add(type)) {
Class<?> superclass = type.getSuperclass();
if (type.isArray()) {
superclass = primitiveTypeToWrapperMap.get(superclass);
}
collectTypeHierarchy(typeHierarchy, createRelated(type, superclass));
for (Class<?> implementsInterface : type.getInterfaces()) {
collectTypeHierarchy(typeHierarchy, createRelated(type, implementsInterface));
}
}
}
} | 9 |
private boolean isName(String token)
{
boolean isPossible = false;
for (String name : getNames())
{
if (name.equalsIgnoreCase(token))
{
isPossible = true;
break;
}
}
return isPossible;
} | 2 |
public static void main(final String[] args) throws Exception {
int runs = 1;
int eat = 0;
if (args.length <= 1) {
Nonstop.usage();
}
for (eat = 0; eat < args.length; eat++) {
if (args[eat].equals("-run")) {
if (++eat >= args.length) {
Nonstop.usage();
}
runs = Integer.parseInt(args[eat]);
if (runs <= 0) {
Nonstop.usage();
}
} else {
// The main class
eat++;
break;
}
}
/* Got all the args. */
if (eat > args.length) {
Nonstop.usage();
}
final BenchmarkSecurityManager sec = new BenchmarkSecurityManager();
System.setSecurityManager(sec);
final String mainClassName = args[eat - 1];
final String[] a = new String[args.length - eat];
System.err.println("Running " + mainClassName);
for (int i = 0; i < runs; i++) {
try {
final Class mainClass = Class.forName(mainClassName);
System.arraycopy(args, eat, a, 0, a.length);
Benchmark.run(mainClass, a);
} catch (final SecurityException e) {
continue;
} catch (final Exception e) {
e.printStackTrace(System.err);
sec.allowExit = true;
System.exit(1);
}
}
sec.allowExit = true;
} | 9 |
@XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "Signature")
public JAXBElement<SignatureType> createSignature(SignatureType value) {
return new JAXBElement<SignatureType>(_Signature_QNAME, SignatureType.class, null, value);
} | 0 |
@Override
public boolean matches(Object argument) {
if (argument instanceof PropertyChangeEvent) {
PropertyChangeEvent event = (PropertyChangeEvent) argument;
return propertyName.equals(event.getPropertyName())
&& event.getOldValue() != null
&& event.getNewValue() != null
&& event.getOldValue() instanceof Integer
&& event.getNewValue() instanceof Integer
&& oldValue == (Integer) event.getOldValue()
&& newValue == (Integer) event.getNewValue();
}
return false;
} | 7 |
public void makeSelection() {
if(list.getSelectedIndex() != -1) {
selection = list.getSelectedValue();
dispose();
}
} | 1 |
@Override
public void performNavigateAction(KeyEvent evt) {
if (evt.isControlDown()) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DOWN:
if (txtUsuario.equals(this.getFocusOwner())) {
txtSenha.requestFocus();
} else if (txtSenha.equals(this.getFocusOwner())) {
btnLogin.requestFocus();
} else if (btnLogin.equals(this.getFocusOwner())) {
btnSair.requestFocus();
}
break;
case KeyEvent.VK_UP:
if (txtSenha.equals(this.getFocusOwner())) {
txtUsuario.requestFocus();
} else if (btnLogin.equals(this.getFocusOwner())) {
txtSenha.requestFocus();
} else if (btnSair.equals(this.getFocusOwner())) {
btnLogin.requestFocus();
}
break;
}
}
} | 9 |
private String tagStyle(Cell cell, CellStyle style) {
if (style.getAlignment() == ALIGN_GENERAL) {
switch (ultimateCellType(cell)) {
case HSSFCell.CELL_TYPE_STRING:
return "style=\"text-align: left;\"";
case HSSFCell.CELL_TYPE_BOOLEAN:
case HSSFCell.CELL_TYPE_ERROR:
return "style=\"text-align: center;\"";
case HSSFCell.CELL_TYPE_NUMERIC:
default:
// "right" is the default
break;
}
}
return "";
} | 5 |
@Override
public boolean setChartOption( String op, String val )
{
boolean bHandled = false;
if( op.equalsIgnoreCase( "Shadow" ) )
{
setHasShadow( true );
bHandled = true;
}
else if( op.equalsIgnoreCase( "ShowLdrLines" ) )
{
setShowLdrLines( true );
bHandled = true;
}
else if( op.equalsIgnoreCase( "Donut" ) )
{
setDonutPercentage( val );
bHandled = true;
}
else if( op.equalsIgnoreCase( "donutSize" ) )
{
setDonutPercentage( val );
bHandled = true;
}
return bHandled;
} | 4 |
public Path getImgPath_CommandBtn(Imagetype type) {
Path ret = null;
switch (type) {
case KEYFOCUS:
ret = this.imgComBtn_KFoc;
break;
case MOUSEFOCUS:
ret = this.imgComBtn_MFoc;
break;
case PRESSED:
ret = this.imgComBtn_Pre;
break;
case DEFAULT:
ret = this.imgComBtn_Def;
break;
default:
throw new IllegalArgumentException();
}
return ret;
} | 4 |
public char skipTo(char to) throws JSONException {
char c;
try {
long startIndex = this.index;
long startCharacter = this.character;
long startLine = this.line;
this.reader.mark(1000000);
do {
c = this.next();
if (c == 0) {
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
this.back();
return c;
} | 3 |
private void dealCards() {
// Give three cards to each player.
for (int i = 0; i < players.length; i++)
deck.dealCards(players[i].getHandPile(), 3);
// Put two cards in the skat.
deck.dealCards(skat, 2);
// Give four cards to each player again.
for (int i = 0; i < players.length; i++)
deck.dealCards(players[i].getHandPile(), 4);
// Give three cards to each player again.
for (int i = 0; i < players.length; i++)
deck.dealCards(players[i].getHandPile(), 3);
// Note, we could've just dealt 10 cards straight up to the player..
// We didn't do this to maintain the traditional conventions, in-case
// it would've ended up with deducted marks on our part.
} | 3 |
public synchronized void removeMember(Long id){
if (ids.contains(id)){
int pos = ids.indexOf(id);
ids.remove(pos);
types.remove(pos);
roles.remove(pos);
}
} | 1 |
private void calcRow(int step, String expression) {
int variableCount = Expression.getVariableCount();
String binaryStep = Integer.toBinaryString(step);
while (binaryStep.length() < variableCount) {
binaryStep = "0" + binaryStep;
}
int binaryCounter = binaryStep.length() - 1;
for (int i = expression.length() - 1; i >= 0; i--) {
if (Character.isLetter(expression.charAt(i))) {
Character c = expression.charAt(i);
for (int j = i; j >= 0; j--) {
if (c.equals(expression.charAt(j))) {
compactTable.get(step + 1).set(j, Character.toString(binaryStep.charAt(binaryCounter)));
expression = expression.substring(0, j) + binaryStep.charAt(binaryCounter) + expression.substring(j + 1);
}
}
binaryCounter--;
}
if (expression.charAt(i) == '0') {
compactTable.get(step + 1).set(i, "0");
}
if (expression.charAt(i) == '1') {
compactTable.get(step + 1).set(i, "1");
}
}
int currentVar = binaryStep.length();
calcStep(expression, 0, step + 1);
//fullTable.add(stringResults);
} | 7 |
public String getShortSuit() {
switch ( suit ) {
case SPADES: return "S";
case HEARTS: return "H";
case DIAMONDS: return "D";
case CLUBS: return "C";
default: return "J";
}
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContainerHolder that = (ContainerHolder) o;
if (image != null ? !image.equals(that.image) : that.image != null)
return false;
if (url != null ? !url.equals(that.url) : that.url != null) return false;
return true;
} | 7 |
public void scaleHunger() {
// Cancel if the player is not applicable
if (!utils.isValidWorld(player) || !utils.isEnabled()) {
setCancelled(true);
return;
}
if (utils.isExempt(player)) {
setCancelled(true);
return;
}
FileConfiguration c = plugin.getConfig();
// Scale the hunger
if(player.isSprinting()) {
player.setFoodLevel((int) Math.round(hunger - c.getDouble("depletion-rate.sprinting")));
} else if(player.isSneaking()) {
player.setFoodLevel((int) Math.round(hunger - c.getDouble("depletion-rate.sneaking")));
} else if(player.isSleeping()) {
player.setFoodLevel((int) Math.round(hunger - c.getDouble("depletion-rate.sleeping")));
} else if(player.isFlying()) {
player.setFoodLevel((int) Math.round(hunger - c.getDouble("depletion-rate.flying")));
} else if(player.getLocation().getBlock().getType().equals(Material.WATER)) {
player.setFoodLevel((int) Math.round(hunger - c.getDouble("depletion-rate.swimming")));
}
} | 8 |
public double getEntrega() {
return entrega;
} | 0 |
private Weibo parseToWeiboSina(JSONObject info) {
Weibo weibo = new Weibo();
try {
String geo = info.getString("geo");
if (geo==null||geo.equals("null")) {
return null;
}
if (setGeo(weibo,geo)==0) {
return null;
}
JSONObject user = info.getJSONObject("user");
weibo.setUid(String.valueOf(user.getLong("id")));
weibo.setHead(user.getString("profile_image_url"));
weibo.setImage(info.getString("original_pic"));
weibo.setName(user.getString("name"));
weibo.setNick(user.getString("screen_name"));
weibo.setSid(String.valueOf(info.getLong("id")));
weibo.setSource(info.getString("source"));
weibo.setSrc(1);
weibo.setText(info.getString("text"));
weibo.setTimestamp(parseDate(info.getString("created_at")));
} catch (JSONException e) {
e.printStackTrace();
}
return weibo;
} | 4 |
@SuppressWarnings("serial")
public Action graphLayout(final String key, boolean animate)
{
final mxIGraphLayout layout = createLayout(key, animate);
if (layout != null)
{
return new AbstractAction(mxResources.get(key))
{
public void actionPerformed(ActionEvent e)
{
final mxGraph graph = graphComponent.getGraph();
Object cell = graph.getSelectionCell();
if (cell == null
|| graph.getModel().getChildCount(cell) == 0)
{
cell = graph.getDefaultParent();
}
graph.getModel().beginUpdate();
try
{
long t0 = System.currentTimeMillis();
layout.execute(cell);
status("Layout: " + (System.currentTimeMillis() - t0)
+ " ms");
}
finally
{
mxMorphing morph = new mxMorphing(graphComponent, 20,
1.2, 20);
morph.addListener(mxEvent.DONE, new mxIEventListener()
{
public void invoke(Object sender, mxEventObject evt)
{
graph.getModel().endUpdate();
}
});
morph.startAnimation();
}
}
};
}
else
{
return new AbstractAction(mxResources.get(key))
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(graphComponent,
mxResources.get("noLayout"));
}
};
}
} | 3 |
@Test
public void TestaaVasemmaltaOikealleEste() {
rakentaja = new Kartanrakentaja(10, 6);
rakentaja.asetaEste(5, 3);
rakentaja.asetaEste(4, 3);
rakentaja.asetaEste(6, 3);
char[][] kartta = rakentaja.getKartta();
Solmu aloitus = new Solmu(5, 0);
Solmu maali = new Solmu(5, 5);
Reitinhaku haku = new Reitinhaku(kartta);
char[][] tulos = haku.etsiReitti(aloitus, maali);
int pituus = 0;
for(int i = 0; i < tulos.length; i++) {
for (int j = 0; j < tulos[0].length; j++) {
if(tulos[i][j] == 'X') {
pituus++;
}
}
}
System.out.println("");
for(int i = 0; i < tulos.length; i++) {
System.out.println("");
for (int j = 0; j < tulos[0].length; j++) {
System.out.print(tulos[i][j]);
}
}
assertEquals(9, pituus);
} | 5 |
@Override
public void run() {
this.init();
while (running) {
this.doLoop();
this.calculateDelta();
drawManager.draw();
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
}
} | 2 |
public void keyReleased(KeyEvent e) {
int key=e.getKeyCode();
if(key == KeyEvent.VK_UP)
dy=0;
if(key == KeyEvent.VK_DOWN)
dy=0;
if(key == KeyEvent.VK_LEFT||key == KeyEvent.VK_RIGHT){
dx=0;
ChangeTex(1);
}
} | 4 |
public static Graph randomTree2() {
int depth = 10;
Graph graph = new Graph(depth * 50, depth * 50);
int a = 0;
int b = -1;
int c = 0;
for (int i = 0; i < depth; i++) {
for (int j = 0; j <= i; j++) {
graph.addVertex(new Vertex(c++, 25 + 25 * (depth - i - 1) + 50
* j, 25 + 50 * i));
}
int k = a + (int) ((b - a + 1) * Math.random());
for (int j = a; j <= k; j++) {
graph.addEdge(j, b + 1 + j - a);
}
for (int j = k; j <= b; j++) {
graph.addEdge(j, b + 2 + j - a);
}
a = b + 1;
b = c - 1;
}
return graph;
} | 4 |
public static void notifyEOS( String sourcename, int queueSize )
{
synchronized( streamListenersLock )
{
if( streamListeners == null )
return;
}
final String srcName = sourcename;
final int qSize = queueSize;
new Thread()
{
@Override
public void run()
{
synchronized( streamListenersLock )
{
if( streamListeners == null )
return;
ListIterator<IStreamListener> i = streamListeners.listIterator();
IStreamListener streamListener;
while( i.hasNext() )
{
streamListener = i.next();
if( streamListener == null )
i.remove();
else
streamListener.endOfStream( srcName, qSize );
}
}
}
}.start();
} | 4 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already using infravision."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) glowing eyes!"):L("^S<S-NAME> invoke(s) glowing red eyes!^?"));
if(mob.location().okMessage(mob,msg))
{
successfulObservation=success;
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
return success;
} | 7 |
public void stepTestOn(PrintWriter oo) {
Stepper stepr;
ScruSet keyPile;
ScruSet valuePile;
SetTable tab;
oo.print("Test fetching of steppers (stepper at a key).\n"+
"");
keyPile = testKeys();
valuePile = testValues();
tab = SetTable.make(testCS());
Stepper stomper = keyPile.stepper();
for (; stomper.hasValue(); stomper.step()) {
Position key = (Position) stomper.fetch();
if (key == null) {
continue ;
}
Stepper stomper2 = valuePile.stepper();
for (; stomper2.hasValue(); stomper2.step()) {
Heaper val = (Heaper) stomper2.fetch();
if (val == null) {
continue ;
}
tab.introduce(key, val);
}
stomper2.destroy();
}
stomper.destroy();
Stepper stomper3 = keyPile.stepper();
for (; stomper3.hasValue(); stomper3.step()) {
Position key2 = (Position) stomper3.fetch();
if (key2 == null) {
continue ;
}
MuSet valSet;
valSet = testValues().asMuSet();
stepr = tab.stepperAt(key2);
oo.print("stepper for key ");
oo.print(key2);
oo.print(" is ");
oo.print(stepr);
oo.print("\n"+
"");
Stepper stomper4 = stepr;
for (; stomper4.hasValue(); stomper4.step()) {
Heaper val3 = (Heaper) stomper4.fetch();
if (val3 == null) {
continue ;
}
valSet.remove(val3);
}
stomper4.destroy();
if ( ! valSet.isEmpty()) {
oo.print("valSet contains ");
oo.print(valSet);
oo.print("\n"+
"");
}
}
stomper3.destroy();
oo.print("end of stepperAt: test\n"+
"\n"+
"");
/*
udanax-top.st:61594:SetTableTester methodsFor: 'tests'!
{void} stepTestOn: oo {ostream reference}
| stepr {Stepper} keyPile {ScruSet of: Position} valuePile {ScruSet of: Heaper}
tab {SetTable} |
oo << 'Test fetching of steppers (stepper at a key).
'.
keyPile _ self testKeys.
valuePile _ self testValues.
tab _ SetTable make: self testCS.
keyPile stepper forEach: [:key {Position} |
valuePile stepper forEach: [:val {Heaper} |
tab at: key introduce: val]].
keyPile stepper forEach: [:key2 {Position} | | valSet {MuSet} |
valSet _ self testValues asMuSet.
stepr _ tab stepperAt: key2.
oo << 'stepper for key ' << key2 << ' is ' << stepr << '
'.
stepr forEach: [:val3 {Heaper} |
valSet remove: val3].
valSet isEmpty not ifTrue: [oo << 'valSet contains ' << valSet << '
']].
oo << 'end of stepperAt: test
'.!
*/
} | 9 |
private HttpRequestBase getMethod(String url, HttpMethod requestMethod, Map<String, String> headers,
Map<String, String> params, File data) {
if (requestMethod == HttpMethod.POST) {
HttpPost httpPost = new HttpPost(url);
setReqHeaders(httpPost, headers);
if (params != null) {
httpPost.setEntity(getParamEntity(params));
}
if (data != null) {
httpPost.setEntity(getFileEntity(data));
}
return httpPost;
} else if (requestMethod == HttpMethod.PUT) {
HttpPut httpPut = new HttpPut(url);
setReqHeaders(httpPut, headers);
if (params != null) {
httpPut.setEntity(getParamEntity(params));
}
if (data != null) {
httpPut.setEntity(getFileEntity(data));
}
return httpPut;
} else if (requestMethod == HttpMethod.DELETE) {
if (params != null) {
url = appendParams(url, mapToQueryString(params));
}
HttpDelete httpDelete = new HttpDelete(url);
setReqHeaders(httpDelete, headers);
return httpDelete;
} else {
if (params != null) {
url = appendParams(url, mapToQueryString(params));
}
HttpGet httpGet = new HttpGet(url);
setReqHeaders(httpGet, headers);
return httpGet;
}
} | 9 |
public static String logging(String xliffFilename, String applicationName) {
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "www-proxy.cs.tcd.ie");
System.getProperties().put("proxyPort", "8080");
LoggerStatus status = null;
Properties prop = new Properties();
InputStream inputConfig = null;
LoggerJena loggerJena = null;
try {
inputConfig = new FileInputStream(Constants.CONFIG_FILENAME);
prop.load(inputConfig);
//Select the correct XSLT stylesheet
switch (applicationName) {
case "leanback_learning":
loggerJena = new LoggerJena(prop.getProperty("SPARQL_ENDPOINT"), prop.getProperty("LBL_PARTITION"), Constants.XSLT_GLOBIC_LBL);
System.out.println("leanback_learning");
break;
case "falcon":
loggerJena = new LoggerJena(prop.getProperty("SPARQL_ENDPOINT"), prop.getProperty("FALCON_PARTITON"), Constants.XSLT_FALCON);
break;
case "test":
loggerJena = new LoggerJena(prop.getProperty("SPARQL_ENDPOINT"), prop.getProperty("DFLT_REP_ID"), Constants.XSLT_FALCON);
break;
}
//log this file
FileInputStream inputStream = new FileInputStream(xliffFilename);
status = loggerJena.log(inputStream, xliffFilename, loggerJena);
System.out.println("STATUS==" + status.getOutput());
return status.getOutput();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(ContentLogging.class.getName()).log(Level.SEVERE, null, ex);
}
return status.getOutput();
} | 4 |
public void processEdit()
{
// set new size to accommodate additional components
setSize(GUI_WIDTH_AFTER_EDIT, GUI_HEIGHT_AFTER_EDIT);
// create south JPanel
south = new JPanel(new BorderLayout());
south.setBackground(Color.LIGHT_GRAY);
// create topSouth JPanel and add components to it
JPanel topSouth = new JPanel();
topSouth.setBackground(Color.LIGHT_GRAY);
topSouth.setLayout(new GridLayout(2, 1));
topSouth.setBorder(new TitledBorder(new EtchedBorder(), "Qualification"));
// create radio buttons for qualification title
njbButton = new JRadioButton("NJB");
njbButton.setBackground(Color.LIGHT_GRAY);
ijbButton = new JRadioButton("IJB");
ijbButton.setBackground(Color.LIGHT_GRAY);
// set the initially selected radio button
// based on the qualification of the selected referee
if (refereeClass.getQualification().charAt(0) == 'N')
njbButton.setSelected(true);
else
ijbButton.setSelected(true);
// create button group for qualification title buttons
// and add buttons to group
ButtonGroup jbGroup = new ButtonGroup();
jbGroup.add(njbButton);
jbGroup.add(ijbButton);
// create new JPanel to be added to the upper part of
// topSouth, and add buttons to panel
JPanel upperTopSouth = new JPanel();
upperTopSouth.setBackground(Color.LIGHT_GRAY);
upperTopSouth.add(njbButton);
upperTopSouth.add(ijbButton);
// add panel to topSouth
topSouth.add(upperTopSouth);
// create radio buttons for qualification level
oneButton = new JRadioButton("1");
oneButton.setBackground(Color.LIGHT_GRAY);
twoButton = new JRadioButton("2");
twoButton.setBackground(Color.LIGHT_GRAY);
threeButton = new JRadioButton("3");
threeButton.setBackground(Color.LIGHT_GRAY);
fourButton = new JRadioButton("4");
fourButton.setBackground(Color.LIGHT_GRAY);
// set initially selected radio button based on the
// qualification level of the selected referee
if (refereeClass.getQualification().charAt(3) == '1')
oneButton.setSelected(true);
else if (refereeClass.getQualification().charAt(3) == '2')
twoButton.setSelected(true);
else if (refereeClass.getQualification().charAt(3) == '3')
threeButton.setSelected(true);
else if (refereeClass.getQualification().charAt(3) == '4')
fourButton.setSelected(true);
// create button group for qualification level buttons
// and add buttons to button group
ButtonGroup numbersGroup = new ButtonGroup();
numbersGroup.add(oneButton);
numbersGroup.add(twoButton);
numbersGroup.add(threeButton);
numbersGroup.add(fourButton);
// create new JPanel to add to the lower part of
// topSouth, and add buttons to panel
JPanel lowerTopSouth = new JPanel();
lowerTopSouth.setBackground(Color.LIGHT_GRAY);
lowerTopSouth.add(oneButton);
lowerTopSouth.add(twoButton);
lowerTopSouth.add(threeButton);
lowerTopSouth.add(fourButton);
// add panel to topSouth
topSouth.add(lowerTopSouth);
// add topSouth to the NORTH section of south
south.add(topSouth, BorderLayout.NORTH);
// create centerSouth JPanel, add components to it
// and set border
JPanel centerSouth = new JPanel();
centerSouth.setBackground(Color.LIGHT_GRAY);
centerSouth.setBorder(new TitledBorder(new EtchedBorder(), "Home Locality"));
// create radio buttons for the home locality
northButton = new JRadioButton("North");
northButton.setBackground(Color.LIGHT_GRAY);
centralButton = new JRadioButton("Central");
centralButton.setBackground(Color.LIGHT_GRAY);
southButton = new JRadioButton("South");
southButton.setBackground(Color.LIGHT_GRAY);
// set initially selected radio button based
// on the home locality of the selected referee
if (refereeClass.getHomeLocality().equals("North"))
northButton.setSelected(true);
else if (refereeClass.getHomeLocality().equals("Central"))
centralButton.setSelected(true);
else if(refereeClass.getHomeLocality().equals("South"))
southButton.setSelected(true);
// create button group for home locality buttons
// and add buttons to group
ButtonGroup homeLocalityGroup = new ButtonGroup();
homeLocalityGroup.add(northButton);
homeLocalityGroup.add(centralButton);
homeLocalityGroup.add(southButton);
// add buttons to centerSouth panel
centerSouth.add(northButton);
centerSouth.add(centralButton);
centerSouth.add(southButton);
// add centerSouth panel to the CENTER part of south
south.add(centerSouth, BorderLayout.CENTER);
// create bottomSouth JPanel and add components to it
JPanel bottomSouth = new JPanel();
bottomSouth.setBackground(Color.LIGHT_GRAY);
bottomSouth.setLayout(new GridLayout(2, 1));
// create check boxes for visiting localities
northCheckBox = new JCheckBox("North");
northCheckBox.setBackground(Color.LIGHT_GRAY);
centralCheckBox = new JCheckBox("Central");
centralCheckBox.setBackground(Color.LIGHT_GRAY);
southCheckBox = new JCheckBox("South");
southCheckBox.setBackground(Color.LIGHT_GRAY);
// handles the home locality having to be in the visiting localities
visitingLocalitiesCheck();
// create new panel, set border, add check boxes
JPanel upperBottomSouth = new JPanel();
upperBottomSouth.setBackground(Color.LIGHT_GRAY);
upperBottomSouth.setBorder(new TitledBorder(new EtchedBorder(), "Visiting Localities"));
upperBottomSouth.add(northCheckBox);
upperBottomSouth.add(centralCheckBox);
upperBottomSouth.add(southCheckBox);
// add panel to bottomSouth
bottomSouth.add(upperBottomSouth);
// create new panel to hold update button
JPanel lowerBottomSouth = new JPanel();
lowerBottomSouth.setBackground(Color.LIGHT_GRAY);
lowerBottomSouth.setBorder(new TitledBorder(new EtchedBorder(), "Update Details"));
// create update button, add action listener
updateButton = new JButton("Update Details");
updateButton.addActionListener(this);
lowerBottomSouth.add(updateButton);
// add panel to bottomSouth
bottomSouth.add(lowerBottomSouth);
// add bottomSouth to SOUTH part of south
south.add(bottomSouth, BorderLayout.SOUTH);
// add south JPanel to JFrame
add(south, BorderLayout.SOUTH);
// disable editButton once pressed
editButton.setEnabled(false);
} | 8 |
public static void main(String[] args) {
File inputFile = new File("QuickSort.txt");
String inputFilePath = inputFile.getAbsolutePath();
// read and parse input file
try {
String strLine = "";
int count = 0;
FileInputStream fstream = new FileInputStream(inputFilePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
a[count ++] = Integer.parseInt(strLine);
}
br.close();
in.close();
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sort(0, a.length - 1);
for (int i = 0; i < a.length; i++) {
//System.out.println(a[i]);
}
System.out.println(comparisonsCount);
} | 4 |
public static int getCategoryIdByName(String categoryName)
{
ResultSet rs=null;
Connection con=null;
PreparedStatement ps=null;
int result=0;
try{
String sql="SELECT CATEGORYID FROM CATEGORY WHERE CATEGORY_NAME=?";
con=ConnectionPool.getConnectionFromPool();
ps=con.prepareStatement(sql);
ps.setString(1, categoryName);
rs=ps.executeQuery();
if(rs.next())
{
result = rs.getInt("CATEGORYID");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally{
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null)
{
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null)
{
try {
ConnectionPool.addConnectionBackToPool(con);;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
} | 8 |
public Combination<Colors> generate(){
List<Token<Colors>> combination = new ArrayList<Token<Colors>>();
List<Colors> colors = Colors.getColors();
Random r = new Random();
for (int i = 0; i < Combination.SIZE; i++) {
int n = r.nextInt(colors.size());
combination.add(new Token<Colors>(colors.get(n)));
colors.remove(n);
}
return new Combination<Colors>(combination);
} | 1 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
ArrayList<Integer> primes = primeNumbers(32769);
while ((line = in.readLine()) != null && line.length() != 0) {
int n = Integer.parseInt(line);
if (n == 0)
break;
int curP0 = 0, times = 0;
for (int i = 0; i < primes.size(); i++) {
curP0 = primes.get(i);
if (curP0 > n / 2)
break;
else if (isPrime[n - curP0])
times++;
}
out.append(times + "\n");
}
System.out.print(out);
} | 6 |
@Override
public int hashCode() {
int result = access != null ? access.hashCode() : 0;
result = 31 * result + (refresh != null ? refresh.hashCode() : 0);
result = 31 * result + (scope != null ? scope.hashCode() : 0);
return result;
} | 3 |
public ArrayList subledger1(String type, String loanid, float amount)
{ //get all details subledger needs
arrayTemp= new ArrayList();
String query = "select * from loan_dtl where loanid="+loanid+" and amordate between to_date('"+startDate.substring(0, 10)+"','yyyy-mm-dd') and to_date('"+endDate.substring(0, 10)+"','yyyy-mm-dd') ";
System.out.println("sub1query"+query);
ResultSet rs;
this.connect();
Statement stmt = null;
String premium_prev, interest_prev, penalty_prev;
float premium, interest, penalty ;
try
{
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
rs.next();
//System.out.println("in sub1 while"+loanid+" "+rs.getString("mon_interest"));
interest_prev=rs.getString("mon_interest");
premium_prev=rs.getString("mon_premium");
interest=rs.getFloat("mon_interest");
premium=rs.getFloat("mon_premium");
//penalty_prev=rs.getString("mon_penalty_prev");
if(amount-rs.getFloat("mon_interest")-rs.getFloat("mon_premium")==0)
{
//premium=0;
//interest=0;
interest=rs.getFloat("mon_interest");
premium=rs.getFloat("mon_premium");
System.out.println("pumasok dito sa zero");
}
else if(interest+premium>amount)
{
//interest=-amount;
if(amount-interest==0){//equals intereset
premium=rs.getFloat("mon_premium");
interest=0;
}
else if (amount-interest<0)//less than interest
{
premium=rs.getFloat("mon_premium");;
interest-=amount;
}
else if (amount-interest>0)//greater than interest
{
interest=0;
if(amount-interest<premium)//less than premium
premium-=(amount-interest);
}
}
arrayTemp.add(type);
//arrayTemp.add(ordtlid);
arrayTemp.add(rs.getString("loanid"));
arrayTemp.add(rs.getString("loandtlid"));
arrayTemp.add(rs.getString("mon_premium"));
arrayTemp.add(rs.getString("mon_interest"));
//arrayTemp.add(rs.getString("mon_penalty"));
arrayTemp.add(String.valueOf(premium));
arrayTemp.add(String.valueOf(interest));
//arrayTemp.add(String.valueOf(penalty));
}
catch (SQLException e)
{
e.printStackTrace();
}
finally{
this.disconnect();
}
return arrayTemp;
} | 7 |
private static boolean isValidCharCode(int code) {
return (0x0020 <= code && code <= 0xD7FF)
|| (0x000A == code)
|| (0x0009 == code)
|| (0x000D == code)
|| (0xE000 <= code && code <= 0xFFFD)
|| (0x10000 <= code && code <= 0x10ffff);
} | 8 |
protected boolean canBreed()
{
return getAge() >= getBreedingAge();
} | 0 |
protected boolean hasGotCollision(Position myFreeposition, List<Position> piecesPositions) {
int x = myFreeposition.getX();
int y = myFreeposition.getY();
Position tmp = new Position(x + 1, y - 2);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setY(y + 2);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setX(x - 1);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setY(y - 2);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setX(x + 2);
tmp.setY(y - 1);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setY(y + 1);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setX(x - 2);
if (piecesPositions.contains(tmp)) {
return true;
}
tmp.setY(y - 1);
if (piecesPositions.contains(tmp)) {
return true;
}
return false;
} | 8 |
public boolean addRecord(long value, int blockID){
//System.out.println( "addRecord() " + value + ", " + blockID );
boolean success = false;
if( !isLeafNode() ){
//System.out.println( "Adding record to internal node! " );
//System.out.println( "addRecord() " + value + ", " + blockID );
//System.out.println( summaryToString() );
//MiniDB_Constants.waitHere();
}
if( hasRoomForAnotherRecord() ){
int slotID = getSlotForValue( value );
int numRecsOnBlock = getCurrNumRecordsOnBlock();
//System.out.println( "now\n" + toString() );
//System.out.println( "Inserting into slot " + slotID );
//System.out.println( "current value in slot is " + getValue(slotID) );
//System.out.println( "numRecsOnBlock is " + numRecsOnBlock );
if( (getValue(slotID) != value) && (slotID < numRecsOnBlock) && (numRecsOnBlock > 0) ) {
//System.out.println( "Shifting" );
//MiniDB_Util.waitHere("");
// shift slots >= slotID since we are inserting a new record
// (not changing the value of an existing record)
//System.arraycopy( this.buffer, offset_slot(slotID), this.buffer, offset_slot(slotID+1), szToShift);
int srcOffset;
int destOffset;
if( isLeafNode() ){
srcOffset = offset_record(slotID);
destOffset = offset_record(slotID+1);
}
else{
srcOffset = offset_valueSlot(slotID);
destOffset = offset_valueSlot(slotID+1);
}
// just shift the whole block, could be more efficient prbly
int szToShift = MiniDB_Constants.BLOCK_SIZE - destOffset;
//int szToShift = (numRecsOnBlock - slotID) * bpt.get_indexRecordSize();
//System.out.println( "pre shift\n" + toString() );
System.arraycopy( this.buffer, srcOffset, this.buffer, destOffset, szToShift);
//System.out.println( "post shift\n" + toString() );
//System.out.println( "Shifted " + szToShift + " bytes starting from " + srcOffset );
}
// else MiniDB_Util.waitHere("not shifting");
// write the record into the slot
setValue( value, slotID );
if( isLeafNode ) setBlockID( blockID, slotID );
else setBlockID( blockID, slotID+1 );
//writeInt( offset_slot(slotID), blockID );
//writeLong( offset_slot(slotID)+MiniDB_Constants.BLK_ID_SIZE, value );
setCurrNumRecordsOnBlock(numRecsOnBlock+1);
}
if( !isLeafNode() ){
//System.out.println( summaryToString() );
//System.out.println( toString() );
//System.out.println( "Added " );
}
//System.out.println( "after add\n" + toString() );
//MiniDB_Util.waitHere("leaving addRecord()");
return success;
} | 8 |
public boolean checkOpposites(String elementDesc)
{
String oppositeElement, oppositeElement2 = "";
elementDesc = elementDesc.toLowerCase();
if(elementDesc.equalsIgnoreCase("earth")) oppositeElement = "lightning";
else if(elementDesc.equalsIgnoreCase("arcane")) oppositeElement = "life";
//else if(elementDesc.equals("cold")) oppositeElement = "steam";
else if(elementDesc.equalsIgnoreCase("fire")) oppositeElement = "cold";
else if(elementDesc.equalsIgnoreCase("lightning"))
{
oppositeElement = "rock";
oppositeElement2 = "water";
}
//else if(elementDesc.equals("life")) oppositeElement = "rock";
//else if(elementDesc.equals("steam")) oppositeElement = "cold";
else if(elementDesc.equalsIgnoreCase("cold")) oppositeElement = "fire";
else if(elementDesc.equalsIgnoreCase("water")) oppositeElement = "lightning";
else return true;
for(Element e : m_elements)
{
if(e.getDesc().equalsIgnoreCase(oppositeElement) ||
e.getDesc().equalsIgnoreCase(oppositeElement2))
return false;
}
return true;
} | 9 |
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode preHead = new ListNode(0);
ListNode lastNot = preHead;
preHead.next = head;
head = head.next;
while(head != null){
if(lastNot.next.val != head.val && lastNot.next.next != head){
lastNot.next = head;
head = head.next;
}else if(lastNot.next.val != head.val && lastNot.next.next == head){
lastNot = lastNot.next;
head = head.next;
}else{
head = head.next;
}
}
if(lastNot.next.next != null){
lastNot.next = null;
}
return preHead.next;
} | 7 |
@Test
public void testThrowExceptionOnReceiveTimeoutIfClosed() {
try {
consumer = new AbstractMessageConsumer(mockTopic) {
};
assertNotNull("No subscription was made",
mockTopic.getTopicSubscriber());
FutureTask<Message> f = getMessageFuture(consumer, 50);
consumer.close();
Message m = f.get(150, TimeUnit.MILLISECONDS);
assertNull("Unexpected message", m);
} catch (InterruptedException e) {
// This happnes if future.get is innterupted
fail("InterruptedException was not thrown as expected, but got ExecutionException");
} catch (ExecutionException e) {
assertEquals(DestinationClosedException.class, e.getCause()
.getClass());
// Success
} catch (TimeoutException e) {
e.printStackTrace();
fail("InterruptedException was not thrown as expected, but got TimeoutException");
} catch (DestinationClosedException e) {
fail("Unexpected exception on constructor");
}
} | 4 |
public boolean initializeGame(ArrayList<String> playerNames, ArrayList<String> playerTypes) throws FileNotFoundException {
isLoaded = false;
this.playerNames = playerNames;
this.playerTypes = playerTypes;
board = new Board();
try {
// Reads countries file
reader = new BufferedReader(new FileReader(countriesFile));
stringBuilder = new StringBuilder();
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
input = stringBuilder.toString();
System.out.println("Input from " + countriesFile + ": " + input);
// Splits the text in the file into an array
countriesArray = input.split("\t");
System.out.println("Loading board...");
// Reads adjacencies file
reader = new BufferedReader(new FileReader(adjacenciesFile));
stringBuilder = new StringBuilder();
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
input = stringBuilder.toString();
System.out.println("Input from " + adjacenciesFile + ": " + input);
// Creates an array of each line from the file
adjacenciesArray = input.split("\t");
// Reads continents file
reader = new BufferedReader(new FileReader(continentsFile));
stringBuilder = new StringBuilder();
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
input = stringBuilder.toString();
System.out.println("Input from " + continentsFile + ": " + input);
continentsArray = input.split("\t");
// Creates game board object
isLoaded = board.loadBoard(countriesArray, adjacenciesArray, continentsArray);
// Creates deck
System.out.println("Populating deck...");
deck = new Deck(board.getCountries());
// Creates ArrayList of players
System.out.println("Preparing players...");
players = new ArrayList<Player>();
// Players are created here
for (i = 0; i < playerNames.size(); i++) {
if (playerTypes.get(i).equals("Human")) {
isAI = false;
} else if (playerTypes.get(i).equals("AI")) {
isAI = true;
} else {
System.out.println("Error: playerType " + playerTypes.get(i) + " not found!");
}
players.add(new Player(playerNames.get(i), 50 - (playerNames.size() * 5), i, isAI));
}
System.out.println("Starting deploy phase...");
current = -1;
deployTurn = -1;
deployPhase = true;
deployed = true;
canTurnInCards = false;
canReinforce = true;
canAttack = false;
canFortify = false;
} catch (FileNotFoundException error) {
System.out.println(error.getMessage());
} catch (IOException error) {
System.out.println(error.getMessage());
}
return isLoaded;
} | 8 |
public String addOperator(String s){
if (position ==0){
return getMessage();
}
if (position ==1){
if(s.equals("="))
return getMessage();
setCalculatorSequence(position,s);
return getMessage();
}
if (position ==2){
if(s.equals("=")){
setCalculatorSequence(position,calculatorSequence.get(position -2));
setCalculatorSequence(position,s);
setCalculatorSequence(position, runAnOperation(position - 4, position - 2));
saveMemory();
return getMessage();
}
else {
setCalculatorSequence(position - 1, s);
return getMessage();
}
}
if (position ==3) {
if(s.equals("=")){
setCalculatorSequence(position,s);
setCalculatorSequence(position, runAnOperation(position - 4, position - 2));
saveMemory();
}
else{
setCalculatorSequence(position,"=");
setCalculatorSequence(position, runAnOperation(position - 4, position - 2));
if (!naN){
saveMemory();
setCalculatorSequence(position, calculatorMemory.get(calculatorMemory.size() - 2));
setCalculatorSequence(position,s);
}
else
saveMemory();
}
return getMessage();
}
if (position ==4){
setCalculatorSequence(position,s);
}
return getMessage();
} | 9 |
public static void mouseRelease() {
if(mousePressed) {
mousePressed = false;
mouseHeld = false;
//mouseRelease = new Point2D.Double(Mouse.getX(), -(Mouse.getY() - Camera.get().displayHeight));
}
} | 1 |
public TurnContext playTurn(Game g) {
TurnContext state = new TurnContext(g, false);
currentCx = state;
if (!getHand().isEmpty())
switchToHand(state);
else if (!getFaceUp().isEmpty())
switchToFaceUp(state);
else if (!getFaceDown().isEmpty())
switchToFaceDown(state);
if (hasValidMove(state) || state.blind) {
state.selection = chooseCard(state, "Choose first card to play", false, true, true);
if (state.selection == null) {
//TODO: let player play an unplayable face up card
//so they can move that card to their hand along with
//the picked up pile
startNewPile(state, "You are unwilling to make any moves.");
} else if (!state.g.isMoveLegal(state.selection)) {
assert state.blind;
putCard(state);
startNewPile(state, "You flipped an unplayable card.");
} else {
finishTurn(state);
}
} else {
startNewPile(state, "You are unable to make any moves.");
}
currentCx = null;
return state;
} | 7 |
public void testSetDayOfYear_int2() {
MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8);
try {
test.setDayOfYear(366);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals("2002-06-09T05:06:07.008+01:00", test.toString());
} | 1 |
private static ConcurrentHashMap<String, String> readHashMap(
String directory) throws IOException, ClassNotFoundException {
FileInputStream fin;
try {
fin = new FileInputStream(directory);
} catch (FileNotFoundException e) {
writeHashMap(directory, new ConcurrentHashMap<String, String>());
fin = new FileInputStream(directory);
}
ObjectInputStream ois = new ObjectInputStream(fin);
@SuppressWarnings("unchecked")
ConcurrentHashMap<String, String> map = (ConcurrentHashMap<String, String>) ois
.readObject();
ois.close();
return map;
} | 1 |
public void doAction(String value) {
char choice = value.toUpperCase().charAt(0);
while (choice != 'A' && choice != 'B' && choice != 'C' && choice != 'D') {
System.out.println("Invalid selection");
choice = getInput().toUpperCase().charAt(0);
}
if (choice == 'D') {
System.out.println("\nCorrect! You recovered quickly and now you have another log");
} else {
System.out.println("\nSorry that is not the correct way to stop the"
+ "\nbleeding quickly. You were not able to pull the wood free."
+ "\nNow you have to walk back to shore with NOTHIN!");
}
} | 5 |
public void nextFlight(ArrayList<Flight> currentPath, ArrayList<String> visited, String fromDest, String toDest) {
Flight recentFlight = currentPath.get(currentPath.size() - 1);
// Are we at our destination?
if (recentFlight.getToDest().equals(toDest)) {
// This is a valid flight path
// Make a copy of the path and add it to the list of valid paths
ArrayList<Flight> goodPath = new ArrayList<Flight>();
for(Flight copyFlight : currentPath) {
goodPath.add(copyFlight);
}
flightPaths.add(new FlightPath(goodPath));
} else {
for(Flight flight : allFlights) {
// Is the fromDest of the flight connected to the toDest of the previous flight?
if (recentFlight.getToDest().equals(flight.getFromDest())) {
// Is the flight not going somewhere we have already been?
if (!visited.contains(flight.getToDest())) {
// Is the flight not too long after the previous flight
if (flight.getFromDate().getDay() <= (recentFlight.getFromDate().getDay() + 1)) {
// Is the flight not before the previous flight
if (flight.getFromDate().getDay() >= recentFlight.getFromDate().getDay()) {
// This is a valid partial path
// Recurse to continue building the path
currentPath.add(flight);
visited.add(flight.getToDest());
nextFlight(currentPath, visited, fromDest, toDest);
currentPath.remove(currentPath.size() - 1);
visited.remove(visited.size() - 1);
}
}
}
}
}
}
} | 7 |
public boolean isMember(User user) {
if (this.isAdmin(user)) return true;
for (int i = 0; i < members.size(); i++) {
if(members.get(i)==user) return true;
}
return false;
} | 3 |
public LinkedList<Theater> getTheatersList(int zone) throws RemoteException{
if(this.lastRequest == -1)
this.lastRequest = System.currentTimeMillis();
if(connectionTimout()){
System.out.println("Connection timout");
return null;
}
if(list.size() > 0)
for(LinkedList<Theater> l : list)
if(l != null && l.getFirst().getZone() == zone)
return l;
//Wasn't on cache
TheatersListReplyMessage reply;
reply = rmiServer.listRequest(zone);
if(reply != null){
this.list.add(reply.getListTheaters());
return reply.getListTheaters();
}
System.out.println("Chegou ao fim a null");
return null;
} | 7 |
private int processZipFile(File file, String targetPath) {
List<Branch> branchs = CsvTool.getBranchs();
int count = 0;
for (Branch branch : branchs) {
if (file.getName().length() < 10) {
continue;
}
/**
* 4~10byte are bank code of branch file ext name should be .zip
*/
if (file.getName().substring(4, 10).equals(branch.getCode())
&& file.getName().endsWith("zip")) {
if (branch.getZipInd() == Branch.ZIP_IND_NEED_FOLDER) {
final String zipFileName = file.getName().substring(0,
file.getName().length() - 3);
/* using filename as folder name */
File f1 = new File(targetPath + "//" + zipFileName);
if (!f1.exists())
f1.mkdirs();
zipTools.unzip(file.getPath(), targetPath + "//"
+ zipFileName);
log.debug("unzip file:" + file.getPath() + " to "
+ targetPath + "//" + zipFileName);
} else {
zipTools.unzip(file.getPath(), targetPath);
}
log.info("branch:" + branch.getCode() + "-" + branch.getName()
+ ":Processed");
count++;
}
}
return count;
} | 6 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Detallecotizacion)) {
return false;
}
Detallecotizacion other = (Detallecotizacion) object;
if ((this.idDetallecotizacion == null && other.idDetallecotizacion != null) || (this.idDetallecotizacion != null && !this.idDetallecotizacion.equals(other.idDetallecotizacion))) {
return false;
}
return true;
} | 5 |
public void testRec(Configuration conf,byte depth){
depth++;
nbAppelListeFils++;
if (depth == 2)
System.out.println("nbappelListeFils : "+nbAppelListeFils);
ArrayList<Configuration> listeConfig = listeFils(conf);
if (depth<depthMax){
for (Configuration c : listeConfig) {
testRec(c, depth);
}
}
else if (depth==depthMax){
for (int i=0; i<listeConfig.size() ; i++) {
nbConfigFils++;
}
}
} | 5 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((affecting()==null)||(!(affecting() instanceof MOB)))
return false;
final MOB mob=(MOB)affecting();
if((affected==mob)
&&(mob!=getCharmer())
&&((mob.amFollowing()==null)||(mob.amFollowing()!=getCharmer()))
&&(mob.location()!=null)
&&(mob.location().isInhabitant(getCharmer())))
CMLib.commands().postFollow(mob,getCharmer(),true);
return super.tick(ticking,tickID);
} | 8 |
private CorbaOrocosConnection(OrocosDataPort port, ConnectionType connectionType,
boolean init, LockPolicy lockPolicy, boolean pull, int bufferSize,
int transport, int dataSize, String connectionName) throws CNoCorbaTransport, CNoSuchPortException {
logger = Logger.getLogger(CorbaOrocosConnection.class);
this.port = port;
this.connectionType = connectionType;
CConnectionModel type;
if(connectionType == ConnectionType.DATA){
type = RTT.corba.CConnectionModel.CData;
}else{
type = RTT.corba.CConnectionModel.CBuffer;
}
RTT.corba.CLockPolicy policy;
if(lockPolicy == LockPolicy.USYNC){
policy = RTT.corba.CLockPolicy.CUnsync;
}else if(lockPolicy == LockPolicy.LOCK_FREE){
policy = RTT.corba.CLockPolicy.CLockFree;
}else{
policy = RTT.corba.CLockPolicy.CLocked;
}
connectionPolicy = new CConnPolicy(type, init, policy, pull, bufferSize, transport, dataSize, connectionName);
CConnPolicyHolder policyHolder = new CConnPolicyHolder(connectionPolicy);
if(port.getPortType() == PortType.INPUT_PORT){
channelElement = port.getComponent().getCDataFlowInterface().buildChannelOutput(port.getName(), policyHolder);
if(port.getComponent().getCDataFlowInterface().channelReady(port.getName(), channelElement)){
logger.info("Createad a connection to the port " + port.getName());
}else{
logger.warn("Connection to the port " + port.getName() + " failed");
}
}else{
channelElement = port.getComponent().getCDataFlowInterface().buildChannelInput(port.getName(), policyHolder);
logger.info("Createad a connection to the port " + port.getName());
}
} | 5 |
public List<Posizione> adiacenti(Posizione posizione) {
List<Posizione> adiacenti = new LinkedList<Posizione>();
int x = posizione.getX();
int y = posizione.getY();
for(int i = -1; i<2; i++) {
for(int j = -1; j<2; j++) {
adiacenti.add(new Posizione(x+i, y+j));
}
}
Iterator<Posizione> it = adiacenti.iterator();
while(it.hasNext()){
Posizione p = it.next();
if ((p.getX()<0) || (p.getX()>=this.dimensione) || (p.getY()<0) ||
(p.getY()>=this.dimensione) || (p.equals(posizione)))
it.remove();
}
Collections.shuffle(adiacenti);
return adiacenti;
} | 8 |
public Light(String color, String location) {
this.color = color;
this.location = location;
light.addMouseListener(this);
switch (location) {
case "north":
rotate(180);
updatePosition(320, 220);
break;
case "east":
rotate(270);
updatePosition(350, 320);
break;
case "south":
updatePosition(250, 350);
break;
case "west":
rotate(90);
updatePosition(220, 250);
break;
}
} | 4 |
public static AppServer getInstance(String strTypeConn) throws Exception
{
if (strTypeConn == null || strTypeConn.equals("Oracle"))
{
if (instanceOracle == null)
{
instanceOracle = new AppServer("Oracle");
}
return instanceOracle;
}
else if (strTypeConn == null || strTypeConn.equals("MySQL"))
{
if (instanceMySQL == null)
{
instanceMySQL = new AppServer("MySQL");
}
return instanceMySQL;
}
else if (strTypeConn == null || strTypeConn.equals("SQLServer"))
{
if (instanceSQLServer == null)
{
instanceSQLServer = new AppServer("SQLServer");
}
return instanceSQLServer;
}
throw new Exception("Unkown Instance");
} | 9 |
@Test
public void resolve() {
print(digitalSum(1000));
} | 0 |
public void givereward(int cluelevel)
{
if (cluelevel == 1)
{
cluereward(Clues.randomClue1(), Clues.randomClue1(), Clues.randomNonClue1(), Clues.randomNonClue1(), Clues.randomRunes1(), 1, 1, 1, 1, 500);
deleteItem(2681, GetItemSlot(2681), 1);
cluelevel = 0;
cluestage = 0;
clueid = 0;
savemoreinfo();
}
if (cluelevel == 2)
{
cluereward(Clues.randomClue2(), Clues.randomClue2(), Clues.randomNonClue2(), Clues.randomNonClue2(), Clues.randomRunes2(), 1, 1, 1, 1, 500);
deleteItem(2682, GetItemSlot(2682), 1);
cluelevel = 0;
cluestage = 0;
clueid = 0;
savemoreinfo();
}
if (cluelevel == 3)
{
cluereward(Clues.randomClue3(), Clues.randomClue3(), Clues.randomNonClue3(), Clues.randomNonClue3(), Clues.randomRunes3(), 1, 1, 1, 1, 500);
deleteItem(2683, GetItemSlot(2683), 1);
cluelevel = 0;
cluestage = 0;
clueid = 0;
savemoreinfo();
}
} | 3 |
@Override
public void action() {
if(agente.getPasso() == 9 && agente.getCuponsCompradosComSucesso().size() > 1){
System.out.println("PASSO 9 AI");
for(ListaDeCupons lista : agente.getCuponsCompradosComSucesso()){
for(Cupom cupom : lista){
System.out.println("***************************************");
System.out.println("Comprei o cupom : " + cupom.toString());
System.out.println("Do agente : " + lista.getAID().getName());
System.out.println("Pelo valor de : R$" + cupom.getValor());
}
}
done = true;
}
} | 4 |
public FieldVisitor visitField(final int access, final String name,
final String desc, final String signature, final Object value) {
String s = remapper.mapFieldName(className, name, desc);
if ("-".equals(s)) {
return null;
}
if ((access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) == 0) {
if ((access & Opcodes.ACC_FINAL) != 0
&& (access & Opcodes.ACC_STATIC) != 0 && desc.length() == 1) {
return null;
}
if ("org/objectweb/asm".equals(pkgName) && s.equals(name)) {
System.out.println("INFO: " + s + " could be renamed");
}
super.visitField(access, name, desc, null, value);
} else {
if (!s.equals(name)) {
throw new RuntimeException("The public or protected field "
+ className + '.' + name + " must not be renamed.");
}
super.visitField(access, name, desc, null, value);
}
return null; // remove debug info
} | 8 |
public static List<TestData> loadData(final String componentName) {
List<TestData> result = new ArrayList<TestData>();
File componentDir = new File("res/testdata/" + componentName);
if (!componentDir.exists() || !componentDir.isDirectory()) {
throw new IllegalArgumentException("Test directory does not exist or is invalid");
}
List<File> testCandidates = traversePath(componentDir);
for (File in : testCandidates) {
if (in.getName().endsWith(".in")) {
File out = new File(in.getPath().replace(".in", ".out"));
try {
List<String> linesIn = new LinkedList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(
in.getPath()))));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
linesIn.add(currentLine);
}
reader.close();
List<String> linesOut = new LinkedList<String>();
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(out.getPath()))));
while ((currentLine = reader.readLine()) != null) {
linesOut.add(currentLine);
}
reader.close();
TestData t;
t = new TestData(linesIn, linesOut);
result.add(t);
} catch (IOException e) {
System.err.println("error loading test data for " + componentName);
e.printStackTrace();
}
}
}
return result;
} | 7 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.