text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
protected static IntervalList[] splitIntervals(IntervalList intervals) {
IntervalList[] subIntervals = new IntervalList[2];
subIntervals[0] = new IntervalList();
subIntervals[1] = new IntervalList();
//If only one interval, split it in half
if (intervals.getIntervalCount() == 1) {
List<Interval> intList = intervals.asList();
String contig = intervals.getContigs().iterator().next();
Interval interval = intList.get(0);
int midPoint = (interval.getFirstPos() + interval.getLastPos())/2;
subIntervals[0].addInterval(contig, interval.getFirstPos(), midPoint);
subIntervals[1].addInterval(contig, midPoint, interval.getLastPos());
return subIntervals;
}
if (intervals.getIntervalCount() == 2) {
List<Interval> intList = intervals.asList();
Iterator<String> contigIt = intervals.getContigs().iterator();
String contig0 = contigIt.next();
String contig1 = contigIt.next();
Interval interval = intList.get(0);
subIntervals[0].addInterval(contig0, interval);
interval = intList.get(1);
subIntervals[1].addInterval(contig1, interval);
return subIntervals;
}
long fullSize = intervals.getExtent();
long extentSoFar = 0;
int index = 0;
for(String contig : intervals.getContigs()) {
for(Interval interval : intervals.getIntervalsInContig(contig)) {
if (extentSoFar > fullSize / 2) {
index = 1;
}
subIntervals[ index ].addInterval(contig, interval);
extentSoFar += interval.getSize();
}
}
//Detect error that crops up when one last interval encountered is bigger
//than half the full extent, in this case last interval size will be zero
if (index == 0) {
Interval bigInterval = subIntervals[0].biggestInterval();
String contig = subIntervals[0].contigOfInterval(bigInterval);
if (bigInterval != null) {
subIntervals[0].removeInterval(bigInterval);
subIntervals[1].addInterval(contig, bigInterval);
}
}
if (subIntervals[0].getExtent() == 0 || subIntervals[1].getExtent() == 0) {
throw new IllegalStateException("Interval subdivision failed...");
}
return subIntervals;
} | 9 |
private static void printMenu() {
System.out.println("What will you like to have?");
for (Integer item : menu.keySet()) {
System.out.println(" " + item + ". " + menu.get(item));
}
} | 1 |
public static void main(String args[]) {
Server myServer = new Server("mySuperGameServer");
User a = new User(myServer, "a");
User b = new User(myServer, "b");
myServer.addUser(a);
System.out.println(myServer.currentUser().hashCode());
myServer.addUser(b);
System.out.println(myServer.currentUser().hashCode());
myServer.addUser(a);
System.out.println(myServer.currentUser().hashCode());
while(true) {
System.out.println("Welcome to QuizDuel!\nYou have to Log in first. What's your name?");
System.out.print("Your Name:");
String name = read();
// User a = new User(myServer, name);
myServer.addUser(new User(myServer, name));
System.out.println("Welcome to the game, "+myServer.currentUser().getName());
System.out.println("You are currently logged in on '"+myServer.getId()+"'");
System.out.println("You can either p)lay a game, show a u)serlist or l)ogin as another user");
String choice = read();
if(choice.equals("l")) {
continue;
}
if(choice.equals("u")) {
System.out.println(myServer.getUserList());
}
if(choice.equals("p")) {
if(myServer.currentUser().showDuels().size() == 0) {
System.out.println("You have no open duels, please login as another user and open a new duel");
System.out.println("Would you like to l)ogin as another user or s)tart a new game?");
String choiceString = read();
if(choiceString.equals("l")) {
continue;
} else {
System.out.println("With who do you want to play?");
System.out.println(myServer.getUserList());
String opponentName = read();
try {
myServer.currentUser().newDuel(myServer.getUserById(Integer.parseInt(opponentName)));
} catch (Exception e) {
System.out.println("Please enter a number");
}
// finally {
System.out.println("New " + myServer.currentUser().showDuels());
// }
}
} else {
System.out.println("You can play in one of the following open duels:");
System.out.println(myServer.currentUser().showDuels().toString());
}
}
}
// alice.newDuel(carol);
// System.out.println("end");
// bob.showDuels();
// alice.showDuels();
} | 7 |
@Override
public boolean equals(Object o) {
if (!(o instanceof Thread)) {
return false;
}
Thread t = (Thread) o;
if (!this.getHeadLine().equals(t.getHeadLine())) {
return false;
}
if (!this.getReplies().equals(t.getReplies())) {
return false;
}
if (!this.getAccount().equals(t.getAccount())) {
return false;
}
if (this.getId() != t.getId()) {
return false;
}
if (!this.getParentCategory().equals(t.getParentCategory())) {
return false;
}
if (!this.getText().equals(t.getText())) {
return false;
}
if (!this.getTime().equals(t.getTime())) {
return false;
}
return true;
} | 8 |
@Override
public void run() {
Game game = pacManBB.game;
int[] pills = game.getPillIndices();
int[] powerPills = game.getPowerPillIndices();
ArrayList<Integer> powerTargets = new ArrayList<Integer>();
ArrayList<Integer> targets = new ArrayList<Integer>();
for( int i=0; i < pills.length; i++ ) //check which pills are available
if( game.isPillStillAvailable(i) )
targets.add( pills[i] );
for( int i=0; i < powerPills.length; i++ ) //check with power pills are available
if( game.isPowerPillStillAvailable(i) ) {
targets.add( powerPills[i] );
powerTargets.add( powerPills[i] );
}
int[] targetsArray=new int[targets.size()]; //convert from ArrayList to array
int[] powerTargetsArray = new int[powerTargets.size()];
for( int i=0; i<targetsArray.length; i++ )
targetsArray[i]=targets.get(i);
for( int i=0; i<powerTargetsArray.length; i++ )
powerTargetsArray[i] = powerTargets.get(i);
if( targetsArray.length > 0 ) {
// System.out.println( "FOUND PILLS TO GO AFTER" );
pacManBB.allAvailablePillIndices = targetsArray;
pacManBB.availablePowerPillIndices = powerTargetsArray;
control.finishWithSuccess();
} else {
// System.out.println( "FOUND no pills TO GO AFTER" );
control.finishWithFailure();
}
} | 7 |
public static void main(final String[] args) throws Exception {
int i = 0;
int flags = ClassReader.SKIP_DEBUG;
boolean ok = true;
if (args.length < 1 || args.length > 2) {
ok = false;
}
if (ok && "-debug".equals(args[0])) {
i = 1;
flags = 0;
if (args.length != 2) {
ok = false;
}
}
if (!ok) {
System.err
.println("Prints the ASM code to generate the given class.");
System.err.println("Usage: ASMifier [-debug] "
+ "<fully qualified class name or class file name>");
return;
}
ClassReader cr;
if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1
|| args[i].indexOf('/') > -1) {
cr = new ClassReader(new FileInputStream(args[i]));
} else {
cr = new ClassReader(args[i]);
}
cr.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(
System.out)), flags);
} | 9 |
private boolean r_Step_1c() {
int v_1;
// (, line 51
// [, line 52
ket = cursor;
// or, line 52
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 52
if (!(eq_s_b(1, "y")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 52
if (!(eq_s_b(1, "Y")))
{
return false;
}
} while (false);
// ], line 52
bra = cursor;
// gopast, line 53
golab2: while(true)
{
lab3: do {
if (!(in_grouping_b(g_v, 97, 121)))
{
break lab3;
}
break golab2;
} while (false);
if (cursor <= limit_backward)
{
return false;
}
cursor--;
}
// <-, line 54
slice_from("i");
return true;
} | 8 |
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
//g2d.setColor(Color.blue);
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
drawInterfaceBackground(g2d);
drawGrids(g2d);
if(!pressedNotes.isEmpty()) {
Iterator<Map.Entry<Integer, Pointer>> it = pressedNotes.entrySet().iterator();
while (it.hasNext()) {
Entry<Integer, Pointer> temp = it.next();
NoteIndex noteIndex = translatePointToNoteIndex(temp.getValue().getLocation());
if(noteIndex != null&&!(temp.getValue().drawState()==INACTIVE)&&activeMenu[noteIndex.getPerson()]==NO_MENU) {
drawNote(g2d, noteIndex.getPerson(), noteIndex.getColumn(), noteIndex.getNote(), 1.125d, 1.125d);
}
}
// TODO Draw Instrument Menu if active here
}
for (int i = 0; i < player.getActiveGrids().size(); i++) {
if (activeMenu[i] == INSTRUMENT_MENU) {
drawInstrumentMenu(g2d, i);
}
if (activeMenu[i] == MENU_MENU) {
drawMenuMenu(g2d, i);
}
}
} | 8 |
public static void main(String[] argv) throws Exception {
Class<Mapper> mhj =(Class<Mapper>) JarLoader.getClassFromJar("C:\\Temp\\1/0.jar", "temperaturetest.Mapper1");
Logger.log("SDssd");
/*Socket sock = new Socket("127.0.0.1", 23456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Amey\\workspace\\example3\\commons\\s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);;
int i =0;
while(bytesRead>0 && !sock.isClosed()){
bos.write(mybytearray, 0, bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
System.out.println(" "+bytesRead);
if(i++==10)
break;
}
bos.close();
sock.close();
*/
//File ab = new File();
//Thread.sleep(3000);
String localFileLocation = "C:/Users/Amey/workspace/example3/exp.jar";
String className = "temperaturetest.MaxTemperatureMapper123";
Class<?> c = null;
try{
ArrayList<String> classNames=new ArrayList<String>();
//ZipInputStream zip=new ZipInputStream(new FileInputStream("E:/example/example3/exp.jar"));
ZipInputStream zip=new ZipInputStream(new FileInputStream(localFileLocation));
for(ZipEntry entry=zip.getNextEntry();entry!=null;entry=zip.getNextEntry())
if(entry.getName().endsWith(".class") && !entry.isDirectory()) {
// This ZipEntry represents a class. Now, what class does it represent?
StringBuilder classNameString=new StringBuilder();
for(String part : entry.getName().split("/")) {
classNameString.append(part);
classNameString.append(".");
if(part.endsWith(".class"))
classNameString.setLength(classNameString.length()-"..class".length()); //extra dot for the one which we inserted
}
classNames.add(className.toString());
}
zip.close();
JarClassLoader jcl = new JarClassLoader(localFileLocation);
Logger.log(classNames.get(0));
c = jcl.loadClass(className);//classNames.get(0));
Type[] t = c.getGenericInterfaces();
Mapper<String, Integer> mp = (Mapper<String, Integer>)c.newInstance();
mp.map((long) 3, "huj", new Context());
}
catch(Exception e){
Logger.log("Error while reding from jar file...");
e.printStackTrace();
}
//return c;
} | 7 |
private void setUpTechnicalsGraphData() {
TreeMap<Float, float[]> technicals = Database.TECHNICAL_PRICE_DATA
.get(Database.dbSet.get(id));
TreeMap<Float, Point2D.Float> marketToStockPairing = pairPriceWithMarketByDate(
technicals, 6);
TreeMap<Float, Float> stockPrices = new TreeMap<Float, Float>();
TreeMap<Float, Float> marketValue = new TreeMap<Float, Float>();
boolean averaging = EarningsTest.singleton.useAveraging.isSelected();
if (averaging) {
int neighborRange = EarningsTest.singleton.daysChoice.getSelectedIndex();
stockPrices = makeAverageListFromPricePair(marketToStockPairing, 0,
neighborRange);
marketValue = makeAverageListFromPricePair(marketToStockPairing, 1,
neighborRange);
} else {
stockPrices = makeListFromPricePair(marketToStockPairing, 0);
marketValue = makeListFromPricePair(marketToStockPairing, 1);
}
bars = createVolumeBars(technicals);
marketTimePath = makePathFromData(marketValue, MARKET);
timePathPoints.clear();
timePath = makePathFromData(stockPrices, INDIVIDUAL);
// depends on timePathPoints
generatePercentComparisonLines(marketToStockPairing);
} | 1 |
public static String encodeInventory(Inventory inventory) {
YamlConfiguration configuration = new YamlConfiguration();
configuration.set("Title", StringUtil.limitCharacters(inventory.getTitle(), 32));
configuration.set("Size", inventory.getSize());
for (int a = 0; a < inventory.getSize(); a++) {
ItemStack s = inventory.getItem(a);
if (s != null) {
configuration.set("Contents." + a, s);
}
}
return Base64Coder.encodeString(configuration.saveToString());
} | 2 |
public String countAndSay(int n) {
StringBuilder res = new StringBuilder("1");
for (int i = 2; i <= n; ++i) {
StringBuilder tmp = new StringBuilder();
int j = 0;
while (j < res.length()) {
int cnt = 1;
while (j + cnt < res.length() && res.charAt(j) == res.charAt(j + cnt)) {
++cnt;
}
tmp.append(cnt).append(res.charAt(j));
j += cnt;
}
res = tmp;
}
return res.toString();
} | 4 |
private List<String> completeResultWithCharactersTill(final String aCharacter) {
List<String> result = new LinkedList<String>();
for (final String anAlphabet : alphabet) {
if (!anAlphabet.equals(aCharacter)) {
if (result.size() >= 1) {
result = addCharacterTo(result, anAlphabet, 2);
} else {
result = addCharacterTo(result, anAlphabet, 1);
}
} else {
break;
}
}
return result;
} | 3 |
private boolean isValidMineLoc(Block block){
final HashSet<Material> naturalMats = new HashSet<Material>(4);
naturalMats.add(Material.COBBLESTONE);
naturalMats.add(Material.DIRT);
naturalMats.add(Material.GRASS);
naturalMats.add(Material.GRAVEL);
naturalMats.add(Material.LOG);
naturalMats.add(Material.NETHERRACK);
naturalMats.add(Material.SAND);
naturalMats.add(Material.SANDSTONE);
naturalMats.add(Material.SNOW_BLOCK);
naturalMats.add(Material.STONE);
if(naturalMats.contains(block.getType())){
int tripCount = 0;
for(BlockFace faceName : this.bChecks){
if(!naturalMats.contains(block.getRelative(faceName).getType()) ){
return false;
}
if(block.getRelative(faceName).getRelative(BlockFace.UP).getTypeId() == 0){
tripCount++;
}
}
return tripCount > 0 ? true : false;
}else{
return false;
}
} | 5 |
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String a = in.readLine();
if (a == null || a.equals(""))break;
String arr[] = a.trim().split(" +");
if (Integer.parseInt(arr[0]) > 1) {
TreeSet<Integer> arbol = new TreeSet<Integer>();
for (int i = 2; i < arr.length; i++){
int x = Math.abs(Integer.parseInt(arr[i-1])-Integer.parseInt(arr[i]));
if(x<=Integer.parseInt(arr[0])-1&&x>0)arbol.add(x);
}
System.out.println(arbol.size()==Integer.parseInt(arr[0])-1?"Jolly":"Not jolly");
} else if (Integer.parseInt(arr[0]) == 1) System.out.println("Jolly");
else System.out.println("Not jolly");
}
} | 9 |
void updateMouse(MouseEvent e,boolean pressed, boolean released,
boolean inside) {
mousepos = e.getPoint();
mousepos.x = (int)(mousepos.x/el.x_scale_fac);
mousepos.y = (int)(mousepos.y/el.y_scale_fac);
mouseinside=inside;
int button=0;
if ((e.getModifiers()&InputEvent.BUTTON1_MASK)!=0) button=1;
if ((e.getModifiers()&InputEvent.BUTTON2_MASK)!=0) button=2;
if ((e.getModifiers()&InputEvent.BUTTON3_MASK)!=0) button=3;
if (button==0) return;
if (pressed) {
mousebutton[button]=true;
keymap[255+button]=true;
if (wakeup_key==-1 || wakeup_key==255+button) {
if (!eng.isRunning()) {
eng.start();
// mouse button is cleared when it is used as wakeup key
mousebutton[button]=false;
keymap[255+button]=false;
}
}
}
if (released) {
mousebutton[button]=false;
keymap[255+button]=false;
}
} | 9 |
@Override
public void endElement(String uri, String localName, String qName) {
// we need to find out if the element ending now corresponded
// to matches in some stacks
// first, get the pre number of the element that ends now:
if (openNodesPreNumbers.isEmpty()) {
// We have no open elements, ignore this element
return;
}
// now look for Match objects having this pre number:
//for (TPEStack stack : rootStack.getDescendantStacks()) {
// if (stack.getPatternNode().getName().equals(qName) && stack.top().getStatus() == Match.STATUS.OPEN && stack.top().getPre() == preOfLastOpen) {
if (current.getName().equals(qName)) {
int preOfLastOpen = openNodesPreNumbers.pop();
TPEStack stack = current.getStack();
// all descendants of this Match have been traversed by now.
Match m = stack.pop();
boolean incomplete = false;
// check if valuePredicates are in the match
if (current.getStack().getPatternNode().getValuePredicate() != null
&& current.getStack().getPatternNode().getValuePredicate().equals(m.getTextValue())) {
incomplete = true;
}
// check if m has child matches for all children
// of its pattern node
for (PatternNode pChild : current.getStack().getPatternNode().getChildren()) {
// pChild is a child of the query node for which m was created
Collection<Match> childMatches = m.getChildren().get(pChild);
if (childMatches.isEmpty() && !pChild.isOptional()) {
// m lacks a child Match for the pattern node pChild
incomplete = true;
break;
}
}
if (incomplete) {
// we remove m from its Stack, detach it from its parent etc.
if (m != rootMatch) {
m.getParent().removeChild(m);
} else {
rootMatch = null;
}
}
m.close();
current = current.getParent();
}
//}
} | 9 |
@Test(expected = DuplicateInstanceException.class)
public void addDuplicateBookingTest() throws DuplicateInstanceException {
Student s = null;
Booking b = null;
try {
s = familyService.findStudent(3);
} catch (InstanceNotFoundException e) {
assertTrue("Student not found", false);
}
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar cb = Calendar.getInstance();
try {
cb.setTime(sdf.parse("27/10/2014"));
} catch (ParseException e) {
assertTrue("Bad format to calendar", false);
}
b = new Booking(cb, s, bookingService.getDiningHall().get(0));
try {
bookingService.create(b);
bookingService.create(b);
} catch (MaxCapacityException e1) {
assertTrue("Full dining hall ", false);
} catch (NotValidDateException e) {
assertTrue("Invalid date", false);
}
} | 4 |
public boolean equals(Object object)
{
try
{
MealyTransition t = (MealyTransition) object;
return super.equals(t) && getLabel().equals(t.getLabel()) && getOutput().equals(t.getOutput());
}
catch(ClassCastException e)
{
return false;
}
} | 3 |
public String getImageName() {
String name = "";
if (itemType != null) {
name = itemType.getImageName();
}
return name;
} | 1 |
private TreeNode successor(TreeNode predecessorNode) {
TreeNode successorNode = null;
if (predecessorNode.left != null) {
successorNode = predecessorNode.left;
while (successorNode.right != null) {
successorNode = successorNode.right;
}
} else {
successorNode = predecessorNode.parent;
while (successorNode != null && predecessorNode == successorNode.left) {
predecessorNode = successorNode;
successorNode = predecessorNode.parent;
}
}
return successorNode;
} | 4 |
@Override
public void onConnect()
{
String channel = config.get("Chan0");
int i = 0;
while(channel != null)
{
this.joinChannel(channel);
channel = config.get("Chan" + ++i);
}
components = new LinkedList<ComponentInterface>();
i = 0;
channel = config.get("Module0");
while(channel != null)
{
String component = channel + channel.substring(channel.lastIndexOf("."));
try
{
Class cl = Class.forName(component);
ComponentInterface obj = (ComponentInterface)cl.newInstance();
obj.init(moduleconfig.get(channel));
components.add(obj);
channel = config.get("Module" + ++i);
}
catch (Exception e)
{
System.err.println("Unable to Load Module " + channel);
System.err.println(e.getMessage());
System.exit(1);
}
}
} | 3 |
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// unconfirmed wrapper?
if (!confirmed) sb.append("[Unconfirmed: ");
// add time
sb.append("Time T+").append(time).append(". ");
// internal/external?
if (threatPosition == THREAT_POSITION_INTERNAL) {
if (threatLevel == THREAT_LEVEL_SERIOUS) {
sb.append("Serious internal threat");
} else sb.append("Internal threat");
} else if (threatLevel == THREAT_LEVEL_SERIOUS) {
sb.append("Serious threat");
} else sb.append("Threat");
sb.append('.');
if (threatPosition != THREAT_POSITION_INTERNAL) {
sb.append(" Zone ");
switch (sector) {
case THREAT_SECTOR_BLUE: sb.append("blue"); break;
case THREAT_SECTOR_WHITE: sb.append("white"); break;
case THREAT_SECTOR_RED: sb.append("red"); break;
default: sb.append("unknown");
}
sb.append('.');
}
if (!confirmed) sb.append(']');
/*s.append("Threat [");
// unconfirmed?
if (!confirmed) s.append("unconfirmed ");
// position?
switch (threatPosition) {
case THREAT_POSITION_EXTERNAL: break;
case THREAT_POSITION_INTERNAL: s.append("internal "); break;
default: s.append("non-positioned ");
}
// add level
switch (threatLevel) {
case THREAT_LEVEL_NORMAL: s.append("threat"); break;
case THREAT_LEVEL_SERIOUS: s.append("serious threat"); break;
default: s.append("unknown threat");
}
s.append("; T+");
s.append(time);
if (threatPosition != THREAT_POSITION_INTERNAL) {
s.append(" in sector ");
switch (sector) {
case THREAT_SECTOR_BLUE: s.append("blue"); break;
case THREAT_SECTOR_WHITE: s.append("white"); break;
case THREAT_SECTOR_RED: s.append("red"); break;
default: s.append("unknown");
}
}
s.append(']');*/
return sb.toString();
} | 9 |
private void fillGroupForm(GroupObject groupObject) {
type("group_name", groupObject.getName());
type("group_header", groupObject.getHeader());
type("group_footer", groupObject.getFooter());
} | 0 |
public String generate() {
if (details)
System.out.println("Producing floors overview. It can be found in: output/"+name+"/overviews");
int dimx = MyzoGEN.DIMENSION_X * chunksX;
int dimy = MyzoGEN.DIMENSION_Y * chunksY;
NoiseMap overviewnoise = null;
try {
overviewnoise = new NoiseMap(dimx, dimy);
NoiseMapBuilderPlane builder = new NoiseMapBuilderPlane();
builder.setSourceModule(noise);
builder.setDestNoiseMap(overviewnoise);
builder.setDestSize(dimx, dimy);
builder.setBounds(0, chunksX * 4, 0, chunksY*4);
builder.build();
} catch (Exception e) {e.printStackTrace();}
ImageCafe image = null;
try {
RendererImage render = new RendererImage();
image = new ImageCafe(dimx, dimy);
render.setSourceNoiseMap(overviewnoise);
render.setDestImage(image);
render.clearGradient();
Gradient gradient = new Gradient(floorSet);
for (int i = 0; i < gradient.gradientPoints.length; i++) {
render.addGradientPoint(gradient.gradientPoints[i], gradient.gradientColors[i]);
}
render.render();
} catch (ExceptionInvalidParam ex) {
ex.printStackTrace();
}
BufferedImage im = Utils.imageCafeToBufferedImage(dimx, dimy, image);
Utils.saveImage(im, "output/"+name+"/overviews/floors_overview.png");
if (details)
System.out.println("Floors overview saved.");
return "No errors.";
} | 5 |
@Override
public void update(final int delta) {
if (startLoading) {
Sounds.get();
Textures.get();
Fonts.get();
final List<Object> options = Config.loadOptions();
Sounds.get().setSoundEnabled(options.isEmpty() ? true : (Boolean) options.get(3));
Sounds.get().setMusicEnabled(options.isEmpty() ? true : (Boolean) options.get(4));
Game.get().setCurrentState(MenuState.name);
}
startLoading = true;
} | 3 |
public void display(){
Dimension currentPanelSize; // Current size of the presentation panel.
double sizeFactor; // Factor between 800x600 grid and current panel size.
if (Debug.audio) System.out.println("AudioPlayer -> display called");
if (null != player){
currentPanelSize = Gui.getSlidePanel().getSize();
// Must typecast here, otherwise integer maths is performed.
sizeFactor = ((double)currentPanelSize.width / (double)800);
if (Debug.audio) System.out.println("AudioPlayer -> display -> scale factor : " + sizeFactor);
// Now apply the scale to the desired coordinates and dimensions.
// These scaled results will be used in this class from now on.
scaledXCoord = (int) (xCoord * sizeFactor);
if (Debug.audio) System.out.println("AudioPlayer -> display -> scaled xCoord : " + scaledXCoord);
scaledYCoord = (int) (yCoord * sizeFactor);
if (Debug.audio) System.out.println("AudioPlayer -> display -> scaled yCoord : " + scaledYCoord);
scaledXDim = (int) (250 * sizeFactor);
if (Debug.audio) System.out.println("AudioPlayer -> display -> scaled xDim : " + scaledXDim);
// Set the size of the JPanel according to input parameters.
mediaPanel.setBounds(scaledXCoord, scaledYCoord, scaledXDim, 25);
// Add the JPanel to the main window.
Gui.getSlidePanel().add(mediaPanel, new Integer(super.getZOrder()));
Gui.getSlidePanel().repaint();
// If autoplay is True, then begin playback immediately.
if (autoplay) {
if (Debug.audio) System.out.println("AudioPlayer -> display -> Autoplay enabled");
player.start();
}
// If autoplay is False, then display the stopped player.
else {
if (Debug.audio) System.out.println("AudioPlayer -> display -> Autoplay disabled");
player.realize();
}
}
} | 9 |
public void run()
{
while(true)
{
try
{
this.NFull.acquire();
this.NEmpty.release();
System.out.println("Comsommateur : " + this.counter--);
}
catch (Exception e)
{
e.printStackTrace();
}
}
} | 2 |
public void setWypoz(Boolean wypoz) {
this.wypoz = wypoz;
} | 0 |
public static void main(String[] args)
{
Logger log = LogManager.getLogger(Log4jTest.class);
log.info("info通过 class 对象来获取 logger 对象");
log.debug("debug通过 class 对象来获取 logger 对象");
log.warn("warn通过 class 对象来获取 logger 对象");
} | 0 |
public void setaField1(int aField1) {
this.aField1 = aField1;
} | 0 |
public static void main(String [] args) throws BiffException, IOException, RowsExceededException, WriteException
{
ArrayList<pinfo> paperlist = new ArrayList<pinfo>();
String title,link,abs, session, author;
Map<String, String> linkinfo = new HashMap<String,String>();
Map<String, String> absinfo = new HashMap<String, String>();
BufferedReader reader = new BufferedReader(new FileReader(new File("final_result.txt")));
while ((title = reader.readLine()) != null) {
link = reader.readLine();
linkinfo.put(title, link);
}
jxl.Workbook workbook = Workbook.getWorkbook(new FileInputStream("papers.xls"));
Sheet sheet = workbook.getSheet("Research Vol 6");
int row = sheet.getRows();
for (int i=1; i<sheet.getRows(); ++i) {
title = sheet.getCell(1,i).getContents();
if (title.equals("eof")) {
break;
}
abs = sheet.getCell(3,i).getContents();
absinfo.put(title, abs);
}
sheet = workbook.getSheet("Research Vol 7");
for (int r = 1; r<sheet.getRows(); ++r) {
title = sheet.getCell(1,r).getContents();
if (title.equals("eof")) {
break;
}
abs = sheet.getCell(3,r).getContents();
absinfo.put(title, abs);
}
//sheet = workbook.getSheet(arg0)
workbook.close();
workbook = Workbook.getWorkbook(new FileInputStream("program.xls"));
sheet = workbook.getSheet("Sheet4");
for (int i=1; i<sheet.getRows(); ++i) {
session = sheet.getCell(0,i).getContents();
if (session.equals("eof")) break;
title = sheet.getCell(1,i).getContents();
author = sheet.getCell(2,i).getContents();
abs = absinfo.get(title);
link = linkinfo.get(title);
if(link == null) link = "none";
paperlist.add(new pinfo("Papers "+session, title, author, abs,link));
}
/*
System.out.println(paperlist.size());
for(pinfo p: paperlist) {
System.out.println(p.session);
System.out.println(p.link);
}*/
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File("tmp.xls"));
jxl.write.WritableSheet ws = wwb.createSheet("Test Shee 1", 0);
jxl.write.Label label_session, label_id, label_title, label_link, label_author,label_abstract;
int c = 96;
for(int i = 0; i<paperlist.size(); ++i) {
pinfo t = paperlist.get(i);
label_session = new jxl.write.Label(0, i, t.session);
label_id = new jxl.write.Label(1, i, (new Integer(c)).toString());
c=c+1;
label_link = new jxl.write.Label(2, i, t.link);
label_title = new jxl.write.Label(3, i, t.title);
label_author = new jxl.write.Label(4, i, t.author);
label_abstract = new jxl.write.Label(5, i, t.abstr);
ws.addCell(label_session);
ws.addCell(label_id);
ws.addCell(label_title);
ws.addCell(label_link);
ws.addCell(label_author);
ws.addCell(label_abstract);
}
wwb.write();
wwb.close();
} | 9 |
public boolean validate() throws Exception
{
boolean result = true;
if (this.products.size() == 0)
throw new Exception("Не указаны товары");
if (this.payed.size() == 0)
throw new Exception("Не указаны платежи");
for(int i = 0; i < this.taxes.length; i++)
if(this.taxes[i] < 0 || this.taxes[i] > 4)
throw new Exception("Неверные параметры налогов");
double total_to_pay = 0.0;
for(Product p : this.products )
total_to_pay += (p.count * p.price);
double total_payed = 0.0;
for(Double payment : this.payed)
total_payed += payment;
if (Math.round(total_payed) < Math.round(total_to_pay))
throw new Exception("Недостаточная оплата ( нужно " + Double.toString(total_to_pay) + ", заплачено " + Double.toString(total_payed) + " )");
return result;
} | 8 |
@Override
public void printAnswer(Object answer) {
if (!(answer instanceof String)) return;
System.out.print((String)answer);
} | 1 |
public void executeOrder(Order order) {
Planet planet = order.getPlanet();
switch (order.getType()) {
case BUILD:
buildOrder(planet, false);
break;
case SPECIAL_BUILD:
buildOrder(planet, true);
break;
case MOBILIZE:
mobilizeOrder(planet, false);
break;
case SPECIAL_MOBILIZE:
mobilizeOrder(planet, true);
break;
case RESEARCH:
researchOrder(planet, false);
break;
case SPECIAL_RESEARCH:
researchOrder(planet, true);
break;
default:
throw new IllegalArgumentException("Unknown order type.");
}
} | 6 |
public static Double[][] readData(String fileName) {
BufferedReader b;
Double[][] data = null;
try {
b = new BufferedReader(new FileReader(fileName));
String line;
// count number of lines
int N = 0;
while ((line = b.readLine()) != null) {
N++;
}
b.close();
// data is of the form: (userID, movieID,rating)_i
data = new Double[N][3];
int count = 0;
b = new BufferedReader(new FileReader(fileName));
while ((line = b.readLine()) != null) {
String[] s = line.split("\t");
try {
for (int i = 0; i < 3; i++)
data[count][i] = new Double(s[i]);
} catch (NumberFormatException nfe) {
System.err.println("input data must be of type integer.");
nfe.printStackTrace();
}
count++;
}
b.close();
} catch (FileNotFoundException e) {
System.err.println("Couldn't read the parameter file. Check the file name: " + fileName);
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return data;
} | 6 |
public static Map<JComponent, List<JComponent>> getComponentMap(
JComponent container, boolean nested) {
HashMap<JComponent, List<JComponent>> retVal =
new HashMap<JComponent, List<JComponent>>();
for (JComponent component : getDescendantsOfType(JComponent.class,
container, false)) {
if (!retVal.containsKey(container)) {
retVal.put(container,
new ArrayList<JComponent>());
}
retVal.get(container).add(component);
if (nested) {
retVal.putAll(getComponentMap(component, nested));
}
}
return retVal;
} | 3 |
public char findCircleStart() {
circularLinkedListNode p1 = head;
circularLinkedListNode p2 = head;
// find meeting point
for (int i = 0; i < nodeCount; i++) {
p1 = p1.next;
p2 = p2.next.next;
if (p1.item == p2.item)
break;
}
p1 = head;
while (p1.item != p2.item) {
p1 = p1.next;
p2 = p2.next;
}
return p1.item;
} | 3 |
private void readDirectory() {
List<File> listfile = new ArrayList<File>();
File folder = new File(path+App.FILE_SEP);
File[] listOfFiles = folder.listFiles();
//compter les sous dossiers
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
listfile.add(listOfFiles[i]);
}
}
for(int i = 0; i < listfile.size(); i++) {
folder = new File("" + listfile.get(i));
listOfFiles = folder.listFiles();
for(int j = 0; j < listOfFiles.length; j++) {
if (listOfFiles[j].isFile()) {
if(listOfFiles[j].getName().endsWith(chromosomes+f_ext)){
this.listexcelchrom.add(listOfFiles[j]);
}else if(listOfFiles[j].getName().endsWith(mitochondrions+f_ext)){
this.listexcelmito.add(listOfFiles[j]);
}else if(listOfFiles[j].getName().endsWith(plasmids+f_ext)){
this.listexcelplasm.add(listOfFiles[j]);
}else if(listOfFiles[j].getName().endsWith(chloroplasts+f_ext)){
this.listexcelchlor.add(listOfFiles[j]);
}
}
}
}
}//writeDirectory | 9 |
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(AjoutDepotForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AjoutDepotForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AjoutDepotForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AjoutDepotForm.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 AjoutDepotForm().setVisible(true);
}
});
} | 6 |
public synchronized int replaceAllByName(String name, JixelEntity entity) {
if (entity == null) {
JixelGame.getConsole().printErr(new NullPointerException("Can not set entity to null"));
return -1;
}
int count = 0;
synchronized (entityList) {
for (int i = 0; i < entityList.size(); i++) {
if (name == null && entity.getName() == null) {
count++;
entityList.set(i, entity);
} else if (name.equals(entity.getName())) {
count++;
entityList.set(i, entity);
}
}
}
return count;
} | 5 |
public ArrayList<PathItem> getLines() {
return lines;
} | 0 |
public String getUsername() {
return username;
} | 0 |
private boolean messageCC(String channel, String sender, String message)
{
if (!channel.equals("#cirno_tv"))
return false;
int duplicateWordCap = 15;
String[] words = message.split(" ");
if (words.length < duplicateWordCap)
return false;
//<3 Encryptio
HashMap<String, Integer> wordsOccurrenceMap = new HashMap<String, Integer>();
for (int i = 0; i < words.length; i++)
{
if (wordsOccurrenceMap.containsKey(words[i].toLowerCase()))
wordsOccurrenceMap.put(words[i].toLowerCase(), wordsOccurrenceMap.get(words[i].toLowerCase()) + 1);
else
wordsOccurrenceMap.put(words[i].toLowerCase(), 1);
}
System.out.println("[" + (double)wordsOccurrenceMap.size() / words.length + "] is the message CC for " + sender + "'s message [" + message + "].");
if ((double)wordsOccurrenceMap.size() / words.length < (1.0 / duplicateWordCap))
//messageCC = (double)containsCount / (words.length - 1.0); //Currently only checking one thing.
//if (messageCC >= CCVALUE)
{
int offenseCount = 1;
if (userPunishMap.containsKey(sender.toLowerCase()))
{
offenseCount = userPunishMap.get(sender.toLowerCase()) + 1;
}
if (offenseCount == 1)
{
logFilter(channel, sender, message, "CC Purge 2s");
acebotCore.addToQueue(channel, "/timeout " + sender + " 2", 1 /*1*/);
//acebotCore.addToQueue(channel, "[Warning] Purging " + sender + ".", 1);
}
if (offenseCount == 2)
{
logFilter(channel, sender, message, "CC Timeout 2m");
acebotCore.addToQueue(channel, "/timeout " + sender + " 120", 1 /*1*/);
acebotCore.addToQueue(channel, "[WARNING] T/O 2m " + sender + ".", 1);
}
if (offenseCount >= 3)
{
logFilter(channel, sender, message, "CC Permaban");
acebotCore.addToQueue(channel, "[ KAPOW ] " + sender + " - Contact a mod if this ban is in error.", 1);
acebotCore.addToQueue(channel, "/ban " + sender, 1 /*1*/);
}
userPunishMap.put(sender.toLowerCase(), offenseCount);
return true;
}
return false;
//Later, we can classfiy (emotes) into one group and make it detect emote spam!
} | 9 |
public static int[] buildFingerPrint(Path path, HashFunction func, int b, int k) {
if (b <= 0 || b > 16)
throw new AssertionError("hyperLogLog : b <= 0 or b > 16");
int m = 1 << b; // m = 2^b
int[] M = new int[m]; // M initialized to 0 by default
// A little more complicated than the first version because we want to
// be able to count the number of k-shingles.
int comp = 0;
StringBuilder strBuilder = new StringBuilder();
LinkedList<Integer> indexes = new LinkedList<Integer>();
for (String s : new WordReader(path))
if (comp < k) {
strBuilder.append(s);
indexes.add(s.length());
comp++;
} else {
strBuilder.replace(0, indexes.poll(), "");
strBuilder.append(s);
indexes.add(s.length());
long x = func.hashString(strBuilder.substring(0));
int j = (int) (x & (m - 1));
long w = x >>> b;
M[j] = Math.max(M[j], rho(w));
}
return M;
} | 4 |
public static VoidParameter getParam(String name) {
VoidParameter current = head;
while (current != null) {
if (name.equalsIgnoreCase(current.getName()))
return current;
if (current instanceof BoolParameter) {
if (name.length() > 2 && name.substring(0, 2).equalsIgnoreCase("no")) {
String name2 = name.substring(2);
if (name2.equalsIgnoreCase(current.getName())) {
((BoolParameter)current).reverse = true;
return current;
}
}
}
current = current.next;
}
return null;
} | 6 |
public void generateWorldChunk(int posHeight){
Block block = new Block((byte) 0);
Random material = new Random();
if (posHeight==0){
for(int x=0; x<chunkBase; x++){
for(int y=0; y<chunkBase; y++){
for(int z=0; z<chunkBase; z++){
if(y==0){
this.voxel[x][y][z]=18;
}
else{
if (y<9){
this.voxel[x][y][z]=02;
}
else{
if (y<11){
this.voxel[x][y][z]=05;
}
else {
this.voxel[x][y][z]=14;
}
}
}
}
}
}
// Just put some random stuff on the ground.
int x =0;
int y = 0;
byte m = 0;
for(int o=0; o<200; o++){
x = material.nextInt(chunkBase);
y = material.nextInt(chunkBase);
m = (byte) (material.nextInt(64) + 1);
voxel[x][11][y]= m;
for(int zz = 12; zz<material.nextInt(chunkBase-1); zz++){
voxel[x][zz][y]=m;
}
}
}
else {
this.voxel=null;
}
} | 9 |
private static void processJarfile(URL resource, String pkgname, ArrayList<Class<?>> classes) {
String relPath = pkgname.replace('.', '/');
String resPath = resource.getPath().replace("%20", " ");
String jarPath = resPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
JarFile jarFile;
try {
jarFile = new JarFile(jarPath);
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException reading JAR File '" + jarPath + "'. Do you have strange characters in your folders? Such as #?", e);
}
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
String className = null;
if (entryName.endsWith(".class") && entryName.startsWith(relPath)
&& entryName.length() > (relPath.length() + "/".length())) {
className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
}
if (className != null) {
Class<?> c = loadClass(className);
if (c != null)
classes.add(c);
}
}
} | 9 |
public void createPollingScheme(String schemeName, int interval,
String notificationMethod, String notificationHost, int port,
String readinessProperty, String readinessValue) {
Folder pollingSchemeFolder;
try {
try {
pollingSchemeFolder = (Folder) session.getObjectByPath("/PollingSchemes");
} catch (CmisObjectNotFoundException e) {
System.out.println("PollingSchemes folder not found: "
+ e.getMessage());
Map<String, String> properties = new HashMap<String, String>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
properties.put(PropertyIds.NAME, "PollingSchemes");
session.getRootFolder().createFolder(properties);
pollingSchemeFolder = (Folder) session.getObjectByPath("/PollingSchemes");
}
Map<String, Object> properties = new HashMap<String, Object>();
if (repositoryType == REP_TYPE_ALFRESCO) {
properties.put(PropertyIds.OBJECT_TYPE_ID,
"cmis:folder,P:poll:scheme");
} else if (repositoryType == REP_TYPE_NUXEO) {
properties.put(PropertyIds.OBJECT_TYPE_ID, "PollingScheme");
}
properties.put(PropertyIds.NAME, schemeName);
properties.put("poll:interval", interval);
properties.put("poll:notificationmethod", notificationMethod);
properties.put("poll:notificationhost", notificationHost);
properties.put("poll:notificationport", port);
properties.put("poll:readinessproperty", readinessProperty);
properties.put("poll:readinessvalue", readinessValue);
try {
if (repositoryType == REP_TYPE_ALFRESCO) {
pollingSchemeFolder.createFolder(properties);
} else if (repositoryType == REP_TYPE_NUXEO) {
pollingSchemeFolder.createFolder(properties);
}
} catch (CmisContentAlreadyExistsException e) {
System.out.println("Could not create polling scheme '"
+ schemeName + "': " + e.getMessage());
}
} catch (ClassCastException e) {
System.out.println("Object is not a CMIS folder.");
}
} | 7 |
private boolean buildingPreconditions(int playerIndex) {
return (playerIndex == serverModel.getTurnTracker().getCurrentTurn() &&
(serverModel.getTurnTracker().getStatus().equals("Playing") ||
serverModel.getTurnTracker().getStatus().equals("FirstRound") ||
serverModel.getTurnTracker().getStatus().equals("SecondRound"))) ? true : false;
} | 4 |
public AvailableGroup getThisItems() {
if (Script.holdExecution())
return new AvailableGroup();
AvailableGroup ret = new AvailableGroup(icache, ecache);
if (icache == null)
ret.add(Inventory.getItems(true));
if (ecache == null) {
if (Bank.isOpen())
ret.add(Equipment.getItems());
else
ret.add(Equipment.getCachedItems());
}
return ret;
} | 4 |
@Override
public String toString() {
return "file ["
+ (filename==null?"embedded":filename )+" "
+ (crc32==null?"":(", crc="+Long.toHexString(crc32.getValue())))+" "
+ (imageAttributes==null?"":imageAttributes.toString())
+"]";
} | 3 |
public static void main(String[] args) throws Exception {
// take the player number from command line and connect to the appropriate
// TCP port
playerNo = Integer.parseInt(args[0].trim());
int port = portOffset + playerNo;
Socket socket = new Socket("localhost", port);
BufferedReader in =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
useImprovedOpponentModel = args.length > 1 && "--improved".matches(args[1]);
player = new Player(useImprovedOpponentModel);
out.print("My name is " + player.name);
out.flush();
char[] cbuf = new char[inputLength];
String input;
// loop to take input and process it
while(true) {
try {
if (in.ready()) {
// take input
in.read(cbuf, 0, inputLength);
input = new String(cbuf);
input = input.trim();
player.receive(input);
// if we're being prompted for an action
// send the result of getAction()
if(inputPrompt.matcher(input).find()) {
out.print(player.getAction(input));
out.flush();
// if input is "SHUTDOWN", close the TCP socket and exit
} else if (input.equals("SHUTDOWN")) {
socket.close();
System.exit(0);
}
}
} catch(Exception e) {
// if there's an exception, print stack trace and exit
System.out.println("Caught exception: ");
e.printStackTrace();
socket.close();
System.exit(0);
}
}
} | 6 |
@SuppressWarnings("unchecked")
public TreeMap arbitrary(Random random, long size)
{
int length = (int) Arbitrary.random(random, 0,
Math.min(Integer.MAX_VALUE, size));
TreeMap map = new TreeMap();
for (int i = 0; i < length; ++i) {
Object key = keyGenerator.arbitrary(random, size);
Object value = valueGenerator.arbitrary(random, size);
map.put(key, value);
}
return map;
} | 1 |
public static Map<String, List<String>> readWords(File f) {
Map<String, List<String>> m = new HashMap<String, List<String>>();
Scanner s = null;
try {
s = new Scanner(f);
while (s.hasNext()) {
String word = s.next();
String alpha = sortLetters(word);
List<String> l = getWordsList(m, alpha);
l.add(word);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println(e);
System.exit(1);
} finally {
if (s != null) {
s.close();
}
}
return m;
} | 5 |
public void addBookLanguage(BookLanguage lng) {
Connection con = null;
PreparedStatement pstmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
pstmt = con.prepareStatement("Insert Into bookLanguage "
+ "(lan_code, lan_name) "
+ "Values(?,?)");
pstmt.setString(1, lng.getCode());
pstmt.setString(2, lng.getName());
pstmt.execute();
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
} | 4 |
public void toggleAmmo() {
speedSpinner.setEnabled(false);
piercingCheck.setEnabled(false);
distanceSpinner.setEnabled(false);
ammoDamageSpinner.setEnabled(false);
diameterSpinner.setEnabled(false);
multiCheck.setEnabled(false);
areaTextureText.setEnabled(false);
movingCheck.setEnabled(false);
durationSpinner.setEnabled(false);
switch(ammoTypeCombo.getSelectedIndex()) {
case(0):
speedSpinner.setEnabled(true);
piercingCheck.setEnabled(true);
distanceSpinner.setEnabled(true);
ammoDamageSpinner.setEnabled(true);
break;
case(1):
speedSpinner.setEnabled(true);
piercingCheck.setEnabled(true);
ammoDamageSpinner.setEnabled(true);
diameterSpinner.setEnabled(true);
multiCheck.setEnabled(true);
areaTextureText.setEnabled(true);
break;
case(2):
ammoDamageSpinner.setEnabled(true);
diameterSpinner.setEnabled(true);
movingCheck.setEnabled(true);
durationSpinner.setEnabled(true);
areaTextureText.setEnabled(true);
break;
case(3):
break;
}
} | 4 |
public void keyPressed(KeyEvent keyEvent) {
if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
iDireccionCanasta = 1;
}
if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
iDireccionCanasta = 2;
}
if(keyEvent.getKeyCode() == KeyEvent.VK_P) {
// si no estan las intrucciones
if (!bInstrucciones){
bPausado = !bPausado;
}
}
if(keyEvent.getKeyCode() == KeyEvent.VK_I) {
// si no esta pausado
if (!bPausado){
bInstrucciones = !bInstrucciones;
}
}
} | 6 |
@Test
public void testReceive() {
try {
consumer = new AbstractMessageConsumer(mockTopic) {
};
} catch (DestinationClosedException e) {
fail("Unexpected exception on constructor");
}
assertNotNull(mockTopic.getTopicSubscriber());
try {
Message msg = new MockMessage("TestMessage");
mockTopic.getTopicSubscriber().onMessage(msg);
FutureTask<Message> future = getMessageFuture(consumer);
Message received = future.get(5, TimeUnit.MILLISECONDS);
assertNotNull("Received message is null ", received);
assertEquals("Message values dont match.", msg.getMessage(),
received.getMessage());
} catch (TimeoutException e) {
fail("Did not receive message in time");
} catch (Exception e) {
logger.error("Error while calling receiving message", e);
fail("Error while calling onMessage:" + e.getMessage());
}
} | 3 |
private int binarySearch(String string, ArrayList<String> array) {
int currentPos = array.size()-1 / 2;
int min = 0;
int max = array.size()-1;
// Returns the location that string will go in the array
return binarySearchTail(array, string, min, max);
} | 0 |
public static void main(String[] args)
{
/** ****************** */
try {
PlasticSettings settings = PlasticSettings.createDefault();
Options.setDefaultIconSize(new java.awt.Dimension(16, 16));
UIManager.put(Options.USE_SYSTEM_FONTS_APP_KEY, settings.isUseSystemFonts());
Options.setGlobalFontSizeHints(settings.getFontSizeHints());
Options.setUseNarrowButtons(settings.isUseNarrowButtons());
Options.setTabIconsEnabled(settings.isTabIconsEnabled());
ClearLookManager.setMode(settings.getClearLookMode());
ClearLookManager.setPolicy(settings.getClearLookPolicyName());
UIManager.put(Options.POPUP_DROP_SHADOW_ENABLED_KEY, settings.isPopupDropShadowEnabled());
PlasticLookAndFeel.setMyCurrentTheme(settings.getSelectedTheme());
PlasticLookAndFeel.setTabStyle(settings.getPlasticTabStyle());
PlasticLookAndFeel.setHighContrastFocusColorsEnabled(settings.isPlasticHighContrastFocusEnabled());
UIManager.setLookAndFeel(settings.getSelectedLookAndFeel());
} catch (Exception e) {
}
/** ****************** */
splash = new SplashScreen();
splash.setProgress(0);
globalActionCollection = new GlobalActionCollection();
statusbar = new AnalyseStatusbar();
splash.setProgress(10);
AnalyseModule mod;
mod = new MeriseModule();
modules.put(mod.getID(), mod);
splash.setProgress(20);
analyseFrame = new AnalyseFrame();
for (Iterator<Entry<String, AnalyseModule>> e = modules.entrySet().iterator(); e.hasNext();) {
e.next().getValue().initGUI(analyseFrame);
}
// analyseFrame.initGUI();
splash.setProgress(90);
aboutWindow = new AboutWindow(analyseFrame);
parametrageWindow = new ParametrageWindow(analyseFrame);
splash.setProgress(100);
analyseFrame.setVisible(true);
splash.setVisible(false);
if (args.length > 0)
analyseFrame.getAnalyseSave().open(args[0]);
} | 3 |
public void addGroup(StringTokenizer tokens) {
int tokenCount = tokens.countTokens();
String[] settings = new String[tokenCount+1];
String line = "";
for (int i = 0; i < tokenCount; i++) {
settings[i] = tokens.nextToken();
line += " " + settings[i];
}
EIError.debugMsg("Image Paint Group:" + line, EIError.ErrorLevel.Notice);
groups.put(Integer.parseInt(settings[1], 16), settings);
} | 1 |
@Override
public void flush(Map<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> threadsAndFields, final SegmentWriteState state) throws IOException {
// Gather all FieldData's that have postings, across all
// ThreadStates
List<FreqProxTermsWriterPerField> allFields = new ArrayList<FreqProxTermsWriterPerField>();
long estimatedNumberOfTerms = 0;
for (Map.Entry<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> entry : threadsAndFields.entrySet()) {
Collection<TermsHashConsumerPerField> fields = entry.getValue();
for (final TermsHashConsumerPerField i : fields) {
final FreqProxTermsWriterPerField perField = (FreqProxTermsWriterPerField) i;
if (perField.termsHashPerField.numPostings > 0) {
allFields.add(perField);
estimatedNumberOfTerms += perField.termsHashPerField.numPostings;
}
}
}
// Sort by field name
Collections.sort(allFields);
final int numAllFields = allFields.size();
// TODO: allow Lucene user to customize this consumer:
final FormatPostingsFieldsConsumer consumer = new FormatPostingsFieldsWriter(estimatedNumberOfTerms,state, fieldInfos);
/*
Current writer chain:
FormatPostingsFieldsConsumer
-> IMPL: FormatPostingsFieldsWriter
-> FormatPostingsTermsConsumer
-> IMPL: FormatPostingsTermsWriter
-> FormatPostingsDocConsumer
-> IMPL: FormatPostingsDocWriter
-> FormatPostingsPositionsConsumer
-> IMPL: FormatPostingsPositionsWriter
*/
int start = 0;
while(start < numAllFields) {
final FieldInfo fieldInfo = allFields.get(start).fieldInfo;
final String fieldName = fieldInfo.name;
int end = start+1;
while(end < numAllFields && allFields.get(end).fieldInfo.name.equals(fieldName))
end++;
FreqProxTermsWriterPerField[] fields = new FreqProxTermsWriterPerField[end-start];
for(int i=start;i<end;i++) {
fields[i-start] = allFields.get(i);
// Aggregate the storePayload as seen by the same
// field across multiple threads
fieldInfo.storePayloads |= fields[i-start].hasPayloads;
}
// If this field has postings then add them to the
// segment
appendPostings(fields, consumer);
for(int i=0;i<fields.length;i++) {
TermsHashPerField perField = fields[i].termsHashPerField;
int numPostings = perField.numPostings;
perField.reset();
perField.shrinkHash(numPostings);
fields[i].reset();
}
start = end;
}
for (Map.Entry<TermsHashConsumerPerThread,Collection<TermsHashConsumerPerField>> entry : threadsAndFields.entrySet()) {
FreqProxTermsWriterPerThread perThread = (FreqProxTermsWriterPerThread) entry.getKey();
perThread.termsHashPerThread.reset(true);
}
consumer.finish();
} | 9 |
public java.lang.Float getByMethod(int method, boolean repeat) {
elapsed = ((double) System.currentTimeMillis() - timeStart) / timeAnim;
if (!repeat && elapsed > 1.0)
elapsed = 1.0;
switch (method) {
case -METHOD_LINE://line
elapsed = elapsed * 2 - 1;
break;
case METHOD_SINE:
elapsed = Math.sin(elapsed * (Math.PI / 2));
break;
case -METHOD_SINE:
elapsed = Math.sin(elapsed * Math.PI);
break;
case METHOD_COS:
elapsed = Math.sin(elapsed * (Math.PI / 2));
break;
case -METHOD_COS:
elapsed = Math.sin(elapsed * Math.PI);
break;
case METHOD_TAN:
elapsed = Math.tan(elapsed * (Math.PI / 4));
break;
case -METHOD_TAN:
elapsed = Math.tan(elapsed * (Math.PI / 2));
break;
}
return (float) (varOld * (1 - elapsed) + varNew * elapsed);
} | 9 |
@Override
public boolean equals(Object obj){
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof User))
return false;
User user = (User)obj;
return this.u_id.equals(user.u_id);
} | 3 |
public void reset()
{
if(!dead)
{
done = false;
moved = false;
attacking = false;
}
updateActions();
} | 1 |
public int getSeqNum(){
return this.seqNum;
} | 0 |
@Override
public String toString() {
return "Offrir{" + "vis_matricule=" + vis_matricule + ", rap_num=" + rap_num + ", med_depotLegal=" + med_depotLegal + ", quantite=" + quantite + '}';
} | 0 |
public static void main(String[] args) throws Exception
{
List<FastaSequence> list = FastaSequence.readFastaFile(ConfigReader.getCREOrthologsDir() + File.separator +
"contig_7000000220927531_postAlign.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(ConfigReader.getCREOrthologsDir() + File.separator +
"contig_7000000220927531_distances.txt")));
writer.write("xFasta\tyFasta\txLocation\tyLocation\txLocation_yLocaiton\tmismatchDistance\tgapToNonGap\tsumDistance\tsameLocation\n");
for(int x=0;x < list.size() -1 ; x++)
{
System.out.println(x );
FastaSequence xSeq = list.get(x);
String xLocation = getLocation(xSeq.getHeader());
for( int y=x+1; y < list.size(); y++)
{
FastaSequence ySeq = list.get(y);
String yLocation= getLocation(ySeq.getHeader());
int numDiffs =0;
int numGapDiffs = 0;
if( xSeq.getSequence().length() != ySeq.getSequence().length())
throw new Exception("No");
for( int z=0; z < xSeq.getSequence().length(); z++)
{
char c1 = xSeq.getSequence().charAt(z);
char c2 = ySeq.getSequence().charAt(z);
if( c1 != '-' || c2 != '-')
{
if ( c1 != c2)
{
if( c1 == '-' || c2 == '-')
numGapDiffs++;
else
numDiffs++;
}
}
}
writer.write(xSeq.getHeader() + "\t" + ySeq.getHeader() + "\t" +
xLocation + "\t" + yLocation + "\t" + getMergedLocation(xLocation, yLocation)+ "\t" +
numDiffs + "\t" + numGapDiffs + "\t" +
(numDiffs + numGapDiffs) + "\t" + xLocation.equals(yLocation) + "\n");
}
}
writer.flush(); writer.close();
} | 9 |
public static void main(String[] args) {
if(args.length > 0) {
portLocal = Integer.parseInt(args[0]);
System.out.println("TAILLE : "+args.length+";ARGS:"+args[0]/*+";ARGS:"+args[1]*/);
controleur = new Controleur();
service = new InterfaceService(portLocal);
lignes = new HashMap<String, Ligne>();
serviceUDP = new ServiceReceptionData();
serviceUDP.start();
fenetre = new Fenetre();
contenuPrincipal = new ConteneurPrincipal();
fenetre.add(contenuPrincipal);
fenetre.setPreferredSize(new Dimension(1270,800));
fenetre.pack();
fenetre.setVisible(true);
stations = new HashMap<String, ArrayList<String>>();
stations.put("1", new ArrayList<String>(){{ add("84:177"); add("83:148"); add("84:122"); add("122:119"); add("160:118"); add("195:148"); add("226:173"); add("257:195"); add("294:225"); add("331:222"); add("378:222"); add("428:222"); add("485:225"); }});
stations.put("2", new ArrayList<String>(){{ add("136:76"); add("233:76"); add("328:77"); add("329:112"); add("333:141"); add("329:181"); add("331:210"); add("380:208"); add("427:210"); add("482:210"); }});
stations.put("3", new ArrayList<String>(){{ add("331:555"); add("330:481"); add("331:377"); add("330:300"); add("327:237"); }});
stations.put("4", new ArrayList<String>(){{ add("484:235"); add("481:271"); add("482:305"); add("482:331"); }});
stations.put("5", new ArrayList<String>(){{ add("447:117"); add("447:167"); add("446:210"); add("481:270"); add("580:299"); add("661:323"); add("733:343"); add("767:351"); add("806:362"); add("848:379"); add("870:414"); add("870:452"); add("873:492"); add("874:530"); }});
stations.put("6", new ArrayList<String>(){{ add("579:57"); add("579:88"); add("578:119"); add("579:152"); add("578:187"); }});
stations.put("7", new ArrayList<String>(){{ add("947:233"); add("945:187"); add("915:178"); add("880:169"); add("842:162"); add("811:149"); add("774:143"); add("707:158"); add("664:173"); add("580:193"); add("579:247"); add("579:300"); add("580:339"); add("579:379");}});
stations.put("8", new ArrayList<String>(){{ add("553:581"); add("697:531"); add("698:473"); add("693:456"); add("697:416"); add("697:287"); add("737:255"); add("739:182"); add("772:150");}});
}
else
System.out.println("Il manque des arguments");
} | 1 |
public HelloWorldSoftware() throws Exception {
frame=new JFrame("Hello world");
frame.setSize(800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
world = new World();
world.setAmbientLight(0, 255, 0);
TextureManager.getInstance().addTexture("box", new Texture("box.jpg"));
box = Primitives.getBox(13f, 2f);
box.setTexture("box");
box.setEnvmapped(Object3D.ENVMAP_ENABLED);
box.build();
world.addObject(box);
world.getCamera().setPosition(50, -50, -5);
world.getCamera().lookAt(box.getTransformedCenter());
} | 0 |
public static Bitmap loadBitmapFromWeb(String location) throws Exception{
final URL url = new URL(location);
final HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
final BufferedImage img = ImageIO.read(connection.getInputStream());
int w = img.getWidth();
int h = img.getHeight();
Bitmap result = new Bitmap(w, h);
img.getRGB(0, 0, w, h, result.pixels, 0, w);
for(int i = 0; i < result.pixels.length; i++){
int src = result.pixels[i];
if(src == 0 || src == 16777215){
src = -2;
}
result.pixels[i] = src;
}
System.out.println("Loaded Bitmap: " +location);
return result;
} | 3 |
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (isVisible()
&& (e.getSource() == optionPane)
&& (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY
.equals(prop))) {
Object value = optionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
// ignore reset
return;
}
// Reset the JOptionPane's value.
// If you don't do this, then if the user
// presses the same button next time, no
// property change event will be fired.
optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if (btnString1.equals(value)) { // Enter pressed
int width = -1;
int height = -1;
try {
width = Integer.parseInt(textFieldWidth.getText());
} catch (NumberFormatException exc) {
// width text was invalid
textFieldWidth.selectAll();
JOptionPane.showMessageDialog(ResizeMapDialog.this,
"The value \"" + textFieldWidth.getText()
+ "\" is not an integer.",
"Please enter an integer value.",
JOptionPane.ERROR_MESSAGE);
textFieldWidth.requestFocusInWindow();
return;
}
try {
height = Integer.parseInt(textFieldHeight.getText());
} catch (NumberFormatException exc) {
// height text was invalid
textFieldHeight.selectAll();
JOptionPane.showMessageDialog(ResizeMapDialog.this,
"The value \"" + textFieldHeight.getText()
+ "\" is not an integer.",
"Please enter an integer value.",
JOptionPane.ERROR_MESSAGE);
textFieldHeight.requestFocusInWindow();
return;
}
// Success:
worldIO.resizeWorld(width, height);
clearAndHide();
} else if (btnString2.equals(value)) { // Cancel pressed
clearAndHide();
}
}
} | 9 |
final boolean method1413(Class258_Sub1 class258_sub1,
Class258_Sub1 class258_sub1_2_, int i, float f) {
try {
anInt2517++;
if (!method1414(35632))
return false;
Class206 class206 = ((OpenGlToolkit) aHa_Sub2_2511).aClass206_7778;
int i_3_ = 30 % ((-55 - i) / 59);
Class348_Sub42_Sub2 class348_sub42_sub2
= new Class348_Sub42_Sub2(aHa_Sub2_2511, 6408,
(((Class258_Sub1) class258_sub1)
.anInt8523),
(((Class258_Sub1) class258_sub1)
.anInt8529));
aHa_Sub2_2511.method3773(-1, class206);
boolean bool = false;
class206.method1508(0, class348_sub42_sub2, -12);
if (class206.method1507(117)) {
OpenGL.glPushMatrix();
OpenGL.glLoadIdentity();
OpenGL.glMatrixMode(5889);
OpenGL.glPushMatrix();
OpenGL.glLoadIdentity();
OpenGL.glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
OpenGL.glPushAttrib(2048);
OpenGL.glViewport(0, 0,
((Class258_Sub1) class258_sub1).anInt8523,
((Class258_Sub1) class258_sub1).anInt8529);
OpenGL.glUseProgramObjectARB(((Class337) aClass337_2513)
.aLong4178);
OpenGL.glUniform1iARB((OpenGL.glGetUniformLocationARB
(((Class337) aClass337_2513).aLong4178,
"heightMap")),
0);
OpenGL.glUniform1fARB((OpenGL.glGetUniformLocationARB
(((Class337) aClass337_2513).aLong4178,
"rcpRelief")),
1.0F / f);
OpenGL.glUniform2fARB
(OpenGL.glGetUniformLocationARB(((Class337)
aClass337_2513).aLong4178,
"sampleSize"),
(1.0F
/ (float) ((Class258_Sub1) class258_sub1_2_).anInt8523),
(1.0F
/ (float) ((Class258_Sub1) class258_sub1_2_).anInt8529));
for (int i_4_ = 0;
i_4_ < ((Class258_Sub1) class258_sub1).anInt8522;
i_4_++) {
float f_5_ = ((float) i_4_
/ (float) (((Class258_Sub1) class258_sub1)
.anInt8522));
aHa_Sub2_2511.method3771((byte) -118, class258_sub1_2_);
OpenGL.glBegin(7);
OpenGL.glTexCoord3f(0.0F, 0.0F, f_5_);
OpenGL.glVertex2f(0.0F, 0.0F);
OpenGL.glTexCoord3f(1.0F, 0.0F, f_5_);
OpenGL.glVertex2f(1.0F, 0.0F);
OpenGL.glTexCoord3f(1.0F, 1.0F, f_5_);
OpenGL.glVertex2f(1.0F, 1.0F);
OpenGL.glTexCoord3f(0.0F, 1.0F, f_5_);
OpenGL.glVertex2f(0.0F, 1.0F);
OpenGL.glEnd();
class258_sub1.method1958
(-26823, 0, ((Class258_Sub1) class258_sub1).anInt8523,
0, 0, i_4_, ((Class258_Sub1) class258_sub1).anInt8529,
0);
}
OpenGL.glUseProgramObjectARB(0L);
OpenGL.glPopAttrib();
OpenGL.glPopMatrix();
OpenGL.glMatrixMode(5888);
OpenGL.glPopMatrix();
bool = true;
}
class206.method1500(2983, 0);
aHa_Sub2_2511.method3770(-422613672, class206);
return bool;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("qi.D("
+ (class258_sub1 != null ? "{...}"
: "null")
+ ','
+ (class258_sub1_2_ != null
? "{...}" : "null")
+ ',' + i + ',' + f + ')'));
}
} | 6 |
@Override
public List<Usuario> filterGrid(String filter) {
List<Usuario> lista = service.findAll();
if("".equals(filter) || filter.equals("*")){
return lista;
}
List<Usuario> filtro = new ArrayList<Usuario>();
for (Usuario user : lista) {
if(user.nome.toUpperCase().startsWith(filter.toUpperCase())){
filtro.add(user);
}
}
return filtro;
} | 4 |
void parse(InputStream in) throws IOException {
while (!endOfFile) {
n = in.read(buffer, 0, bufSize);
if (n < 0) {
endOfFile = true;
n = 1;
buffer[0] = '\n';
}
for (int i = 0; i < n; i++) {
char c = (char) buffer[i];
if (state == ParseState.COMMENT) { // comment, skip to end of line
if (c == '\r' || c == '\n') {
state = ParseState.NORMAL;
}
else {
continue;
}
}
if (state == ParseState.ESCAPE) {
sb.append(c);
// if the EOL is \r\n, \ escapes both chars
state = c == '\r' ? ParseState.ESC_CRNL : ParseState.NORMAL;
continue;
}
switchC(c);
}
}
} | 8 |
private boolean collision() {
for(Platform p : level.platforms) {
if(p != null) {
int left = x + 11;
int right = x + 21;
if(right >= p.x && left <= p.x + p.getPixelWidth()) {
if(y >= p.y-3 && y <= p.y + p.getPixelHeight()) {
y = p.y;
return true;
}
}
}
}
return false;
} | 6 |
public void startWork ()
{
try
{
boolean hashFound = false;
String inputLine;
Scanner netScanner;
String serverString;
String instType;
//Open socket to server
toServer = new Socket (hostAddr, portNumber);
//Set up output from socket
socketOutput = new PrintWriter(toServer.getOutputStream(), true);
//Set up input to socket
socketInput = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
//Gets one line of input from the user's command line
commandLine = new BufferedReader(new InputStreamReader(System.in));
//Keep getting input lines until ctrl+d
System.out.print ("[CLIENT] Enter message to send to server and get a chunk of work: ");
while ((!hashFound) && ((inputLine = commandLine.readLine()) != null))
{
//Send the userInput line to the server
socketOutput.println ("[COMMAND] GiveWork");
//Get response from server
serverString = socketInput.readLine();
System.out.println ("[SERVER->CLIENT] Message received from server: \"" + serverString + "\"");
netScanner = new Scanner (serverString);
netScanner.next(); //Skip the [COMMAND] for now
instType = netScanner.next(); //Read in the command type
if ("Work".equals(instType))
{
workMode(netScanner);
System.out.print ("[CLIENT] Enter message to send to server and get a chunk of work: ");
//Get another line of input at the top of this loop
}
else if ("Found!".equals(instType))
{
//read in the answer
netScanner.next(); //Skip over the "Answer is:"
netScanner.next();
System.out.print ("[SERVER] Server says answer has been found. ");
System.out.println ("Plaintext is: \"" + netScanner.next() + "\"");
hashFound = true; //Exit the Client from here
}
else
{
System.out.println ("[NETERROR] Received an invalid command via network!");
}
}
//Close everything off when we're done with it
toServer.close();
socketOutput.close();
socketInput.close();
commandLine.close();
System.out.println ("[SYSTEM] Client has finished working. Terminating.");
}
catch (UnknownHostException uhe)
{
System.out.println ("[ERROR] UnknownHostException for host \"" + hostAddr + "\"");
System.exit(1);
}
catch (IOException ioe)
{
System.out.print ("[ERROR] IOException: Could not connect ");
System.out.println ("to \"" + hostAddr + "\" on port \"" + portNumber + "\".");
System.exit(1);
}
} | 6 |
public static final String getFileContents(String file) throws Exception
{
InputStream is = null;
if (!GoCoin.hasValue(file)) { throw new FileNotFoundException("File must be passed!"); }
try
{
File f = new File(file);
if (!f.exists()) { throw new FileNotFoundException("File ["+file+"] not found!"); }
is = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line = "";
StringBuilder sb = new StringBuilder();
//if for some crazy reason there are multiple lines, the last line wins
while ((line = in.readLine()) != null)
{
sb.append(line).append("\n");
}
return sb.toString();
}
catch (Exception e)
{
throw e;
}
finally
{
if (is != null)
{
try { is.close(); }
catch (IOException e) { }
}
}
} | 6 |
@Override
public void mouseEntered(MouseEvent e) {} | 0 |
public void setScheiding(GregorianCalendar datum) {
if (scheiding == null && huwelijk != null && datum.after(huwelijk)) {
scheiding = datum;
}
} | 3 |
public WorkTable(String firstName) throws SQLException{
db = new DBAccess();
String type = "";
boolean musician = false;
boolean actor = false;
Statement statement = db.connection.createStatement();
ResultSet result = null;
works = new ArrayList<String>();
ResultSet typeOfPerson = statement.executeQuery("SELECT \"postgres\".\"Person\".\"Type\" FROM \"postgres\".\"Person\" WHERE \"postgres\".\"Person\".\"FirstName\" = '" + firstName + "' ");
while (typeOfPerson.next()) {
type = typeOfPerson.getString("Type");
if(type.equals("Musician")) {
musician = true;
} else {
actor = true;
}
}
if (musician) {
result = statement.executeQuery("SELECT \"postgres\".\"Album\".\"Name\" FROM \"postgres\".\"Person\" JOIN \"postgres\".\"Album\" ON \"Person\".\"Id\"=\"Album\".\"Id\" WHERE \"Person\".\"FirstName\" = '" + firstName + "' ");
while (result.next()) {
works.add(result.getString("Name"));
}
}
if (actor) {
result = statement.executeQuery("SELECT \"postgres\".\"Movie\".\"Name\" FROM \"postgres\".\"Person\" JOIN \"postgres\".\"Movie\" ON \"Person\".\"Id\"=\"Movie\".\"Id\" WHERE \"Person\".\"FirstName\" = '" + firstName + "' ");
while (result.next()) {
works.add(result.getString("Name"));
}
}
} | 6 |
public static boolean isPrimeTrunc(int k, ArrayList<Integer> arr) {
if (k / 10 == 0)
return false;
for (int i = 1; k / i > 0; i *= 10) {
if (!(Collections.binarySearch(arr, k / i) >= 0)) {
return false;
}
}
for (int i = 10; k / i > 0; i *= 10) {
if (!(Collections.binarySearch(arr, k % i) >= 0)) {
return false;
}
}
return true;
} | 5 |
public void testMinus_int() {
Seconds test2 = Seconds.seconds(2);
Seconds result = test2.minus(3);
assertEquals(2, test2.getSeconds());
assertEquals(-1, result.getSeconds());
assertEquals(1, Seconds.ONE.minus(0).getSeconds());
try {
Seconds.MIN_VALUE.minus(1);
fail();
} catch (ArithmeticException ex) {
// expected
}
} | 1 |
public void setOptions(String[] options) throws Exception {
// Pruning options
m_unpruned = Utils.getFlag('U', options);
m_reducedErrorPruning = Utils.getFlag('R', options);
m_binarySplits = Utils.getFlag('B', options);
m_useMDLcorrection = !Utils.getFlag('J', options);
String confidenceString = Utils.getOption('C', options);
if (confidenceString.length() != 0) {
if (m_reducedErrorPruning) {
throw new Exception("Setting CF doesn't make sense " +
"for reduced error pruning.");
} else {
m_CF = (new Float(confidenceString)).floatValue();
if ((m_CF <= 0) || (m_CF >= 1)) {
throw new Exception("CF has to be greater than zero and smaller than one!");
}
}
} else {
m_CF = 0.25f;
}
String numFoldsString = Utils.getOption('N', options);
if (numFoldsString.length() != 0) {
if (!m_reducedErrorPruning) {
throw new Exception("Setting the number of folds" +
" does only make sense for" +
" reduced error pruning.");
} else {
m_numFolds = Integer.parseInt(numFoldsString);
}
} else {
m_numFolds = 3;
}
// Other options
String minNumString = Utils.getOption('M', options);
if (minNumString.length() != 0) {
m_minNumObj = Integer.parseInt(minNumString);
} else {
m_minNumObj = 2;
}
String seedString = Utils.getOption('Q', options);
if (seedString.length() != 0) {
m_Seed = Integer.parseInt(seedString);
} else {
m_Seed = 1;
}
} | 8 |
public boolean intersects(S2Cell cell, S2Point[] vertices) {
// Return true if this cap intersects any point of 'cell' excluding its
// vertices (which are assumed to already have been checked).
// If the cap is a hemisphere or larger, the cell and the complement of the
// cap are both convex. Therefore since no vertex of the cell is contained,
// no other interior point of the cell is contained either.
if (height >= 1) {
return false;
}
// We need to check for empty caps due to the axis check just below.
if (isEmpty()) {
return false;
}
// Optimization: return true if the cell contains the cap axis. (This
// allows half of the edge checks below to be skipped.)
if (cell.contains(axis)) {
return true;
}
// At this point we know that the cell does not contain the cap axis,
// and the cap does not contain any cell vertex. The only way that they
// can intersect is if the cap intersects the interior of some edge.
double sin2Angle = height * (2 - height); // sin^2(capAngle)
for (int k = 0; k < 4; ++k) {
S2Point edge = cell.getEdgeRaw(k);
double dot = axis.dotProd(edge);
if (dot > 0) {
// The axis is in the interior half-space defined by the edge. We don't
// need to consider these edges, since if the cap intersects this edge
// then it also intersects the edge on the opposite side of the cell
// (because we know the axis is not contained with the cell).
continue;
}
// The Norm2() factor is necessary because "edge" is not normalized.
if (dot * dot > sin2Angle * edge.norm2()) {
return false; // Entire cap is on the exterior side of this edge.
}
// Otherwise, the great circle containing this edge intersects
// the interior of the cap. We just need to check whether the point
// of closest approach occurs between the two edge endpoints.
S2Point dir = S2Point.crossProd(edge, axis);
if (dir.dotProd(vertices[k]) < 0
&& dir.dotProd(vertices[(k + 1) & 3]) > 0) {
return true;
}
}
return false;
} | 8 |
private static void assertThatParamsCanBeBound(String template, Object[] parameters) {
int nbTokens = countTokens(template);
if (nbTokens != parameters.length) {
String message = "绑定参数到查询语句[" + template + "]失败:参数个数[" + parameters.length + "]和Shell中Token个数[" + nbTokens
+ "]不匹配";
throw new IllegalMongoShellException(message);
}
} | 1 |
public static void repaintWhileDealing(CardPanel panel) {
panel.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | 1 |
public boolean addCoef(String name, BigDecimal coefficient) {
if (name != null && !name.equals("") && !this.existInList(name) && coefficient != BigDecimal.ZERO && this.coefficientList != null) {
Unit unit = new Unit(name, coefficient, false);
this.coefficientList.add(unit);
unit.setType(this);
return true;
}
return false;
} | 5 |
public void processGedcomFile(GedcomReader reader) throws IOException,
GedcomReaderException, PropertyException {
for (GedcomRecord record = reader.nextRecord(); record != null; record = reader
.nextRecord()) {
if (record.getLevel() != 0)
throw new GedcomReaderException("Level is not zero in " + record,
reader.getLineNumber());
String tag = record.getTag();
GedcomObjectFactory factory = null;
if (tag.equalsIgnoreCase("INDI"))
factory = personFactory;
else if (tag.equalsIgnoreCase("FAM"))
factory = familyFactory;
else if (tag.equalsIgnoreCase("NOTE"))
factory = noteFactory;
else if (tag.equalsIgnoreCase("SOUR"))
factory = sourceFactory;
else if (tag.equalsIgnoreCase("TRLR")) {
makeSets();
return;
} else
factory = null;
if (factory != null)
factory.processGedcomRecord(record, reader);
else
ignoreRecord(record, reader);
}
} | 8 |
protected void recalcsz(Coord max) {
sz = max.add(wbox.bsz().add(mrgn.mul(2)).add(tlo).add(rbo)).add(-1, -1);
wsz = sz.sub(tlo).sub(rbo);
if (folded)
wsz.y = wsz.y / 2;
asz = wsz.sub(wbox.bl.sz()).sub(wbox.br.sz()).sub(mrgn.mul(2));
} | 1 |
public ViewController(Frame frame, GameServerSocket socket) {
server = socket;
view = frame;
initEvents();
} | 0 |
private boolean isChunkOpDone(int x, int z, int op)
{
if (x < 0 || x >= xSize)
return true;
if (z < 0 || z >= zSize)
return true;
if (savedChunks[x][z])
return true;
if (chunks[x][z] == null)
return false;
return chunks[x][z].opsDone[op];
} | 6 |
@Override public void sign(String apikey) {
this.apikey = apikey;
} | 0 |
static void translateXML() throws Exception {
BufferedReader jin = new BufferedReader(new FileReader("37.xml"));
FileWriter citeSeer = new FileWriter("citeSeer.txt");
FileWriter assistant = new FileWriter("assistant.txt");
String line, lineMark, lineInfo, lines = "";
int count = 0, position1, position2, position3;
while ((line = jin.readLine()) != null) {
position1 = line.indexOf('<');
position2 = line.indexOf('>');
lineMark=line.substring(position1 + 1, position2);
//System.out.println(lineMark);
if (isAKeyWord(lineMark)) {
lineInfo = line.substring(position2 + 1, line.length());
position3 = lineInfo.indexOf('<');
while (position3 < 0) {
lineInfo += jin.readLine();
position3 = lineInfo.indexOf('<');
}
lineInfo = lineInfo.substring(0, position3);
lines += lineInfo+" ";
} else if (isASopWord(lineMark)) {
if (!lines.equals("")) toToken(++count, lines, citeSeer, assistant);
lines = "";
}
}
System.out.println("\nTotal books processed:\t" + count);
jin.close();
} | 5 |
public String[] build(int[] values) {
int a[] = new int[10];
Arrays.fill(a,0);
int n = values.length;
for(int i = 0;i < n;i++){
a[values[i]]++;
}
int f = 0;
for(int i = 0;i < 10;i++){
if(a[i] > f)f = a[i];
}
String ans[] = new String[f + 1];
Arrays.fill(ans,"");
for(int i = f;i > 0 ;i--){
for(int j = 0;j < 10;j++){
if(a[j] > 0){
ans[i] += "X";
a[j]--;
}else{
ans[i] += ".";
}
}
}
ans[0] = "..........";
return ans;
} | 6 |
private void startServer_adbMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startServer_adbMenuActionPerformed
try {
adbController.startServer();
} catch (IOException ex) {
logger.log(Level.ERROR, "An error occurred while starting the ADB server!");
ex.printStackTrace(System.err);
}
}//GEN-LAST:event_startServer_adbMenuActionPerformed | 1 |
public void analyze(String param) {
StringTokenizer st = new StringTokenizer(param);
// System.err.println("in analyze " + param);
if (st.countTokens() < 2) return;
String first_word = st.nextToken().toLowerCase();
// System.err.println("in analyze(first_word) " + first_word);
if (first_word.equals("a")) {
analyzeAnchor(st.nextToken(""));
} else if (first_word.equals("frame")) {
analyzeFrame(st.nextToken(""));
} else if (first_word.equals("base")) {
extractBase(st.nextToken(""));
}
} | 4 |
private void acao166(Token token) throws SemanticError {
if (tipoFator != Tipo.INTEIRO && tipoFator != Tipo.REAL) {
throw new SemanticError("Operador unário exige operando numérico",
token.getPosition());
}
if(!indexandoVetorParametro)
parametroAtualPodeSerReferencia = false;
} | 3 |
public String getCurSongname() {
if (mp3list != null) {
return mp3list.getSong().getName();
}
return "nichts";
} | 1 |
Subsets and Splits