method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
6722ac0a-9f88-4317-bf24-d3b3531c8ceb
| 3
|
@Override
public Venda ListById(int id_fornecedor) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
Venda v = new Venda();
try{
conn = ConnectionFactory.getConnection();
pstm = conn.prepareStatement(LISTBYID);
rs = pstm.executeQuery();
while (rs.next()){
v.setQuantidade(rs.getInt("nome_fn"));
v.setDtVenda(rs.getDate("telefone_fn"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao listar vendas " + e);
}finally{
try{
ConnectionFactory.closeConnection(conn, pstm, rs);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e);
}
}
return v;
}
|
b944dcdd-770e-484e-850b-d717cfd5b3d7
| 2
|
public static int countVertices(Poly p, Segment s) {
int count = 0;
for(int i = 0; i < p.size(); i++) {
if(containsPoint(s, p.get(i))) {
count++;
}
}
return count;
}
|
ac117a6d-ae91-46c8-9329-8db2166bd5e3
| 1
|
public static void main(String[] args) {
// ArrayMerge am = new ArrayMerge();
// int[] a = { 1, 2, 9, 10, 13, -1, -1, -1, -1, -1, -1, -1 };
// int[] b = {4,5,7,9,11,12,14};
//
// am.merge(a, b, 5, 7);
// for(int i = 0; i<a.length;i++){
// System.out.print(a[i]+" ");
// }
// int[] sa = {3,6,7,9,11,12,14,18,19,20,23};
// OneSidedBinarySearch osbs = new OneSidedBinarySearch();
// System.out.println(osbs.oneSidedBinarySearch(sa, 20));
// sortAnagramsOfStringArray saosa = new sortAnagramsOfStringArray();
// String[] arr = { "abc", "oipqe", "bca", "cfgt", "jncik", "tcfg",
// "kijnc", "poieq" };
// saosa.sortAnagrams(arr);
// for (int i = 0; i < arr.length; i++)
// System.out.print(arr[i] + " ");
int[] arr = { 5, 6, 7, 8, 1, 2, 3, 4 };
//int[] arr = { 5, 1, 3 };
RotatedBinarySearch rbs = new RotatedBinarySearch();
//System.out.println(rbs.binarySearch(arr, 0, arr.length - 1, 3));
System.out.println(rbs.rotatedBinarySearch(arr, 3));
// LinkedListSorting lls = new LinkedListSorting(1000000);
// //System.out.println(lls);
// lls.sortLinkedList();
// lls.sortLinkedList2();
// BubbleSort bs = new BubbleSort();
// System.out.println("BS: " + bs.bubbleSort("3474281112000910acb"));
// System.out.println("BS2: " + bs.bubbleSort2("3474281112000910acb"));
// System.out.println("BS3: " + bs.bubbleSort3("3474281112000910acb"));
//
// SelectionSort ss = new SelectionSort();
// System.out.println("SS: " + ss.selectionSort("3474281112000910acb"));
// System.out.println("SS2: " + ss.selectionSort2("3474281112000910acb"));
// System.out.println("SS stable: " + ss.selectionSortStable("3474281112000910acb"));
//
// InsertionSort is = new InsertionSort();
// System.out.println("IS: " + is.insertionSort3("3474281112000910acb"));
//
MergeSort ms = new MergeSort();
System.out.println("MS: " + ms.mergeSort("3474281112000910acb"));
//
// QuickSort qs = new QuickSort();
// System.out.println("QS: " + qs.quickSort("3474281112000910acb"));
// SortedArrayInterspersed_11_5 sai = new
// SortedArrayInterspersed_11_5();
// String[] strs= {"ab","","","bce","","","","ea","ef"};
// System.out.println(sai.MutatedBinarySearch(strs, "ef"));
// BinarySearch bsea = new BinarySearch();
// int[] bsarr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23 };
// int index = bsea.binarySearch(bsarr, 4);
// System.out.println("return index: " + index);
// index = bsea.binarySearchIterative(bsarr, 4);
// System.out.println("return index: " + index);
//
// int[] qsarr = { 6, 4, 9, 10, 30, 15 };
// QuickSelect qse = new QuickSelect();
// int KthEle = qse.selectKth(qsarr, 1);
// System.out.println("-------Kth element is: " + KthEle);
//
// int[] qsarr2 = { 4, 2, 5, 8, 9, 1 };
// int KthEleRec = qse.selectKthRec(qsarr2, 6);
// System.out.println("KthRec element is: " + KthEleRec);
//
// TwoSorted_CheckIntersection tsci = new TwoSorted_CheckIntersection();
// int[] tscia = { 3, 6, 7, 9, 11, 12, 14, 18, 19, 20, 23 };
// int[] tscib = { 2, 3, 10, 13, 14, 17, 18 };
// int[] tscic = tsci.getIntersection(tscia, tscib);
// for (int i = 0; i < tscic.length; i++) {
// System.out.print(tscic[i] + " ");
// }
// System.out.println();
//
// MultiKeySort mks = new MultiKeySort();
// mks.Sort();
// System.out.println("-----");
// mks.Sort2();
//
RadixSort rs = new RadixSort();
int[] rsarr = { 3, 66, 887, 139, 101, 12, 14, 18, 19, 20, 23 };
rs.radixSort(rsarr);
System.out.print("Radix Sort: ");
for (int tmp: rsarr) {
System.out.print(tmp + " ");
}
System.out.println();
}
|
807cde38-d40d-45c4-83e6-459692df99b6
| 9
|
public FlyAWayView(SingleFrameApplication app) {
super(app);
initComponents();
Controller.Instance().addObserver(this);
this.renderMarqueeText();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
this.getFrame().setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.getFrame().addWindowListener(new FlyAwayWindowListener());
btnSchedule.setVisible(false);
User u = Controller.Instance().getLoggedIn();
lblWelkom.setText("Welcome: " + u.getUsername());
if (u.getRank() == Rank.ADMIN) {
btnUsers.setEnabled(true);
} else if (u.getRank() == Rank.STAFF) {
//Als user een staff member is(voor rooster)
JButton[] btnArray = {
btnAirport, btnFlight, btnPlane, btnStaff, btnUsers, btnCountry, btnAirmarshall
};
butonVisible(btnArray, false);
btnSchedule.setVisible(true);
}
}
|
2a231496-73d2-49c0-983d-b7df241f1398
| 5
|
public static int[][] loadMethod(File file) {
try {
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<ArrayList<Integer>> posList = new ArrayList<ArrayList<Integer>>();
while ((line = br.readLine()) != null) {
String[] vals = line.split("\\s+");
posList.add(new ArrayList<Integer>());
for (String a : vals) {
posList.get(posList.size() - 1).add(Integer.parseInt(a));
}
}
reader.close();
br.close();
int columns = posList.size();
int rows = posList.get(0).size();
int[][] cus = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cus[i][j] = posList.get(j).get(i);
}
}
return cus;
} catch (IOException ex) {
return new int[1][1];
}
}
|
e53ccb35-78aa-4959-801e-84e996a49561
| 7
|
public Value get(Key key1)
{
if (size() > 0)
{
Node<Key, Value> x = root;
while(x != null)
{
int cmp = key1.compareTo(x.key1); //compare with the left key of Node
if (cmp < 0)
{
x = x.left;
}
else if (cmp > 0) //bigger than left key and this Node is 3-Node
{
if (x.key2 != null) //has key2
{
cmp = key1.compareTo(x.key2);
if (cmp < 0) //bigger than left key and smaller than right key
{
x = x.middle;
}
else if (cmp > 0) // bigger than right key
{
x = x.right;
}
else //equal to the right key
{
return x.val2;
}
}
else //no key2
{
x = x.right;
}
}
else // equal to the left key
{
return x.val1;
}
}
}
return null;
}
|
0ba90a52-9485-4825-af9a-7b43ffd566c8
| 2
|
public void startElement(String name)
throws IOException, XMLWriterException {
if (!bDocumentOpen) {
throw new XMLWriterException(
"Can't start new element, no open document.");
}
if (bStartTagOpen) {
w.write(">" + newLine);
}
writeIndent();
w.write("<" + name);
openElements.push(name);
bStartTagOpen = true;
}
|
1ca4832d-dfba-4551-b21e-982567f0c3ed
| 6
|
ArrayList<movePair> possibleMoves(Point[] grid, Pair pr) {
ArrayList<movePair> possible = new ArrayList<movePair>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
Point currentPoint = pointAtGridIndex(grid, i, j);
if (currentPoint.value == 0) {
continue;
}
for (Pair d : directionsForPair(pr)) {
if (isValidBoardIndex(i + d.p, j + d.q)){
Point possiblePairing = pointAtGridIndex(grid, i + d.p, j + d.q);
if (currentPoint.value == possiblePairing.value) {
possible.add(new movePair(true, currentPoint, possiblePairing));
possible.add(new movePair(true, possiblePairing, currentPoint));
}
}
}
}
}
return possible;
}
|
cae397ce-c1eb-4358-98d3-88d38dea7496
| 6
|
public static ArrayList<ArrayList<Integer>> combine2(int n, int k) {
if(n<k||k==0) return null;
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
// boundary case
if(n==k) {
ArrayList<Integer> al = new ArrayList<Integer>();
for(int i=1;i<=n;++i) {
al.add(i);
}
all.add(al);
return all;
}
// general case
// mind when k==1, k-1==0, you then can't handle this situation and will get StackOverFlow exception.
for(int i=n;i>=k;--i)
for(ArrayList<Integer> al: combine(i-1, k-1)) {
al.add(i);
all.add(al);
}
return all;
}
|
6250d0ed-0b22-4d5e-adf2-de4adeff4602
| 5
|
@Override
public void keyPressed(int k) {
if(k == KeyEvent.VK_ENTER){
select();
}
if(k == KeyEvent.VK_UP) {
currentChoice--;
if(currentChoice == -1) {
currentChoice = options.length - 1;
}
}
if(k == KeyEvent.VK_DOWN) {
currentChoice++;
if(currentChoice == options.length) {
currentChoice = 0;
}
}
}
|
9f2e86bc-268a-4af7-a63e-b99e45e67ae3
| 1
|
private void readLine() {
try {
line = bf.readLine();
lineCount++;
pos = 0;
lastPos = 0;
}
catch ( IOException e ) {
e.printStackTrace();
}
}
|
49a0a8c8-a52b-41d6-bdf3-20e5a410a522
| 2
|
private String validateDirective(String directive) {
directive = directive.substring(directive.indexOf(".") + 1, // Retrieve the directive from the line w/o the period
directive.indexOf(" ")); // Stop at the end of the directive (Do not fetch the operand)
for (String dir : directives) {
if (dir.equals(directive)) return directive; // If the directive matches a valid directive from the list, return the directive
}
return "ERROR"; // We do not have a valid directive, report the error
}
|
c95eb7c5-2c09-4293-9826-699152244021
| 4
|
private void drawHUD(Graphics g) {
boolean underground = yOffset <= -GameModel.GROUND_LEVEL;
// Version
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
g.setColor(Color.WHITE);
g.drawString(Configurables.GAME_VERSION, 5, getHeight() - 10);
// Money
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 24));
g.setColor(new Color(0, underground?255:0, 0, 128));
String money = String.format("$%,d", model.getBankAccount().getMoney());
int moneyX = getWidth() - g.getFontMetrics().stringWidth(money) - 5;
g.drawString(money, moneyX, 25);
// Fuel
final int fuelProgressBarWidth = 200;
g.setColor(new Color(underground?255:0, underground?255:0, underground?255:0, 172));
g.drawRect(moneyX - fuelProgressBarWidth - 5, 6, fuelProgressBarWidth, 20);
g.fillRect(moneyX - fuelProgressBarWidth - 5, 6,
model.getRobot().getFuelTank().getFuelPercent() * fuelProgressBarWidth / 100, 20);
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
g.setColor(Color.WHITE);
g.drawString("Fuel", moneyX - fuelProgressBarWidth/2 - 15, 19);
}
|
1959d676-be69-401d-8aea-e32bb094d897
| 3
|
public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException {
JSONObject jo = new JSONObject();
if (properties != null && !properties.isEmpty()) {
Enumeration enumProperties = properties.propertyNames();
while(enumProperties.hasMoreElements()) {
String name = (String)enumProperties.nextElement();
jo.put(name, properties.getProperty(name));
}
}
return jo;
}
|
2b9da33a-6bbb-4659-89bb-0f894ae2da93
| 2
|
private IBlock createBlock(int index) throws IOException {
if (storageMode != StorageMode.File) {
if (allowedMaxOffHeapBlockCount < 0) {
return new DefaultStorageBlock(dir, index, capacityPerBlock, StorageMode.File);
}
allowedMaxOffHeapBlockCount --;
}
return new DefaultStorageBlock(dir, index, capacityPerBlock, storageMode);
}
|
beef0303-6239-482e-89de-9dbf6f453da3
| 8
|
public static boolean updateOperatorCardinality(Operator o,
Map<String, Integer> tableAliasToId,
Map<String, TableStats> tableStats) {
if (o instanceof Filter) {
return updateFilterCardinality((Filter) o, tableAliasToId,
tableStats);
} else if (o instanceof Join) {
return updateJoinCardinality((Join) o, tableAliasToId, tableStats);
} else if (o instanceof HashEquiJoin) {
return updateHashEquiJoinCardinality((HashEquiJoin) o,
tableAliasToId, tableStats);
} else if (o instanceof Aggregate) {
return updateAggregateCardinality((Aggregate) o, tableAliasToId,
tableStats);
} else {
DbIterator[] children = o.getChildren();
int childC = 1;
boolean hasJoinPK = false;
if (children.length > 0 && children[0] != null) {
if (children[0] instanceof Operator) {
hasJoinPK = updateOperatorCardinality(
(Operator) children[0], tableAliasToId, tableStats);
childC = ((Operator) children[0]).getEstimatedCardinality();
} else if (children[0] instanceof SeqScan) {
childC = tableStats.get(
((SeqScan) children[0]).getTableName())
.estimateTableCardinality(1.0);
}
}
o.setEstimatedCardinality(childC);
return hasJoinPK;
}
}
|
f6562c43-e7f9-4675-8acd-2cef7b69cd13
| 8
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (gender != other.gender)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
|
67be6cd4-4ea3-484d-8cf1-c9dc297888bc
| 9
|
private int pruneLists(String desc, HashedMap<ByteChars, java.util.ArrayList<ResourceData>> cache,
int lowater, int hiwater)
{
long min_age = dsptch.getSystemTime() - config.minttl_lookup;
int delcnt = 0;
java.util.Iterator<ByteChars> it = cache.keysIterator();
while (it.hasNext()) {
if (pruneList(cache, null, it, min_age) == null) delcnt++;
}
if (hiwater != 0 && lowater != 0 && cache.size() >= hiwater) {
int excess = cache.size() - lowater;
it = cache.keysIterator();
while (it.hasNext()) {
if (excess == 0) break;
if (pruneList(cache, null, it, 0) != null) continue;
delcnt++;
excess--;
}
}
if (delcnt != 0) logger.trace(LOGLBL+"pruned cache="+desc+" - deleted entries="+delcnt);
return delcnt;
}
|
6bd37176-bd49-483c-907e-bfe9856cb48b
| 7
|
public void calculateVelocity() {
// If the current velocity is 0, simply add the acceleration to it
if (velocity.equals(new Vector())) {
velocity.add(acceleration);
}
// Otherwise,
else {
// If the couch is moving forward
if (movingForward()) {
// And it is accelerating backwards (braking)
if (Vector.opposites(acceleration, realDirection)) {
// And the acceleration is greater than the velocity, set
// velocity to 9
if (acceleration.length() > velocity.length()) {
velocity = new Vector();
}
// Otherwise, just keep braking
else {
velocity.add(acceleration);
}
}
// If it isn't accelerating backwards (speeding up), add it to
// the velocity
else {
velocity.add(acceleration);
}
}
// If the couch is moving backwards
else {
// And the acceleration is not opposite the way the couch is
// facing (the couch braking in reverse)
if (!Vector.opposites(acceleration, realDirection)) {
// And the acceleration is greater than the velocity, reset
// the velocity to 0
if (acceleration.length() > velocity.length()) {
velocity = new Vector();
}
// Otherwise, just add the acceleration to the velocity
// (brake in reverse)
else {
velocity.add(acceleration);
}
}
// If the couch is accelerating backwards, add the acceleration
// to the velocity if the velocity has not reached the maximum
// reverse speed
else if (velocity.length() < maxReverseSpeed) {
velocity.add(acceleration);
}
}
}
// Reset the acceleration
acceleration = new Vector();
}
|
5725af51-44e3-4185-91f5-4cc5b62d7a70
| 0
|
public void setTime(String newTime) {
time = newTime;
}
|
d03c579a-528d-472b-82c5-bf5bfd92c5a7
| 0
|
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
}
|
316daeba-67b4-4a1d-ac8b-d496e007ca41
| 9
|
private void chooseOrder() {
print("Choosing order.");
choiceFound = false;
boolean poor = false;
// check if poor
if (money <= menu.getCheapestItem())
poor = true;
while (!choiceFound) {
if (pastChoices.size() == menu.getSize()) {
print("No more choices available...");
event = AgentEvent.noAvailableFood;
return;
}
int c = Math.abs(rGenerator.nextInt() % 4);
choice = menu.getChoice(c);
double p = menu.getCost(choice);
if (p <= money) {
for (String pc : pastChoices) {
if (choice.equals(pc)) {
if (poor && p == menu.getCheapestItem()) {
event = AgentEvent.foodTooExpensive;
return;
}
choiceFound = false;
break;
}
}
choiceFound = true;
} else {
pastChoices.add(choice); // add item to list of unavailable
if (pastChoices.size() == menu.getSize()) { // if it was the
// last available
// item,
event = AgentEvent.foodTooExpensive; // decide to pay or to
// leave
return;
}
}
}
customerGui.setAlerting();
waiter.msgReadyToOrder(this);
}
|
838fc0a7-d7f3-415c-9617-eab900ba9f07
| 6
|
public void mouseMoved(int x, int y) {
if ((x >= theComponent.getX()) && ((x <= (theComponent.getX() + buttonWidth)))) {
if ((y >= theComponent.getY()) && (y <= (theComponent.getY() + buttonHeight))) {
if ((y > theComponent.getY()) && (y < (theComponent.getY() + buttonHeight))) {
isMouseOver = true;
} else {
isMouseOver = true;
}
} else {
isMouseOver = false;
}
} else {
isMouseOver = false;
}
}
|
a2b0373e-498a-44bb-a81d-b2e984f41220
| 8
|
public static void computeCoefficients(Artist[] artists,DatabaseConnector db,int k){
String stringArtists="";
int i=0;
for(Artist a:artists){
if(i>0){stringArtists+=",";}
stringArtists+="\""+a.name+"\"";
i++;
}
String[] topTags=new String[k];
String query="select tag,sum(count) as c from artisttags where artist in ("+stringArtists+") group by tag order by c desc limit "+k;
String stringCoeff="";
try {
ResultSet s=db.statement.executeQuery(query);
s.first();
i=0;
while(!s.isAfterLast()){
topTags[i]=s.getString(1);
if(i>0){stringCoeff+=",";}
stringCoeff+="sum(case when tag=\""+s.getString(1)+"\" then count else 0 end)/sum(count) ";
s.next();
i++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
query="SELECT "+stringCoeff;
query+="from artisttags where artist in ("+stringArtists+") group by artist order by artist";
try {
ResultSet s=db.statement.executeQuery(query);
s.first();
i=0;
while(!s.isAfterLast()){
//System.out.println(artists[i].name);
artists[i].coefficients=new double[k];
for(int j=1;j<=k;j++){
artists[i].coefficients[j-1]=s.getDouble(j);
}
s.next();
i++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
3aad962a-f9b5-4b84-943f-c6f1b1b7bdf2
| 0
|
public void addQuizGPS(String title,int quizId,ArrayList<String> imageList, ArrayList<Boolean> imageInventoryList,ArrayList<String> soundList,
ArrayList<Boolean> soundInventoryList, int narration,String paragraphList, String preNote, String postNote,
String goTo, int points, String date,double x,double y,
double width, double height, int timestop, String wrong)
{
Element quizModule = doc.createElement("quiz");
createQuiz(title,quizId,imageList,imageInventoryList,soundList,soundInventoryList,narration,paragraphList,preNote,postNote,quizModule);
Element answerModule = doc.createElement("answermodule");
quizModule.appendChild(answerModule);
Element answerElement = doc.createElement("answer");
createAnswerModule("GPS",goTo,points,date,wrong,timestop,answerElement);
answerModule.appendChild(answerElement);
Element coordinatesModule = doc.createElement("coordinates");
answerElement.appendChild(coordinatesModule);
Element xElement = doc.createElement("x");
xElement.appendChild(doc.createTextNode(Double.toString(x)));
coordinatesModule.appendChild(xElement);
Element yElement = doc.createElement("y");
yElement.appendChild(doc.createTextNode(Double.toString(y)));
coordinatesModule.appendChild(yElement);
Element widthElement = doc.createElement("width");
widthElement.appendChild(doc.createTextNode(Double.toString(width)));
coordinatesModule.appendChild(widthElement);
Element heightElement = doc.createElement("height");
heightElement.appendChild(doc.createTextNode(Double.toString(height)));
coordinatesModule.appendChild(heightElement);
}
|
d6417238-7875-4eca-9798-f84b404b6802
| 9
|
private Map<String, TermObject> search_by_phrase(String phrase)
{
TermObject _to = null;
List<String> terms = this.split_phrase_into_terms(phrase);
Map<String, TermObject> _result = new HashMap<String, TermObject>();
int _num_t = terms.size();
if(_num_t < 1) return null;
try
{
for(int i = 0; i < _num_t; ++i)
{
String t = terms.get(i);
_to = this.ixreader.findTermObject(t);
_result.put(t, _to);
}
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
// Try to find all terms in the successive positions in the docs
// First, merge search results of all terms in the phrase
Map<String, TermObject> s_intersect_result = this.intersect_search_result(terms, _result);
TermObject to = new TermObject(phrase);
TermObject f_to = s_intersect_result.get(terms.get(0));
if(f_to == null) return null;
Integer dummy[] = {}, docs_first_term[] = f_to.getPostings().keySet().toArray(dummy);
// Check each doc
for(int i = 0; i < docs_first_term.length; ++i)
{
// Check each position of the first term emerges
int doc_id = docs_first_term[i];
ArrayList<Integer> pos_list = s_intersect_result.get(terms.get(0)).getPostings().get(doc_id);
for(int j = 0; j < pos_list.size(); ++j)
{
int pos = pos_list.get(j);
// Try to check all other terms in the successive positions or not
boolean is_successive = true;
int next_pos = pos + 1;
for(int k = 1; k < _num_t; ++k)
{
ArrayList<Integer> other_pos_list = s_intersect_result.get(terms.get(k)).getPostings().get(doc_id);
if(!other_pos_list.contains(new Integer(next_pos)))
{
is_successive = false;
break;
}
next_pos++;
}
// If all terms appear together, add this doc into it and record its position
if(is_successive)
{
// Then check if they are successive in the document or not
to.addPostings(doc_id, pos);
to.addDocFreq(doc_id);
to.addCollectionFreq();
}
}
}
this.s_results.put(phrase, to);
// Add result doc id into query_doc_set
this.query_doc_set.addAll(to.getPostings().keySet());
Map<String, TermObject> rv = new HashMap<String, TermObject>();
rv.put(phrase, to);
return rv;
}
|
ceca7ea7-5e2b-4485-9548-d74acef5f413
| 3
|
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == okButton) {
SetConfig.this.okButtonActionPerformed(evt);
}
else if (evt.getSource() == cancelButton) {
SetConfig.this.cancelButtonActionPerformed(evt);
}
else if (evt.getSource() == browseButton) {
SetConfig.this.browseButtonActionPerformed(evt);
}
}
|
14fe174c-775f-45ba-912b-1f247e3bf9ed
| 4
|
public Animate(BufferedImage[] images,
int startingIndex, int loopCount, boolean reverseWhenDone, boolean removeWhenDone, long timePerImage) {
this.children = images;
if (images == null) {
logger.error(new NullPointerException(), "images given to Animation component were null");
}
if (startingIndex < 0 || startingIndex > children.length) {
logger.error(new IllegalArgumentException(), "invalid index ", startingIndex, " in animate component, valid range is 0-", images.length);
}
this.index = startingIndex;
// As when we either reach an index of 0 when reversing or the end we
// consider that to be one 'loop' iteration, we must multiply it by two
// if it expects to loop twice.
desiredLoopAmount = reverseWhenDone ? loopCount * 2 : loopCount;
this.reverseWhenDone = reverseWhenDone;
this.removeWhenDone = removeWhenDone;
this.timePerImage = timePerImage;
}
|
8da3c237-b787-466f-96aa-46f5afdbb4d6
| 3
|
public void draw(Graphics2D g2) {
try {
stageManager.draw(g2);
if (showFps) {
g2.drawString(Main.version, WIDTH - 60, 15);
g2.drawString("FPS: " + fps, WIDTH - 60, 30);
}
Graphics g = this.getGraphics();
if (g != null) {
g.drawImage(image, 0, 0, WIDTH * 2, HEIGHT * 2, null);
g.dispose();
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
f9c89ff3-35d1-40e1-953f-03e1287c38f2
| 5
|
public static int menu(String question, ArrayList<String> menu){
if(menu.size() <= 0) {
return -1;
}
else if(menu.size() == 1) {
return 0;
}
out.println(question);
for(int i = 0; i < menu.size(); i++){
out.println((i + 1) + ": " + menu.get(i));
}
int choice = in.nextInt();
while(choice < 1 || choice > menu.size()) {
out.println("please enter a valid number");
choice = in.nextInt();
}
return choice - 1;
}
|
a96c6ec0-8248-4bcb-a69b-271ed2647cfb
| 6
|
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("************ Calling Captcha Servlet *********");
ServletOutputStream outputStream=null;
BufferedImage captchaImg=null;
try {
GRSCaptchaUtil grsCaptchaUtil = GRSCaptchaUtil.getInstance();
String captchaStr = grsCaptchaUtil.getCaptchaString(new Integer(5));
captchaImg = grsCaptchaUtil.getCaptchaImage(captchaStr, 200,60);
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
outputStream = response.getOutputStream();
if (outputStream != null && captchaImg != null) {
ImageIO.write(captchaImg, "jpeg", outputStream);
System.out.println("************ Writing the Captcha Image *********");
}
HttpSession session=(HttpSession)request.getSession(false);
System.out.println(captchaStr);
session.setAttribute("CAPTCHA_STRING", captchaStr);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
if (outputStream != null && captchaImg != null) {
captchaImg.flush();
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
|
5fee8ede-b5de-469a-8627-79229f85e85c
| 9
|
public void applyConfig(JsonObject values) {
for (Map.Entry<String, JsonElement> entry : values.entrySet()) {
switch (entry.getKey()) {
case "prefix": prefix = entry.getValue().getAsString(); break;
case "name": name = entry.getValue().getAsString(); break;
case "title": title = entry.getValue().getAsString(); break;
case "pagebreak": pagebreak = entry.getValue().getAsBoolean(); break;
case "notitle": notitle = entry.getValue().getAsBoolean(); break;
case "noheader": noheader = entry.getValue().getAsBoolean(); break;
case "wiki": wiki = entry.getValue().getAsString(); break;
case "entrypicture": entrypicture = entry.getValue().getAsBoolean(); break;
}
}
}
|
7bbc2b1a-9509-4764-a00c-1163f95cc001
| 4
|
protected MyPGPid(byte[] buffer, short offset, byte length) {
// G+D uses non-zero offset, JCOP uses offset=0
if(length > 9) {
// data offset is used for application specific parameter.
// initialization with default offset (AID offset).
short dataOffset = offset;
// Install parameter detail. Compliant with OP 2.0.1.
// | size | content
// |------|---------------------------
// | 1 | [AID_Length]
// | 5-16 | [AID_Bytes]
// | 1 | [Privilege_Length]
// | 1-n | [Privilege_Bytes] (normally 1Byte)
// | 1 | [Application_Proprietary_Length]
// | 0-m | [Application_Proprietary_Bytes]
// shift to privilege offset
dataOffset += (short)( 1 + buffer[dataOffset]);
// finally shift to Application specific offset
dataOffset += (short)( 1 + buffer[dataOffset]);
// Here dataOffset points to policy (app. proprietary) len
/*
if((short)(offset+length)>dataOffset) { // Policy is present
// Application_Proprietary_Length must be 5
// Application_Proprietary_Bytes is:
// | size | content
// |------|-----------------------
// | 1 | Number of expired ENC keys to keep
// | 2 | Max size of transfer buffer (in bytes)
// | 1 | Use different PIN and key for RFID
// | 1 | OOB user consent needed
short polLen=buffer[dataOffset];
if(((short)(dataOffset+polLen-offset) > length) || (polLen != 5)) { // Check if policy is complete
ISOException.throwIt( ISO7816.SW_DATA_INVALID );
}
++dataOffset;
// Limit of 255 old ENC keys
m_maxKeys+=buffer[dataOffset];
++dataOffset;
m_bSize=(short)Util.makeShort(buffer[dataOffset], buffer[(short)(dataOffset+1)]);
++dataOffset; ++dataOffset;
if(0!=(byte)buffer[dataOffset]) {
m_separateAuth=true;
++m_maxKeys; // Requires an extra key...
++m_nPins; // ... and an extra PIN
}
++dataOffset;
if(0!=buffer[dataOffset]) {
// Needs card-specific code!
ISOException.throwIt( ISO7816.SW_INS_NOT_SUPPORTED ) ;
// m_oobAuth=buffer[dataOffset];
}
++dataOffset;
// *** These can fail: if so, then abort install
// To RAM: prevent EEPROM wearout and clear buffer when card is removed
m_transferBuffer = JCSystem.makeTransientByteArray(m_bSize, JCSystem.CLEAR_ON_DESELECT);
// Pre-allocate space for all keys
//@@@ Should allocate space for key IDs too!
m_keyPair = new KeyPair[m_maxKeys];
for(short c=0; c<m_maxKeys; ++c)
m_keyPair[c]=new KeyPair(DEF_ALG, DEF_LEN);
m_CAKey= (PublicKey)KeyBuilder.buildKey( DEF_CAKEYTYPE, DEF_LEN, false);
}
*/
// ORIGINAL INIT CODE FROM JOpenPGPCard
loginData = new DataObject((byte)0x00, (byte)0x5e, (short)254);
url = new DataObject((byte)0x5f, (byte)0x50, (short)254);
name = new DataObject((byte)0x5b, (short)39);
langPref = new DataObject((byte)0x5f, (byte)2d, (short)8);
sex = new DataObject((byte)0x5f, (byte)35, (short)1);
aid = new DataObject((byte)0x4f, (short)16);
fingerprints = new DataObject((byte)00, (byte)0xc5, (short)60, true);
fingerprintsCA = new DataObject((byte)00, (byte)0xc6, (short)60, true);
dateGeneration = new DataObject((byte)00, (byte)0xcd, (short)12, true);
signCount = new DataObject((byte)0, (byte)0x93, (short)3, true);
keySign = new KeyPair(DEF_ALG, DEF_KEY_LEN);
keyDecrypt = new KeyPair(DEF_ALG, DEF_KEY_LEN);
keyAuth = new KeyPair(DEF_ALG, DEF_KEY_LEN);
chv1 = new OwnerPIN(CHV_RETRY, CHV1_LENGTH);
chv2 = new OwnerPIN(CHV_RETRY, CHV2_LENGTH);
chv3 = new OwnerPIN(CHV_RETRY, CHV3_LENGTH);
chv1.update(DEFAULT_CHV1, (byte)0, (byte)6);
chv2.update(DEFAULT_CHV2, (byte)0, (byte)6);
chv3.update(DEFAULT_CHV3, (byte)0, (byte)8);
sig = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
tmpData = JCSystem.makeTransientByteArray((short)512, JCSystem.CLEAR_ON_DESELECT);
// Set proper Algorithm Attributes according to defined preferences
Util.setShort(algAttrSign, (short)3, DEF_KEY_LEN);
Util.setShort(algAttrDec, (short)3, DEF_KEY_LEN);
Util.setShort(algAttrAuth, (short)3, DEF_KEY_LEN);
algAttrSign[5] = (DEF_ALG == KeyPair.ALG_RSA) ? (byte) 0x01 : (byte) 0x03;
algAttrDec[5] = (DEF_ALG == KeyPair.ALG_RSA) ? (byte) 0x01 : (byte) 0x03;
algAttrAuth[5] = (DEF_ALG == KeyPair.ALG_RSA) ? (byte) 0x01 : (byte) 0x03;
// END ORIGINAL CODE FROM JOpenPGPCard
// Register OP2 applet
register(buffer, (short)(offset + 1), (byte)buffer[offset]);
} else {
// Register non-OP2 applet
register();
}
}
|
85e40947-74be-4d17-8e81-dd8b3129b13e
| 6
|
public static JMenu makeMenu(String items, String label, int shortcuts[])
{
JMenu ret = new JMenu();
if (label != null) ret.setText(label);
String[] a = items.split("\\|");
int i = 0;
for (String b : a)
{
if (b.equals("-"))
ret.addSeparator();
else
{
JMenuItem tmenui = new JMenuItem();
if (shortcuts != null && shortcuts[i] != 0)
{
int mods = 0;
mods |= InputEvent.SHIFT_MASK;
mods |= InputEvent.CTRL_MASK;
mods |= InputEvent.ALT_MASK;
KeyStroke ks = KeyStroke.getKeyStroke(shortcuts[i],mods);
tmenui.setAccelerator(ks);
}
int io = b.replace("\\\\","..").replace("\\&","..").indexOf("&");
if (io != -1)
{
tmenui.setMnemonic(b.charAt(io + 1));
b = b.substring(0,io) + b.substring(io + 1);
}
tmenui.setText(b);
ret.add(tmenui);
}
i++;
}
return ret;
}
|
228c30b4-2089-4c23-b192-9dfcd2dca2e1
| 7
|
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
}
|
b7d19760-a61d-4f77-95f8-fd89d408a6f4
| 8
|
public void setRoom(int x, int y, Room newRoom) {
// if we're adding a real room to an empty place, howManyRooms++
if ((newRoom != null) && (myWorld[x][y] == null)) {
howManyRooms++;
} // if we're blanking (nulling) a real room, howManyRooms--
else if ((newRoom == null) && (myWorld[x][y] != null)) {
howManyRooms--;
}
//if(newRoom==null){ ?? }
if((x < 0) ||(x >= worldWidth)) {
throw new IllegalArgumentException("Room xLocation " +x + " out of bounds. It must be between 0 and "+(worldWidth - 1) + ".");
}
if((y < 0) ||(y >= worldWidth)) {
throw new IllegalArgumentException("Room yLocation " +y + " out of bounds. It must be between 0 and "+(worldHeight - 1) + ".");
}
myWorld[x][y] = newRoom;
}
|
544df27b-a236-4792-86a0-199a64ed75a5
| 4
|
public static List<Question> getQuizQuestions(int QuizDbId)
{
try
{
String query = String.format("select qq.QUIZID, q.QUESTIONID, q.QUESTIONTEXT, q.ISVALIDATED, qa.ANSWERID, qa.ANSWERTEXT, qa.ISCORRECT from Question q right join \n" +
"QuestionAnswer qa on Q.QUESTIONID = \n" +
"qa.QUESTIONID\n" +
"join QuizQuestion qq on qq.QUESTIONID = q.QUESTIONID\n" +
"where qq.QUIZID = %d", QuizDbId);
ResultSet rs = getQueryResults(query);
List<Question> questions = new ArrayList<Question>();
Question q = new Question("");
int lastqid = 0, currqid =0;
List<Answer> answers = new ArrayList<Answer>();
while(rs.next())
{
currqid = rs.getInt("QUESTIONID");
if (lastqid == 0)
{
q = new Question(rs.getString("QuestionText"));
q.dbId = rs.getInt("QuestionID");
Answer a = new Answer(rs.getString("AnswerText"), rs.getBoolean("IsCorrect"));
a.dbId = rs.getInt("AnswerID");
q.answers.add(a);
}
else if (lastqid == currqid)
{
Answer a = new Answer(rs.getString("AnswerText"), rs.getBoolean("IsCorrect"));
a.dbId = rs.getInt("AnswerID");
q.answers.add(a);
}
else
{
questions.add(q);
q = new Question(rs.getString("QuestionText"));
q.dbId = rs.getInt("QuestionID");
Answer a = new Answer(rs.getString("AnswerText"), rs.getBoolean("IsCorrect"));
a.dbId = rs.getInt("AnswerID");
q.answers.add(a);
}
lastqid = currqid;
}
questions.add(q);
return questions;
}
catch(SQLException se)
{
return null;
}
}
|
82c0fc41-2ec6-464c-a47a-66f62116d7a4
| 3
|
@Test
public void testInvalidConstruction() {
Tile t;
try {
t = new Tile(null, new Room());
fail("IllegalArgumentException was expected");
}
catch (IllegalArgumentException e){
//expected
}
try {
t = new Tile(new Point(1, 2), null);
fail("IllegalArgumentException was expected");
}
catch (IllegalArgumentException e){
//expected
}
try {
t = new Tile(null, null);
fail("IllegalArgumentException was expected");
}
catch (IllegalArgumentException e){
//expected
}
}
|
fa87d901-6d2d-4400-b95b-8ff6a63433d9
| 9
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UrlEntity url1 = (UrlEntity) o;
if (count != null ? !count.equals(url1.count) : url1.count != null) return false;
if (lastTime != null ? !lastTime.equals(url1.lastTime) : url1.lastTime != null) return false;
if (url != null ? !url.equals(url1.url) : url1.url != null) return false;
return true;
}
|
c6fe2a68-a2e4-46ab-9a6d-24a77025697c
| 8
|
@Override
public boolean equals(Object other) {
if (other == null || !other.getClass().equals(this.getClass())) {
return false;
}
Revision revision = (Revision) other;
boolean boolCommitID = commitID.equals(revision.commitID);
boolean boolParentIDToDiffFiles = parentIDToDiffFiles.equals(revision.parentIDToDiffFiles);
boolean boolCompilable = compilable == revision.compilable;
boolean boolTestResult = (testResult == null && revision.testResult == null)
|| (testResult != null && testResult.equals(revision.testResult));
return boolCommitID && boolParentIDToDiffFiles && boolCompilable && boolTestResult;
}
|
ec0a957a-9877-4d31-996a-903dd5f00191
| 7
|
private void readPrefixes() throws Exception {
String path = PATH + "router-" + router_number + ".txt";
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
/* Reads the file line-by-line */
while ((line = br.readLine()) != null) {
/* Skips lines that don't start "prefix " */
if (!line.startsWith("prefix ")) continue;
String[] splitStr = line.split(" ");
/* Skips improperly formated lines */
if (splitStr.length != 3) continue;
String key = splitStr[1];
String[] keySplit = key.split("/");
/* Skips improperly formated prefixes */
if (keySplit.length != 2) continue;
int prefixLength = Integer.parseInt(keySplit[1]);
prefixLength /= 8; // in bytes
String[] ipSplit = keySplit[0].split("\\.");
/* Skips improperly formatted IPv4 addresses in the prefix */
if (ipSplit.length != 4) continue;
key = "";
/* Rebuilds prefix with only the relevant bytes.
* Example: "10.2.0.0/16" -> "10.2" */
for (int i = 0; i < prefixLength; i++) {
key += "." + ipSplit[i];
}
InetAddress value = null;
/* Skips invalid IPv4 addresses */
try {
value = InetAddress.getByName(splitStr[2]);
} catch (UnknownHostException e) {
continue;
}
prefixes.put(key.substring(1), value);
}
br.close();
}
|
ec3efb4a-d6f0-4802-81a5-86039891d050
| 3
|
private void jTextField4KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField4KeyPressed
if (evt.getKeyCode() == 38) {
jTextField3.grabFocus();
} else if (evt.getKeyCode() == 40) {
jList1.grabFocus();
} else if (evt.getKeyCode() == 39) {
cmbPublisher.grabFocus();
}
}//GEN-LAST:event_jTextField4KeyPressed
|
6dc938ea-ce0f-4ddb-b2db-c74d12dbda6b
| 2
|
@Override
public String toString(){
if(map.isEmpty())
return "empty mapping";
String result = "";
for(Map.Entry<Byte, Byte> entry: map.entrySet()){
result += ", "+(char)entry.getKey().byteValue()+"->"+ (char)entry.getValue().byteValue();
}
return result.substring(2);
}
|
4a33fe62-8202-4c46-9a3f-d9c16900d723
| 8
|
public void testFoundColony() {
Game game = getGame();
Map map = getCoastTestMap(plainsTileType);
game.setMap(map);
Colony colony = getStandardColony(3, 1, 8);
Player dutch = colony.getOwner();
Tile colonyTile = colony.getTile();
assertEquals(colonyTile.getType(), plainsTileType);
Unit colonist = colony.getUnitList().get(0);
Tile workedTile = null;
for (ColonyTile ct : colony.getColonyTiles()) {
if (ct.isColonyCenterTile()) continue;
workedTile = ct.getWorkTile();
if (workedTile.isInUse()) {
break;
} else if (workedTile.getType() == plainsTileType) {
colonist.setWorkType(spec().getPrimaryFoodType());
ct.add(colonist);
break;
}
}
assertTrue(workedTile.isInUse());
FreeColTestCase.IndianSettlementBuilder builder
= new FreeColTestCase.IndianSettlementBuilder(game);
IndianSettlement camp = builder.build();
Player indianPlayer = camp.getOwner();
Tile campTile = camp.getTile();
assertEquals(campTile.getType(), plainsTileType);
Tile nativeTile = null;
for (Tile t : camp.getTile().getSurroundingTiles(1)) {
if (t.getType() == plainsTileType) {
nativeTile = t;
break;
}
}
assertEquals(nativeTile.getOwner(), indianPlayer);
Player french = game.getPlayer("model.nation.french");
Colony frenchColony = getStandardColony(3, 9, 8);
frenchColony.changeOwner(french);
assertEquals(frenchColony.getTile().getType(), plainsTileType);
Tile frenchTile = null;
for (Tile t : frenchColony.getTile().getSurroundingTiles(1)) {
if (t.getType() == plainsTileType) {
frenchTile = t;
break;
}
}
assertEquals(frenchTile.getOwner(), french);
Tile landTile = map.getTile(1, 1);
Tile lcrTile = map.getTile(2, 2);
lcrTile.add(new LostCityRumour(game, lcrTile,
LostCityRumour.RumourType.NO_SUCH_RUMOUR, "fake"));
Tile waterTile = map.getTile(12, 12);
assertTrue(!waterTile.isLand());
assertTrue("Can own empty tile",
dutch.canOwnTile(landTile));
assertFalse("Europeans can not own tile with an LCR on it",
dutch.canOwnTile(lcrTile));
assertTrue("Natives can own tile with an LCR on it",
indianPlayer.canOwnTile(campTile));
assertTrue("Europeans can own water tile",
dutch.canOwnTile(waterTile));
assertFalse("Natives can not own water tile",
indianPlayer.canOwnTile(waterTile));
assertEquals("Can found on land",
NoClaimReason.NONE,
dutch.canClaimToFoundSettlementReason(landTile));
assertEquals("Can found on unsettleable tile",
NoClaimReason.TERRAIN,
dutch.canClaimToFoundSettlementReason(waterTile));
assertEquals("Can not found on LCR",
NoClaimReason.RUMOUR,
dutch.canClaimToFoundSettlementReason(lcrTile));
assertEquals("Can not found on water",
NoClaimReason.TERRAIN,
indianPlayer.canClaimToFoundSettlementReason(waterTile));
assertEquals("Can not found on settlement",
NoClaimReason.SETTLEMENT,
dutch.canClaimToFoundSettlementReason(campTile));
assertEquals("Can not found on tile in use",
NoClaimReason.WORKED,
dutch.canClaimToFoundSettlementReason(workedTile));
assertEquals("Can not found on European tile",
NoClaimReason.EUROPEANS,
dutch.canClaimToFoundSettlementReason(frenchTile));
assertEquals("Can not found on native tile",
NoClaimReason.NATIVES,
dutch.canClaimToFoundSettlementReason(nativeTile));
assertEquals("Can use land",
NoClaimReason.NONE,
dutch.canClaimForSettlementReason(landTile));
assertEquals("Can use unsettleable tile",
NoClaimReason.NONE,
dutch.canClaimForSettlementReason(waterTile));
assertEquals("Europeans can not use LCR",
NoClaimReason.RUMOUR,
dutch.canClaimForSettlementReason(lcrTile));
assertEquals("Natives can use LCR",
NoClaimReason.NONE,
indianPlayer.canClaimForSettlementReason(lcrTile));
assertEquals("Europeans can use water",
NoClaimReason.NONE,
dutch.canClaimForSettlementReason(waterTile));
assertEquals("Natives can not use water",
NoClaimReason.WATER,
indianPlayer.canClaimForSettlementReason(waterTile));
assertEquals("Can not use on settlement",
NoClaimReason.SETTLEMENT,
dutch.canClaimForSettlementReason(campTile));
assertEquals("Can not use tile in use",
NoClaimReason.WORKED,
dutch.canClaimForSettlementReason(workedTile));
assertEquals("Can not use European tile",
NoClaimReason.EUROPEANS,
dutch.canClaimForSettlementReason(frenchTile));
assertEquals("Can not use native tile",
NoClaimReason.NATIVES,
dutch.canClaimForSettlementReason(nativeTile));
}
|
ee0dc682-9ff9-4c29-99f6-e40f166c41b4
| 4
|
public int getPlayer1Score() {
boolean test = false;
if (test || m_test) {
System.out.println("Game :: getPlayer1Score() BEGIN");
}
if (test || m_test) {
System.out.println("Game :: getPlayer1Score() END");
}
return m_player1Score;
}
|
66858015-06f8-4c5a-b3da-450b3929ae85
| 4
|
public static <T extends DC> Set<Pair<T,T>> getPhiMax(Set<Set<Pair<T,T>>> allPhis)
{ Similarity simMax,sim;
if(allPhis!=null)
{ Set<Pair<T,T>> phiMax=allPhis.a;
simMax=getPhiSim(allPhis.a);
for(Set<Set<Pair<T,T>>> p=allPhis;p!=null;p=p.next)
{ sim=getPhiSim(p.a);
if(sim.greater(simMax))//here if sim=simMax the result will not be replaced
{ simMax=sim;
phiMax=p.a;
}
else
{ continue;
}
}
if(phiMax!=null)
{return phiMax;}
else
{ throw new RuntimeException("Silly codes: allSets: "+allPhis+"\n simMax: "+simMax+"\n phiMax: "+phiMax);
}
}
else
{ throw new RuntimeException("One-to-one mappings between two sets "+allPhis+" is null?");
}
}
|
1ece350e-b63b-48e1-853d-ff4995cbddd8
| 4
|
@Override
public ArrayList<BoardPosition> getPossibleDestinations(Board board) {
ArrayList<BoardPosition> possibleDestinations = new ArrayList<BoardPosition>();
if (board.pieces[targetPosition.getColumn()][targetPosition.getRow()] != null) {
if (board.pieces[targetPosition.getColumn()][targetPosition.getRow()].getColor() != pieceColor) {
possibleDestinations.add(targetPosition);
}
} else if (board.enPassantPosition != null && targetPosition.equals(board.enPassantPosition)) {
possibleDestinations.add(targetPosition);
}
return possibleDestinations;
}
|
69f30f7b-084b-403e-9963-6e060ea44a26
| 5
|
private void createNewPath() {
JTextField edgeName = new JTextField(20);
JTextField edgeWeight = new JTextField(20);
JPanel newEdgePanel;
newEdgePanel = new JPanel(new GridLayout(3,1,5,2));
newEdgePanel.add(new JLabel("Vad ska förbindelsen heta?"));
newEdgePanel.add(edgeName);
newEdgePanel.add(new JLabel("Hur lång tid tar det?"));
newEdgePanel.add(edgeWeight);
Neuron n1 = getFirstSelectedNeuron();
Neuron n2 = getLastSelectedNeuron();
String title = String.format("Skapa förbindelse mellan %s och %s", n1.getName(), n2.getName());
//"complex" just to be able to set focus
boolean doLoop = true;
while(doLoop){
int result = JOptionPane.showOptionDialog(win, newEdgePanel,
title,JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"OK", "Cancel"}, edgeName);
if (result == JOptionPane.OK_OPTION) {
try {
if(edgeName.getText().length()<1){
JOptionPane.showMessageDialog(win, "Ett Namn,bitte,tack,thankyou!");
}else{
neuronListGraph.connect(n1, n2, edgeName.getText(), Integer.parseInt(edgeWeight.getText()));
doLoop = false;
}
} catch (NullPointerException nullE) {
JOptionPane.showMessageDialog(win, "Du fyllde inte i alla fällt");
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(win,"Tid får bara vara heltal!");
}
}else{
doLoop= false;
}
}
addLine("invokeOnLineClick", new Color(60, 118, 61), neuronListGraph, neuronListGraph.getNeuronPair(n1, n2));
validate();
repaint();
}
|
62e8b229-444e-41a1-b9eb-714a4cbfa8d2
| 7
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) {
if (obj.getClass() == String.class) {
return name.equals((String) obj);
}
return false;
}
Variable other = (Variable) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
|
d98ec606-c7f2-443d-aaf5-626f52240c62
| 4
|
public Tile tile(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height) {
return Tile.OOB;
} else {
return tiles[x][y];
}
}
|
fc3e46b7-32bb-4814-923a-0b45ae4ac484
| 2
|
public MeanFilterDialog(final Panel panel) {
setTitle("Mean filter");
setBounds(1, 1, 250, 140);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width / 3 - getWidth() / 3, size.height / 3
- getHeight() / 3);
this.setResizable(false);
setLayout(null);
JPanel pan = new JPanel();
pan.setBorder(BorderFactory.createTitledBorder("Mask size"));
pan.setBounds(0, 0, 250, 70);
JLabel sizeLabel = new JLabel("Size = ");
final JTextField sizeField = new JTextField("3");
sizeField.setColumns(3);
JButton okButton = new JButton("OK");
okButton.setSize(250, 40);
okButton.setBounds(0, 70, 250, 40);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int size;
try {
size = Integer.valueOf(sizeField.getText());
} catch (NumberFormatException ex) {
new MessageFrame("Invalid values");
return;
}
if (size % 2 == 0) {
new MessageFrame("Invalid values");
return;
}
panel.setImage(MaskUtils.applyMeanMask(panel.getImage(), size, size));
panel.repaint();
dispose();
}
});
pan.add(sizeLabel);
pan.add(sizeField);
add(pan);
add(okButton);
}
|
17b7cb10-86be-46ab-b5d6-17a4e8979e73
| 4
|
public void update(GameContainer gc, StateBasedGame sbg, GameplayState gs, int delta) {
for (Entry<Long, Enemy> enemy : this.enemies.entrySet()) {
enemy.getValue().update(gc, sbg, gs, delta);
if (enemy.getValue().isDead()) {
this.toBeRemoved.add(enemy.getKey());
}
else
level.addEnemyToTile(enemy.getValue());
}
if (!this.toBeRemoved.isEmpty()) {
for (Long enemyId : this.toBeRemoved) {
this.removeEnemy(enemyId);
}
this.toBeRemoved.clear();
}
}
|
3a0d3e08-5652-4e69-a576-a875a8e71418
| 1
|
@Override
public boolean canMove(Board board, Field currentField, Field emptyField) {
return this.validSetupForMove(currentField, emptyField) && board.clearPathBetween(currentField, emptyField);
}
|
0df93396-aaec-4267-90b8-a8e5b51d2e0a
| 8
|
private static AbstractResultSet doVoting(
AbstractResultSet[] secondaryResSets, Match matchCriterion,
boolean typeChecking, int voteThreshhold) throws FileNotFoundException {
AbstractResultSet res = new EnsembleResultSet();
res.docNumber = secondaryResSets[0].docNumber;
String resType = "";
for(AbstractResultSet r : secondaryResSets)
resType += r.shortType;
res.resultType = resType;
int votes;
for(int i = 0; i < secondaryResSets.length; i++)
for(Concept con : secondaryResSets[i].concepts)
{
votes = 1;
for(int j = 0; j < secondaryResSets.length; j++)
{
if (i == j)
continue;
if(secondaryResSets[j].containsMatchingCriterion(con, matchCriterion,typeChecking))
{
System.out.println("vote");
votes++;
}
}
System.out.println(con);
System.out.println(votes);
if(votes >= voteThreshhold)
res.concepts.add(con);
}
// 'containsMatchingCriterion' modifies the ResSets. so reset them before returning.
for(AbstractResultSet asr : secondaryResSets)
asr.reset();
return res;
}
|
58d516f4-91c1-4021-872d-df07dadcc49e
| 5
|
private void create(Color bg, Animation init, String fieldTitle) {
setPreferredSize(new Dimension(GUIConstants.DEFAULT_FIELD_WIDTH, FIELDHEIGHT));
setBackground(bg);
setLayout(new VerticalLayout(5, VerticalLayout.CENTER));
setBorder(BorderFactory.createTitledBorder(fieldTitle));
JRadioButton noAnimation = new JRadioButton(Field.strAnimationOriginal);
JRadioButton animHSlow = new JRadioButton(Field.strAnimationHorizontal + " & " + Field.strAnimationSlow);
JRadioButton animVSlow = new JRadioButton(Field.strAnimationVertical + " & " + Field.strAnimationSlow);
JRadioButton animHFast = new JRadioButton(Field.strAnimationHorizontal + " & " + Field.strAnimationFast);
JRadioButton animVFast = new JRadioButton(Field.strAnimationVertical + " & " + Field.strAnimationFast);
noAnimation.setBackground(bg);
animHSlow.setBackground(bg);
animVSlow.setBackground(bg);
animHFast.setBackground(bg);
animVFast.setBackground(bg);
noAnimation.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
originalAnimChosen();
}
});
animHSlow.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
horizontalSlowAnimChosen();
}
});
animVSlow.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
verticalSlowAnimChosen();
}
});
animHFast.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
horizontalFastAnimChosen();
}
});
animVFast.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
verticalFastAnimChosen();
}
});
ButtonGroup btnGroup = new ButtonGroup();
btnGroup.add(noAnimation);
btnGroup.add(animHSlow);
btnGroup.add(animVSlow);
btnGroup.add(animHFast);
btnGroup.add(animVFast);
add(noAnimation);
add(animHSlow);
add(animVSlow);
add(animHFast);
add(animVFast);
switch (init) {
case ORIGINAL:
noAnimation.setSelected(true);
break;
case RECTANGLE_H_FAST:
animHFast.setSelected(true);
break;
case RECTANGLE_H_SLOW:
animHSlow.setSelected(true);
break;
case RECTANGLE_V_FAST:
animVFast.setSelected(true);
break;
case RECTANGLE_V_SLOW:
animVSlow.setSelected(true);
break;
default:
noAnimation.setSelected(true);
break;
}
}
|
2548d6db-7a6a-44f3-a80e-938751e0947c
| 7
|
private Token scanTag() {
// See the specification for details.
Mark startMark = reader.getMark();
char ch = reader.peek(1);
String handle = null;
String suffix = null;
if (ch == '<') {
reader.forward(2);
suffix = scanTagUri("tag", startMark);
if (reader.peek() != '>') {
throw new ScannerException("while scanning a tag", startMark,
"expected '>', but found '" + reader.peek() + "' (" + ((int) reader.peek())
+ ")", reader.getMark());
}
reader.forward();
} else if (Constant.NULL_BL_T_LINEBR.has(ch)) {
suffix = "!";
reader.forward();
} else {
int length = 1;
boolean useHandle = false;
while (Constant.NULL_BL_LINEBR.hasNo(ch)) {
if (ch == '!') {
useHandle = true;
break;
}
length++;
ch = reader.peek(length);
}
handle = "!";
if (useHandle) {
handle = scanTagHandle("tag", startMark);
} else {
handle = "!";
reader.forward();
}
suffix = scanTagUri("tag", startMark);
}
ch = reader.peek();
if (Constant.NULL_BL_LINEBR.hasNo(ch)) {
throw new ScannerException("while scanning a tag", startMark,
"expected ' ', but found '" + ch + "' (" + ((int) ch) + ")", reader.getMark());
}
TagTuple value = new TagTuple(handle, suffix);
Mark endMark = reader.getMark();
return new TagToken(value, startMark, endMark);
}
|
95a81f33-3719-43ab-9cb4-9540b2547000
| 3
|
public List<String> readActiveDates() {
List<String> retList = new ArrayList<String>();
try {
ResultSet rs = _sqLite.query("SELECT DISTINCT date(time_login) AS dt FROM login;");
while (rs.next()) {
try {
String tmpStr = rs.getString("dt");
retList.add(tmpStr);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return retList;
}
|
b663b5bc-cd4b-4733-8872-42e6b1f51071
| 4
|
@Override
protected void onTextMessage(CharBuffer text) throws IOException {
Message message = new Message(text.toString());
RoboBase robo_base = RoboBase.getInstance();
String status;
switch (message.getCommand()) {
case LOGIN:
status = robo_base.isOnline(message.getRobotName()) ? "ok" : "error: offline";
break;
case TURN_RIGHT:
Robot robot = robo_base.getRobot(message.getRobotName());
if (robot != null) {
robot.turnRight();
status = "ok";
} else {
status = "error: offline";
}
break;
default:
status = "error: unsupported command";
break;
}
getWsOutbound().writeTextMessage(
CharBuffer.wrap("<message><status>" + status + "</status></message>"));
}
|
51814717-dcb9-4275-b1a9-73ef59b10f34
| 7
|
public void start(){
setSize(300, 300);
setTitle("Serial Port Manager");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
SerialDevices[] devices = SerialDevices.values();
HashMap<String, String> content = PortList.readFromFile(PortList.FILE_LOCATION);
for(SerialDevices device: devices){
if(device != SerialDevices.MANUAL_PORT_DEVICE){
JLabel label = new JLabel(device.name(), JLabel.RIGHT);
label.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 15));
typeLabels.add(label);
nameFields.add(new JTextField(content.get(device.name()),10));
}
}
for(JLabel label: typeLabels){
types.add(label);
}
for(JTextField text: nameFields){
names.add(text);
}
types.setLayout(new GridLayout(typeLabels.size(), 1));
names.setLayout(new GridLayout(nameFields.size(), 1));
setLayout(new GridLayout(2, 1));
JPanel editPanel = new JPanel();
editPanel.add(types);
editPanel.add(names);
JPanel buttonPanel = new JPanel(new GridLayout(3,1));
buttonPanel.add(saveQuit);
buttonPanel.add(showPorts);
buttonPanel.add(help);
add(editPanel);
add(buttonPanel);
setVisible(true);
saveQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
HashMap<String, String> toSave = new HashMap<String, String>();
for(JLabel label: typeLabels){
toSave.put(label.getText(), nameFields.get(typeLabels.indexOf(label)).getText());
}
PortList.writeToFile(toSave);
dispose();
}
});
showPorts.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
@SuppressWarnings("rawtypes")
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("Availables serial ports:");
if ( ! ports.hasMoreElements()) {
System.out.println("\tNo serial ports found");
}
while (ports.hasMoreElements()) {
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
final String name = port.getName();
System.out.printf("\t%s\n", name);
}
}
});
help.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showConfirmDialog(gui, "The ports entered in this tool are used by many sensor \n" +
"implementations to connect to the sensor on the right port. \n" +
"Please enter the full port path ('/dev/ttyUSB0')", "Serial Manager Help", JOptionPane.PLAIN_MESSAGE);
}
});
}
|
228af498-fd22-4f55-b47e-c69d05492f1a
| 9
|
public void start() {
// TODO Auto-generated method stub
Socket socket = null;
try {
socket = new Socket("127.0.0.1",6116);
} catch (UnknownHostException e) {
logger.log(Level.WARNING,"Can't connect", e);
} catch (IOException e) {
logger.log(Level.WARNING,"Can't io", e);
return;
}
if(socket == null)
return;
final PlayerSocket pSocket = new PlayerSocket(socket);
JSONObject msg = new JSONObject();
msg.put("a", "join");
msg.put("uid", this.id);
pSocket.sendMsg(String.valueOf(msg));
if((Integer.parseInt(id) % 3) == 0) {
pSocket.shutdown();
return;
}
//Start reading
ScheduledExecutorService readThread = Executors.newSingleThreadScheduledExecutor();
// then, when you want to schedule a task
Runnable task = new Runnable() {
@Override
public void run() {
while(true) {
JSONObject obj = pSocket.readMsg();
if(obj.containsKey("a")) {
if("ACK".equals(obj.get("a"))) {
logger.info("ACK");
}
if("match".equals(obj.get("a"))) {
logger.info("match: " + id + "|" + String.valueOf(obj));
pSocket.shutdown();
break;
}
}
logger.info(String.valueOf(obj));
if(obj == null)
break;
}
}
};
readThread.submit(task);
}
|
ac87dd14-7811-4811-a9ca-34ef67b1514f
| 9
|
public static void main(String[] args) {
String keyPass = "fanjun" ;
InputStream inputStream = CertificateSignatureMain.class.getResourceAsStream("rsa.jks");
InputStream inStream = CertificateSignatureMain.class.getResourceAsStream("rsa.cer");
try {
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, new SecureRandom());
SecretKey secretKey = kg.generateKey();
//公钥对密钥加密
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(inStream);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.WRAP_MODE, cert);
// rsaCipher.init(Cipher.WRAP_MODE, cert.getPublicKey());
byte[] keyWrapBytes = rsaCipher.wrap(secretKey);
//私钥对密钥解密
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(inputStream, keyPass.toCharArray());
PrivateKey privateKey = (PrivateKey)keyStore.getKey("rsa", keyPass.toCharArray());
Cipher rsaCipher1 = Cipher.getInstance("RSA");
rsaCipher1.init(Cipher.UNWRAP_MODE, privateKey);
Key unWrapKey = rsaCipher1.unwrap(keyWrapBytes, "AES", Cipher.SECRET_KEY);
//密钥匹配判断
System.out.println(unWrapKey.equals(secretKey));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}finally{
try {
inputStream.close();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
2b20fb5b-a5ea-4841-9cd1-17cc713b401b
| 3
|
public static int getRotatedMapChunkX(int rotation, int y, int x) {
rotation &= 3;
if (rotation == 0) {
return x;
}
if (rotation == 1) {
return y;
}
if (rotation == 2) {
return 7 - x;
} else {
return 7 - y;
}
}
|
27104bad-23e4-483a-bb73-7affef195f5d
| 4
|
public void update() throws IOException {
// update player
player.update();
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety()
);
// set background
bg.setPosition(tileMap.getx(), tileMap.gety());
// attack enemies
player.checkAttack(enemies);
// update all enemies
for(int i = 0; i < enemies.size(); i++) {
Enemy e = enemies.get(i);
e.update();
if(e.isDead()) {
enemies.remove(i);
i--;
explosions.add(
new Explosion(e.getx(), e.gety()));
}
}
// update explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).update();
if(explosions.get(i).shouldRemove()) {
explosions.remove(i);
i--;
}
}
}
|
8385c885-40fb-48f1-ad16-d7aeb4603229
| 0
|
public String variableForState(State state) {
return (String) MAP.get(state);
}
|
7d1e3cfb-0e6b-4829-b344-4c109461b534
| 7
|
public String toTreeString( int depth ) {
StringBuilder result = new StringBuilder();
if (nodeType != NodeType.VALUE) {
result.append(indent(depth));
result.append( nodeType.toString() );
if ( valueToken != null && ( nodeType == NodeType.EXPRESSION || nodeType == NodeType.TERM ) ) {
result.append( " " ).append( valueToken.getType().toString() );
}
result.append( "\n" );
} else {
if ( valueToken != null ) {
result.append(indent(depth));
result.append( valueToken.toString() ).append( "\n" );
} else {
result.append(indent(depth));
result.append( "null\n" );
}
}
if (children != null) {
children.forEach( child -> {
if ( child != null ) {
result.append( child.toTreeString( depth + 1 ) );
}
} );
} else {
result.append( "<empty>" );
}
return result.toString();
}
|
93927153-2bc9-4151-901c-5c50f3c671ce
| 9
|
public static void start(File fileName) {
if(fileName==null)
return;
InstrumentReplacer replace = new InstrumentReplacer();
putInstruments();
try {
Scanner file = new Scanner(fileName);
String songText = file.nextLine();
replace.setParams(songText,fileName);
file.close();
} catch(FileNotFoundException e) {
ErrorDialogs.fileNotFound();
e.printStackTrace();
return;
} catch(NoSuchElementException e) {
ErrorDialogs.noText();
e.printStackTrace();
return;
} catch(FormatException e) {
ErrorDialogs.formatIssue();
e.printStackTrace();
return;
}
String combo = InstrumentRepDialog.showInstrumentRepDialog();
if (combo == null)
return;
String change = combo.split(" ")[0];
Character ch = instruments.get(change.toLowerCase());
String changeTo = combo.split(" ")[1];
Character chT = instruments.get(changeTo.toLowerCase());
try {
replace.writeOldFile();
}
catch (Exception e) {
ErrorDialogs.unwritableFile();
e.printStackTrace();
return;
}
String newFile = replace.changeNew(ch, chT);
try {
PrintStream writer = new PrintStream(fileName);
writer.print(newFile);
writer.close();
} catch (FileNotFoundException e) {
ErrorDialogs.fileNotFound();
e.printStackTrace();
return;
} catch (SecurityException e) {
ErrorDialogs.unwritableFile();
e.printStackTrace();
return;
} catch (Exception e) {
ErrorDialogs.unanticipatedError();
e.printStackTrace();
return;
}
JOptionPane.showMessageDialog(null, "Complete!",
"Instrument Replacer", JOptionPane.INFORMATION_MESSAGE);
}
|
def6d8ce-9ee1-41ad-bfb7-126861f9a522
| 1
|
public synchronized void InsertContent(String list_name, String content, int article_id) {
try {
content_ste.executeUpdate("INSERT INTO zhangyu_sca.article_content (article_id , list_name, list_content) values ( '" + article_id + "' , '" + list_name + "' , '" + content + "');");
} catch (Exception e) {
e.printStackTrace();
}
}
|
cc1d4909-15ce-48c7-827c-fb8fd07b3c35
| 5
|
public void scanThrough(int numTiles) {
for (int n = 0 ; n < numTiles ;) {
final int scanX, scanY ;
if (scan == 0) {
scanX = scanY = 0 ;
initSeeds() ;
}
else {
scan = lfsr.nextVal() ;
scanX = scan / size ;
scanY = scan % size ;
if (scan == seed) scan = 0 ;
}
if (scanX >= size || scanY >= size) continue ;
scanAt(scanX, scanY) ;
n++ ;
}
lastScanIndex = (lastScanIndex + numTiles) % totalTiles ;
}
|
cf48e92f-c872-42fb-aeab-40e7932692ad
| 9
|
public JScrollPane createTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode(getString("TreeDemo.music"));
DefaultMutableTreeNode catagory = null ;
DefaultMutableTreeNode artist = null;
DefaultMutableTreeNode record = null;
// open tree data
URL url = getClass().getResource("/resources/tree.txt");
try {
// convert url to buffered string
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
// read one line at a time, put into tree
String line = reader.readLine();
while(line != null) {
// System.out.println("reading in: ->" + line + "<-");
char linetype = line.charAt(0);
switch(linetype) {
case 'C':
catagory = new DefaultMutableTreeNode(line.substring(2));
top.add(catagory);
break;
case 'A':
if(catagory != null) {
catagory.add(artist = new DefaultMutableTreeNode(line.substring(2)));
}
break;
case 'R':
if(artist != null) {
artist.add(record = new DefaultMutableTreeNode(line.substring(2)));
}
break;
case 'S':
if(record != null) {
record.add(new DefaultMutableTreeNode(line.substring(2)));
}
break;
default:
break;
}
line = reader.readLine();
}
} catch (IOException e) {
}
tree = new JTree(top) {
public Insets getInsets() {
return new Insets(5,5,5,5);
}
};
tree.setEditable(true);
return new JScrollPane(tree);
}
|
dba02885-c91d-4678-bd9d-1fe8db438e15
| 4
|
private void itmMnuRelatorioProjetoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmMnuRelatorioProjetoActionPerformed
if (usuarioLogado.getTipo().equals("Gerente") || usuarioLogado.getTipo().equals("Diretor")) {
ProjetoBO projetoBO = new ProjetoBO();
//chamar o relatorio
try {
String relatorio = System.getProperty("user.dir")
+ "/relatorios/RelatorioProjetos.jasper";
//criar fonte de dados
JRBeanCollectionDataSource fonteDados = new JRBeanCollectionDataSource(projetoBO.listaProjeto(usuarioLogado));
//gerar relatorio
JasperPrint relatorioGerado = JasperFillManager.fillReport(relatorio, null, fonteDados);
//exibir o relatorio na tela
JasperViewer jasperViewer = new JasperViewer(relatorioGerado, false);
jasperViewer.setVisible(true);
} catch (JRException ex) {
System.out.println("Falha ao gerar Relatorio: " + ex.getMessage());
} catch (SQLException ex) {
Logger.getLogger(TelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(null, "Você não possui previlégios para acessar \n "
+ " o Relatorio de Atividades de Projeto!",
"Relatorio de Atividades de Projeto", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_itmMnuRelatorioProjetoActionPerformed
|
ce917d6b-92c9-45f5-9209-4347d73bde98
| 7
|
public static boolean isWorkingDay(DayOfWeek day){
switch(day){
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
return true;
case SUNDAY:
case SATURDAY:
return false;
}
return false;
}
|
19661478-9b70-460b-9af2-1f7e090a7f9d
| 1
|
private JLabel getLbEstado() {
if (lbEstado == null) {
lbEstado = new JLabel("Estado:");
}
return lbEstado;
}
|
6708b46b-b57c-4d10-80f9-3cd847abcaa3
| 7
|
private boolean isHorizontalWin(int player) throws Exception {
boolean result = false;
if ((player < 0) || (player > TicTacToeBoard.PLAYER_O)) {
throw new Exception("Invalid player index -- must be 0 or 1");
}
String playerSymbol;
if( player == PLAYER_X) {
playerSymbol = X;
} else {
playerSymbol = O;
}
for (int row = 0; row < SIZE; row++) {
if ((square[row][0] == square[row][1])
&& (square[row][1] == square[row][2])
&& (square[row][0] == playerSymbol)) {
result = true;
break;
}
}
return result;
}
|
90705a66-6455-4452-9f89-1c55c465e44b
| 0
|
public Activator() {
}
|
2ef6480e-ba24-47d6-8f99-5874a7adf4d6
| 9
|
public static void loadSmsBase(){
ImD=new ImportDriver(getConfigDirectoryPath(), "", "");
if(ImD.verifyConnection()){
System.out.println("Connected to database fontlineSms");
try{
rs=ImD.executer("SELECT * FROM message");
if(rs !=null){
while(rs.next()){
System.out.println("id: "+rs.getInt("id"));
System.out.println("Date: "+rs.getInt("Date"));
System.out.println("Expediteur: "+rs.getString("senderMsisdn"));
System.out.println("Message: "+rs.getString("textContent")+"\n\n");
String chaine=rs.getString("textContent");
String chaineTab[]=chaine.split(" ");
if (chaineTab.length!=0){
for(int i = 0; i<chaineTab.length; i++){
System.out.println("chaine("+i+")="+chaineTab[i]);
}
if(result !=null){
while(result.next()){
if (result.getString("numero_membre")==chaineTab[0]){
result.moveToInsertRow();
result.updateString("telephone",chaineTab[1]);
result.insertRow();
break;
}
}
}
}
else{ System.out.println("the database is empty");}
}
}
else{
System.out.println("the database is empty");
}
}catch(SQLException ex){
Logger.getLogger(ImportDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Connection to message failed !!!");
}
}
|
619c02ec-bfd3-42e7-aab5-936d1dec8fbe
| 6
|
private void collision(LinkedList<GameObject> object) {
for (int i = 0; i < handler.objects.size(); i++) {
GameObject tempObject = handler.objects.get(i);
switch (tempObject.getID()) {
case Block:
if (getBoundsTop().intersects(tempObject.getBounds())) {
y = tempObject.getY() + tempObject.getHeight();
velY = 0;
}
if (getBounds().intersects(tempObject.getBounds())) {
y = tempObject.getY() - height;
velY = 0;
falling = false;
jumping = false;
} else {
falling = true;
}
if (getBoundsLeft().intersects(tempObject.getBounds())) {
x = tempObject.getX() + tempObject.getWidth();
}
if (getBoundsRight().intersects(tempObject.getBounds())) {
x = tempObject.getX() - width;
}
break;
default:
break;
}
}
}
|
4fffe4dd-e191-403c-9d2c-b836d63cc275
| 3
|
void table3(){
int startNumber = 2;
StringBuilder currentLine = new StringBuilder();
do{
for (int secondMultNumber = 1; secondMultNumber <= 10; secondMultNumber++) {
for (int firstMultNumber = startNumber; firstMultNumber < startNumber + 4; firstMultNumber++) {
currentLine.append(getExpression(firstMultNumber, secondMultNumber) + " ");
}
System.out.println(currentLine);
currentLine.delete(0, currentLine.length());
}
System.out.println();
startNumber += 4;
}while (startNumber < 10);
}
|
23995f72-1f2c-47c9-a76a-5d770ff26a00
| 7
|
public CheckResultMessage checkG(int day) {
BigDecimal g = new BigDecimal(0);
int row1 = get(10, 2);
int clums1 = get(11, 2);
int total1 = get(13, 2);
if (version.equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
for (int i = row1; i < total1; i++) {
g = g.add(getValue(row1, clums1 + day, 2));
}
if (0 != (g.compareTo(getValue(total1, clums1 + day, 2)))) {
return error("支付机构单个账户报表<" + fileName + ">增加银行余额的特殊业务合计 G:"
+ day + "日错误");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
for (int i = row1; i < total1; i++) {
g = g.add(getValue(row1, clums1, 2));
}
if (0 != (g.compareTo(getValue(total1, clums1 + day, 2)))) {
return error("支付机构单个账户报表<" + fileName + ">增加银行余额的特殊业务合计 F:"
+ day + "日错误");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付机构单个账户报表<" + fileName + ">增加银行余额的特殊业务合计 G:" + day
+ "日正确");
}
|
d0c1e3d2-eb67-4d88-959d-7f5f2809edd2
| 2
|
public static double angle2DBetween(double[] coord1, double[] coord2)
{
if (coord1.length != coord2.length && coord1.length != 2)
throw new IllegalArgumentException (
"Number of dimensions is not valid for the provided coordinates");
double xDiff = coord2[0] - coord1[0];
double yDiff = coord2[1] - coord1[1];
double angle = Math.toDegrees (Math.atan2 (yDiff, xDiff)) - 180;
return angle;
}
|
1d13ff95-72e4-46c4-947f-912ab2a14a65
| 3
|
@Test
public void testMeilleurParcour()
{
Random rand = Mockito.mock(Random.class);
LandSensor sensor = new LandSensor(rand);
// On crée un chemin de terre.
Mockito.when(rand.nextInt(Land.CountLand())).thenReturn(0);
try {
sensor.getPointToPointEnergyCoefficient(new Coordinates(0,0), new Coordinates(0,1));
sensor.getPointToPointEnergyCoefficient(new Coordinates(0,1), new Coordinates(1,1));
sensor.getPointToPointEnergyCoefficient(new Coordinates(1,1), new Coordinates(2,1));
sensor.getPointToPointEnergyCoefficient(new Coordinates(2,1), new Coordinates(3,1));
sensor.getPointToPointEnergyCoefficient(new Coordinates(3,1), new Coordinates(4,1));
sensor.getPointToPointEnergyCoefficient(new Coordinates(4,1), new Coordinates(5,1));
sensor.getPointToPointEnergyCoefficient(new Coordinates(5,1), new Coordinates(5,0));
} catch (LandSensorDefaillance landSensorDefaillance) {
landSensorDefaillance.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InaccessibleCoordinate inaccessibleCoordinate) {
inaccessibleCoordinate.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
// Tout le reste n'est que sable
Mockito.when(rand.nextInt(Land.CountLand())).thenReturn(3);
Robot r = new Robot();
r.land(new Coordinates(0,0), sensor);
List<Instruction> parcour = new ArrayList<Instruction>();
parcour.add(Instruction.FORWARD);
parcour.add(Instruction.TURNRIGHT);
parcour.add(Instruction.FORWARD);
parcour.add(Instruction.FORWARD);
parcour.add(Instruction.FORWARD);
parcour.add(Instruction.FORWARD);
parcour.add(Instruction.FORWARD);
parcour.add(Instruction.TURNRIGHT);
parcour.add(Instruction.FORWARD);
try {
r.computeRoadTo(new Coordinates(5,0));
Assert.assertTrue(parcour.equals(r.getRoadBook().getInstructions()));
/*
Ce test echoue car le robot prefere faire :
TURNRIGHT
FORWARD
FORWARD
FORWARD
FORWARD
FORWARD
c'est a dire un chemin coutant 17 d'energie alors qu'il pourrait contourner la
zone sableuse en utilisant le chemin de terre, chemin plus long mais ne coutant
que 7 d'energie
*/
} catch (UnlandedRobotException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
|
f8578efc-ab84-402e-86b5-da1ae806dc8e
| 5
|
private CycAccess establishAndVerifyCycAccess(final String hostname, final String port)
throws UnknownHostException, IOException, CycApiException {
final StringBuffer hostnamePortBuffer = new StringBuffer();
hostnamePortBuffer.append(hostname);
hostnamePortBuffer.append("/");
hostnamePortBuffer.append(port);
final String hostnamePort = hostnamePortBuffer.toString();
Log.current.print("hostname/port: " + hostnamePort);
// obtain the existing cycAccess if this is not the first time
Object[] cycAccessInfo = (Object[]) cycAccesses.get(hostnamePort);
CycAccess cycAccess = null;
if (cycAccessInfo != null)
cycAccess = (CycAccess) cycAccessInfo[0];
Log.current.println(" cycAccess: " + cycAccess);
if (cycAccess != null) {
// verify that the existing connection is valid, or too-long unused
if (! ((CycConnection) cycAccess.getCycConnection()).isValidBinaryConnection()) {
Log.current.println("Socket not connected for " + cycAccess);
cycAccess.close();
cycAccess = null;
}
else if (((Long) cycAccessInfo[1]).longValue() + MAX_UNACCESSED_MILLIS < System.currentTimeMillis()) {
Log.current.println("Maximum unused time exceeded for " + cycAccess);
cycAccess.traceOn();
cycAccess.close();
cycAccess = null;
}
}
if (cycAccess == null) {
Log.current.println("Creating new cycAccess for " + hostnamePort);
cycAccess = new CycAccess(hostname, Integer.parseInt(port));
Log.current.println("Created cycAccess for " + hostnamePort);
cycAccessInfo = new Object[2];
cycAccessInfo[0] = cycAccess;
}
cycAccessInfo[1] = new Long(System.currentTimeMillis());
cycAccesses.put(hostnamePort, cycAccessInfo);
return cycAccess;
}
|
88a881d3-7a0d-46e4-9fa7-13d8a4bc44b3
| 3
|
private boolean korjaaSijainti()
{
ArrayList<Suunta> suunnat = paivitaTormaystarkistus().suunnat();
if(suunnat.isEmpty())
return true;
else if(suunnat.contains(Suunta.OIKEA))
return yritaPoistuaTormaamasta(Suunta.VASEN);
else if(suunnat.contains(Suunta.VASEN))
return yritaPoistuaTormaamasta(Suunta.OIKEA);
else
return false;
}
|
4f62887e-37eb-4936-86fe-2ce63c4e771f
| 1
|
@Override
public List<NepticalData> getAllData() {
if (fragments.isEmpty()) {
return new ArrayList<>();
}
return getDataModule(fragments.get(fragments.size() - 1)).getAllData();
}
|
0e27dc89-7bf1-40dd-bdd0-f073acf9b676
| 1
|
public synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
|
edd795b6-e10c-4b86-8d6a-e79f2632fb97
| 7
|
public void loadHeader(BufferedReader bin) throws MaltChainedException {
String fileLine = "";
Pattern tabPattern = Pattern.compile("\t");
try {
while ((fileLine = bin.readLine()) != null) {
if (fileLine.length() == 0 || fileLine.charAt(0) != '\t') {
break;
}
String items[];
try {
items = tabPattern.split(fileLine.substring(1));
} catch (PatternSyntaxException e) {
throw new SymbolException("The header line of the symbol table '"+fileLine.substring(1)+"' could not split into atomic parts. ", e);
}
if (items.length != 3) {
throw new SymbolException("The header line of the symbol table '"+fileLine.substring(1)+"' must contain four columns. ");
}
addSymbolTable(items[0], Integer.parseInt(items[1]), items[2]);
}
} catch (NumberFormatException e) {
throw new SymbolException("The symbol table file (.sym) contains a non-integer value in the header. ", e);
} catch (IOException e) {
throw new SymbolException("Could not load the symbol table. ", e);
}
}
|
be0d4c0c-2b8a-403e-9479-46d1c02b756b
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Insert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Insert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Insert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Insert.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 Insert().setVisible(true);
}
});
}
|
9a62b650-6476-44ba-844d-92cab39d6c03
| 8
|
private Vector2f rectCollide(Vector2f oldPos, Vector2f newPos, Vector2f size1,
Vector2f pos2, Vector2f size2){
Vector2f res = new Vector2f(0, 0);
if(newPos.getX() + size1.getX() < pos2.getX() ||
newPos.getX() - size1.getX() > pos2.getX() + size2.getX() * size2.getX() * size2.getX() ||
oldPos.getY() + size1.getY() < pos2.getY() ||
oldPos.getY() - size1.getY() > pos2.getY() + size2.getY() * size2.getY() * size2.getY()) {
res.setX(1);
}
if(oldPos.getX() + size1.getX() < pos2.getX() ||
oldPos.getX() - size1.getX() > pos2.getX() + size2.getX() * size2.getX() * size2.getX() ||
newPos.getY() + size1.getY() < pos2.getY() ||
newPos.getY() - size1.getY() > pos2.getY() + size2.getY() * size2.getY() * size2.getY()){
res.setY(1);
}
return res;
}
|
198cc4e8-c185-4c70-9e4e-a684e95f0d1c
| 7
|
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Type)) {
return false;
}
Type t = (Type) o;
if (sort != t.sort) {
return false;
}
if (sort >= ARRAY) {
if (len != t.len) {
return false;
}
for (int i = off, j = t.off, end = i + len; i < end; i++, j++) {
if (buf[i] != t.buf[j]) {
return false;
}
}
}
return true;
}
|
7a744a56-d3f7-4763-80df-5623da422b44
| 9
|
public void Afficher()
{
String res = "";
for (int i = 0; i < this.hauteur; i++)
{ // Parcours le premier tableau
for (int j = 0; j < this.largeur; j++)
{ // Parcours le second tableau
switch (this.background[i][j])
{
case MUR : res = res +"M"; break;
case HERBE : res = res +"H"; break;
case ROUTE : res = res +"R"; break;
case TERRE : res = res +"T"; break;
case TOWER : res = res +"O"; break;
case UNITE : res = res +"X"; break;
case QG : res = res + "G"; break;
}
res = res + " ";
}
res = res + "\n"; // Permet de revenir à la ligne au moment de passer à la ligne suivante du tableau
}
System.out.print(res);
}
|
778509e6-33d1-4d83-8d36-e8682ca6a7aa
| 8
|
@Override
public Iterable<ImmutableToken> tokenizeDocument( String document
, Set<String> stopwords
)
{
PorterStemmer stemmer = new PorterStemmer();
int index = 0;
Matcher whitespaceMatcher = null;
List<ImmutableToken> tokens = new ArrayList<ImmutableToken>();
while(document !=null && index < document.length())
{
whitespaceMatcher = whitespacePattern.matcher(document.substring(index));
boolean found = whitespaceMatcher.find();
String token = null;
if(found)
{
int newIndex = index + whitespaceMatcher.end();
//If length is zero, it means that the "token" was just a run of whitespace, so discard
//Otherwise, add this as a new token
if(document.substring(index, newIndex-1).length()>0)
{
token = document.substring(index, newIndex - 1);
}
index = newIndex;
}
else
{
//This should never execute, because if index < line.length, then another token will be found,
//even if it's just whitespace to be discarded
token = document.substring(index);
index = document.length();
}
if(token != null && token.length() > 0)
{
String tokenNormalized = token.toLowerCase().replaceAll("[^A-Za-z ]", "");
if(tokenNormalized.length() > 2 && !stopwords.contains(tokenNormalized))
{
tokens.add(new ImmutableToken(tokenNormalized, stemmer.stem(tokenNormalized)));
}
}
}
return tokens;
}
|
eca1030d-e1e8-4521-935c-1037d7224c7a
| 3
|
public void mouseReleased(MouseEvent e) {
if (documentViewModel.getViewToolMode() ==
DocumentViewModel.DISPLAY_TOOL_TEXT_SELECTION) {
textSelectionHandler.mouseReleased(e);
} else if (documentViewModel.getViewToolMode() ==
DocumentViewModel.DISPLAY_TOOL_SELECTION ||
documentViewModel.getViewToolMode() ==
DocumentViewModel.DISPLAY_TOOL_LINK_ANNOTATION) {
annotationHandler.mouseReleased(e);
}
}
|
4fbf3142-cd44-485c-8dc3-1bdd4ef6ea34
| 3
|
public void draw(Graphics2D g) {
bg.draw(g);
tileMap.draw(g);
player.draw(g);
for (int i = 0; i < enemys.size(); i++)
((Enemy) enemys.get(i)).draw(g);
teleport.draw(g);
for (int i = 0; i < explosions.size(); i++) {
((Explosion) explosions.get(i)).setMapPosition(
(int) tileMap.getx(), (int) tileMap.gety());
((Explosion) explosions.get(i)).draw(g);
}
hud.draw(g);
if (title != null)
title.draw(g);
}
|
8b61c718-1d0e-4321-b458-37e6594966bc
| 4
|
@EventHandler(priority = EventPriority.MONITOR)
public void onEnchant(EnchantItemEvent event){
Player player = (Player)event.getEnchanter();
String playername = player.getName();
World world = player.getWorld();
Boolean staff = false;
String worldname = world.getName();
Map<Enchantment, Integer> ench = event.getEnchantsToAdd();
ItemStack item = event.getItem();
int cost = event.getExpLevelCost();
double x = (int) Math.floor(player.getLocation().getX());
double y = (int) Math.floor(player.getLocation().getY());
double z = (int) Math.floor(player.getLocation().getZ());
if (getConfig.PlayerEnchants()) {
if (player.hasPermission("PlayerLogger.staff")) {
staff = true;
}
if (getConfig.logFilesEnabled()) {
filehandler.logEnchant(playername, ench, item, cost, worldname, x, y, z, staff);
}
if (getConfig.MySQLEnabled()) {
addData.add(playername,"enchant", item+" "+ench+" Xp Cost:"+cost, x, y, z, worldname, staff);
}}}
|
4701b2ea-5905-4413-8ead-2922fae8ae24
| 0
|
public static void main(String[] args) {
String[] hostNames = initializeHostNames();
// Parse the parameters (fill gaps with defaults):
Alloy alloy = parseInput(args, hostNames);
// Run stuff:
buildAndRunGui(alloy, hostNames);
alloy.runSimulation();
// Exit:
System.out.println("Good-bye!");
}
|
97930b87-ae85-4ee9-ba55-2be9e8b1d512
| 6
|
public boolean reserveSeat(int theaterId, int line, int column){
if(line == -1 || column == -1)
return false;
TheaterSeats seats = TheaterSeatsCatalog.getTheaterSeats(theaterId);
//if it isn't on cache, then we must seek on the disk
if(seats == null){
seats = loadSeatsFromDisk(new File(workingDir + File.separator + theaterId +".txt"));
//Was on the disk
if(seats != null){
TheaterSeatsCatalog.addTheaterSeats(seats); //Add it to the cache
if(seats.getSeatStatus(line, column) != 'O'){
TheaterSeatsCatalog.setSeatStatus(theaterId, line, column, 'O');
writeToDisk(seats);
return true;
}
return false; //couldn't be reserved.
}
return false;//couldn't be found on disk, either.
}
//It's on cache, so we check right from the cache
if(seats.getSeatStatus(line, column) != 'O'){
seats.setSeatStatus(line, column, 'O'); //make the reservation
writeToDisk(seats); //write the new state of the theater to disk
TheaterSeatsCatalog.addTheaterSeats(seats); //Update the cache
return true;
}
return false;
}
|
a25119de-7390-45d5-947e-70fd2f7c16eb
| 5
|
final void method1716(boolean bool) {
anInt6050++;
if (bool != false)
method1714(-51, -128);
if (((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136)
.aClass239_Sub25_7271.method1830((byte) -123)
&& !Node.method2714(7351,
((Class348_Sub51)
((Class239) this).aClass348_Sub51_3136)
.aClass239_Sub25_7271
.method1829(-32350)))
((Class239) this).anInt3138 = 0;
if (((Class239) this).anInt3138 < 0
|| (((Class239) this).anInt3138 ^ 0xffffffff) < -3)
((Class239) this).anInt3138 = method1710(20014);
}
|
43857eec-0530-4361-af0d-9fee8319c92a
| 6
|
public void save(ConnectionWrapper cw, String subClassName, Long realId) throws SQLException
{
// store a reference to the subclass table entry
Integer subClassNameId = adapter.getPersist().getClassNameNumberMap().getNumber(cw, subClassName);
addValueTrio(Defaults.REAL_CLASS_COL, subClassNameId, Integer.class);
if (realId != null)
{
id = realId;
}
String stmt = getRowInsertionStatement();
PreparedStatement ps = cw.prepareStatement(stmt);
fillRowInsertionStatement(ps, cw);
Tools.logFine(ps);
ps.execute();
ps.close();
if (!isArray())
{
// store the id of the inserted row
if (realId == null)
{
id = adapter.getPersist().getLastId(cw, getTableName());
}
// save the protection entries
protectionStack.save(this.getTableName(), id, cw);
}
else
{
// add the entries of the array
if (realId == null)
{
id = adapter.getPersist().getLastId(cw,NameGenerator.getArrayTablename(adapter));
}
protectionStack.save(NameGenerator.getArrayTablename(adapter), id, cw);
adapter.getPersist().getArrayEntryWriter().addArrayEntries(cw, id, object, delayBuffer);
}
if (delayBuffer != null && object != null)
{
delayBuffer.setUndefinedIds(id, System.identityHashCode(object));
}
}
|
d05aa72f-d08a-4d5c-9e61-1ddb392bc395
| 9
|
public FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term,
final float minSimilarity, final int prefixLength, boolean transpositions) throws IOException {
if (minSimilarity >= 1.0f && minSimilarity != (int)minSimilarity)
throw new IllegalArgumentException("fractional edit distances are not allowed");
if (minSimilarity < 0.0f)
throw new IllegalArgumentException("minimumSimilarity cannot be less than 0");
if(prefixLength < 0)
throw new IllegalArgumentException("prefixLength cannot be less than 0");
this.terms = terms;
this.term = term;
// convert the string into a utf32 int[] representation for fast comparisons
final String utf16 = term.text();
this.termText = new int[utf16.codePointCount(0, utf16.length())];
for (int cp, i = 0, j = 0; i < utf16.length(); i += Character.charCount(cp))
termText[j++] = cp = utf16.codePointAt(i);
this.termLength = termText.length;
this.dfaAtt = atts.addAttribute(LevenshteinAutomataAttribute.class);
//The prefix could be longer than the word.
//It's kind of silly though. It means we must match the entire word.
this.realPrefixLength = prefixLength > termLength ? termLength : prefixLength;
// if minSimilarity >= 1, we treat it as number of edits
if (minSimilarity >= 1f) {
this.minSimilarity = 0; // just driven by number of edits
maxEdits = (int) minSimilarity;
raw = true;
} else {
this.minSimilarity = minSimilarity;
// calculate the maximum k edits for this similarity
maxEdits = initialMaxDistance(this.minSimilarity, termLength);
raw = false;
}
if (transpositions && maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) {
throw new UnsupportedOperationException("with transpositions enabled, distances > "
+ LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + " are not supported ");
}
this.transpositions = transpositions;
this.scale_factor = 1.0f / (1.0f - this.minSimilarity);
this.maxBoostAtt = atts.addAttribute(MaxNonCompetitiveBoostAttribute.class);
bottom = maxBoostAtt.getMaxNonCompetitiveBoost();
bottomTerm = maxBoostAtt.getCompetitiveTerm();
bottomChanged(null, true);
}
|
11cdbe09-201c-41e8-8c2c-e1daa13a9fcd
| 2
|
private void lockOnReportDir(File reportDir) {
synchronized (files) {
while (files.contains(reportDir))
try {
files.wait();
} catch (InterruptedException ex) {
logger.log(SEVERE, Thread.currentThread().getName() +" INTERRUPTED", ex);
}
files.add(reportDir);
files.notifyAll(); // must own the lock
}
}
|
c6fedd12-d526-43d2-ab4d-aae330b4a6f6
| 0
|
public void templateMethod() {
System.out.println("前処理:" + LoggerUtils.getSig());
// 独自処理はサブクラスで実装
method();
System.out.println("後処理:" + LoggerUtils.getSig());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.