method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
5aa5f148-fc7b-4b37-b302-5b5dd56131dc | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TabelKeyAccount other = (TabelKeyAccount) obj;
if (!Objects.equals(this.kodeKa, other.kodeKa)) {
return false;
}
return true;
} |
6013fe44-16ea-4ecb-b45a-4e1bdd1693e7 | 8 | static void lengthLimitedCodeLengths(Cookie cookie, int[] frequencies, int maxBits,
int[] bitLengths) {
cookie.resetPool();
int n = frequencies.length;
int nn = 0;
Node[] leaves = cookie.leaves1;
for (int i = 0; i < n; i++) {
if (frequencies[i] != 0) {
leaves[nn] = cookie.node(frequencies[i], i, null);
nn++;
}
}
if (nn == 0) {
return;
}
if (nn == 1) {
bitLengths[leaves[0].count] = 1;
return;
}
Node[] leaves2 = cookie.leaves2;
System.arraycopy(leaves, 0, leaves2, 0, nn);
sort(leaves2, leaves, 0, nn);
Node[] list0 = cookie.list0;
Node node0 = cookie.node(leaves[0].weight, 1, null);
Node[] list1 = cookie.list1;
Node node1 = cookie.node(leaves[1].weight, 2, null);
for (int i = 0; i < maxBits; ++i) {
list0[i] = node0;
list1[i] = node1;
}
int numBoundaryPmRuns = 2 * nn - 4;
for (int i = 0; i < numBoundaryPmRuns; i++) {
boolean last = i == numBoundaryPmRuns - 1;
boundaryPm(cookie, leaves, list0, list1, nn, maxBits - 1, last);
}
for (Node node = list1[maxBits - 1]; node != null; node = node.tail) {
for (int i = node.count - 1; i >= 0; --i) {
bitLengths[leaves[i].count]++;
}
}
} |
94c2841e-ac22-4cc0-bac9-eed60d257033 | 0 | @Id
@GeneratedValue
public int getId() {
return id;
} |
ff8840a1-e63c-4f43-a3a6-fa06e56a0e91 | 0 | public int getGraphX() {
return graphX;
} |
5d64f762-1cd2-4203-ad32-0901764111df | 3 | public boolean load(String audiofile) {
try {
setFilename(audiofile);
sample = AudioSystem.getAudioInputStream(getURL(filename));
clip.open(sample);
return true;
} catch (IOException e) {
return false;
} catch (UnsupportedAudioFileException e) {
return false;
} catch (LineUnavailableException e) {
return false;
}
} |
4cf26eab-512d-4cbb-b855-add113de64c2 | 1 | @SuppressWarnings("unchecked")
private static final Object[] decodeList(byte[] bencoded_bytes, int offset) throws BencodingException
{
ArrayList list = new ArrayList();
offset++;
Object[] vals;
while(bencoded_bytes[offset] != (byte)'e')
{
vals = decode(bencoded_bytes,offset);
offset = ((Integer)vals[0]).intValue();
list.add(vals[1]);
}
offset++;
return new Object[] {new Integer(offset), list};
} |
dd67c726-2052-4fdf-92bd-b6c7483531d4 | 1 | public ArrayList<Integer> encodage(String motACoder)
{
tailleMot = motACoder.length();
trieTableur(motACoder);
ArrayList<Integer> code = new ArrayList<Integer>();
//Ajout de la position du mot de depart
//code.add(String.valueOf(positionChaine).charAt(0));
leCode = positionChaine +"";
//Ajout de chaque dernier caractere de chaque ligne du tableur
for(ArrayList<Integer> mot : tableurTrie)
{
leCode += mot.get(tailleMot-1);
code.add(mot.get(tailleMot-1));
}
return code;
} |
08e80458-95c3-451f-8d84-3c9647ea47bc | 4 | public boolean createLocalRC()
{
// if a local RC already exists
if (localRC_ != null)
{
System.out.println(super.get_name() + ".setLocalRC(): Warning - " +
"a local Replica Catalogue entity already exists.");
return false;
}
// if a RC has already assigned/allocated for this resource
if (rcID_ != -1 || super.output == null)
{
System.out.println(super.get_name() + ".setLocalRC(): Warning - " +
"a regional Replica Catalogue entity is already allocated " +
"to this resource.");
return false;
}
boolean result = false;
try
{
String name = super.get_name() + "_localRC";
localRC_ = new RegionalRC(name, super.get_id(), super.output);
// RM has to be aware that the RC is now on the local site
replicaManager_.setReplicaCatalogue( super.get_id() );
rcID_ = super.get_id();
result = true;
}
catch (Exception e) {
result = false;
}
return result;
} |
dcee829d-6644-494a-b303-2f0471165a14 | 5 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// Create Offer
try {
if (jTextField1.getText().trim().equals(jTextField3.getText().trim())) {
JOptionPane.showMessageDialog(this, "Asset and currency type id cannot be same", "Asset validation", JOptionPane.ERROR_MESSAGE);
return;
}
if (jTextField2.getText().trim().equals(jTextField4.getText().trim())) {
JOptionPane.showMessageDialog(this, "Asset and currency account id cannot be same", "Asset account validation", JOptionPane.ERROR_MESSAGE);
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int selling = 1;
if (jComboBox3.getSelectedItem().toString().equals("Buy")) {
selling = 0;
}
boolean status = Market.createOrder(serverID, nymID, jTextField1.getText(), jTextField2.getText(), jTextField3.getText(), jTextField4.getText(), jTextField5.getText(), jTextField6.getText(), jTextField7.getText(), jTextField8.getText(), selling);
setCursor(Cursor.getDefaultCursor());
if (status) {
JOptionPane.showMessageDialog(this, "Order created successfully", "Order Creation", JOptionPane.INFORMATION_MESSAGE);
Helpers.longDelay();
MainPage.refreshMarketOfferList(serverID, nymID);
// DEBUGGING: The above call is what happens after the order creation.
} else {
JOptionPane.showMessageDialog(this, "Order cannot be created", "Order Creation", JOptionPane.ERROR_MESSAGE);
}
this.dispose();
} catch (Exception e) {
e.printStackTrace();
} finally {
setCursor(Cursor.getDefaultCursor());
}
}//GEN-LAST:event_jButton1ActionPerformed |
2994ba3d-3c9d-4234-ae97-bee75c912e38 | 6 | public static void main(String[] args)
{
// Load frame from disk
byte[] frameBytes = new Frame("data/token.plain").bytes;
// Setup analyzers
List<AbstractAnalyzer> analyzers = new LinkedList<>();
analyzers.add(new StringAnalyzer());
analyzers.add(new TimestampAnalyzer());
// Run analyzers
for (AbstractAnalyzer analyzer : analyzers)
{
analyzer.setBytes(frameBytes);
analyzer.analyze();
}
// Print output with byte map
StringBuilder output = new StringBuilder();
output.append("Analyzed frame with ").append(frameBytes.length).append(" bytes. Map:");
for (int i = 0; i < frameBytes.length; i++)
{
boolean marked = false;
if (i % BYTEMAP_LINE_SIZE == 0)
{
output.append("\n").append(i).append(": ");
}
for (AbstractAnalyzer analyzer : analyzers)
{
if (analyzer.getMark(i) != null)
{
output.append(analyzer.getMark(i));
marked = true;
}
}
if (!marked)
{
output.append("_");
}
}
System.out.println(output);
} |
5b6fc52a-3e5f-4236-ae30-db00c4c74824 | 5 | protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
if (tabPane.isRequestFocusEnabled() && tabPane.hasFocus() && isSelected && tabIndex >= 0 && textRect.width > 8) {
g.setColor(AbstractLookAndFeel.getTheme().getFocusColor());
BasicGraphicsUtils.drawDashedRect(g, textRect.x - 4, textRect.y + 1, textRect.width + 8, textRect.height);
}
} |
912b8221-6e26-4047-b6bc-c27c06ba48e4 | 8 | public final String toString() {
final StringBuffer result = new StringBuffer();
boolean comma = false;
result.append("\n[");
for (Method method : this.getClass().getMethods()) {
final String methodName = method.getName();
if ((methodName.startsWith("get") || methodName.startsWith("is"))
&& !methodName.startsWith("getClass")) {
result.append(comma ? ", " : "");
comma = true;
result.append(methodName.startsWith("is") ? methodName
.substring(2) : methodName.substring(3));
result.append(":");
try {
final Object obj = method.invoke(this, null);
result.append(obj != null ? obj : "null");
} catch (Exception e) {
result.append("null(E)");
LOGGER.error(e.getLocalizedMessage(),e);
}
}
}
result.append("]");
return result.toString();
} |
dd29ec97-c5db-407c-9cb3-b3d7208b9d37 | 6 | @Override
public void actionPerformed(ActionEvent ae) {
if(currX == newX && currY == newY)
timer.stop();
// Check for infinite slope
if(newX != currX) {
slope = (newY - currY) / (newX - currX);
// Moving to the left
if(newX < currX) {
currX--;
currY -= slope;
}
// Moving to the right
else if(newX > currX) {
currX++;
currY += slope;
}
}
else {
if(currY < newY)
currY++;
else
currY--;
}
this.setBounds((int)currX, (int)currY, 50, 50);
this.repaint();
this.revalidate();
} |
e3a55e32-80d6-4e65-a857-623336bcbf2e | 8 | @Override
public void swapRaces(Race newR, Race oldR)
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room room=e.nextElement();
for(int i=0;i<room.numInhabitants();i++)
{
final MOB M=room.fetchInhabitant(i);
if(M==null)
continue;
if(M.baseCharStats().getMyRace()==oldR)
M.baseCharStats().setMyRace(newR);
if(M.charStats().getMyRace()==oldR)
M.charStats().setMyRace(newR);
}
for(final Enumeration<MOB> e2=CMLib.players().players();e2.hasMoreElements();)
{
final MOB M=e2.nextElement();
if(M.baseCharStats().getMyRace()==oldR)
M.baseCharStats().setMyRace(newR);
if(M.charStats().getMyRace()==oldR)
M.charStats().setMyRace(newR);
}
}
} |
4637e127-5dc1-4578-931f-f01640db9ec8 | 6 | @Override
public Iterator<BxTreeEntry> find(final int key, final boolean includeKey) {
int size = getSize();
if(size == 0) {
return Utils.emptyIterator();
}
return new Iterator<BxTreeEntry>() {
private LeafNode nextNode = LeafNode.this;
private Iterator<BxTreeEntry> currentBaseIter = null;
private BxTreeEntry val = getNext();
@Override
public boolean hasNext() {
return val != null;
}
private BxTreeEntry getNext() {
while(currentBaseIter == null || !currentBaseIter.hasNext()) {
if(nextNode == null) {
return null;
}
currentBaseIter = nextNode.baseFind(key, includeKey);
int nextNodePage = nextNode.getLink();
nextNode = nextNodePage == 0 ? null : new LeafNode(nextNodePage, bm);
}
return currentBaseIter.next();
}
@Override
public BxTreeEntry next() {
if(!hasNext()) {
throw new IllegalStateException();
}
BxTreeEntry old = val;
val = getNext();
return old;
}
@Override
public void remove() {
throw new RuntimeException();
}
};
} |
64743ad0-07c8-444b-95be-5bf38a364a47 | 1 | @Override
public String getDataAsText(Column column) {
switch (column.getID()) {
case 0:
return getName();
default:
return getSecond();
}
} |
c285f7e4-13cc-4e1a-aef7-63182d31e245 | 0 | public Grafika produkujemyGrafike(){
return new GrafikaDlaLaptopa();
} |
7038fa0d-0f85-4fde-9631-71c7f1570726 | 5 | private boolean receiveDataGridlet(DataGridlet dg) {
if (dg == null) {
return false;
}
// get a list of required files
LinkedList list = (LinkedList) (dg.getRequiredFiles()).clone();
int serviceLevel = dg.getNetServiceLevel(); // get priority
// for each file, check whether it is available or not
for (int i = 0; i < list.size(); i++) {
String filename = (String) list.get(i); // get file name
// if the file is already on the local storage, the
// transfer from a remote site is not needed
if (contains(filename)) {
dg.deleteRequiredFile(filename); // delete from the list
}
// if the file is not available, then make a replica request
else {
// if the file should have higher QoS
if (serviceLevel == 1) {
priorityFile_.add(filename);
}
Object[] packet = new Object[2];
packet[0] = filename;
packet[1] = super.resIdObj_;
sim_schedule(outputPort_, 0, DataGridTags.CTLG_GET_REPLICA,
new IO_data(packet, DataGridTags.PKT_SIZE, super.rcID_));
}
}
// if all files are available locally
if (dg.getRequiredFiles().size() == 0) {
dg.setResourceParameter(super.resourceID_, 0);
policy_.gridletSubmit(dg, false); // start executing this job
} else { // otherwise, put into the queue
waitingDataGridlet_.add(dg);
}
return true;
} |
3d7c66ff-58e0-47a2-9113-7a9bbeda3ecb | 3 | public static String convertLineEndings(String text) {
if (line_ending.equals("unix")) {
return convertToUnix(text);
} else if (line_ending.equals("pc")) {
return convertToPC(text);
} else if (line_ending.equals("mac")) {
return convertToMac(text);
} else {
return text;
}
} |
cc8ea14c-6ccf-4b54-aa24-65a64a440d7a | 2 | public static Image convert(Image image) {
if (image.isRgb())
return convertToHsv((RgbImage) image);
else if (image.isHsv())
return convertToRgb((HsvImage)image);
return null;
} |
95631331-686e-44a3-8472-b8cf3b39d833 | 6 | public void removeEntry(Stella_Object key, Stella_Object value) {
{ KeyValueList self = this;
{ KvCons cursor = self.theKvList;
KvCons previouscursor = null;
if (cursor != null) {
if (Stella_Object.eqlP(cursor.key, key) &&
Stella_Object.eqlP(cursor.value, value)) {
self.theKvList = cursor.rest;
KvCons.freeKvCons(cursor);
return;
}
while (cursor.rest != null) {
previouscursor = cursor;
cursor = cursor.rest;
if (Stella_Object.eqlP(cursor.key, key) &&
Stella_Object.eqlP(cursor.value, value)) {
previouscursor.rest = cursor.rest;
KvCons.freeKvCons(cursor);
return;
}
}
}
}
}
} |
99053034-af4e-4287-9490-74684a93f5b0 | 0 | public Route getRoute() {
return this._route;
} |
1b9a975f-c7ac-4e1d-9b71-b3c378fbb8f7 | 3 | void doReceive(final File file, final boolean resume) {
new Thread() {
public void run() {
BufferedOutputStream foutput = null;
Exception exception = null;
try {
// Convert the integer address to a proper IP address.
int[] ip = _bot.longToIp(_address);
String ipStr = ip[0] + "." + ip[1] + "." + ip[2] + "." + ip[3];
// Connect the socket and set a timeout.
_socket = new Socket(ipStr, _port);
_socket.setSoTimeout(30*1000);
_startTime = System.currentTimeMillis();
// No longer possible to resume this transfer once it's underway.
_manager.removeAwaitingResume(DccFileTransfer.this);
BufferedInputStream input = new BufferedInputStream(_socket.getInputStream());
BufferedOutputStream output = new BufferedOutputStream(_socket.getOutputStream());
// Following line fixed for jdk 1.1 compatibility.
foutput = new BufferedOutputStream(new FileOutputStream(file.getCanonicalPath(), resume));
byte[] inBuffer = new byte[BUFFER_SIZE];
byte[] outBuffer = new byte[4];
int bytesRead = 0;
while ((bytesRead = input.read(inBuffer, 0, inBuffer.length)) != -1) {
foutput.write(inBuffer, 0, bytesRead);
_progress += bytesRead;
// Send back an acknowledgement of how many bytes we have got so far.
outBuffer[0] = (byte) ((_progress >> 24) & 0xff);
outBuffer[1] = (byte) ((_progress >> 16) & 0xff);
outBuffer[2] = (byte) ((_progress >> 8) & 0xff);
outBuffer[3] = (byte) ((_progress >> 0) & 0xff);
output.write(outBuffer);
output.flush();
delay();
}
foutput.flush();
}
catch (Exception e) {
exception = e;
}
finally {
try {
foutput.close();
_socket.close();
}
catch (Exception anye) {
// Do nothing.
}
}
_bot.onFileTransferFinished(DccFileTransfer.this, exception);
}
}.start();
} |
d4e8fbee-c5e9-49ff-9841-8866041b9408 | 2 | public DataBase(){
this.driver = "org.apache.derby.jdbc.EmbeddedDriver";
this.url = "jdbc:derby:"+db_name+";create="+create+";user="+user+";password="+pass;
try{
Class.forName(driver);
this.con = DriverManager.getConnection(this.url);
if(create.equalsIgnoreCase("true"))
this.createDatabase();
}
catch(SQLException | ClassNotFoundException e){
}
} |
c516fbd6-16ed-4bf4-84ce-af5fc276ebe7 | 5 | public String recieveMsg(String msg) {
if(msg.contains(LOGIN) || msg.contains(REGIS)) {
String[] authentication = msg.split(",");
if(authentication[0].equalsIgnoreCase(LOGIN)) {
if(authentication.length == 3) return authentication(authentication[1], authentication[2]);
else return "LOGIN_FAILED";
}else {
return registration(authentication[1], authentication[2]);
}
}else if(msg.contains(VOTE)) {
//VOTE : criteria_id1,project_name1
//#
//POINT : project_id1,point1 : project_id2,point2
//#
//username
String[] temp_msg = msg.split("#");
String username = temp_msg[2];
//User who vote ---- VOTE : criteria_id1,project_name1-----------------------------------
User user = user_dao.findUserByName(username);
// Vote for Ballot
voteForBallot(temp_msg[0], user);
// Vote for Point -- POINT : project_id1,point1 : project_id2,point2 ------------------------------------------
voteForPoint(temp_msg[1]);
}
return "VOTE_COMPELTE";
} |
8e97df52-0e04-4df4-88f1-93bbdbf00e18 | 3 | public String printAST()
{
StringBuilder ret = new StringBuilder();
if(((Terminal)rhs.get(0)).Name == "IF"){
ret.append("if (");
ret.append(((Expr)rhs.get(2)).printAST());
ret.append(")\r\n");
switch(rhs.size())
{
case 5:
ret.append(((Stmt)rhs.get(4)).printAST());
break;
case 7:
ret.append(((ClosedStmt)rhs.get(4)).printAST());
ret.append("else\r\n");
ret.append(((OpenStmt)rhs.get(6)).printAST());
break;
}
}else{
ret.append(((ClosedStmt)rhs.get(0)).printAST());
}
return ret.toString();
} |
13e60af3-b25e-4fa6-a73d-24cbc61ab836 | 8 | private void parseNow(int parseDepth) throws XMLException {
data = new Hashtable<String,Object>();
types = new Hashtable<String,String>();
Iterator<?> it = elt.getChildren().iterator();
while( it.hasNext() ) {
Element key = (Element) it.next();
if( !key.getName().equals("key"))
throw new XMLException( "Key expected in dict: " + key.getName() );
if( !it.hasNext() )
throw new XMLException( "Missing Value after key: " + key.getText() );
Element value = (Element) it.next();
if( data.get( key.getText() ) != null )
throw new XMLException( "Duplicate key: " + key.getText() );
if( value.getName().equals( "dict" ) ) {
data.put( key.getText(), new XMLDict( value, parseDepth-1, cleanSubTree ) );
} else if( value.getName().equals( "array" ) ) {
data.put( key.getText(), new XMLArray( value, parseDepth-1, cleanSubTree ) );
} else {
data.put( key.getText(), value.getText() );
}
types.put( key.getText(), value.getName() );
}
if( cleanSubTree )
elt.detach();
elt = null;
} |
8e4ecd46-f148-48aa-bfbd-4fef3843c475 | 8 | public int compare(Sprite s0, Sprite s1) {
if (s0.y + s0.x < s1.y + s1.x) return -1;
if (s0.y + s0.x > s1.y + s1.x) return 1;
if (s0.x < s1.x) return -1;
if (s0.x > s1.x) return 1;
if (s0.y < s1.y) return -1;
if (s0.y > s1.y) return 1;
if (s0.z < s1.z) return -1;
if (s0.z > s1.z) return 1;
return 0;
} |
13c1f90a-79d1-4d69-8c3c-0b213a290178 | 0 | public boolean hasMoved() {
return moved;
} |
318603f3-a578-4b0c-aabf-22db0dee1f8f | 8 | public static void main(String[] args) {
int totalPage = 7;
int currentPageNo =10;
int pad = 6;
if (currentPageNo > totalPage) {
currentPageNo = totalPage;
}
if (currentPageNo <= 0) {
currentPageNo = 1;
}
System.out.println("上一页: " + (currentPageNo - 1));
if (currentPageNo - pad > 2) {
System.out.println("第1页");
System.out.println("...");
for(int i = pad; i >= 1; i--){
System.out.println("第" + (currentPageNo - i) + "页");
}
}else {
for(int i = 1; i < currentPageNo; i++){
System.out.println("第" + (i) + "页");
}
}
System.out.println("当前页: " + currentPageNo);
if (currentPageNo + pad < totalPage - 1) {
for (int i = 0; i < pad; i++) {
System.out.println("第" + (currentPageNo + i + 1) + "页");
}
System.out.println("...");
System.out.println("第" + (totalPage) + "页");
}else {
for(int i = currentPageNo ; i < totalPage ; i++){
System.out.println("第" + (i + 1) + "页");
}
}
System.out.println("下一页: " + (currentPageNo + 1));
} |
ff22433b-55f8-46cd-83b6-e990f6a373a4 | 7 | public void service(HttpServletRequest hreq,HttpServletResponse hres)
{
try
{
if(hreq.isRequestedSessionIdValid())
{
con.setAutoCommit(true);
String text=hreq.getParameter("ctext");
HttpSession hs=hreq.getSession(false);
System.out.println("entered into commadd");
String uname=(String)hs.getAttribute("uname");
String temp=(String)hs.getAttribute("uids");
int uids=Integer.parseInt(temp);
temp=(String)hreq.getParameter("tno");
int tno=Integer.parseInt(temp);
System.out.println("tno in commadd class:"+tno);
hs.removeAttribute("tno");
if(temp!=null&&text!=null&&text.trim()!=null&&text.trim().length()!=0)
{
PreparedStatement pstmt=con.prepareStatement("insert into commdbs values(cs.nextval,?,?,?,?)");
pstmt.setInt(1,tno);
pstmt.setInt(2,uids);
pstmt.setString(3,text);
pstmt.setString(4,uname);
int i;
i=pstmt.executeUpdate();
}
System.out.println("redirecting to home page");
String s=hres.encodeURL("homeurl");
hres.sendRedirect(s);
}
else
{
String sr=hres.encodeURL("invalidurl");
hres.sendRedirect(sr);
}
}
catch(Exception e)
{
System.out.println(e);
try{
String sr=hres.encodeURL("errorurl");
hres.sendRedirect(sr);
}
catch(Exception e2)
{System.out.println(e2);}
}
} |
05909410-6aba-43a3-b2c8-ed698f8abc53 | 9 | public void solveEquation(String equation) {
WAEngine engine = new WAEngine();
engine.setAppID(appid);
engine.addFormat("plaintext");
WAQuery query = engine.createQuery();
query.setInput(equation);
try {
// For educational purposes, print out the URL we are about to send:
System.out.println("Query URL:");
System.out.println(engine.toURL(query));
System.out.println("");
WAQueryResult queryResult = engine.performQuery(query);
if (queryResult.isError()) {
System.out.println("Query error");
System.out.println(" error code: " + queryResult.getErrorCode());
System.out.println(" error message: " + queryResult.getErrorMessage());
} else if (!queryResult.isSuccess()) {
System.out.println("Query was not understood; no results available.");
} else {
// Got a result.
for (WAPod pod : queryResult.getPods()) {
if (!pod.isError()) {
String title = pod.getTitle();
if (title.equals("Result")) {
System.out.println(title);
System.out.println("------------");
for (WASubpod subpod : pod.getSubpods()) {
for (Object element : subpod.getContents()) {
if (element instanceof WAPlainText) {
System.out.println(((WAPlainText) element).getText());
}
}
}
}
}
}
}
} catch (WAException e) {
e.printStackTrace();
}
} |
a107e172-0810-47f5-991d-fdf2f03a0c04 | 1 | private ItemDAO(){
try{
session = HibernateUtil.getSessionFactory().openSession();
}catch(ExceptionInInitializerError e){
JOptionPane.showMessageDialog(null, "Sorry can't connect to database",
"Error", JOptionPane.ERROR_MESSAGE);
logger.error("Cant connect to database");
System.exit(1);
}
} |
89eef7f7-2dcb-469c-9f1f-6831f90f63cb | 8 | String getClassForParameter(String object, String field, boolean type) {
for (KVP def : comps.entries) {
if (object.equals(def.getKey())) {
String clname = def.getValue().toString();
clname = getComponentClassName(clname);
Class c;
try {
c = getClassLoader().loadClass(clname);
} catch (ClassNotFoundException ex) {
throw new ComponentException("Class not found: '" + clname
+ "'");
}
try {
if (type) {
String canName = c.getField(field).getType()
.getCanonicalName();
if (canName == null) {
throw new ComponentException(
"No canonical type name for : " + field);
}
return canName;
} else {
Role r = c.getField(field).getAnnotation(Role.class);
if (r != null) {
return r.value();
}
return Role.VARIABLE;
}
} catch (NoSuchFieldException ex) {
throw new ComponentException("No such field: " + field);
} catch (SecurityException ex) {
throw new ComponentException("Cannot access : " + field);
}
}
}
throw new ComponentException("Cannot find component '" + object
+ "'. in '" + object + "." + field + "'");
} |
3fade0cb-b11e-4149-ac12-c6825479ae42 | 2 | static List<Card> getTopCards(List<List<Card>> sets) {
Card topA;
Card topB;
Card top;
List<Card> tops;
List<Card> setA;
List<Card> setB;
setA = sets.get(0);
setB = sets.get(1);
topA = null;
topB = null;
tops = new ArrayList<>();
top = null;
if (setA != null) {
topA = setA.get(setA.size()-1);
top = topA;
if (setB != null) {
topB = setB.get(setB.size()-1);
}
}
tops.add(topA);
tops.add(topB);
return tops;
} |
537a7e09-493d-4c49-aef4-14e887b8bf53 | 8 | public String toDiagonalString(){
StringBuilder sb = new StringBuilder();
int m = columns;
int n = rows;
for (int slice = 0; slice < m + n - 1; slice++) {
int z1 = slice < n ? 0 : slice - n + 1;
int z2 = slice < m ? 0 : slice - m + 1;
for (int j = slice - z2; j >= z1; --j) {
sb.append(boardArray[j][slice - j]);
}
sb.append("\n");
}
m = columns;
n = rows;
for (int slice = 0; slice < m + n - 1; slice++) {
int z1 = slice < n ? 0 : slice - n + 1;
int z2 = slice < m ? 0 : slice - m + 1;
for (int j = slice - z2; j >= z1; --j) {
sb.append(boardArray[columns-1-j][slice - j]);
}
sb.append("\n");
}
return sb.toString();
} |
642c2a35-ea8c-497c-a399-74b599e63fdb | 8 | private boolean deprecated_acquireOverheadData_WINDOWS(BufferedReader brSocket, PrintWriter pwSocket)
{
this.dataAcquisitionComplete = false;
try
{
sendCommand_RAW_ToAgent("hostname");
this.myHostName = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %username%");
this.myUserName = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %homedrive%");
this.myHomeDrive = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %NUMBER_OF_PROCESSORS%");
this.myNumberOfProcessors = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %OS%");
this.myOS_Type = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %PROCESSOR_ARCHITECTURE%");
this.myProcessorArchitecture = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %SystemRoot%");
this.mySystemRoot = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %USERDOMAIN%");
this.myUserDomain = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %USERPROFILE%");
this.myUserProfile = brSocket.readLine();
sendCommand_RAW_ToAgent("echo %TEMP%");
this.myTempPath = brSocket.readLine();
sendCommand_RAW_ToAgent("wmic os get caption /value");
this.myOS = brSocket.readLine();
try { this.myOS.replace("Caption=", ""); }
catch (Exception localException1)
{
}
sendCommand_RAW_ToAgent("wmic os get CSDVersion /value");
this.myServicePack = brSocket.readLine();
try { this.myServicePack.replace("CSDVersion=", ""); }
catch (Exception localException2)
{
}
sendCommand_RAW_ToAgent("wmic os get CountryCode /value");
this.myCountryCode = brSocket.readLine();
try { this.myCountryCode.replace("CountryCode=", ""); }
catch (Exception localException3)
{
}
sendCommand_RAW_ToAgent("wmic os get NumberOfUsers /value");
this.myNumberOfUsers = brSocket.readLine();
try { this.myNumberOfUsers.replace("NumberOfUsers=", ""); }
catch (Exception localException4)
{
}
sendCommand_RAW_ToAgent("wmic os get Version /value");
this.myVersionNumber = brSocket.readLine();
try { this.myVersionNumber.replace("Version=", ""); }
catch (Exception localException5)
{
}
sendCommand_RAW_ToAgent("wmic os get SerialNumber /value");
this.mySerialNumber = brSocket.readLine();
try { this.myVersionNumber.replace("SerialNumber=", ""); }
catch (Exception localException6)
{
}
sendCommand_RAW_ToAgent("wmic os get OSArchitecture /value");
this.myOS_Architecture = brSocket.readLine();
try { this.myOS_Architecture.replace("OSArchitecture=", ""); } catch (Exception localException7) {
}
RelayBot_ServerSocket.updateConnectedImplants();
this.dataAcquisitionComplete = true;
return true;
}
catch (Exception e)
{
Driver.eop("acquireOverheadData_WINDOWS", this.strMyClassName, e, e.getLocalizedMessage(), false);
RelayBot_ServerSocket.updateConnectedImplants();
this.dataAcquisitionComplete = true;
}return false;
} |
3cb74520-32c9-48f3-8cfa-ffa6c3f196ab | 4 | private int readFully(byte[] b, int offs, int len)
throws BitstreamException
{
int nRead = 0;
try
{
while (len > 0)
{
int bytesread = source.read(b, offs, len);
if (bytesread == -1)
{
while (len-->0)
{
b[offs++] = 0;
}
break;
//throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
}
nRead = nRead + bytesread;
offs += bytesread;
len -= bytesread;
}
}
catch (IOException ex)
{
throw newBitstreamException(STREAM_ERROR, ex);
}
return nRead;
} |
6d90079c-2266-4de0-9104-6582f307bb42 | 7 | public void merge(AirNowDataSite site){
if (site.getLatitude() != 0 || site.getLongitude() != 0 || site.getElevation() != 0){
setLatitude(site.getLatitude());
setLongitude(site.getLongitude());
setElevation(site.getElevation());
}
AirNowDataPoint[][] dataPoints = site.getDataPoints();
for (AirNowDataPoint[] a : dataPoints){
for (AirNowDataPoint dataPoint : a){
addDataPoint(dataPoint);
}
}
for (String dataType : site.dataTypes){
if (dataTypes.indexOf(dataType) == -1){
dataTypes.add(dataType);
}
}
} |
df818233-13b3-4d35-97dd-85ce421b2ccf | 9 | @Get
public String represent()
{
try
{
host = (getRequestAttributes().get("host") == null) ? host :
((String) getRequestAttributes().get("host")).trim();
port = (getRequestAttributes().get("port") == null) ? port :
Integer.parseInt(((String) getRequestAttributes().get("port")).trim());
option = (getRequestAttributes().get("option") == null) ? "" :
((String) getRequestAttributes().get("option")).trim();
if(option.equals("retrive"))
return IpcClient.getService(host, port, "Firewall").retrive();
else if(option.equals("run"))
{
if(IpcClient.getService(host, port, "Firewall").run(null))
return "<message>Firewall running</message>";
else
return "<error>Error: running firewall</error>";
}
else if(option.equals("disable"))
{
if(IpcClient.getService(host, port, "Firewall").disable())
return "<message>Firewall disabled</message>";
else
return "<error>Error: disable firewall</error>";
}
else
return "<error>Invalid Option</error>";
//return IpcClient.getService("Firewall").retrive();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "<error>Firewall Error Exception GET</error>";
}
} |
f6c101cc-eaff-4f4a-9c72-42d57f3fede3 | 0 | public AutomatonDrawer getDrawer() {
return drawer;
} |
bb257af0-e23d-4a6f-a5a6-0f263ac80f88 | 1 | @Override
public void printAnswer(Object answer) {
if (!(answer instanceof String)) return;
System.out.print((String)answer);
} |
30929c63-bb79-4cd5-981e-5194e8fd5a78 | 6 | @Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
showHelp(sender);
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("list")) {
sender.sendMessage(StringUtils.join(plugin.getConfigHelper()
.getSequences().getKeys(false), ", "));
return true;
}
if (args.length > 0) {
try {
parseCommand(sender, args);
} catch (SequenceError e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
return false;
} |
118188b4-c7f9-417a-be7d-55f0ec94a796 | 2 | public static void main(String args[]) {
long begin = System.currentTimeMillis();
int total = 475748;
int limit = 31716;
ExecutorService executorService = Executors.newFixedThreadPool(total
/ limit);
for (int i = 0; i <= total / limit; i++) {
String name = "T" + i;
executorService.execute(new SetTF(name, i * limit, limit));
}
executorService.shutdown();
while (!executorService.isTerminated()) {
}
long end = System.currentTimeMillis();
System.out.println("total time: " + (end - begin) / 1000);
} |
8052f299-3377-45e2-b3fd-3017092d28a6 | 4 | private void getStartFiles() {
try {
dataFolder.mkdir();
info("Downloading changelog and readme...");
downloadFile("https://raw.github.com/GetPerms/GetPerms/master/Changelog.txt", changeLog);
downloadFile("https://raw.github.com/GetPerms/GetPerms/master/ReadMe.txt", readMe);
info("The changelog and readme can be found in 'plugins/GetPerms/'");
debug("Downloads succeded. firstRun being set to false...");
configuration.set("firstRun", false);
} catch (MalformedURLException e) {
debug("MalformedURLException thrown, setting firstRun to true...");
configuration.set("firstRun", true);
printStackTrace(e);
warn("Error downloading readme and changelog!");
info("The readme is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/ReadMe.txt");
info("and the changelog is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/Changelog.txt");
} catch (FileNotFoundException e) {
debug("FileNotFoundException thrown, setting firstRun to true...");
configuration.set("firstRun", true);
printStackTrace(e);
warn("Error downloading readme and changelog!");
info("The readme is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/ReadMe.txt");
info("and the changelog is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/Changelog.txt");
} catch (IOException e) {
debug("IOException thrown, setting firstRun to true...");
configuration.set("firstRun", true);
printStackTrace(e);
warn("Error downloading readme and changelog!");
info("The readme is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/ReadMe.txt");
info("and the changelog is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/Changelog.txt");
} catch (NoSuchAlgorithmException e) {
debug("NoSuchAlgorithmException thrown, setting firstRun to true...");
configuration.set("firstRun", true);
printStackTrace(e);
warn("Error downloading readme and changelog!");
info("The readme is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/ReadMe.txt");
info("and the changelog is available at");
info("https://raw.github.com/GetPerms/GetPerms/master/Changelog.txt");
}
} |
f873c0e7-d430-4a52-b1ab-48b32d37ff10 | 7 | public static void Command(CommandSender sender, String[] args)
{
if(sender.hasPermission("gm.survival.others"))
{
Player target = Bukkit.getPlayer(args[1]);
if(target != null)
{
if (target.getGameMode() != GameMode.SURVIVAL)
{
target.setGameMode(GameMode.SURVIVAL);
if(sender instanceof Player)
{
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, (Player) sender, target, true, false, false, null);
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, (Player) sender, target, false, true, false, null);
}
else
{
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, null, target, true, false, false, null);
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, null, target, false, true, false, null);
}
}
else
{
if(sender instanceof Player)
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, (Player) sender, target, true, false, false, null);
else
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, null, target, true, false, false, null);
}
}
else
{
if(sender instanceof Player)
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Error 404: Player Not Found").toString(), sender, (Player) sender, null, true, false, false, args[0]);
else
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Error 404: Player Not Found").toString(), sender, null, null, true, false, false, args[0]);
}
}
else
{
if(sender instanceof Player)
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, (Player) sender, null, true, false, false, null);
else
me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, null, null, true, false, false, null);
}
} |
7ce932ed-631e-417c-a9dc-8304274adf39 | 6 | public void changeChannels(String newChannel) {
if (listening.contains(channel.toLowerCase()))
listening.remove(channel.toLowerCase());
channel = newChannel.toLowerCase();
listening.add(channel.toLowerCase());
// create it if it doesn't exist
ChatChannel chan = ChannelManager.getChannel(channel.toLowerCase());
if (chan == null) {
chan = new ChatChannel(channel);
ChannelManager.channels.add(chan);
if (MCNSAChat3.thread != null)
MCNSAChat3.thread.write(new ChannelUpdatePacket(chan));
}
// welcome them
PluginUtil.sendLater(name, "Welcome to channel " + chan.color + chan.name + "&f!");
ArrayList<String> names = new ArrayList<String>();
for (ChatPlayer p : PlayerManager.getPlayersListeningToChannel(chan.name))
if (!chan.modes.contains(ChatChannel.Mode.LOCAL) || p.server.equals(this.server))
names.add(p.name);
PluginUtil.sendLater(name, "Players here: " + PluginUtil.formatPlayerList(names.toArray(new String[0])));
} |
3e4efdd4-7aef-47dd-985c-5170ad5beb42 | 1 | public List<String> inOrderWithInformation(BinaryNode<K,V,W> root)
{
if(root != null)
{
inOrderWithInformation(root.left);
inOrderWithInformation(root.right);
l.add(root.address.toString());
}
return (l);
} |
5e0b2208-da86-44c1-82fa-ce99d035b38b | 6 | private void classify() throws TooManyDendritesException {
final int MINPOINTS = 2;
if (this.classiferEnabled) {
//prepare the incoming data
LinkedList<Double> dendriteValues = new LinkedList<Double>();
for (AbstractNode d : this.getDendrites()) {
dendriteValues.add((double) d.getAxon());
}
Vec frame = new DenseVector(dendriteValues);
this.frames.add(new DataPoint(frame,null,null));
DataSet dataset = new SimpleDataSet(this.frames);
if (this.frames.size() > 2) {
try {
int[] designations = dbscan.cluster(dataset,MINPOINTS,(int[])null);
this.cluster = DBSCAN.createClusterListFromAssignmentArray(designations, dataset);
StringBuilder buffer = new StringBuilder();
for (int designation : designations) {
buffer.append(designation); buffer.append(' ');
}
this.data = buffer.toString();
this.caughtRuntimeException = false;
} catch (RuntimeException e) {
//This seems to be a bug in the library. Just going to compensate for it
System.out.println("Exception");
this.caughtRuntimeException = true;
}
}
} else {
if (this.getDendrites().size() > 1) {
throw new TooManyDendritesException();
} else {
this.data+=this.getDendrites().getFirst().getAxon()+" ";
}
}
} |
7b15bbfb-f284-4dac-93db-cef37c1e8ae2 | 2 | public String value() {
if (position >= 0 && position < items.length) {
return items[position];
} else {
return null;
}
} |
7ed88545-53f1-4ebf-b2a7-b11fe6240813 | 1 | public static void main(String[] args){ //The actual program
progress.setStringPainted(true); //So the progressbar can have text on it
progress.setString("Click download to begin"); //Info on the bar
list.setEditable(false);
list.setLineWrap(true);
dir.setEditable(false);
dir.setLineWrap(true);
modsDisplay.setLineWrap(true);
modsDisplay.setEditable(false);
error.setEditable(false);
error.setLineWrap(true);
selectedModlist = new File(CONSTS.MIFUDIR+"/modlist/modlist.txt");
System.out.println("Default Selected: "+selectedModlist);
list.setText(selectedModlist.toString());
dlDir = CONSTS.MIFUDIR.toString();
System.out.println("Default Selected: "+dlDir);
dir.setText(dlDir);
/*
* If this is the first time running MIFU, This creates the default dir
*/
if (!CONSTS.MIFUDIR.exists()){
CONSTS.MIFUDIR.mkdir(); //Creates the default dir
new File(CONSTS.MIFUDIRS+"/modlist").mkdir();
System.out.println("MIFU Directory created");
}
//Downloads our default modlist.txt
Download.downloadfile(CONSTS.ourModlist, CONSTS.MIFUDIRS, "/modlist/modlist.txt");
//Check for update
Updater.checkForMIFUUpdate();
/*
* GUI
*/
JLabel mifudesc = new JLabel("Mod Installer From URL");
JLabel modslbl = new JLabel("Downloads:");
JLabel listlbl = new JLabel("Modlist:");
JLabel dirlbl = new JLabel("Directory:");
JScrollPane scroll = new JScrollPane(modsDisplay);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mifudesc.setFont(font);
modslbl.setFont(font);
listlbl.setFont(font);
dirlbl.setFont(font);
Color color = new Color(frame.getBackground().getRGB());
list.setBackground(color);
dir.setBackground(color);
error.setBackground(color);
/*
* Create the layout
*/
addSomething(mifudesc,"label",0,0,4,1);
addSomething(Box.createHorizontalStrut(20),"spacer",1,0,1,10);
addSomething(modslbl,"label",5,0,1,1);
addSomething(scroll,"textbox",5,2,1,13);
addSomething(Box.createVerticalStrut(10),"spacer",0,1,5,1);
addSomething(listlbl,"label",0,2,4,1);
addSomething(list,"label",0,3,3,1);
addSomething(Box.createVerticalStrut(10),"spacer",0,4,4,1);
addSomething(dirlbl,"label",0,5,4,1);
addSomething(dir,"label",0,6,3,1);
addSomething(Box.createVerticalStrut(30),"spacer",0,7,4,1);
addSomething(error,"label",0,8,3,1);
addSomething(Box.createVerticalStrut(30),"spacer",0,9,4,1);
//addSomething(cprofile, "chkbox", 0,10,3,1);
addSomething(Box.createVerticalStrut(10),"spacer",0,10,3,1);
addSomething(chMods,"button",0,11,1,1);
addSomething(Box.createHorizontalStrut(10),"spacer",1,11,1,1);
addSomething(chDir,"button",2,11,1,1);
addSomething(Box.createHorizontalStrut(10),"spacer",3,11,1,1);
addSomething(Box.createVerticalStrut(10),"spacer",0,12,4,1);
addSomething(dlMods,"button",0,13,3,1);
addSomething(Box.createVerticalStrut(10),"spacer",0,14,4,1);
addSomething(progress,"progress",0,15,6,1);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(frame.getWidth()+10,frame.getHeight()+10);
frame.setResizable(false);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
frame.setVisible(true); //Display the GUI
System.out.println(CONSTS.MIFUDIR);
} |
3a7537f3-8231-44cd-8f16-da83c8a02dfa | 7 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String lable,
String[] args) {
if(cmd.getName().equalsIgnoreCase("setJob")){
Player p = (Player) sender;
String Job = args[1];
String name = args[0];
if(!plugin.isPlayer(name)){
p.sendMessage(red + name + " is not a player or is not online");
return true;
}
Player target = Bukkit.getPlayer(name);
if(args.length != 2){
p.sendMessage(red + "not enough arguments!" );
return true;
}
if(!Job.equalsIgnoreCase("Farmer")){
p.sendMessage(red + Job + " is not a job");
return false;
}
FcPlayers fcp = new FcPlayers(plugin, target);
fcp.setPlayerJob(Job);
target.sendMessage(dgreen + "You are now a " + gold + Job);
p.sendMessage(dblue + "You have set "+ dgreen + name + dblue +" job to " + dgreen + Job );
if(!p.isOp()){
p.sendMessage(red + "You must be Op to do this command!");
return false;
}
}
if(cmd.getName().equalsIgnoreCase("farmer")){
Player p = (Player) sender;
FcPlayers fcp = new FcPlayers(plugin, p);
String cmd1 = " info";
p.sendMessage(dgreen + "farm " + cmd1);
p.sendMessage(dgreen + "farm " + cmd1);
p.sendMessage(dgreen + "farm " + cmd1);
p.sendMessage(dgreen + "farm " + cmd1);
p.sendMessage(dgreen + "farm " + cmd1);
if(args[0].equalsIgnoreCase(cmd1)){
}
}
return false;
} |
0347adba-be12-4e82-bd23-22c3091c06ac | 4 | @Subscribe
public void login(LoginEvent event) throws SQLException {
String player = event.getConnection().getName();
if(player==null){
return;
}
String connection = event.getConnection().getAddress().getAddress().toString();
if(!plugin.getUtilities().playerExists(player)){
plugin.getUtilities().createPlayer(player, connection);
}else{
plugin.getUtilities().updateIP(player, connection);
}
if(plugin.chatEnabled && !plugin.onlinePlayers.containsKey(player)){
plugin.getUtilities().getChatPlayer(player);
}
} |
a1e56f31-cc06-42f1-8266-78a4917be153 | 6 | public static void startupDescribe() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupDescribe.helpStartupDescribe1();
}
if (Stella.currentStartupTimePhaseP(4)) {
Stella.$STRING_TO_OBJECT_FUNCTIONS$ = KeyValueList.newKeyValueList();
Stella.$INTEGER_TO_OBJECT_FUNCTIONS$ = List.list(Stella.NIL);
Stella.$DEFAULT_DESCRIBE_MODE$ = Stella.KWD_VERBOSE;
Stella.$SLOTOPTIONSLOTS$.setDefaultValue(null);
Stella.$CLASSOPTIONSLOTS$.setDefaultValue(null);
Stella.$CLASSUNSTRINGIFIEDOPTIONS$.setDefaultValue(null);
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupDescribe.helpStartupDescribe2();
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *STRING-TO-OBJECT-FUNCTIONS* (KEY-VALUE-LIST OF TYPE CODE-WRAPPER) (NEW KEY-VALUE-LIST) :DOCUMENTATION \"Table of functions (keyed by type of object returned) that can\nbe called to search for an object identified by a string.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *INTEGER-TO-OBJECT-FUNCTIONS* (LIST OF CODE-WRAPPER) (LIST) :DOCUMENTATION \"List of functions that can be called to search for\nan object identified by an integer.\")");
Stella.$STRING_TO_OBJECT_FUNCTIONS$.clear();
Stella.$STRING_TO_OBJECT_FUNCTIONS$.insertAt(Stella.SGT_STELLA_CLASS, FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "stringToClass", new java.lang.Class [] {Native.find_java_class("java.lang.String")})));
Stella.$STRING_TO_OBJECT_FUNCTIONS$.insertAt(Stella.SGT_STELLA_CONTEXT, FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "stringToContext", new java.lang.Class [] {Native.find_java_class("java.lang.String")})));
Stella.$STRING_TO_OBJECT_FUNCTIONS$.insertAt(Stella.SGT_STELLA_METHOD_SLOT, FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "stringToFunction", new java.lang.Class [] {Native.find_java_class("java.lang.String")})));
Stella.$STRING_TO_OBJECT_FUNCTIONS$.insertAt(Stella.SGT_STELLA_SLOT, FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "stringToSlot", new java.lang.Class [] {Native.find_java_class("java.lang.String")})));
Stella.$STRING_TO_OBJECT_FUNCTIONS$.insertAt(Stella.SGT_STELLA_OBJECT, FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "stringToSurrogateValue", new java.lang.Class [] {Native.find_java_class("java.lang.String")})));
Stella.$STRING_TO_OBJECT_FUNCTIONS$.insertAt(Stella.SGT_STELLA_DEMON, FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "stringToDemon", new java.lang.Class [] {Native.find_java_class("java.lang.String")})));
Stella.$INTEGER_TO_OBJECT_FUNCTIONS$.insert(FunctionCodeWrapper.wrapFunctionCode(Native.find_java_method("edu.isi.stella.Stella", "integerToContext", new java.lang.Class [] {java.lang.Integer.TYPE})));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DEFAULT-DESCRIBE-MODE* KEYWORD :VERBOSE :PUBLIC? TRUE :DOCUMENTATION \"Specifies the print mode for `describe' when no second\nargument is given.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PRETTY-PRINT-LIST-CUTOFF* INTEGER 5 :PUBLIC? TRUE :DOCUMENTATION \"Lists longer than the cutoff are truncated during\npretty printing.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SLOTOPTIONSLOTS* (CONS OF STORAGE-SLOT) NULL :DOCUMENTATION \"List of slots containing storage-slot options\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CLASSOPTIONSLOTS* (CONS OF STORAGE-SLOT) NULL :DOCUMENTATION \"List of slots containing class options\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CLASSUNSTRINGIFIEDOPTIONS* PROPERTY-LIST NULL :DOCUMENTATION \"Plist of unstringifed class options\")");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} |
a3e58b03-d5f4-4eed-920a-26b6417ae5d0 | 5 | public void visitCallStaticExpr(final CallStaticExpr expr) {
if (expr.method() != null) {
print(expr.method().declaringClass());
}
print(".");
if (expr.method() != null) {
print(expr.method().nameAndType().name());
}
print("(");
if (expr.params() != null) {
for (int i = 0; i < expr.params().length; i++) {
expr.params()[i].visit(this);
if (i != expr.params().length - 1) {
print(", ");
}
}
}
print(")");
} |
0c04faf0-f13b-4863-a96e-982318d02d69 | 1 | @Override
public String getAnswerText() {
return isKeyword ?
String.format("\"%s\" is Java key word.", word) :
String.format("\"%s\" is NOT Java key word.", word);
} |
18649ea1-7de3-4cc9-9379-c57d2426f597 | 9 | public void run() {
while(true) {
long then = System.currentTimeMillis();
for (int j = 0; j < DDT; j++) {
for (int i = 0; i < agents.length; i++)
agents[i].control(agents, null);
shuffle(agents);
for (int i = 0; i < agents.length; i++)
agents[i].step();
}
repaint();
long interval = (long) Math.floor(1000 * DT * DDT);
long now = System.currentTimeMillis();
interval -= now - then;
if (interval < 0) {
System.err.println("time overrun");
} else {
try {
t.sleep(interval);
} catch(InterruptedException e) {
System.exit(1);
}
}
if (threadSuspended) {
synchronized(this) {
while (threadSuspended) {
try {
t.wait();
} catch(InterruptedException e) {
System.exit(1);
}
}
}
}
}
} |
ea513549-d778-4dc2-a2be-a29db34d96d0 | 7 | public ByteBuffer getData() {
ByteBuffer buf = ByteBuffer.allocate(getLength());
// write the header
buf.putShort(getFormat());
buf.putShort((short) getLength());
buf.putShort(getLanguage());
// write the various values
buf.putShort((short) (getSegmentCount() * 2));
buf.putShort(getSearchRange());
buf.putShort(getEntrySelector());
buf.putShort(getRangeShift());
// write the endCodes
for (Iterator i = segments.keySet().iterator(); i.hasNext();) {
Segment s = (Segment) i.next();
buf.putShort((short) s.endCode);
}
// write the pad
buf.putShort((short) 0);
// write the startCodes
for (Iterator i = segments.keySet().iterator(); i.hasNext();) {
Segment s = (Segment) i.next();
buf.putShort((short) s.startCode);
}
// write the idDeltas for segments using deltas
for (Iterator i = segments.keySet().iterator(); i.hasNext();) {
Segment s = (Segment) i.next();
if (!s.hasMap) {
Integer idDelta = (Integer) segments.get(s);
buf.putShort(idDelta.shortValue());
} else {
buf.putShort((short) 0);
}
}
// the start of the glyph array
int glyphArrayOffset = 16 + (8 * getSegmentCount());
// write the idRangeOffsets and maps for segments using maps
for (Iterator i = segments.keySet().iterator(); i.hasNext();) {
Segment s = (Segment) i.next();
if (s.hasMap) {
// first set the offset, which is the number of bytes from the
// current position to the current offset
buf.putShort((short) (glyphArrayOffset - buf.position()));
// remember the current position
buf.mark();
// move the position to the offset
buf.position(glyphArrayOffset);
// now write the map
char[] map = (char[]) segments.get(s);
for (int c = 0; c < map.length; c++) {
buf.putChar(map[c]);
}
// reset the data pointer
buf.reset();
// update the offset
glyphArrayOffset += map.length * 2;
} else {
buf.putShort((short) 0);
}
}
// make sure we are at the end of the buffer before we flip
buf.position(glyphArrayOffset);
// reset the data pointer
buf.flip();
return buf;
} |
0ce2f857-8128-4dad-81b7-c703a592a5db | 1 | @Override
public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException {
List paramList1 = new ArrayList<>();
List paramList2 = new ArrayList<>();
StringBuilder sb = new StringBuilder(UPDATE_QUERY);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_ID_COUNTRY, DB_CITY_ID_COUNTRY, criteria, paramList1, sb, COMMA);
Appender.append(DAO_CITY_NAME, DB_CITY_NAME, criteria, paramList1, sb, COMMA);
Appender.append(DAO_CITY_STATUS, DB_CITY_STATUS, criteria, paramList1, sb, COMMA);
Appender.append(DAO_CITY_PICTURE, DB_CITY_PICTURE, criteria, paramList1, sb, COMMA);
Appender.append(DAO_ID_DESCRIPTION, DB_CITY_ID_DESCRIPTION, criteria, paramList1, sb, COMMA);
sb.append(WHERE);
Appender.append(DAO_ID_CITY, DB_CITY_ID_CITY, beans, paramList2, sb, AND);
Appender.append(DAO_ID_COUNTRY, DB_CITY_ID_COUNTRY, beans, paramList2, sb, AND);
Appender.append(DAO_CITY_NAME, DB_CITY_NAME, beans, paramList2, sb, AND);
Appender.append(DAO_CITY_STATUS, DB_CITY_STATUS, beans, paramList2, sb, AND);
Appender.append(DAO_CITY_PICTURE, DB_CITY_PICTURE, beans, paramList2, sb, AND);
Appender.append(DAO_ID_DESCRIPTION, DB_CITY_ID_DESCRIPTION, beans, paramList2, sb, AND);
return sb.toString();
}
}.mapQuery();
paramList1.addAll(paramList2);
try {
return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn);
} catch (DaoException ex) {
throw new DaoQueryException(ERR_CITY_UPDATE, ex);
}
} |
c318a656-790e-4122-b7f6-72ee77cdec22 | 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(TrainModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TrainModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TrainModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TrainModel.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 TrainModel(1).setVisible(true);
}
});
} |
5b642ae5-e993-4ccd-9439-42433a24cde7 | 6 | public void assertObject(Handle factHandle, PropagationContext propagationContext, WorkingMemory wm) {
try {
Object object = factHandle.getObject();
Class clazz = object.getClass();
Method method = clazz.getMethod("get"+fieldName);
Object result = method.invoke(object);
if(((String)result).equals(value)){
sinkPropagator.propagateAssertObject(factHandle, propagationContext, wm);
}
} catch (IllegalAccessException ex) {
Logger.getLogger(AlphaNode.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(AlphaNode.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(AlphaNode.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(AlphaNode.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(AlphaNode.class.getName()).log(Level.SEVERE, null, ex);
}
} |
b51b7289-0858-441b-811e-8136a11daf7a | 3 | public void setLastName(String lastName) throws Exception{
if (lastName.length() < MIN_INT_VALUE || lastName.toString() == null || lastName.length() > MAX_CHAR){
throw new IllegalArgumentException(NAME_ERR);
}
this.lastName = lastName;
} |
58d7229e-501f-40cf-ac5c-f8fd80af559d | 2 | public AccountManagerHandler(AccountManager target){
try {
logger.addHandler(new java.util.logging.FileHandler());
// logger.addHandler(new java.util.logging.ConsoleHandler());
} catch (SecurityException e) {
logger.warning(e.toString());
} catch (IOException e) {
logger.warning(e.toString());
}
this.target = target;
} |
ba49a931-bee6-45f5-bf30-18c4a902c33b | 2 | @Test
public void testShortCoding() {
Debugger.tc(() -> {
byte[] buf = null;
for (int s = Short.MIN_VALUE; s <= Short.MAX_VALUE; s++) {
buf = BytesUtils.encodeShort((short) s);
short bs = BytesUtils.decodeShort(buf, new Offset());
if (bs != s) {
System.err.println(String.format("Wrong with %d while bs = %d, and buf = %s", s, bs
, Arrays.toString(buf)));
}
}
}, (cost) -> {
System.out.println(String.format("testShortCoding cost %fs.", cost / Math.pow(10, 9)));
});
} |
4b4fcf9a-ea28-4a69-b5fb-06e2f04a2be5 | 0 | public SqlSelector(Connection connetion) {
this.connetion = connetion;
} |
0f0d8af9-5f5c-441e-a3d5-faecdea1dfd8 | 2 | public BitSet getAvailablePieces() {
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (piece.available()) {
availablePieces.set(piece.getIndex());
}
}
}
return availablePieces;
} |
6122c43f-9b0e-4bb2-bdc9-9bf09e7d292c | 7 | @Override
public StatusType getInput(Object object){
StatusType gameStatus = StatusType.PLAYING;
do {
try{
this.display(); // display the menu
// get commaned entered
String command = this.getCommand();
switch (command) {
case "B":
this.displayHelp(HelpMenuView.BOARD);
break;
case "G":
this.displayHelp(HelpMenuView.GAME);
break;
case "L":
this.displayHelp(HelpMenuView.LOCATION);
break;
case "M":
this.displayHelp(HelpMenuView.MARKER);
break;
case "Q":
return StatusType.QUIT;
}
}catch (SudokuException ex) {
System.out.println("\n\t" + ex.getMessage());
}
} while (!gameStatus.equals(StatusType.QUIT));
return gameStatus;
} |
398a004e-1db4-4df6-9657-b2680bac7fe0 | 4 | public void setState(int newState) {
if(state != null) state.dispose();
if(newState == SPLASH) {
state = new PlayState(this);
}
if(newState == TITLE) {
state = new TitleState(this);
}
if(newState == PLAY) {
state = new PlayState(this);
}
} |
69c5b2d6-2135-405b-b95c-420af2b84bfa | 9 | public Object getValueAt(Object o, int i) {
Conflict c = (Conflict) o;
switch (i) {
case 0:
return c.getRelativeId();
case 1:
return c.getType();
case 2:
return c.getActual() == null ? "" : c.getActual().getUserFriendlyValue();
case 3:
return c.getReference() == null ? "" : c.getReference().getUserFriendlyValue();
case 4:
return c.getComment();
case 5:
return c.getDescription() == null ? "" : c.getDescription();
}
return null;
} |
9b176f57-d202-4ee2-9700-e870e5435c83 | 3 | private int getIndexToWrite() { //returns the first empty particle array index, and if none exist returns the location of the "oldest" particle instead
int oldestParticleAge = 0;
int oldestParticleIndex = 0;
for (int particleIndex = 0; particleIndex < particleArray.length; particleIndex++) {
if (particleArray[particleIndex] == null) {
return particleIndex;
} else if (particleArray[particleIndex].getAge() > oldestParticleAge) {
oldestParticleAge = particleArray[particleIndex].getAge();
oldestParticleIndex = particleIndex;
}
}
return oldestParticleIndex;
} |
3aa582bd-6370-4962-ba94-c37dc54cae28 | 3 | static TreeInfo recurseDirs(File startDir, String regex) {
TreeInfo result = new TreeInfo();
for (File item : startDir.listFiles()) {
if (item.isDirectory()) {
result.dirs.add(item);
result.addAll(recurseDirs(item, regex));
} else // Regular file
if (item.getName().matches(regex))
result.files.add(item);
}
return result;
} |
b50b4bc1-5246-425a-b778-c60d45bfdc5f | 2 | public void editLocation() {
World<T> world = parentFrame.getWorld();
Location loc = display.getCurrentLocation();
if (loc != null) {
T occupant = world.getGrid().get(loc);
if (occupant == null) {
MenuMaker<T> maker = new MenuMaker<T>(parentFrame, resources, displayMap);
JPopupMenu popup = maker.makeConstructorMenu(occupantClasses, loc);
Point p = display.pointForLocation(loc);
popup.show(display, p.x, p.y);
} else {
MenuMaker<T> maker = new MenuMaker<T>(parentFrame, resources, displayMap);
JPopupMenu popup = maker.makeMethodMenu(occupant, loc);
Point p = display.pointForLocation(loc);
popup.show(display, p.x, p.y);
}
}
parentFrame.repaint();
} |
4e5be5b6-a6f5-4e33-a777-130446a6bc63 | 5 | public void saveRecord(String name){
if( name == null || name.equals(""))
name = "未命名存档";
int score = Game.enemy_killed * 100 + Game.propScore ;
PreparedStatement pstmt = null ;
try{
pstmt = ConnectionUtil.getInstance().prepareStatement(""
+ "insert into t_record(id, time, stage, score, name) values(id_creator.nextval,?,?,?,?)");
pstmt.setDate(1, new java.sql.Date (new java.util.Date().getTime()));
pstmt.setInt(2, Game.stage);
pstmt.setInt(3, score);
pstmt.setString(4, name);
pstmt.execute();
}catch(Exception e){
e.printStackTrace();
}finally{
if( pstmt != null)
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
9f17e552-56e0-4536-bc73-b59506c538a5 | 8 | private void RcodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RcodigoActionPerformed
vtexto = Ctexto.getText();
DefaultTableModel tr = (DefaultTableModel)tabla.getModel();
try
{
Statement s = cone.getMiConexion().createStatement();
String consul="select * from correpo where edo_reg = 'A' and grupo = '"+Cgrupo+"' and codigo like '%"+vtexto+"%'";
ResultSet rs = s.executeQuery(consul);
while (rs.next())
{
String var1 = rs.getString("id");
String var2 = (PROCE.verfecha(rs.getString("fecha_rec")));
String var3 = rs.getString("des_rem");
String var4 = rs.getString("codigo");
String var5 = rs.getString("nro_oficio");
tr.addRow(new Object[]{var1, var2, var3, var4, var5,});
tabla.setModel(tr);
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = tabla.getColumnModel().getColumn(i);
if (i == 0) {column.setPreferredWidth(0);}
if (i == 1) {column.setPreferredWidth(15);}
if (i == 2) {column.setPreferredWidth(250);}
if (i == 3) {column.setPreferredWidth(10);}
if (i == 4) {column.setPreferredWidth(10);}
}
}
}
catch (Exception e)
{
}
}//GEN-LAST:event_RcodigoActionPerformed |
76a46994-8417-4349-9247-0eebc2ffd849 | 9 | private Object getMultiArray(Class<?> prototype) {
int start = _next;
int type = nextType(CLASS_MULTI_ARRAY, CLASS_REREF);
if (type == CLASS_REREF) {
_next = start;
Object array = get(null, null);
if (array == null || array.getClass().isArray()) {
return array;
} else {
throw new ConversionException("Referenced object is not an array");
}
}
Object result;
try {
_depth++;
int componentClassHandle = nextType();
checkSize(1);
int dimensions = _bytes[_next++] & 0xFF;
if (prototype == null) {
prototype = Array.newInstance(classForHandle(componentClassHandle), new int[dimensions]).getClass();
}
int length = decodeElementCount();
result = Array.newInstance(prototype.getComponentType(), length);
_serializedItemCount++;
registerEncodedObject(result);
Class<?> componentType = prototype.getComponentType();
if (componentType.getComponentType().isArray()) {
for (int index = 0; index < length; index++) {
Array.set(result, index, getMultiArray(componentType));
}
} else {
for (int index = 0; index < length; index++) {
Array.set(result, index, get(null, null));
}
}
} finally {
_depth--;
}
closeVariableLengthItem();
return result;
} |
09ee536a-8bb0-42ef-9329-d41d636dc6bb | 9 | @Override
protected void paintComponent(Graphics gg) {
Graphics3D g = Graphics3D.create(gg);
w = (getWidth() - (leftGap + gap * hand.size())) / hand.size();
int h = getHeight() - 2 * gap;
int x = leftGap;
int y = gap;
Font font = new Font("Arial", Font.BOLD, 50);
for (Json card : Lists.reverse(hand)) {
int rank = card.getInt("rank");
CardColor c = CardColor.valueOf(card.get("color"));
Rect r = new Rect(x, y, w, h);
boolean showInfo = !this.myHand;
if (onEye) {
showInfo = false;
}
g.color(Color.black).fill(r);
if (showInfo || card.has("showColor")) {
g.color(c.getColor()).fill(r.grow(-3, -3));
}
if (rank > 0) {
g.font(font).color(Color.white).text(showInfo || card.has("showRank") ? rank + "" : "?", r);
}
x += gap;
x += w;
}
if (!this.myHand && !player.equalsIgnoreCase("board")) {
g.draw(eye, 0, getHeight() / 2 - eye.getHeight() / 2);
}
} |
648df7c1-14a7-4a73-9f7f-edb02706417f | 2 | public static void find2Methods(Object self, String superMethod,
String thisMethod, int index,
String desc, java.lang.reflect.Method[] methods)
{
synchronized (methods) {
if (methods[index] == null) {
methods[index + 1] = thisMethod == null ? null
: findMethod(self, thisMethod, desc);
methods[index] = findSuperMethod(self, superMethod, desc);
}
}
} |
57a8a2be-7199-49f8-b8e1-a9f0e28c7147 | 2 | public int getIdAmount(String id) {
int amount = 0;
for(int i=0;i<identity.size();i++) {
if(identity.get(i).contains(id)) {
amount++;
}
}
return amount;
} |
c1feb8b1-da99-440e-a35e-576655a4409a | 5 | public MainWindow() {
this.eventHandler = new MainEventHandler();
// TODO don't do this, create a real package
PackageManager.getInstance().registerCommand(
SafeResourceLoader.getString("COMMAND_SHUTDOWN",
"com.ikalagaming.omega.core.resources.PackageManager",
"shutdown"), Editor.getInstance());
this.resources =
ResourceBundle.getBundle(
"com.ikalagaming.omega.gui.resources.gui",
Localization.getLocale());
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (final UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
catch (final ClassNotFoundException e) {
e.printStackTrace();
}
catch (final InstantiationException e) {
e.printStackTrace();
}
catch (final IllegalAccessException e) {
e.printStackTrace();
}
// this.setExtendedState(Frame.MAXIMIZED_BOTH);// full screen
this.setTitle(SafeResourceLoader.getString("MainWindow.title",
this.resources, "MAIN_WINDOW_TITLE"));
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent event) {
EventManager
.getInstance()
.fireEvent(
new PackageEvent(
Editor.getInstance().getName(),
"editor",
SafeResourceLoader
.getString(
"COMMAND_SHUTDOWN",
"com.ikalagaming.omega.core.resources.PackageManager",
"shutdown")));
}
});
this.setBounds(100, 100, 562, 487);
this.contentPane = new JPanel();
this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
this.contentPane.setLayout(new BorderLayout(0, 0));
this.setContentPane(this.contentPane);
final JPanel menuPanel = new JPanel();
this.contentPane.add(menuPanel, BorderLayout.NORTH);
menuPanel.setLayout(new BorderLayout(0, 0));
final JPanel panel_1 = new JPanel();
menuPanel.add(panel_1, BorderLayout.NORTH);
panel_1.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
final JMenuBar menuBar = new JMenuBar();
panel_1.add(menuBar);
final Menu menu_file =
new Menu(SafeResourceLoader.getString(
"MainWindow.menubar.file", this.resources, "FILE"));
final MenuItem menuitem_file_new =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.file.new", this.resources, "NEW"));
final MenuItem menuitem_file_open =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.file.open", this.resources, "OPEN"));
final MenuItem menuitem_file_save =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.file.save", this.resources, "SAVE"));
final MenuItem menuitem_file_saveas =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.file.saveas", this.resources,
"SAVE_AS"));
final MenuItem menuitem_file_exit =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.file.exit", this.resources, "EXIT"));
menu_file.addActionListener(this.eventHandler);
menuitem_file_new.addActionListener(this.eventHandler);
menuitem_file_open.addActionListener(this.eventHandler);
menuitem_file_save.addActionListener(this.eventHandler);
menuitem_file_saveas.addActionListener(this.eventHandler);
menuitem_file_exit.addActionListener(this.eventHandler);
menu_file.setID(ScriptRegistry.register(menu_file, "file"));
menuitem_file_new.setID(ScriptRegistry.register(menuitem_file_new,
"file.new"));
menuitem_file_open.setID(ScriptRegistry.register(menuitem_file_open,
"file.open"));
menuitem_file_save.setID(ScriptRegistry.register(menuitem_file_save,
"file.save"));
menuitem_file_saveas.setID(ScriptRegistry.register(
menuitem_file_saveas, "file.saveas"));
menuitem_file_exit.setID(ScriptRegistry.register(menuitem_file_exit,
"file.exit"));
menu_file.add(menuitem_file_new);
menu_file.add(menuitem_file_open);
menu_file.add(menuitem_file_save);
menu_file.add(menuitem_file_saveas);
menu_file.add(new JSeparator());// divides the sections
menu_file.add(menuitem_file_exit);
// edit menu
final Menu menu_edit =
new Menu(SafeResourceLoader.getString(
"MainWindow.menubar.edit", this.resources, "EDIT"));
final MenuItem menuitem_edit_undo =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.undo", this.resources, "UNDO"));
final MenuItem menuitem_edit_redo =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.redo", this.resources, "REDO"));
final MenuItem menuitem_edit_cut =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.cut", this.resources, "CUT"));
final MenuItem menuitem_edit_copy =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.copy", this.resources, "COPY"));
final MenuItem menuitem_edit_paste =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.paste", this.resources,
"PASTE"));
final MenuItem menuitem_edit_delete =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.delete", this.resources,
"PASTE"));
final MenuItem menuitem_edit_find =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.find", this.resources, "FIND"));
final MenuItem menuitem_edit_findnext =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.findnext", this.resources,
"FIND_NEXT"));
final MenuItem menuitem_edit_replace =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.replace", this.resources,
"REPLACE"));
final MenuItem menuitem_edit_selectall =
new MenuItem(SafeResourceLoader.getString(
"MainWindow.menubar.edit.selectall", this.resources,
"SELECT_ALL"));
menu_edit.addActionListener(this.eventHandler);
menuitem_edit_undo.addActionListener(this.eventHandler);
menuitem_edit_redo.addActionListener(this.eventHandler);
menuitem_edit_cut.addActionListener(this.eventHandler);
menuitem_edit_copy.addActionListener(this.eventHandler);
menuitem_edit_paste.addActionListener(this.eventHandler);
menuitem_edit_delete.addActionListener(this.eventHandler);
menuitem_edit_find.addActionListener(this.eventHandler);
menuitem_edit_findnext.addActionListener(this.eventHandler);
menuitem_edit_replace.addActionListener(this.eventHandler);
menuitem_edit_selectall.addActionListener(this.eventHandler);
menu_edit.setID(ScriptRegistry.register(menu_edit, "edit"));
menuitem_edit_undo.setID(ScriptRegistry.register(menuitem_edit_undo,
"edit.undo"));
menuitem_edit_redo.setID(ScriptRegistry.register(menuitem_edit_redo,
"edit.redo"));
menuitem_edit_cut.setID(ScriptRegistry.register(menuitem_edit_cut,
"edit.cut"));
menuitem_edit_copy.setID(ScriptRegistry.register(menuitem_edit_copy,
"edit.copy"));
menuitem_edit_paste.setID(ScriptRegistry.register(menuitem_edit_paste,
"edit.paste"));
menuitem_edit_delete.setID(ScriptRegistry.register(
menuitem_edit_delete, "edit.delete"));
menuitem_edit_find.setID(ScriptRegistry.register(menuitem_edit_find,
"edit.find"));
menuitem_edit_findnext.setID(ScriptRegistry.register(
menuitem_edit_findnext, "edit.findnext"));
menuitem_edit_replace.setID(ScriptRegistry.register(
menuitem_edit_replace, "edit.replace"));
menuitem_edit_selectall.setID(ScriptRegistry.register(
menuitem_edit_selectall, "edit.selectall"));
menu_edit.add(menuitem_edit_undo);
menu_edit.add(menuitem_edit_redo);
menu_edit.add(new JSeparator());
menu_edit.add(menuitem_edit_cut);
menu_edit.add(menuitem_edit_copy);
menu_edit.add(menuitem_edit_paste);
menu_edit.add(menuitem_edit_delete);
menu_edit.add(new JSeparator());
menu_edit.add(menuitem_edit_find);
menu_edit.add(menuitem_edit_findnext);
menu_edit.add(menuitem_edit_replace);
menu_edit.add(menuitem_edit_selectall);
menuBar.add(menu_file);
menuBar.add(menu_edit);
final JPanel panel_2 = new JPanel();
final FlowLayout flowLayout = (FlowLayout) panel_2.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
menuPanel.add(panel_2, BorderLayout.SOUTH);
final JToolBar fileToolbar = new JToolBar();
panel_2.add(fileToolbar);
final Button btnNew =
new Button(SafeResourceLoader.getString(
"MainWindow.toolbar.new", this.resources, "NEW"));
btnNew.setID(ScriptRegistry.register(btnNew, "new"));
btnNew.addActionListener(this.eventHandler);
fileToolbar.add(btnNew);
final Button btnOpen =
new Button(SafeResourceLoader.getString(
"MainWindow.toolbar.open", this.resources, "OPEN"));
btnOpen.setID(ScriptRegistry.register(btnOpen, "open"));
btnOpen.addActionListener(this.eventHandler);
fileToolbar.add(btnOpen);
final Button btnSave =
new Button(SafeResourceLoader.getString(
"MainWindow.toolbar.save", this.resources, "SAVE"));
fileToolbar.add(btnSave);
btnSave.addActionListener(this.eventHandler);
btnSave.setID(ScriptRegistry.register(btnSave, "save"));
final Button btnSaveas =
new Button(SafeResourceLoader.getString(
"MainWindow.toolbar.saveas", this.resources, "SAVE_AS"));
fileToolbar.add(btnSaveas);
btnSaveas.addActionListener(this.eventHandler);
btnSaveas.setID(ScriptRegistry.register(btnSaveas, "saveas"));
final Button btnSaveall =
new Button(SafeResourceLoader.getString(
"MainWindow.toolbar.saveall", this.resources,
"SAVE_ALL"));
fileToolbar.add(btnSaveall);
btnSaveall.addActionListener(this.eventHandler);
btnSaveall.setID(ScriptRegistry.register(btnSaveall, "saveall"));
final JToolBar editAsToolbar = new JToolBar();
panel_2.add(editAsToolbar);
final JLabel lblEditAs =
new JLabel(SafeResourceLoader.getString(
"MainWindow.toolbar.editas", this.resources, "EDIT_AS"));
editAsToolbar.add(lblEditAs);
final EditorTypeComboBox<EditorType> comboBox =
new EditorTypeComboBox<>();
comboBox.setModel(new DefaultComboBoxModel<Object>(EditorType.values()));
editAsToolbar.add(comboBox);
comboBox.addActionListener(this.eventHandler);
final JPanel infoBar = new JPanel();
this.contentPane.add(infoBar, BorderLayout.SOUTH);
final JLabel lblWords =
new JLabel(SafeResourceLoader.getString(
"MainWindow.infobar.line", this.resources, "CUR_LINE"));
infoBar.add(lblWords);
final JLabel lblLnnum = new JLabel("line");
infoBar.add(lblLnnum);
final JLabel lblColumn =
new JLabel(SafeResourceLoader.getString(
"MainWindow.infobar.column", this.resources,
"CUR_COLUMN"));
infoBar.add(lblColumn);
final JLabel lblColnum = new JLabel("colnum");
infoBar.add(lblColnum);
this.tabbedPane = new JTabbedPane(SwingConstants.TOP);
this.contentPane.add(this.tabbedPane, BorderLayout.CENTER);
this.setID(ScriptRegistry.register(this, "main"));
try {
EventManager.getInstance().registerEventListeners(this);
}
catch (final Exception e) {
e.printStackTrace();
}
} |
d9f00340-b3f2-4919-88b9-8497fb83bce6 | 6 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
BigInteger zero = BigInteger.ZERO;
while ((line = in.readLine()) != null && line.length() != 0) {
String[] data = line.trim().split(" ");
BigInteger a = new BigInteger(data[0]);
BigInteger b = new BigInteger(data[1]);
int count = 0;
out.append("[");
if (a.compareTo(b) < 0) {
out.append("0;");
a = b;
b = new BigInteger(data[0]);
count++;
}
BigInteger div = a.divide(b), res = a.mod(b);
while (!div.equals(zero) && !res.equals(zero)) {
out.append(div + (count++ == 0 ? ";" : ","));
a = b;
b = res;
div = a.divide(b);
res = a.mod(b);
}
out.append(a + "]\n");
}
System.out.print(out);
} |
1119ec4c-b8c6-4074-a477-605c3ee6dc13 | 2 | public boolean canHaveAsLightGrenade(LightGrenade lg) {
for (Element e : elements) {
if (e.getPositions().contains(lg.getPosition()))
return false;
}
return true;
} |
128c9c49-8314-4b50-b12e-8401326689f9 | 8 | @Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
//get incoming text
String inText = aJCas.getDocumentText();
//split lines
String[] lines = inText.split("\n");
Token token;
int indexCount=0;
int dummy=0;
int q_a=0;
int countLine=1;
System.out.println("=================== TOKEN ANNOTATOR ======================");
/*for(int L=0;L<lines.length;L++){
System.out.println(lines[L].toString());
System.out.println("Length: "+lines[L].length());
}*/
int[] maxLs=new int [lines.length];
for(int numL=0; numL < lines.length; numL++){
String eachline = lines[numL];
String cutline=null;
String[] words;
if(numL==0)
maxLs[numL]=lines[numL].length();
else{
maxLs[numL]=maxLs[numL-1]+lines[numL].length()+2;
}
//System.out.println("MAXLS: "+maxLs[numL]);
if(eachline.startsWith("Q ")){
cutline=eachline.substring(2, eachline.length());
indexCount=indexCount+2;
q_a=1;
}else if(eachline.startsWith("A ")){
cutline=eachline.substring(4, eachline.length());
indexCount=indexCount+4;
q_a=0;
}
//words = cutline.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
//words = cutline.replaceAll("[']","_").toLowerCase().split("\\s+");
words = cutline.replaceAll("['.,?!]"," ").toLowerCase().split("\\s+");
for(int ws=0;ws<words.length;ws++){
token=new Token(aJCas);
int beg_ind=0,end_ind=0;
//System.out.println(words[ws].toString());
beg_ind = cutline.toLowerCase().indexOf(words[ws])+indexCount+dummy;
end_ind=beg_ind+words[ws].length();
//System.out.println("i: "+beg_ind);
//System.out.println("j: "+end_ind);
if(q_a==1){
token.setToken_type("Q");
token.setLine_doc(0);
}else if(q_a==0){
token.setToken_type("A");
//Get line in document
if(end_ind<maxLs[countLine]){
token.setLine_doc(countLine);
}else{
countLine++;
token.setLine_doc(countLine);
}
}
token.setBegin(beg_ind);
token.setEnd(end_ind);
token.setCasProcessorId(this.annotatorID);
token.setConfidence(1.0);
token.addToIndexes();
}
indexCount=0;
dummy=dummy+lines[numL].length()+1;
}
//System.out.println("=======================================================");
System.out.println("");
} |
71579433-c543-4fd3-9e6e-a05a2fae0120 | 9 | /* */ @EventHandler
/* */ public void onPlayerInteract(PlayerInteractEvent event)
/* */ {
/* 185 */ if (Main.getAPI().isSpectating(event.getPlayer()))
/* */ {
/* 187 */ if (Main.getAPI().isReadyForNextScroll(event.getPlayer()))
/* */ {
/* 189 */ if (Main.getAPI().getSpectateMode(event.getPlayer()) == SpectateMode.SCROLL)
/* */ {
/* 191 */ if ((event.getAction() == Action.LEFT_CLICK_AIR) || (event.getAction() == Action.LEFT_CLICK_BLOCK))
/* */ {
/* 193 */ if (Bukkit.getServer().getOnlinePlayers().length > 2)
/* */ {
/* 195 */ Main.getAPI().scrollLeft(event.getPlayer(), Main.getAPI().getSpectateablePlayers());
/* 196 */ Main.getAPI().disableScroll(event.getPlayer(), 5L);
/* */ }
/* */
/* */ }
/* 200 */ else if ((event.getAction() == Action.RIGHT_CLICK_AIR) || (event.getAction() == Action.RIGHT_CLICK_BLOCK))
/* */ {
/* 202 */ if (Bukkit.getServer().getOnlinePlayers().length > 2)
/* */ {
/* 204 */ Main.getAPI().scrollRight(event.getPlayer(), Main.getAPI().getSpectateablePlayers());
/* 205 */ Main.getAPI().disableScroll(event.getPlayer(), 5L);
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */
/* 215 */ event.setCancelled(true);
/* 216 */ return;
/* */ }
/* */ } |
e811ee57-1665-4b4e-bf15-5dc3e677631a | 3 | private String getCommaStringFromArrayList(ArrayList<String> a)
{
if (a.size() == 0)
{
return "";
} else
{
String s = "";
for (int i=0;i<a.size();i++)
{
if (i != a.size()-1)
s = s + a.get(i) + ",";
else
s = s + a.get(i);
}
return s;
}
} |
8f7ce02b-c947-49ea-a23c-1b8b3e64de50 | 0 | @Test
public void test_get_file_missing()
{
Assert.assertNull(getFile("bogus_key!"));
} |
30038aba-5bbc-4966-ab75-01617168be1d | 9 | @EventHandler
public void onInteract(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
String worldName = player.getLocation().getWorld().getName();
// We do not have to check on this world.
if (plugin.getAPI().isDisabledWorld(worldName))
return;
// Ignore creative?
if (plugin.getConfigHandler().shouldIgnoreCreative()) {
if (player.getGameMode().equals(GameMode.CREATIVE))
return;
}
actionType action = actionType.RIGHT_CLICK_MOB;
if (event.getRightClicked().getType().equals(EntityType.PLAYER)) {
// Action is right clicked player
action = actionType.RIGHT_CLICK_PLAYER;
}
ItemStack item = player.getItemInHand();
// No item in hand, so nothing to check
if (item == null)
return;
String blockAction = action.toString();
// Check if restrictions are disabled on this world.
if (plugin.getAPI().isDisabledWorld(item, worldName)) {
return;
}
Restriction r = plugin.getResManager().getRestriction(item);
// No restriction for this item found.
if (r == null)
return;
List<Requirement> failed = r.getFailedRequirements(player, action);
// All requirements are met, allow to use.
if (failed.isEmpty())
return;
// Cannot use this item
event.setCancelled(true);
plugin.getMessageHandler().sendMessage(player,
plugin.getConfigHandler().getMessage(message.NOT_ALLOWED_TO_USE, blockAction));
// Show what the player still has to do to use this item.
for (Requirement failedReq : failed) {
player.sendMessage(ChatColor.RED + "- " + failedReq.getDescription());
}
} |
9596f72e-3f2c-4b9c-9970-bd4a09e590a8 | 5 | static boolean isElevatedTile(int x, int y) {
anInt1332++;
if (x < 0 || (y ^ 0xffffffff) > -1 || x >= Class348_Sub33.settingFlags[1].length || (Class348_Sub33.settingFlags[1][x].length ^ 0xffffffff) >= (y ^ 0xffffffff))
return false;
if ((Class348_Sub33.settingFlags[1][x][y] & 0x2) != 0)
return true;
return false;
} |
e4895d2f-2468-44cd-be41-f8c1a2dd80ce | 7 | public void spaceHorizontal(FastVector nodes) {
// update undo stack
if (m_bNeedsUndoAction) {
addUndoAction(new spaceHorizontalAction(nodes));
}
int nMinX = -1;
int nMaxX = -1;
for (int iNode = 0; iNode < nodes.size(); iNode++) {
int nX = getPositionX((Integer) nodes.elementAt(iNode));
if (nX < nMinX || iNode == 0) {
nMinX = nX;
}
if (nX > nMaxX || iNode == 0) {
nMaxX = nX;
}
}
for (int iNode = 0; iNode < nodes.size(); iNode++) {
int nNode = (Integer) nodes.elementAt(iNode);
m_nPositionX.setElementAt((int) (nMinX + iNode * (nMaxX - nMinX) / (nodes.size() - 1.0)), nNode);
}
} // spaceHorizontal |
5d1ded2e-ded2-47b6-965a-2a46ffc702e5 | 0 | public FrameProcessCalculate(){
initialize();
} |
e44b8026-5f19-4d3f-89d5-57a01cb953cc | 6 | public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
input = container.getInput();
GameState state = game.getCurrentState();
if (!(state instanceof World)) return;
prevVelocity.set(velocity);
invMass = 1F / size;
edgeLength = (float) Math.sqrt(size);
x1 = x - edgeLength / 2;
x2 = x + edgeLength / 2;
y1 = y - edgeLength / 2;
y2 = y + edgeLength / 2;
prevX = x;
prevY = y;
velocity.add(force.scale(invMass));
force.set(0, 0);
x += velocity.x;
y += velocity.y;
float speed = 100F;
if (playerControlled) {
Vector2f inputV = new Vector2f();
input = container.getInput();
if (input.isKeyDown(Input.KEY_UP)) {
inputV.add(new Vector2f(0, -1));
}
if (input.isKeyDown(Input.KEY_DOWN)) {
inputV.add(new Vector2f(0, 1));
}
if (input.isKeyDown(Input.KEY_LEFT)) {
inputV.add(new Vector2f(-1, 0));
}
if (input.isKeyDown(Input.KEY_RIGHT)) {
inputV.add(new Vector2f(1, 0));
}
inputV.normalise();
inputV.scale(speed);
force.add(inputV);
}
velocity.scale(0.95F);
} |
11d15c2b-996b-4cee-8e0d-ae53be8c9da7 | 8 | private void resolveSummonProperties(SummonableService instance_, Class<?> clazz_)
{
//System.out.println("Summon.resolveSummonProperties(): " + clazz_.getName());
Field[] fields = clazz_.getDeclaredFields();
// Property fields
for (Field field : fields)
{
// allow to change private field
field.setAccessible(true);
//System.out.println("\t" + field.getName());
if (field.isAnnotationPresent(ServiceProperty.class))
try
{
//System.out.println("ANNOTATION PRESENT: " + field.getName());
instance_.getProperties().createProperty(field.getName(), String.valueOf(field.get(instance_)));
instance_.getProperties().createProperty(field);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
// Restart property
Method[] methods = clazz_.getDeclaredMethods();
for (Method method : methods)
{
method.setAccessible(true);
if (method.isAnnotationPresent(RestartService.class))
{
instance_.addRestartService(method);
}
}
// call parents
if (!clazz_.equals(ServiceAbstract.class))
{
//System.out.println("SUPERCLASS: " + clazz_.getSuperclass().getName());
resolveSummonProperties(instance_, clazz_.getSuperclass());
}
} |
77107407-93c2-43cd-aa09-09c33e6f3183 | 5 | int alignmentConstant (String align) {
if (align.equals("LEFT")) return SWT.LEFT;
if (align.equals("RIGHT")) return SWT.RIGHT;
if (align.equals("TOP")) return SWT.TOP;
if (align.equals("BOTTOM")) return SWT.BOTTOM;
if (align.equals("CENTER")) return SWT.CENTER;
return SWT.DEFAULT;
} |
68eba07f-1e9b-4474-b82b-2a6ba38d2f0c | 1 | @Override
public void pause(int objectId) {
AudioChannel channel = channels.get(objectId);
if (channel != null) {
alSourcePause(channel.source);
}
} |
de0434ad-87ab-4651-a0f6-9edd679f42ff | 0 | public void setTarget(String value) {
this.target = value;
} |
1c652031-1635-4551-b514-5cd93eb3894b | 4 | public Rectangle2D.Float getBounds() {
// lazy load the bounds as the calculation is very expensive
if (bounds == null) {
// word bounds build from child word bounds.
for (WordText word : words) {
if (bounds == null) {
bounds = new Rectangle2D.Float();
bounds.setRect(word.getBounds());
} else {
bounds.add(word.getBounds());
}
}
// empty line text check, return empty bound.
if (bounds == null) {
bounds = new Rectangle2D.Float();
}
}
return bounds;
} |
5a41d7d2-54ac-472f-9d79-71d48aeac44c | 3 | private void itmMnuProjetoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmMnuProjetoActionPerformed
// Menu - Cadastro > ItemMenu - PROJETO
DepartamentoBO depBO = new DepartamentoBO();
Departamento DEPexistente = null;
try {
DEPexistente = depBO.SelectDepartamentos();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao selecionar o departamento",
"Cadastro de Projetos", JOptionPane.ERROR_MESSAGE);
}
if (DEPexistente == null) {
JOptionPane.showMessageDialog(null, "Não existe departamentos cadastrados\n"
+ "É necessário cadastrar no minimo um Departamento !!!", "Cadastro de Projetos", JOptionPane.ERROR_MESSAGE);
} else {
//Instancia uma tela de cadastro de Projeto se o usuario que esta logado for Um Gerente;
//caso não seja um Gerente é exibida uma mensagem ao usuario do sistema.
//Obs: Somente Gerente pode cadastrar Projeto
if (usuarioLogado.getTipo().equals("Gerente")) {
CadastroProjetoForm cadastroProjetoForm = new CadastroProjetoForm(usuarioLogado);
cadastroProjetoForm.setVisible(true);
centralizaForm(cadastroProjetoForm);
JDP1.add(cadastroProjetoForm);
} else {
JOptionPane.showMessageDialog(null, "Você não possui previlégios para acessar \n "
+ "a Tela de Cadastros de projeto!!!", "Cadastro de Projeto", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_itmMnuProjetoActionPerformed |
6f4f6265-5b39-4530-8a9a-a4538692f16f | 6 | private synchronized void changeBid(int auction, Bid bid, Bid newBid) {
Bid activeBid = getBid(auction);
if (activeBid != null) {
if (activeBid.same(bid)) {
bids[auction] = newBid;
} else {
Bid child;
while ((child = activeBid.getReplacing()) != null && !child.same(bid))
{
activeBid = child;
}
if (child != null && child.same(bid)) {
activeBid.setReplacing(newBid);
}
}
}
} |
00676a57-1316-470a-909d-413c9f2c268a | 5 | public static void recDFS(Vertice v) {
for (Aresta a : v.getArestas()) {
// checa se a aresta do v entrada ja foi visitada
if (!a.checkVisitado()) {
// tmp == vertice de destino
Vertice tmp = a.getDestino();
if (!tmp.checkVisitado()) {
a.visitar();
tmp.visitar();
if (go) {
System.out.println();
go = false;
}
System.out.print("-> GO A:" + a.getCusto() + " V: "
+ tmp.getID());
// System.out.print("segue: " +tmp.getID());
back = true;
// invoca recursividade
recDFS(tmp);
if (back) {
System.out.println();
back = false;
}
// System.out.print("volta: " +v.getID());
System.out.print("-> BACK A:" + a.getCusto() + " V:"
+ v.getID());
go = true;
}
}
}
} |
959e9fb9-c82f-4157-93d5-7ba462868225 | 9 | private void getData(){
try {
cbSubject.removeAllItems();
cbObject.removeAllItems();
cbVerb.removeAllItems();
cbLocation.removeAllItems();
cbLocationObject.removeAllItems();
ConnectDatabase cdb = new ConnectDatabase();
ResultSet result = cdb.st.executeQuery("SELECT idsubjects, SubjectName FROM subjects");
cbSubject.addItem(new comboItem("", -1));
cbObject.addItem(new comboItem("", -1));
while(result.next()) {
cbSubject.addItem(new comboItem(result.getString("SubjectName"), result.getInt("idsubjects")));
cbObject.addItem(new comboItem(result.getString("SubjectName"), result.getInt("idsubjects")));
}
result = cdb.st.executeQuery("SELECT idevents, EventName FROM events");
cbVerb.addItem(new comboItem("", -1));
while(result.next()) {
cbVerb.addItem(new comboItem(result.getString("EventName"), result.getInt("idevents")));
}
result = cdb.st.executeQuery("SELECT idplaces, PlaceName FROM places");
cbLocation.addItem(new comboItem("", -1));
cbLocationObject.addItem(new comboItem("", -1));
while(result.next()) {
cbLocation.addItem(new comboItem(result.getString("PlaceName"), result.getInt("idplaces")));
cbLocationObject.addItem(new comboItem(result.getString("PlaceName"), result.getInt("idplaces")));
}
cdb.st.close();
}
catch( Exception e ) {
e.printStackTrace();
}
try {
ConnectDatabase cdb = new ConnectDatabase();
CallableStatement cs = cdb.con.prepareCall("{call SelectSentences()}");
ResultSet result = cs.executeQuery();
String SubType = "-1", SubName, SubPlaceName, Verb, ObjName, ObjPlaceName, ObjType= "-1";
textPane.setText("");
while(result.next()) {
SubType = result.getString("SubjectTypesID");
ObjType = result.getString("objTypesID");
SubName = result.getString("SubjectName");
SubPlaceName = result.getString("PlaceName");
Verb = result.getString("EventName");
ObjName = result.getString("ObjectName");
ObjPlaceName = result.getString("ObjPlaceName");
StyledDocument doc = textPane.getStyledDocument();
System.out.println(SubName);
System.out.println(SubType);
try {
Style style = textPane.addStyle("Style", null);
if (SubType.equals("0")){
StyleConstants.setForeground(style, Color.blue);}
else{StyleConstants.setForeground(style, Color.red);}
doc.insertString(doc.getLength(), SubName + " ", style);
StyleConstants.setForeground(style, Color.orange);
doc.insertString(doc.getLength(), " (" + SubPlaceName + ") ", style);
StyleConstants.setForeground(style, Color.gray);
doc.insertString(doc.getLength(), Verb +" ", style);
if (ObjType.equals("0")){
StyleConstants.setForeground(style, Color.blue);}
else{StyleConstants.setForeground(style, Color.red);}
doc.insertString(doc.getLength(), ObjName, style);
StyleConstants.setForeground(style, Color.orange);
doc.insertString(doc.getLength(), " (" + ObjPlaceName + ") \n", style);
}
catch (BadLocationException ex){}
}
cdb.st.close();
}
catch(SQLException ex){System.out.print(ex);}
} |
50bd97d8-15b1-451a-9bc6-cee3fb80d4fb | 4 | public double averageBytes() {
int runs = runs();
double[] sizes = new double[runs];
int retries = runs / 2;
final Runtime runtime = Runtime.getRuntime();
for (int i = 0; i < runs; i++) {
Thread.yield();
long used1 = memoryUsed(runtime);
int number = create();
long used2 = memoryUsed(runtime);
double avgSize = (double) (used2 - used1) / number;
// System.out.println(avgSize);
if (avgSize < 0) {
// GC was performed.
i--;
if (retries-- < 0)
throw new RuntimeException(
"The eden space is not large enough to hold all the objects.");
} else if (avgSize == 0) {
throw new RuntimeException(
"Object is not large enough to register, try turning off the TLAB with -XX:-UseTLAB");
} else {
sizes[i] = avgSize;
}
}
Arrays.sort(sizes);
return sizes[runs / 2];
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.