method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
4a358a7b-2b35-44ab-8534-f4b2cb3f73ba | 0 | public synchronized void addFrame(Image image,
long duration)
{
totalDuration += duration;
frames.add(new AnimFrame(image, totalDuration));
} |
04eb74d4-a9e7-4e87-8956-5920144f5561 | 6 | public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} |
e630f4b8-d8ec-4c79-b815-c0f8cc721035 | 5 | public void handleStartTag( HTML.Tag t, MutableAttributeSet a,
int pos )
{
if ( t == HTML.Tag.SELECT)
{
Object value = getValueOfAttribute(a, "name") ;
if (value != null)
{
if (value.toString().hashCode() == "systran_lp".hashCode())
{
selection++ ;
// System.out.println( "START " + t.toString() ) ;
}
}
}
else if (selection > 0)
{
if (t == HTML.Tag.OPTION)
{
String str = (String) getValueOfAttribute(a, "value") ;
insert(str) ;
// System.out.println( "option <" +str +">") ;
// logText = true ;
}
}
} |
12f36b34-4e29-4642-9d6a-c45b2e09db2d | 0 | public Iterator iterator() {
return new BallIterator(this);
} |
ccc2cec3-2c8e-413a-8413-ea661bb33435 | 2 | public void removeNode(final Object key) {
final GraphNode node = getNode(key);
Assert.isTrue(node != null, "No node for " + key);
succs(node).clear();
preds(node).clear();
if (removingNode == 0) {
nodes.removeNodeFromMap(key);
} else if (removingNode != 1) {
throw new RuntimeException();
}
// Removing a node invalidates the orderings
preOrder = null;
postOrder = null;
nodeModCount++;
edgeModCount++;
} |
23617224-60ae-490c-a486-9ed0c388c8cb | 4 | public boolean fromDocument(Document document) {
boolean result = true;
NodeList serversList = document.getElementsByTagName(C.servers);
NodeList tasksList = document.getElementsByTagName(C.tasks);
for (int i=0; i<serversList.getLength(); i++) {
result = result && servers.fromElement((Element)serversList.item(i));
}
for (int i=0; i<tasksList.getLength(); i++) {
result = result && tasks.fromElement((Element)tasksList.item(i));
}
return result;
} |
d67d28b9-58f7-4be0-9a21-df2427e330f1 | 3 | String getResourceCamelOrLowerCase(boolean mandatory, String ending) {
String name = getConventionalName(true, ending);
URL found = getClass().getResource(name);
if (found != null) {
return name;
}
System.err.println("File: " + name + " not found, attempting with camel case");
name = getConventionalName(false, ending);
found = getClass().getResource(name);
if (mandatory && found == null) {
final String message = "Cannot load file " + name;
System.err.println(message);
System.err.println("Stopping initialization phase...");
throw new IllegalStateException(message);
}
return name;
} |
fb2ff292-49f1-4df0-9d5e-b8e78892e6f7 | 2 | private void loadSplashes() {
try (BufferedReader reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/splash/splash text"))) {
Icon splashIcon;
String line = null;
while((line = reader.readLine()) != null) {
// Load each screen
splashIcon = new Icon(line);
splashIcon.setPosition(() -> Camera.get().getDisplayWidth(0.5f), () -> Camera.get().getDisplayHeight(0.5f));
splashIcon.setAlignments(VerticalAlign.CENTER, HorizontalAlign.CENTER);
splashImages.add(splashIcon);
}
} catch (IOException e) {
e.printStackTrace();
}
} |
f9c526ea-ae83-4417-9ce1-a480a265020c | 2 | public void encode(OutputStream os, BencodeType... values) throws IOException {
if (values != null) {
for (BencodeType value : values) {
value.encode(os);
}
}
} |
d760852d-0489-4653-9445-fc8031b98a23 | 8 | public ListChooserTF(Frame frame, Component locationComp, String labelText,
String title, Object[] data, int initialIndex, String longValue,
String okLabel, String[] inputTextLabel, int[] inputTextMinValue, int[] inputTextMaxValue, int[] inputTextDefaultValues ) {
super(frame, locationComp, labelText, title, data, initialIndex,
longValue, okLabel);
if(inputTextLabel==null || inputTextMaxValue==null || inputTextMinValue==null || inputTextDefaultValues==null || inputTextLabel.length!=inputTextMaxValue.length || inputTextLabel.length!=inputTextMinValue.length||inputTextLabel.length!=inputTextDefaultValues.length){
throw new IllegalArgumentException("arrays must have same length");
}
Box northPanel = new Box(BoxLayout.Y_AXIS);
getContentPane().add(northPanel, BorderLayout.NORTH);
inputText = new DefTextField[inputTextLabel.length];
textValue = new int[inputTextLabel.length];
for(int i = 0;i<inputTextLabel.length;i++){
inputText[i] = new DefTextField(5);
inputText[i].setText(String.valueOf(inputTextDefaultValues[i]));
northPanel.add(
Graph.createPanel(inputText[i], inputTextLabel[i], null));
}
this.inputTextMinValue = inputTextMinValue;
this.inputTextMaxValue = inputTextMaxValue;
} |
994b9753-34d6-4203-b3f7-a93104ed90cf | 8 | public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int biggestNum = Integer.MIN_VALUE;
int smallestNum = Integer.MAX_VALUE;
int biggestOddNumber = Integer.MIN_VALUE;
boolean oddNumberFound = false;
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
if (input > biggestNum) {
biggestNum = input;
}
if (input % 2 != 0) {
if (!oddNumberFound) {
biggestOddNumber = input;
oddNumberFound = true;
} else if (input >= biggestOddNumber) {
biggestOddNumber = input;
}
}
if (input < smallestNum) {
smallestNum = input;
}
}
System.out.println("The biggest number is: " + biggestNum);
System.out.println("The smallest number is: " + smallestNum);
if (oddNumberFound) {
System.out.println("The biggest odd number is : " + biggestOddNumber);
} else {
System.out.println("There is no odd number in the sequence!");
}
} |
06999060-b59e-4500-bfcf-76e50b46045f | 8 | public Token run(List<Token> tokens) {
for (Token token : tokens) {
if (token instanceof ValueToken) {
values.push((ValueToken) token);
continue;
}
OperatorToken o = (OperatorToken) token;
if (Operator.OPEN_PARENTHESIS == o.getOperator()) {
operators.push(o);
bracketCnt++;
} else if (Operator.CLOSE_PARENTHESIS == o.getOperator()) {
while (operators.peek().getOperator() != Operator.OPEN_PARENTHESIS) {
operate();
}
operators.pop();
bracketCnt--;
} else {
if(!operators.empty() && o.getPriority() < operators.peek().getPriority()) {
operate();
}
operators.push(o);
}
}
while (!operators.empty()) {
operate();
}
// todo bracket 개수 검사
return values.pop();
} |
02724efb-b036-4523-b57b-af9a1405f84c | 3 | static void indexStatistic(){
/*record # of entries with different hitting number */
long entryRcord[] = new long[7];
Iterator<Entry<String, long[]>> iter = index.entrySet().iterator();
while(iter.hasNext()){
Entry<String, long[]> entry= iter.next();
long meta[] = new long[M+2];
meta = entry.getValue();
if(meta[0]<=5){
entryRcord[(int) meta[0]]++;
}else{
entryRcord[6]++;
}
}
int i=0;
for(i=0;i<6;i++){
resultRecord.println("# of entries with counter " +i+" : " + entryRcord[i]);
}
resultRecord.println("# of entries with counter larger than " +i +" : " +entryRcord[i]);
} |
ff07cbdd-555b-400a-a011-282f0e084a51 | 1 | public Long getLongItem(String... names) throws ReaderException {
try {
return Long.parseLong(getItem(names).toString());
} catch (NumberFormatException e) {
throw new ReaderException("No key exists with this type, keys: " + _parseMessage(names) + ". In file: " + ConfigurationManager.config_file_path);
}
} |
e9bc504b-5668-423c-b173-145cafb1cd1c | 0 | public Worker () {
//initial settings
results = new String[VALUE_ITERATIONS_NUMBER];
this.keyboard = new BufferedReader(new InputStreamReader(System.in));
System.out.println(MSG_WELCOME);
//start
this.lifeCycle();
} |
2b7d9d23-6d19-46ae-81c2-7a698a1f96f6 | 9 | public void init() {
grid = new Cell[8][8];
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
grid[x][y] = new CellImpl(new Point(y, x));
}
}
for (int q = 0; q < 6; q++) {
grid[0][q + 1].setPiece(Checker.WHITE);
grid[7][q + 1].setPiece(Checker.WHITE);
grid[q + 1][0].setPiece(Checker.BLACK);
grid[q + 1][7].setPiece(Checker.BLACK);
}
gridCount = new int[4][3][16];
for (int q = 0; q < 4; q++) {
for (int w = 0; w < 3; w++) {
for (int e = 0; e < 16; e++) {
gridCount[q][w][e] = 0;
}
}
}
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
for (int direction = 0; direction < DIRECTION.length; direction++) {
int d = DIRECTION[direction];
int color = getCell(new Point(y, x)).getPieceColor();
int index = getIndex(new Point(y, x), d);
gridCount[d][color][index]++;
}
}
}
} |
2ef60025-2cac-434c-bd1f-803ed4a835ee | 3 | private static MobInventory getMobInventory(int invId)
throws SlickException {
QueryExecutor qe = new QueryExecutor();
qe.SendQuery("SELECT * FROM RPG372DB_Inventory WHERE invId='" + invId
+ "'");
if (qe.resultSize() == 0)
return null;
MobInventory mobInv = new MobInventory(null);
int tempId;
for (int i = 0; i < 16; i++) {
tempId = Integer.parseInt(qe.vals.get(i).get(2));
if (tempId == 0)
continue;
else {
mobInv.addItem(ItemFactory.getItem(tempId));
}
}
return mobInv;
} |
2ec278d4-964c-4366-b46d-847b1bc95c7d | 7 | private JPopupMenu getSelectionPopupMenu() {
JPopupMenu popup = new JPopupMenu("Selection");
// MenuBar -> Selection -> Copy
JMenuItem menuItemCopy = new JMenuItem("Copy");
menuItemCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
copySelection();
}
} );
popup.add(menuItemCopy);
// MenuBar -> Selection -> Paste
JMenuItem menuItemPaste = new JMenuItem("Paste");
menuItemPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pasteLine();
}
} );
popup.add(menuItemPaste);
popup.addSeparator();
// MenuBar -> Selection -> Join
JMenuItem menuItemJoinSelection = new JMenuItem("Join (Channel)");
menuItemJoinSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!mainFrame.isConnected())
return;
String chan = mainFrame.getSelection().trim();
if (IRCUtil.isChannel(chan)) {
conn.doJoin(chan);
} else if (chan.length() > 0) {
conn.doJoin("#"+ chan);
}
}
} );
popup.add(menuItemJoinSelection);
// MenuBar -> Selection -> Whois
JMenuItem menuItemWhoisUser = new JMenuItem("Whois (User)");
menuItemWhoisUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!mainFrame.isConnected())
return;
conn.doWhois(mainFrame.getSelection());
}
} );
popup.add(menuItemWhoisUser);
popup.addSeparator();
// MenuBar -> Selection -> ChanCenter
JMenuItem menuItemChanCenter = new JMenuItem("Control Center");
menuItemChanCenter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = mainFrame.getSelectedComponent();
if (component instanceof ChanPanel)
((ChanPanel)component).openControlCenter();
}
} );
popup.add(menuItemChanCenter);
JMenuItem menuItemPasteDialog = new JMenuItem("Full Message");
menuItemPasteDialog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = mainFrame.getSelectedComponent();
if (component instanceof ChanPanel || component instanceof QueryPanel) {
String chan = ((PanelTemplate)component).getWindowName();
new PasteDialog(mainFrame, chan);
}
}
} );
popup.add(menuItemPasteDialog);
return popup;
} |
0e608054-b7ea-47a0-a2ed-4551d2587006 | 6 | public static List getAllRelationsWithPrefix(Module module, boolean localP, String prefix) {
{ Iterator iter = Logic.allNamedDescriptions(module, localP);
List result = List.newList();
String downcasedprefix = Native.stringDowncase(prefix);
{ NamedDescription description = null;
Iterator iter000 = iter;
Cons collect000 = null;
while (iter000.nextP()) {
description = ((NamedDescription)(iter000.value));
if ((!Logic.classP(description)) &&
((prefix != null) &&
Stella.startsWithP(GuiServer.getLogicObjectName(description, "FALSE"), downcasedprefix, 0))) {
if (collect000 == null) {
{
collect000 = Cons.cons(description, Stella.NIL);
if (result.theConsList == Stella.NIL) {
result.theConsList = collect000;
}
else {
Cons.addConsToEndOfConsList(result.theConsList, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(description, Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
}
return (result);
}
} |
3f270191-04b9-4c93-8758-ce1b0df4848f | 2 | public Element toElement(CashOffice cashOffice) {
Element cashOfficeElement = new Element("cashOffice");
List<Seance> seances = cashOffice.getSeances();
for (Seance seance : seances) {
Element seanceElement = new SeanceTranslator().toElement(seance);
Element ticketsElement = new Element("tickets");
List<Ticket> tickets = seance.getTicketsByCOid(cashOffice.getNumber());
for (Ticket ticket : tickets) {
ticketsElement.addContent(new TicketTranslator().toElement(ticket));
}
seanceElement.addContent(ticketsElement);
cashOfficeElement.addContent(seanceElement);
}
cashOfficeElement.setAttribute("id", Integer.toString(cashOffice.getNumber()));
return cashOfficeElement;
} |
7db026d4-e04e-4942-a067-9fdc85c401f6 | 8 | public void setSelectedTool(Tool tool){
if(tool == Tool.FOREGROUND){
this.toForeground();
return;
}
if(tool == Tool.BACKGROUND){
this.toBackground();
return;
}
if(tool == Tool.EDIT){
this.edit();
return;
}
selectedTool = tool;
for(ToolButton button : toolButtons){
if(button.getTool() == tool){
button.setBackground(selectedColor);
}
else {
button.setBackground(null);
}
}
switch (tool) {
case MOVE:
this.setCursor(new Cursor(Cursor.MOVE_CURSOR));
break;
case RESIZE:
this.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
break;
case DELETE:
this.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(MauseIcon.delete.getIcon(), new Point(16,16), "deleteCursor"));
break;
default:
this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
break;
}
} |
96420624-3135-452d-8485-1faf85c73c56 | 1 | public void testSeDurationBeforeEnd_long2() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
try {
test.setDurationBeforeEnd(-1);
fail();
} catch (IllegalArgumentException ex) {}
} |
65ce7bb4-73d0-4a56-bfd7-62a341dfdbd6 | 9 | public String buildConfigStructureAux(NodeList nl, Element element, String path){
String path_aux = path;
String nodeName;
Node node;
NodeList cn;
int cnSize;
List<Node> lst;
int i = 0;
while(nl.getLength() > i){
path=path_aux;
node = nl.item(i);
cn = node.getChildNodes();
cnSize = cn.getLength();
if(node.getNodeType() == Node.ELEMENT_NODE){
nodeName = node.getNodeName();
if(cnSize == 0){
List<String> nodeNamePaths = _paths.get(nodeName);
//testar se a folha ja existe noutro caminho
if(_paths.containsKey(nodeName) && nodeNamePaths.size() > 1){
nodeName = changeNodeName(nodeNamePaths, path, nodeName);
}
if(!_leafs.containsKey(nodeName)){
i++;
continue;
}
lst = _leafs.get(nodeName);
//System.out.println("Depois: " + nodeName);
Node n;
for(int k = 0; lst.size() > k ; k++){
Element el = this._OutputXMLDoc.createElement(nodeName);
n = lst.get(k);
el.appendChild(this._OutputXMLDoc.createTextNode(/*_sm.preProcessString(*/n.getTextContent()/*)*/));
NamedNodeMap attrs = n.getAttributes();
Node attr;
for (int j=0; j<attrs.getLength(); j++) {
attr = attrs.item(j);
el.setAttribute(attr.getNodeName(),/* _sm.preProcessString(*/attr.getTextContent()/*)*/);
}
element.appendChild(el);
}
}
if(cnSize > 0){
Element el = this._OutputXMLDoc.createElement(nodeName);
/*NamedNodeMap attrs = getGroupNodeAttributes(nodeName, _XMLStructureDoc.getDocumentElement());
Node attr;
for (int k=0; k<attrs.getLength(); k++) {
attr = attrs.item(k);
el.setAttribute(attr.getNodeName(), attr.getTextContent());
}*/
element.appendChild(el);
path = buildConfigStructureAux(cn, el, path + nodeName + "\\");
}
}
i++;
}
return path;
} |
7cd2900d-67c2-4184-bb3e-8d0734ff42a6 | 6 | public static Proposition findOrCreateFunctionProposition(GeneralizedSymbol predicate, Cons inputarguments) {
{ Proposition proposition = Logic.beginCreatingFunctionProposition(predicate, inputarguments);
Proposition duplicate = ((!Logic.descriptionModeP()) ? Proposition.findDuplicateFunctionProposition(proposition) : ((Proposition)(null)));
if (duplicate != null) {
return (duplicate);
}
proposition = Proposition.finishCreatingFunctionProposition(proposition);
{ boolean testValue000 = false;
if (!((BooleanWrapper)(KeyValueList.dynamicSlotValue(proposition.dynamicSlots, Logic.SYM_LOGIC_DESCRIPTIVEp, Stella.FALSE_WRAPPER))).wrapperValue) {
testValue000 = true;
}
else {
{ boolean alwaysP000 = true;
{ int i = Stella.NULL_INTEGER;
int iter000 = 0;
int upperBound000 = proposition.arguments.length() - 2;
loop000 : for (;iter000 <= upperBound000; iter000 = iter000 + 1) {
i = iter000;
if (!(!Logic.variableP((proposition.arguments.theArray)[i]))) {
alwaysP000 = false;
break loop000;
}
}
}
testValue000 = alwaysP000;
}
}
if (testValue000) {
Proposition.runGoesTrueDemons(proposition);
}
}
return (proposition);
}
} |
26524d70-39c1-4649-aab7-3024e149018a | 1 | protected void demo16() throws IOException, UnknownHostException, CycApiException {
if (cycAccess.isOpenCyc()) {
Log.current.println("\nThis demo is not available in OpenCyc");
}
else {
Log.current.println("Demonstrating usage of the rkfPhraseReader api function.\n");
String phrase = "penguins";
CycFort inferencePsc =
cycAccess.getKnownConstantByGuid("bd58915a-9c29-11b1-9dad-c379636f7270");
CycFort rkfEnglishLexicalMicrotheoryPsc =
cycAccess.getKnownConstantByGuid("bf6df6e3-9c29-11b1-9dad-c379636f7270");
CycList parsingExpression = cycAccess.rkfPhraseReader(phrase,
rkfEnglishLexicalMicrotheoryPsc,
inferencePsc);
Log.current.println("the result of parsing the phrase \"" + phrase + "\" is\n" + parsingExpression);
}
} |
99070b2b-92cd-499d-892d-c275ccc5f6af | 0 | Xpp3Dom createTimeStamp(final Date date) {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
return createElementWithText("timestamp", dateFormat.format(date));
} |
0c5e538b-3990-43da-bff3-08ec5529386d | 7 | public Set<Unit> collectMinerals(Set<Unit> drones, Set<Unit> minerals) {
// System.out.println("collectMinerals!");
Set<Unit> claimedMinerals = new HashSet<Unit>();
if (drones==null || drones.isEmpty() || minerals==null || minerals.isEmpty()){
return claimedMinerals;
}
for (Unit drone : drones) {
for (Unit mineral : minerals) {
double distance = Math.sqrt(Math.pow(
mineral.getX() - drone.getX(), 2)
+ Math.pow(mineral.getY() - drone.getY(), 2));
// System.out.println("distance: " + distance);
if (distance < 300) {
bwapi.rightClick(drone.getID(), mineral.getID());
claimedMinerals.add(mineral);
break;
}
}
}
return claimedMinerals;
} |
1455e2c4-8a61-42dc-90e8-a802c6aa8131 | 1 | @Override
public void addSubProcess(ProductType productType, SubProcess subProcess) {
productType.addSubProcess(subProcess);
tx.begin();
if (em.contains(subProcess)) em.merge(subProcess);
else em.persist(subProcess);
tx.commit();
} |
cad12934-23b8-4e3d-9334-df93651eb225 | 4 | public ArrayList<TreeNode> generate(int start, int end) {
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
if (start > end) {
TreeNode root = null;
result.add(root);
return result;
}
for (int i = start; i <= end; i++) {
ArrayList<TreeNode> leftList = generate(start, i - 1);
ArrayList<TreeNode> rightList = generate(i + 1, end);
for (int j = 0; j < leftList.size(); j++) {
for (int k = 0; k < rightList.size(); k++) {
TreeNode root = new TreeNode(i);
root.left = leftList.get(j);
root.right = rightList.get(k);
result.add(root);
}
}
}
return result;
} |
81614690-f21b-4f8b-84f4-9e7573c73b14 | 9 | private void persist(String cubeIdentifier) throws PersistErrorException,
PageFullException, IOException, SchemaNotExistsException,
CubeNotExistsException {
SchemaClientInterface schemaClient = SchemaClient.getSchemaClient();
Schema schema = schemaClient.getSchema(cubeIdentifier);
// numberOfDimensions
int numberOfDimensions = schema.getDimensions().size();
// numberOfPages & pageLengths & numberOfPageSegmentsInDimension &
// dimensionLengths
long numberOfPages = PageHelper.getNumberOfPages(schema);
long pageLengths[] = PageHelper.getPageLengths(schema);
long numberOfPageSegmentsInDimension[] = PageHelper
.getNumberOfPageSegmentsInDimensions(schema);
long dimensionLengths[] = DimensionHelper.getDimensionLengths(schema);
System.out.println("numberOfPages:" + numberOfPages);
System.out.println("dimensionLength "
+ Arrays.toString(dimensionLengths));
System.out.println("pageLengths:" + Arrays.toString(pageLengths));
System.out.println("numberOfPageSegmentsInDimension:"
+ Arrays.toString(numberOfPageSegmentsInDimension));
Page page;
// double data;
for (long pageNo = 0; pageNo < numberOfPages; pageNo += 1) {
// construct a page
List<CubeElement<Double>> elementList = new ArrayList<CubeElement<Double>>();
long pointForPage[] = Serializer.deserialize(
numberOfPageSegmentsInDimension,
new BigInteger(String.valueOf(pageNo)));
long pointForElement[][] = new long[2][numberOfDimensions];
for (int i = 0; i < numberOfDimensions; i += 1) {
pointForElement[0][i] = pointForPage[i] * pageLengths[i];
pointForElement[1][i] = pointForElement[0][i] + pageLengths[i]
- 1;
}
System.out.println("Page:\t" + pageNo + "\tstart:\t"
+ Arrays.toString(pointForElement[0]) + "\tend:\t"
+ Arrays.toString(pointForElement[1]));
long[] start = pointForElement[0];
long[] end = pointForElement[1];
long[] point = new long[numberOfDimensions];
long[] lengths = pageLengths;
int pointLength = numberOfDimensions;
int pointAmount = 1;
for (int i = 0; i < pointLength; i++) {
pointAmount *= end[i] - start[i] + 1;
}
for (int i = 0; i < point.length; i++) {
point[i] = start[i];
}
elementList.add(new CubeElement<Double>(Serializer.serialize(
dimensionLengths, point).longValue(), r.nextDouble()
* dataRange));
for (int i = 0; i < pointAmount - 1; i++) {
point[pointLength - 1]++;
if (point[pointLength - 1] >= lengths[pointLength - 1]) {
for (int j = pointLength - 1; j >= 0; j--) {
if (point[j] >= lengths[j] && j > 0) {
point[j] = 0;
point[j - 1]++;
} else {
break;
}
}
}
elementList.add(new CubeElement<Double>(Serializer.serialize(
dimensionLengths, point).longValue(), this.r
.nextDouble() * dataRange));
}
page = new Page(cubeIdentifier, pageNo, elementList);
page.persist();
}
} |
7ddb5dbd-66d3-477b-a017-d32c3b6a62e3 | 8 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == m_defaultButton) {
m_matrix.initialize();
matrixChanged();
} else if (e.getSource() == m_openButton) {
openMatrix();
} else if (e.getSource() == m_saveButton) {
saveMatrix();
} else if ( (e.getSource() == m_classesField)
|| (e.getSource() == m_resizeButton) ) {
try {
int newNumClasses = Integer.parseInt(m_classesField.getText());
if (newNumClasses > 0 && newNumClasses != m_matrix.size()) {
setValue(new CostMatrix(newNumClasses));
}
} catch (Exception ex) {}
}
} |
8a293731-1b9a-45b3-8595-92ab0f364d8d | 4 | private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
// TODO add your handling code here:
if (correo != null) {
int confirma = JOptionPane.showConfirmDialog(this, "¿Seguro que desea eliminar este correo?", "Confirma", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirma == 0) {
try {
if (registraCorreo.eliminarCorreoByID(correo.getId() + "")) {
JOptionPane.showMessageDialog(this, "El correo se ha eliminado.", "Correo eliminado.", JOptionPane.INFORMATION_MESSAGE);
lblCorreo.setText("");
lblOrigen.setText("");
lblGrupo.setText("");
correo = null;
}
} catch (SQLException ex) {
Logger.getLogger(VistaEliminar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}else{
JOptionPane.showMessageDialog(this, "Busca un correo primero.", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btnEliminarActionPerformed |
effae8ab-8c94-4ed4-992f-623acf9d1070 | 6 | private String seperateField(String temp)
{
String field = "";
for(int i = 1; i <= temp.length(); i++)
{
if(temp.substring(i - 1, i).equals(","))
{
break;
}
else if(temp.substring(i - 1, i).equals(">"))
{
break;
}
else
{
field = field + temp.substring(i - 1, i);
if(temp.length() == i)
{
temp = "";
}
}
}
if(field.length() > 1)
{
if(field.substring(0, 1).equals(" "))
{
field = field.substring(1);
}
}
return field;
} |
ff2fbee6-72db-4dc4-aa80-9d9bba9f352c | 4 | public static File showSaveDialog(String title) {
final ExtensionFileFilter filter = new ExtensionFileFilter();
JFileChooser Save = new JFileChooser();
JFrame frame = new JFrame();
frame.setIconImage(Program.programIcon);
if (title.compareTo(Tools.getLocalizedString(ActionType.EXPORT.name()
+ ".Name")) == 0) {
filter.setDescription(Tools.getLocalizedString("FILE_TYPE_PDF"));
filter.addExtension(".pdf");
Save.setDialogTitle(Tools.getLocalizedString(ActionType.EXPORT
.name() + ".Name"));
Save.setSelectedFile(new File(Tools.getLocalizedString("UNTITLED")
+ ".pdf"));
} else {
filter.setDescription(Tools.getLocalizedString("FILE_TYPE_KS"));
filter.addExtension(".ks");
Save.setDialogTitle(title);
Save.setSelectedFile(new File(Tools.getLocalizedString("UNTITLED")
+ ".ks"));
}
Save.setFileFilter(filter);
Save.setFileSelectionMode(JFileChooser.FILES_ONLY);
File file = null;
int result = Save.showSaveDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
file = Save.getSelectedFile();
if (file.exists()) {
Object[] options = { Tools.getLocalizedString("YES"),
Tools.getLocalizedString("NO") };
int n = JOptionPane
.showOptionDialog(
Save,
Tools.getLocalizedString("FILE_ALREADY_EXIST")
+ " "
+ file.getName()
+ " "
+ Tools.getLocalizedString("FILE_ALREADY_EXIST2"),
Tools.getLocalizedString("CONFIRM_SAVE_REPLACE"),
JOptionPane.YES_NO_OPTION,
JOptionPane.YES_NO_OPTION, null, options,
options[0]);
if (n == JOptionPane.NO_OPTION) {
file = null;
Tools.showSaveDialog(title);
}
}
}
return file;
} |
a46a55b0-72fb-4f51-8dcc-815c32809dbf | 2 | public Node getNode( int id ){
for( Node node : nodes ){
if( node.getID() == id ){
return node;
}
}
return null;
} |
f6efa46b-d558-4807-bf66-291869f1d363 | 3 | public DnDAlternativeVoteResult(List<Vote> votes, Set<Candidate> candidateSet) {
winners = new ArrayList<Option>();
List<String> winnersGUIDs = computeAVResult(votes, 42);
for (String winnerGUID : winnersGUIDs) {
for (Candidate candidate : candidateSet) {
if (winnerGUID.equals(candidate.getGUID())) {
winners.add(candidate);
break;
}
}
}
} |
c32347a7-1013-4303-9455-84c549ffd0cf | 9 | static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} |
b001f654-fcd6-4713-b4c7-a92fcba3c52a | 0 | public static void main(String[] args) {
ChocolateChip chip = new ChocolateChip();
chip.chomp();
ChocolateChipProtected chipProtected = new ChocolateChipProtected();
chipProtected.chomp();
} |
f3b8f476-686e-4020-8291-b87e471b4ad4 | 3 | public static void startRound(){
round = round + 1;
gui.initialiseRound();
letGen = new LetterGen();
while(howHardCanItBe() == false)
{
letGen = new LetterGen();
}
if(Game.round == 1){
gui.setRoundText("Let's Begin! Round 1");
}
else if(Game.round == 5){
gui.setRoundText("Last Round, Final Chance!");
gui.setNextRoundText("Finish Game");
}
else {
gui.setRoundText("ROUND " + round);
}
gui.setLetter1("" + letGen.getLetter1());
gui.setLetter2("" + letGen.getLetter2());
gui.setLetter3("" + letGen.getLetter3());
} |
a98c96aa-92da-41e7-af9e-8e6d307e3eb2 | 7 | public ArrayList<String> cbEscolhaProjetos(String codDepartamento) throws SQLException {
ArrayList<String> Projeto = new ArrayList<>();
Connection conexao = null;
PreparedStatement comando = null;
ResultSet resultado = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_SELECT_TODOS_PROJETOS_DEPARTAMENTO);
comando.setString(1, codDepartamento);
resultado = comando.executeQuery();
Projeto.removeAll(Projeto);
while (resultado.next()) {
Projeto.add(resultado.getString("NOME"));
}
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
return Projeto;
} |
56c3547c-dee0-4df1-a04a-8050be604cf1 | 1 | public static void main(String[] args) throws IOException {
StaticDynamicUncertaintyULHSolver solverWithoutADI = new StaticDynamicUncertaintyULHSolver();
StaticDynamicUncertaintyWithADIULHSolver solverWithADI = new StaticDynamicUncertaintyWithADIULHSolver();
ConstantNormalDistributedProblemGenerator problemGenerator = new ConstantNormalDistributedProblemGenerator();
EqualDivisionNormalDistributedOrdersGenerator demandGenerator = new EqualDivisionNormalDistributedOrdersGenerator(4, 0);
FileWriter fileWriter = new FileWriter(new File("results/CostEffectExperiment1a.csv"));
System.out.println("Period;Setup patterns identical;TotalCostQuotientWithoutADI;#Setups;TotalCostDifferenceWithADI;#Setups");
fileWriter.write("Period;Setup patterns identical;TotalCostQuotientWithoutADI;#Setups;TotalCostDifferenceWithADI;#Setups\n");
for (int setupCost = 5; setupCost < 7000; setupCost+=5){
NormalDistributedStochasticLotsizingProblem problem = problemGenerator.generate(20, 50.0, 25.0, setupCost*1.0, 1, 0.95f, demandGenerator);
AbstractStochasticLotSizingSolution solutionWithoutADI = solverWithoutADI.solve(problem);
AbstractStochasticLotSizingSolution solutionWithADI = solverWithADI.solve(problem);
boolean setupEqual = ArraysUtils.deepEquals(solutionWithADI.getSetupPattern(), solutionWithoutADI.getSetupPattern());
String outString = setupCost+";"+setupEqual
+";"+ (solutionWithoutADI.getTotalSetupCosts(problem)/solutionWithoutADI.getTotalInventoryCosts(problem))
+";"+ solutionWithoutADI.getNumberOfSetupPeriods()
+";"+(solutionWithADI.getTotalSetupCosts(problem)/solutionWithADI.getTotalInventoryCosts(problem))
+";"+ solutionWithADI.getNumberOfSetupPeriods();
System.out.println(outString);
fileWriter.write(outString+"\n");
}
fileWriter.close();
} |
05116925-58a3-4aed-bb13-6fb8958f1c02 | 8 | protected Collection createCollection(Class destClass) {
if (destClass == List.class || destClass == ArrayList.class) {
return new ArrayList(); // list默认为ArrayList
}
if (destClass == LinkedList.class) {
return new LinkedList();
}
if (destClass == Vector.class) {
return new Vector();
}
if (destClass == Set.class || destClass == HashSet.class) {
return new HashSet(); // set默认为HashSet
}
if (destClass == LinkedHashSet.class) {
return new LinkedHashSet();
}
if (destClass == TreeSet.class) {
return new TreeSet();
}
throw new BeanMappingException("Unsupported Collection: [" + destClass.getName() + "]");
} |
f4699c14-203b-44e6-8a52-05e8100a8a69 | 9 | public void create(Qualificador qualificador) {
if (qualificador.getQualificadorAplicacaoCollection() == null) {
qualificador.setQualificadorAplicacaoCollection(new ArrayList<QualificadorAplicacao>());
}
if (qualificador.getQualificadorProdutoCollection() == null) {
qualificador.setQualificadorProdutoCollection(new ArrayList<QualificadorProduto>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Collection<QualificadorAplicacao> attachedQualificadorAplicacaoCollection = new ArrayList<QualificadorAplicacao>();
for (QualificadorAplicacao qualificadorAplicacaoCollectionQualificadorAplicacaoToAttach : qualificador.getQualificadorAplicacaoCollection()) {
qualificadorAplicacaoCollectionQualificadorAplicacaoToAttach = em.getReference(qualificadorAplicacaoCollectionQualificadorAplicacaoToAttach.getClass(), qualificadorAplicacaoCollectionQualificadorAplicacaoToAttach.getCodigoQualificadorAplicacao());
attachedQualificadorAplicacaoCollection.add(qualificadorAplicacaoCollectionQualificadorAplicacaoToAttach);
}
qualificador.setQualificadorAplicacaoCollection(attachedQualificadorAplicacaoCollection);
Collection<QualificadorProduto> attachedQualificadorProdutoCollection = new ArrayList<QualificadorProduto>();
for (QualificadorProduto qualificadorProdutoCollectionQualificadorProdutoToAttach : qualificador.getQualificadorProdutoCollection()) {
qualificadorProdutoCollectionQualificadorProdutoToAttach = em.getReference(qualificadorProdutoCollectionQualificadorProdutoToAttach.getClass(), qualificadorProdutoCollectionQualificadorProdutoToAttach.getCodigoQualificadorProduto());
attachedQualificadorProdutoCollection.add(qualificadorProdutoCollectionQualificadorProdutoToAttach);
}
qualificador.setQualificadorProdutoCollection(attachedQualificadorProdutoCollection);
em.persist(qualificador);
for (QualificadorAplicacao qualificadorAplicacaoCollectionQualificadorAplicacao : qualificador.getQualificadorAplicacaoCollection()) {
Qualificador oldCodigoQualificadorOfQualificadorAplicacaoCollectionQualificadorAplicacao = qualificadorAplicacaoCollectionQualificadorAplicacao.getCodigoQualificador();
qualificadorAplicacaoCollectionQualificadorAplicacao.setCodigoQualificador(qualificador);
qualificadorAplicacaoCollectionQualificadorAplicacao = em.merge(qualificadorAplicacaoCollectionQualificadorAplicacao);
if (oldCodigoQualificadorOfQualificadorAplicacaoCollectionQualificadorAplicacao != null) {
oldCodigoQualificadorOfQualificadorAplicacaoCollectionQualificadorAplicacao.getQualificadorAplicacaoCollection().remove(qualificadorAplicacaoCollectionQualificadorAplicacao);
oldCodigoQualificadorOfQualificadorAplicacaoCollectionQualificadorAplicacao = em.merge(oldCodigoQualificadorOfQualificadorAplicacaoCollectionQualificadorAplicacao);
}
}
for (QualificadorProduto qualificadorProdutoCollectionQualificadorProduto : qualificador.getQualificadorProdutoCollection()) {
Qualificador oldCodigoQualificadorOfQualificadorProdutoCollectionQualificadorProduto = qualificadorProdutoCollectionQualificadorProduto.getCodigoQualificador();
qualificadorProdutoCollectionQualificadorProduto.setCodigoQualificador(qualificador);
qualificadorProdutoCollectionQualificadorProduto = em.merge(qualificadorProdutoCollectionQualificadorProduto);
if (oldCodigoQualificadorOfQualificadorProdutoCollectionQualificadorProduto != null) {
oldCodigoQualificadorOfQualificadorProdutoCollectionQualificadorProduto.getQualificadorProdutoCollection().remove(qualificadorProdutoCollectionQualificadorProduto);
oldCodigoQualificadorOfQualificadorProdutoCollectionQualificadorProduto = em.merge(oldCodigoQualificadorOfQualificadorProdutoCollectionQualificadorProduto);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} |
39e9e4c3-9e7d-4de9-9b31-b6e9c1fa0d8d | 8 | public void readFields(DataInput in) throws IOException {
String data = new String(in.readLine());
try {
String tokens[] = data.split("[=]|[\\{]|[\\}]|[,]");
if(data.indexOf("Book") != -1 || tokens.length > 0) {
for( int i = 0; i < tokens.length ; i++) {
if(tokens[i].indexOf("title") != -1)
title = tokens[i+1];
else if(tokens[i].indexOf("author") != -1)
author = tokens[i+1];
else if(tokens[i].indexOf("releaseDate") != -1)
releaseDate=tokens[i+1];
else if(tokens[i].indexOf("language") != -1)
language=tokens[i+1];
}
}
else{
logger.warn("Book:Invalid Record read " + data);
}
}
catch(Exception ex) {
logger.error("Book:Error Record read " + data);
ex.printStackTrace();
}
} |
b5789204-d255-4afc-b561-e3706c393768 | 5 | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(commandLabel.equalsIgnoreCase("whois")) {
if(sender.hasPermission("basics.command.whois.self")) {
if(args.length == 0) {
sender.sendMessage(ChatColor.GRAY + "IP: " + player.getAddress().toString());
sender.sendMessage(ChatColor.GRAY + "Display Name: " + player.getDisplayName());
sender.sendMessage(ChatColor.GRAY + "Food Level: " + player.getFoodLevel());
}else {
sender.sendMessage(ChatColor.RED + "Too few or too many arguments");
}
}
if(sender.hasPermission("basics.command.whois.other")) {
if(args.length == 1) {
sender.sendMessage(ChatColor.GRAY + "IP: " + player.getAddress().toString());
sender.sendMessage(ChatColor.GRAY + "Display Name: " + player.getDisplayName());
sender.sendMessage(ChatColor.GRAY + "Food Level: " + player.getFoodLevel());
}
}
}
return false;
} |
af026e38-f5d4-4112-a56f-3828983742dd | 5 | public static Integer getNextPort(String listenHostname, String hostname) {
String[] split = pare(listenHostname, hostname);
if(split == null) {
return null;
}
String[] split2 = split[0].split(":");
String portnum;
if(split2.length<=1) {
try {
return Integer.parseInt(split2[0]);
} catch (NumberFormatException nfe) {
return 25565;
}
} else if(split2.length == 2) {
portnum = split2[1];
} else {
return null;
}
try {
return Integer.parseInt(portnum);
} catch (NumberFormatException nfe) {
return null;
}
} |
a02fb74d-a3b4-4f13-b9d7-9746caca1be3 | 8 | @Override
public boolean hasNext() {
try {
String tmp;
this.block.delete(0, this.block.length());
do {
tmp = br.readLine();
if (null == tmp)
return false;
if (tmp.contains(" lo ") || tmp.contains(" sit0 ")) {
continue;
}
block.append(" ");
block.append(tmp);
} while (!"".equals(tmp.trim()));
if ("".equals(block.toString().trim())) {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
return false;
} else {
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
} |
f9b481e2-b672-4363-a997-2d608c479454 | 8 | public void login(boolean reconnect)
{
// ok it is a connection request
name = tf.getText().trim();
// empty username ignore it
if(name.length() == 0)
return;
// empty serverAddress ignore it
String server = tfServer.getText().trim();
if(server.length() == 0)
return;
// empty or invalid port numer, ignore it
String portNumber = tfPort.getText().trim();
if(portNumber.length() == 0)
return;
int port = 0;
try {
port = Integer.parseInt(portNumber);
}
catch(Exception en) {
return; // nothing I can do if port number is not valid
}
// try creating a new Client with GUI
client = new Client(server, port, name, this);
// test if we can start the Client
try {
if(!client.start())
return;
} catch (BadLocationException e) {
e.printStackTrace();
}
// client.start_heartbeat();
//Check gui version
// client.sendMessage(new ChatMessage(ChatMessage.VERSION, _guiVersion));
tf.setText("");
label.setText("Enter your message below");
connected = true;
// disable login button
login.setEnabled(false);
// enable the 2 buttons
logout.setEnabled(true);
whoIsIn.setEnabled(true);
Nudge.setEnabled(true);
// disable the Server and Port JTextField
tfServer.setEditable(false);
tfPort.setEditable(false);
// Action listener for when the user enter a message
tf.addActionListener(this);
lblstatus.setText("Status : Connected");
if (connected && !reconnect)
{
client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
KeepAliveClient k = new KeepAliveClient(client);
k.start();
}
} |
81821945-6409-4966-98ec-13ff2cc9bc52 | 9 | final Model method1554(boolean bool, int i) {
anInt2796++;
int i_0_ = anInt2792;
int i_1_ = anInt2767;
if (bool) {
i_1_ = anInt2775;
i_0_ = anInt2822;
}
if ((i_0_ ^ 0xffffffff) == 0)
return null;
Model class124
= Class300.createModel(0,
((ItemLoader) (((ItemDefinition) this)
.aClass255_2761)).modelIndexLoader,
i_0_);
if ((((Model) class124).anInt1830 ^ 0xffffffff) > i)
class124.method1092(2, 54);
if ((i_1_ ^ 0xffffffff) != 0) {
Model class124_2_
= Class300.createModel(0, (((ItemLoader)
((ItemDefinition) this).aClass255_2761)
.modelIndexLoader), i_1_);
if ((((Model) class124_2_).anInt1830 ^ 0xffffffff) > -14)
class124_2_.method1092(2, i ^ ~0x78);
Model[] class124s = { class124, class124_2_ };
class124 = new Model(class124s, 2);
}
if (aShortArray2777 != null) {
for (int i_3_ = 0; i_3_ < aShortArray2777.length; i_3_++)
class124.recolorTriangles(aShortArray2777[i_3_], (byte) 126,
aShortArray2771[i_3_]);
}
if (aShortArray2785 != null) {
for (int i_4_ = 0;
(aShortArray2785.length ^ 0xffffffff) < (i_4_ ^ 0xffffffff);
i_4_++)
class124.method1095(aShortArray2785[i_4_], 0,
aShortArray2801[i_4_]);
}
return class124;
} |
7da8f557-4c83-458f-9d33-9ce4ac347ba8 | 3 | public static <T extends DC> Equality getPhiEqu(Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>> done)
{ if(done!=null)
{ if(done.getNext()!=null)
{ return new Equality(done.getFst().fst().snd().delta(done.getFst().snd().snd()).equa().getValue()&&getPhiEqu(done.getNext()).getValue());
}
else
{ return new Equality(done.getFst().fst().snd().delta(done.getFst().snd().snd()).equa().getValue());
}
}
else
{ return new Equality(false);
}
} |
d3f7b8d6-bf60-4749-99a8-fdf646487333 | 5 | private boolean routeBetween(Tile a, Tile b) {
if (a == b) return false ;
//
// Firstly, determine the correct current route.
// TODO: Allow the road search to go through arbitrary Boardables, and
// screen out any non-tiles or blocked tiles?
final Route route = new Route(a, b) ;
final RoadSearch search = new RoadSearch(
route.start, route.end, Element.FIXTURE_OWNS
) ;
search.doSearch() ;
route.path = search.fullPath(Tile.class) ;
route.cost = search.totalCost() ;
//
// If the new route differs from the old, delete it. Otherwise return.
final Route oldRoute = allRoutes.get(route) ;
if (roadsEqual(route, oldRoute)) return false ;
if (verbose) {
I.say("Route between "+a+" and "+b+" has changed!") ;
this.reportPath("Old route", oldRoute) ;
this.reportPath("New route", route ) ;
}
//
// If the route needs an update, clear the tiles and store the data.
if (oldRoute != null) deleteRoute(oldRoute) ;
if (search.success()) {
allRoutes.put(route, route) ;
toggleRoute(route, route.start, true) ;
toggleRoute(route, route.end , true) ;
world.terrain().maskAsPaved(route.path, true) ;
clearRoad(route.path) ;
}
return true ;
} |
97bc5b3f-0699-4993-aff5-6f86ee1289ca | 1 | @Override
public void receiveAlert(AIAlert alert, float urgency, Hostility hostility) {
switch(alert) {
case ATTACKED:
priority = 1f;
break;
}
} |
5fca9e3e-2053-4af1-8e74-4c6abefe5871 | 7 | public static void main(String[] args){
if(args.length != 3){
System.out.println("args: id of this server, ip address of another server, ip address of database");
return;
}
Server server = null;
try {
server = new Server(Integer.parseInt(args[0]), "rmi://"+args[2]+":10001/db");
//register server to port 10001
LocateRegistry.createRegistry(10001);
//bind server object to a rmi address
Naming.bind("rmi://localhost:10001/server", server);
System.out.println("start server " + server.id);
Thread.sleep(5000);
server2 = (IConnection) Naming.lookup("rmi://"+args[1]+":10001/server");
server.leaderElection();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AlreadyBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
6211989b-349e-45c3-b4a6-25796ae62246 | 2 | public void stop(IntBuffer source) {
if(source != null)
if(AL10.alIsSource(source.get(0)))
AL10.alSourceStop(source);
} |
428136fa-c8db-4fcd-b48d-796be6c2bffb | 5 | public Request(Socket socket) {
if(socket == null){
return;
}
try {
InputStreamReader isr = new InputStreamReader(
socket.getInputStream());
BufferedReader brInput = new BufferedReader(isr);
String line = brInput.readLine();
while (line != null && !line.equals("")) {
parseLine(line);
line = brInput.readLine();
}
// Parse Content
StringBuilder requestContent = new StringBuilder();
for (int i = 0; i < contentLength; i++) {
requestContent.append((char) brInput.read());
}
parseRequestParameterFromString(requestContent.toString());
// line=brInput.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
fac17f1d-19cd-4b4e-8e49-127014889408 | 5 | public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("test2101.txt");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
SortListMaker slm = null;
try {
slm = new SortListMaker(fr);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
List list = slm.makeSortedList();
System.out.println("sorted result: ");
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
} catch (Exception e1) {
e1.printStackTrace();
}
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
1412117d-5251-487e-a8ff-c15bc1e74ba7 | 9 | Power(String name, int properties, String imgFile, String helpInfo) {
this.name = name ;
this.helpInfo = helpInfo ;
this.buttonTex = Texture.loadTexture(IMG_DIR+imgFile) ;
this.properties = properties ;
} |
a93abc86-7547-4932-8153-01bde19fdb34 | 7 | private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
b49b96ba-3181-4bbe-b3b3-04ccc12bf73e | 7 | private <T, R> Pair<ConvertType, TypeConverter<T, R>> getConvertInfo(T instance, Class<R> targetClass) {
boolean isNull = (instance == null);
if (instance != null && (targetClass.equals(instance.getClass()) || targetClass.isAssignableFrom(instance.getClass()))) {
return new Pair(ConvertType.identity, null);
}
Class sourceClass = (isNull) ? null : instance.getClass();
if (!isNull) {
TypeConverter typeConverter = converterRegistry.resolveTypeConverter(sourceClass, targetClass);
if (typeConverter != null) {
return new Pair(ConvertType.converter, typeConverter);
}
}
// now, if no type converters and if instance is null, then, the none convert type will be applied
if (instance == null) {
return new Pair(ConvertType.none, null);
}
return new Pair(ConvertType.complex, null);
} |
5e658a96-dc6c-4e72-9e44-e19bc6b70d99 | 6 | @Test
public void testPlayCvC() {
//fail("Not yet implemented");
RockPaperScissors myRPSgame = new RockPaperScissors();
assertTrue(myRPSgame.playCvC() <=2);
int battleResult=0;
int Zeroes=0, Ones=0, Twos=0, tooBig=0, tooSmall=0;
for(int i=0;i<50;i++){
battleResult=myRPSgame.playCvC();
if (battleResult<0) tooSmall++ ;
if (battleResult==0) Zeroes++ ;
if (battleResult==1) Ones++ ;
if (battleResult==2) Twos++ ;
if (battleResult>2) tooBig++ ;
}
assertTrue(tooSmall==0);
assertTrue(Zeroes>0);
assertTrue(Ones>0);
assertTrue(Twos>0);
assertTrue(tooBig==0);
} |
6eb214dd-d367-4074-b75f-5245b0897dd1 | 4 | public boolean arenaStart(Player player, String name) {
if (!this.arenas.containsKey(name)) {
player.sendMessage(ChatColor.RED + this.lang.getString("arenaStart.notContainsKey"));
return true;
}
if (this.games.containsKey(name)) {
if (this.games.get(name).hasPlayers()) {
player.sendMessage(ChatColor.RED + this.lang.getString("arenaStart.containsKey"));
return true;
} else {
this.games.remove(name);
}
}
Game game = new Game(this, this.arenas.get(name));
if (!game.hasPlayers()) {
player.sendMessage(ChatColor.RED + this.lang.getString("arenaStart.notHasPlayers"));
} else {
this.games.put(name, game);
}
return true;
} |
33fdf042-f001-48a6-a149-9e47c1d430c1 | 2 | public static void endAllOwnedBy(String owner){
for(ScheduleData data : schedules){
if(data.getOwner().equalsIgnoreCase(owner)) endSchedule(data.getScheduleID());
}
} |
0fcba815-6d69-47a1-9072-35cc170dc621 | 9 | @Override
public Command planNextMove(Info info){
int warning_radius = 300;
int danger_radius = 100;
InfoDetail next_target;
warning_zone = new Ellipse2D.Double((double)(info.getX() - warning_radius/2), (double)(info.getY() - warning_radius/2), warning_radius, warning_radius);
danger_zone = new Ellipse2D.Double((double)(info.getX() - danger_radius/2), (double)(info.getY() - danger_radius/2), danger_radius, danger_radius);
Random r = new Random();
if(info.getX() < 50 || info.getX() > GameData.GAME_WIDTH - 50){
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT, 90, CommandType.NONE);
}
if(info.getY() < 50 || info.getY() > GameData.GAME_HEIGTH - 50){
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT, 90, CommandType.NONE);
}
InfoDetail immediate_danger = null;
for(InfoDetail d : info.getGrenades()){
if(warning_zone.contains((double)d.getX(),(double) d.getY())){
if(danger_zone.contains((double)d.getX(), (double)d.getY())){
FLAG_DANGER = true;
}
else{
FLAG_DANGER = false;
}
FLAG_WARNING = true;
int deg = 90 - DegreeOfVectors(info.getX(), info.getY(), info.getDirection(),d);
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_LEFT,deg, CommandType.NONE);
}
else{
FLAG_WARNING = false;
}
/* if(immediate_danger == null){
immediate_danger = d;
}
if(Math.abs(info.getX() - immediate_danger.getX()) > Math.abs(info.getX() - d.getX()) && Math.abs(info.getY() - immediate_danger.getY()) > Math.abs(info.getY() - d.getY())){
immediate_danger = d;
}
Line2D help = new Line2D.Double(immediate_danger.getX(), immediate_danger.getY(), immediate_danger.getX() + Math.cos(Math.toRadians(immediate_danger.getDirection())) * (warning_radius + 50) ,immediate_danger.getY() + Math.sin(Math.toRadians(immediate_danger.getDirection()))* (warning_radius + 50));
if(help.intersects(warning_zone.getBounds2D())){
int deg = 90 - DegreeOfVectors(info.getX(), info.getY(), info.getDirection(),d);
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_LEFT,deg, CommandType.NONE);
}*/
}
if(info.isCanShoot() && info.getEnemies().size() > 0){
next_target = info.getEnemies().get(r.nextInt(info.getEnemies().size()));
int real_degree = DegreeOfVectors(info.getX(), info.getY(), info.getDirection(), next_target);
return new Command(CommandType.NONE, CommandType.TURN_RIGHT, real_degree, CommandType.SHOOT);
}
return new Command(CommandType.MOVE_FORWARD, CommandType.NONE, 0, CommandType.NONE);
} |
5af64ddb-f4c7-4a75-9ce2-cc893d583f7a | 7 | @Override
public void run()
{
while(finish == false)
{
//Prüfen ob der PathCollector nioch gebraucht wird
if(System.currentTimeMillis() - time > timeout)
{
stop();
}
//Neuen Weg erkunden
if(Paths.size() < maxpaths)
{
searchNewPath();
}
//Debug
System.out.println("Neuer Weg: " + Paths.size());
//Debug Ende
//Aenderungen der Welt beachten
if((numlines != Reflines.size()) || (numgoals != Refgoals.size()))
{
//Neue Welt uebernehmen
copyWorld();
//Alle Pfade auf Gueltigkeit pruefen
for(int i=Paths.size()-1; i>=0; i--)
{
//Debug
System.out.println("Weg auf gültigkeit prüfen...");
//Debug Ende
if(!Paths.elementAt(i).confirmValidity(Lines, Goals))
{
Paths.remove(i);
//Debug
System.out.println("Pfad " + i + " ist nicht mehr gültig, die Anzahl ist nun " + Paths.size());
//Debug Ende
}
}
//Aenderung der Wege bekanntmachen
changes++;
}
}
} |
b09c2736-c0dd-43e7-9faa-91566e698c15 | 8 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((action == null) ? 0 : action.hashCode());
result = prime * result
+ ((emagResource == null) ? 0 : emagResource.hashCode());
result = prime * result + ((endTime == null) ? 0 : endTime.hashCode());
result = prime * result
+ ((exception == null) ? 0 : exception.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((inputJson == null) ? 0 : inputJson.hashCode());
result = prime * result
+ ((responseJson == null) ? 0 : responseJson.hashCode());
result = prime * result
+ ((startTime == null) ? 0 : startTime.hashCode());
return result;
} |
5aac628c-0f86-4a4a-bd24-cd6db2e6c8fe | 0 | public DisplayMode getCurrentDisplayMode() {
return device.getDisplayMode();
} |
b223072f-f6e3-4d93-a155-5c6f3370ff19 | 6 | public void update(){
move();
action();
checkLasers();
if(health<=0) {
alive = false;
if (this instanceof Minions) {
for(int q=0;q<objects.size();q++){
if(objects.get(q)==parent&&kind==1){
parent.count--;
}
}
}
} else if (health>maxhealth){
health=maxhealth;
}
} |
a2a92e99-b01d-4de6-858b-67cc64c23816 | 3 | @Override
public void applyEffect(Joueur jou){
jou.setPositionCourante(super.getMonopoly().getCarreau(11));
jou.setToursPrison(4);
if(jou.getLiberationPrison()){
Scanner sc = new Scanner(System.in);
System.out.printf("Vous possédez une carte Libération de Prison. Voulez-vous l'utiliser ? (y/n)");
String reponse = sc.nextLine();
if(reponse == "y"){
jou.setLiberationPrison(false);
jou.setToursPrison(0);
}
else if(reponse == "n"){
}
else{
System.out.printf("Reponse invalide");
}
}
} |
28318914-709f-47d1-92f2-e039dcfb9f0c | 7 | @Override
public Item peekFirstItem()
{
if(packageText().length()==0)
return null;
final List<XMLLibrary.XMLTag> buf=CMLib.xml().parseAllXML(packageText());
if(buf==null)
{
Log.errOut("Packaged","Error parsing 'PAKITEM'.");
return null;
}
final XMLTag iblk=CMLib.xml().getPieceFromPieces(buf,"PAKITEM");
if((iblk==null)||(iblk.contents()==null))
{
Log.errOut("Packaged","Error parsing 'PAKITEM'.");
return null;
}
final String itemi=iblk.getValFromPieces("PICLASS");
final Environmental newOne=CMClass.getItem(itemi);
final List<XMLLibrary.XMLTag> idat=iblk.getContentsFromPieces("PIDATA");
if((idat==null)||(newOne==null)||(!(newOne instanceof Item)))
{
Log.errOut("Packaged","Error parsing 'PAKITEM' data.");
return null;
}
CMLib.coffeeMaker().setPropertiesStr(newOne,idat,true);
return (Item)newOne;
} |
081594e5-e94a-4465-ab25-11bb5823ef30 | 2 | public List<Octo> getAll() {
List<Octo> result = new ArrayList<Octo>();
for(EntityBase ent: db.getItems())
{
if(ent instanceof Octo)
result.add((Octo)ent);
}
return result;
} |
211f9c8f-51b6-4003-809a-4c45bdd6a143 | 4 | public void computeIORatio() {
long fInputKeyValuePairsNum = 0;
long fOutputKeyValuePairsNum = 0;
long fInputBytes = 0;
long fOutputBytes = 0;
for(Reducer fr : finishedReducerList) {
Reduce reduce = fr.getReduce();
fInputKeyValuePairsNum += reduce.getInputKeyValuePairsNum();
fOutputKeyValuePairsNum += reduce.getOutputKeyValuePairsNum();
fInputBytes += reduce.getInputBytes();
fOutputBytes += reduce.getOutputBytes();
}
if(fInputKeyValuePairsNum == 0) {
recordsIoRatio = 0;
bytesIoRatio = 0;
}
else {
recordsIoRatio = (double) fOutputKeyValuePairsNum / fInputKeyValuePairsNum;
bytesIoRatio = (double) fOutputBytes / fInputBytes;
}
} |
5a2bc5b6-e7a8-4047-80e0-b105b98e7b80 | 2 | public static ActiveDeactiveType valOf(Character val) throws Exception {
if (val.equals(Active.getVal())) {
return Active;
} else if (val.equals(Inactive.getVal())) {
return Inactive;
}
throw new Exception("Kode tidak terdaftar");
} |
d739d339-3939-4242-aecc-3c70fcda3d98 | 1 | public static void debug() {
try
{
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
f386f940-93b2-4c17-be1b-0202fac8b24a | 7 | public void merge(Pair p, int ind) {
edges.remove(ind);
/*int xxx = ind;
while (xxx >= 0) {
edges.remove(xxx);
xxx = edges.indexOf(p);
}*/
Iterator<Pair> it = edges.iterator();
while (it.hasNext()) {
Pair n = it.next();
if (p.v2 == n.v1 || p.v2 == n.v2) {
if (p.v2 == n.v1) {
int has = edges.indexOf(new Pair(p.v1, n.v2));
if (has >= 0) {
Pair existed = edges.get(has);
existed.num += n.num;
it.remove();
} else {
n.v1 = p.v1;
}
} else if (p.v2 == n.v2) {
int has = edges.indexOf(new Pair(p.v1, n.v1));
if (has >= 0) {
Pair existed = edges.get(has);
existed.num += n.num;
it.remove();
} else {
n.v2 = p.v1;
}
}
}
}
} |
a6775b54-f60b-4ba3-82ab-831c8d23d01a | 1 | public void setAvailability(Date dateAt, Object val) {
// check, if date is already existing
RosterAvailability r = checkAvailability (dateAt);
if (r == null) {
rosterAvailability.add(new RosterAvailability (dateAt.getTime(), (int)val));
rosterChangeSupport.firePropertyChange("rosterAvailability", null, val);
}
else {
Integer oldVal = r.getAvailabilityCode();
r.setAvailabilityCode ((int)val);
rosterChangeSupport.firePropertyChange("rosterAvailability", oldVal, val);
}
} |
8645b92c-ca66-4fb8-a6d2-667899a4e09a | 1 | public static CtMethod wrapped(CtClass returnType, String mname,
CtClass[] parameterTypes,
CtClass[] exceptionTypes,
CtMethod body, ConstParameter constParam,
CtClass declaring)
throws CannotCompileException
{
CtMethod mt = new CtMethod(returnType, mname, parameterTypes,
declaring);
mt.setModifiers(body.getModifiers());
try {
mt.setExceptionTypes(exceptionTypes);
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
Bytecode code = makeBody(declaring, declaring.getClassFile2(), body,
parameterTypes, returnType, constParam);
mt.getMethodInfo2().setCodeAttribute(code.toCodeAttribute());
return mt;
} |
d9b7deee-beb4-4040-83ec-11fd05c520b0 | 9 | static boolean isStandardProperty(Class clazz) {
return clazz.isPrimitive() ||
clazz.isAssignableFrom(Byte.class) ||
clazz.isAssignableFrom(Short.class) ||
clazz.isAssignableFrom(Integer.class) ||
clazz.isAssignableFrom(Long.class) ||
clazz.isAssignableFrom(Float.class) ||
clazz.isAssignableFrom(Double.class) ||
clazz.isAssignableFrom(Character.class) ||
clazz.isAssignableFrom(String.class) ||
clazz.isAssignableFrom(Boolean.class);
} |
58959b70-7394-45e4-b69c-fcb7c1ec198f | 2 | public static String getConcatedString(ArrayList<String> strings) {
String retString = new String();
for (int i = 0; i < strings.size(); i++) {
if (i > 0)
retString = retString + "&&&";
retString = retString + strings.get(i);
}
return retString;
} |
39720c31-12ec-4f3f-b973-e9e8fb04a4c1 | 1 | @Override
public void show(){
for (T item : getHistogram().keySet()) {
System.out.println(item + " " + getHistogram().get(item));
}
} |
806af72f-362b-43fe-b850-f362bc23a6ef | 2 | @Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
return null;
} |
c1dbe3f4-d5e8-4a4a-a35d-3504e44beb84 | 3 | public void AddChild(int id, int i, RoomItem Child)
{
if (i < 1)
{
for (int i_ = 0; i_ < MAX_CHILDS_PER_WIRED; i_++)
{
Items[id][i_] = null;
}
}
if (Child == null) return;
Items[id][i] = Child;
ItemOriginal_ExtraData[id][i] = Child.ExtraData;
ItemOriginal_X[id][i] = Child.X;
ItemOriginal_Y[id][i] = Child.Y;
ItemOriginal_Z[id][i] = Child.Z;
ItemOriginal_Rot[id][i] = Child.Rot;
ItemOriginal_WallPos[id][i] = Child.WallPos;
} |
63727c60-7257-48fa-bc59-080cb7b435f2 | 5 | public String sellStock(Stock st, int numShares){
portfolio = qs.qsort(portfolio, 0); // 0 sorts by ticker name, handy when printing
int index = -1;
// check if they already own some shares in that stock
String searchedTicker = st.getTicker();
// traverse until ticker is found in portfolio
for (int i = 0; i < portfolio.size(); i++){
StockPosition temp = portfolio.get(i);
String tempTicker = temp.getTicker();
if (tempTicker.equals(searchedTicker)){ // this is the index of that ticker in portfolio
index = i;
break;
}
}
if (index == -1)
return "Invalid stock";
else if (portfolio.get(index).getNumShares() < numShares)
return "You do not own sufficient shares";
else{
portfolio.get(index).sellShares(numShares);
money += st.getPrice() * numShares;
if (portfolio.get(index).getNumShares() <= 0)
portfolio.remove(index);
return "Sold " + numShares + " shares";
}
} |
384f13b7-c68d-46cd-853b-8e394e13033c | 5 | public String buscarClientePorFecha(String fecha){
//##########################CARGA_BASE DE DATOS#############
tablaDeClientes();
//##########################INGRESO_VACIO###################
if(fecha.equals("")){
fecha = "No busque nada";
return resultBusqueda = "Debe ingresar datos a buscar";
}
int longitud = datos.size();
for(int i = 0; i<longitud;i++){
String FechaBuscado = datos.get(i).getContact_date();
if (FechaBuscado.equals(fecha)){
db_Temp.add(datos.get(i));
resultBusqueda = datos.get(i).getContact_date();
}
}
if (db_Temp.size()>0){
for (int j=0; j<db_Temp.size();j++){
System.out.println("SU BÚSQUEDA POR FECHA DE CONTACTO MUESTRA LOS SIGUIENTES RESULTADOS\t" + "\n");
mostrar(j);
}
}else{
resultBusqueda = "No se encontraron registros para los filtros ingresados";
}
return resultBusqueda;
} |
4b7a9513-30a1-4091-972a-da3042b99915 | 0 | public static void main(String[] args)
{
FrameWithPanel frame = new FrameWithPanel("This is Frame With Panel !");
Panel panel = new Panel();
frame.setSize(200, 200);
frame.setBackground(Color.BLUE);
frame.setLayout(null);
panel.setSize(100, 100);
panel.setBackground(Color.CYAN);
frame.add(panel);
frame.setVisible(true);
} |
1d531d5c-59f7-4f17-b800-750e0d597881 | 8 | final public Expression IntExpression() throws ParseException {
final Variable v;
final String s;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case VARIABLE:
v = Variable();
{if (true) return new VariableExpression(v);}
break;
case STRING_END:
case INTEGER:
case FLOAT:
case CHARACTER:
s = IntString(IN_INTEGER);
{if (true) return new IntExpression(s);}
break;
default:
jj_la1[48] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
} |
5808aba7-09d1-4775-94fa-b9100657bbcd | 5 | public long Problem3() {
long n=Long.parseLong("600851475143");
long maior=0;
while(n!=1) {
int i=2;
while (i<=n) {
if (Utility.isPrime(i) && n%i==0) {
if (i>maior) {
maior = i;
}
n/=i;
break;
}
i++;
}
}
return maior;
} |
a5229828-957b-405e-ac38-8bb9947aed00 | 0 | @Override
public boolean isConverted() {
// TODO Auto-generated method stub
return false;
} |
7901b0e6-3f5f-4f1b-8684-38b562d26ca9 | 1 | public AbstractTab() {
createContent();
Settings s = Settings.getInstance();
timestampFormat = "";
if ( s.isViewEnabled("timestamp-enabled") )
timestampFormat = s.getViewTimestampFormat();
isChatLoggingEnabled = s.isEventEnabled("log-chat");
} |
38bf9daf-76ee-4fef-ad9e-3164160cad5c | 4 | public static void reverse(int[] arr, int from, int to){
//determine the number of swaps
int iters=0;
if(from>to){
iters=((arr.length-from)+to+1)/2;
} else {
iters=(to-from+1)/2;
}
//do the swaps
while(iters>0){
swap(arr,from,to);
iters--;
//update indexes
from++;
to--;
//check for wrap around
if(from>=arr.length){ from=0; }//increment with wraparound
if(to<0){ to=arr.length-1; }//decrement with wraparound
}
} |
66888a4e-7497-47cd-b121-efc989789bd4 | 1 | @SuppressWarnings("deprecation")
public void testConstructor_RP_RP_PeriodType5() throws Throwable {
YearMonthDay dt1 = null;
YearMonthDay dt2 = null;
try {
new Period(dt1, dt2, PeriodType.standard());
fail();
} catch (IllegalArgumentException ex) {}
} |
027d5a7c-ccbb-4bea-8922-9d3c8d1a759a | 3 | public String toString(){
String str = (aluno != null ? aluno.toString() : "");
str += (getMedia() != null ? " " + getMedia().toString() : "");
str += (getSituacao() != null ? " " + getSituacao() : "");
return str;
} |
f78e0829-a942-44d7-adf2-ebf9af8b4c81 | 6 | public TableModel obtenerResumenMembresiasDB(int ano, String mes) {
Connection conn = null;
Statement stmt = null;
String query = "SELECT TC.IDCLIENTE, NOMBRE, FECHA_INICIO, DURACION, "
+ "DESCRIPCION, PRECIO FROM GYMDB.CLIENTES TC JOIN "
+ "GYMDB.MEMBRESIAS AS TM ON TC.IDCLIENTE = TM.IDCLIENTE WHERE "
+ "FECHA_INICIO LIKE '" + ano + "-" + mes + "-%'";
ResultSet rs = null;
try {
conn = conectar(conn);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
int numCols = metaData.getColumnCount();
Vector nombresCols = new Vector();
// Get the column names
for (int column = 0; column < numCols; column++) {
nombresCols.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numCols; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, nombresCols);
} catch (SQLException se) {
System.out.println("Error: " + se);
return null;
} finally {
try {
stmt.close();
} catch (SQLException ex) {
System.out.println(ex);
}
try {
conn.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
} |
442dcbc5-f36f-4caa-a684-bf237cbe5206 | 7 | final void method80(int i) {
if (Class184.aBoolean2469)
Class318_Sub1_Sub2.writeScriptSettings(i + -110);
anInt5170++;
Class59_Sub1_Sub1.method556(false);
if (Class348_Sub8.currentToolkit != null)
Class348_Sub8.currentToolkit.destroy();
if (Class34.aFrame476 != null) {
LoadingStage.method527(Class34.aFrame476,
Class348_Sub23_Sub1.signlink, false);
Class34.aFrame476 = null;
}
if (Class348_Sub40_Sub8.gameConnection != null) {
Class348_Sub40_Sub8.gameConnection.method1700((byte) 36);
Class348_Sub40_Sub8.gameConnection = null;
}
ModelPolygon.method1265(16);
Class348_Sub4.ondemandWorker.resetSocket(i ^ ~0x44);
Class39.aClass112_520.method1051(true);
if (Class76.aClass169_1286 != null) {
Class76.aClass169_1286.method1303((byte) 16);
Class76.aClass169_1286 = null;
}
try {
Class299_Sub2.mainIndexBufferedFile.method790((byte) -62);
for (int i_6_ = i; i_6_ < 37; i_6_++)
Class100.bufferedCacheFiles[i_6_].method790((byte) 118);
Class235.tableIndexBufferedFile.method790((byte) -84);
Class374.randomDatBufferedFile.method790((byte) 80);
Class348_Sub46.method3317((byte) -53);
} catch (Exception exception) {
/* empty */
}
} |
ee9bc807-48dd-4731-810c-bfdc2dd93758 | 2 | @Override
public String toString() {
if (reversed) {
reverse();
}
Element tmp = firstElement;
String result = "";
while (tmp != null) {
result += tmp.getValue() + " ";
tmp = tmp.getNextElement();
}
return result;
} |
68208bb2-8e8a-4b53-9c45-2845bc3b4b2e | 8 | public boolean containsTree(Node<T> root, Node<T> otherRoot) {
if(root ==null || otherRoot ==null){
return false;
}
if(root.data.compareTo(otherRoot.data)==0){
if(matchTree(root,otherRoot,false)){
return true;
}
}
if(root.left!=null){
if(containsTree(root.left,otherRoot)){
return true;
}
}
if(root.right!=null) {
if(containsTree(root.right,otherRoot)){
return true;
}
}
return false;
} |
41bb46c8-fdd3-46b1-a4ad-053a83c2c382 | 2 | public Point getRoute(int x, int y)
{
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return route[y][x];
} |
3c986af1-b8a6-490d-a5c9-c6eeb4c381f4 | 0 | public void makeInactive() {
this.setBorder(BorderFactory.createEmptyBorder());
this.setDefaultBackgroundColor();
} |
2592b19d-2ced-4fe5-a0ad-d1e3075531ae | 0 | public static boolean mouseButtonState(int button) {
return mouseState[button - 1];
} |
f66eb803-27cf-4c5e-a77f-a7cf52676a04 | 8 | private void forward(int[] sequence, double[][] fwd, double[] scaling) {
int T = sequence.length;
int S = this.getNumberOfStates();
double[] pi = this.pi;
double[][] a = this.a;
double[][] b = this.b;
// 1. Initialization
scaling[0x00] = 0.0d;
for (int i = 0; i < S; i++) {
double fwdi = pi[i] * b[i][sequence[0]];
fwd[0][i] = fwdi;
scaling[0] += fwdi;
}
if (scaling[0] > 0.0) { // Scaling
double sc = 1.0d / scaling[0x00];
for (int i = 0; i < S; i++) {
fwd[0][i] *= sc;
}
}
// 2. Induction
for (int t = 1; t < T; t++) {
scaling[t] = 0.0d;
for (int i = 0; i < S; i++) {
double p = b[i][sequence[t]];
double sum = 0.0;
for (int j = 0; j < S; j++) {
sum += fwd[t - 1][j] * a[j][i];
}
sum *= p;
fwd[t][i] = sum;
scaling[t] += sum;// scaling coefficient
}
if (scaling[t] > 0.0) { // Scaling
double sc = 1.0d / scaling[t];
for (int i = 0; i < S; i++) {
fwd[t][i] *= sc;
}
}
}
} |
1433b287-6557-4dfe-be94-b8d57521479a | 1 | public int getPriority() {
return postfix ? 800 : 700;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.