method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
0c78fde0-8aa7-4bf9-8f3c-ca6744cdb306
| 6
|
private void recalculateCellSize(int minSize)
{
if (numRows == 0 || numCols == 0)
{
cellSize = 0;
}
else
{
JViewport vp = getEnclosingViewport();
Dimension viewableSize = (vp != null) ? vp.getSize() : getSize();
int desiredCellSize = Math.min(
(viewableSize.height - extraHeight()) / numRows,
(viewableSize.width - extraWidth()) / numCols) - 1;
// now we want to approximate this with
// DEFAULT_CELL_SIZE * Math.pow(2, k)
cellSize = DEFAULT_CELL_SIZE;
if (cellSize <= desiredCellSize)
while (2 * cellSize <= desiredCellSize)
cellSize *= 2;
else
while (cellSize / 2 >= Math.max(desiredCellSize, MIN_CELL_SIZE))
cellSize /= 2;
}
revalidate();
}
|
50bad855-22c9-40b0-a082-7c9eb48d818f
| 8
|
private void commandSwitch(){
//Takes an input from the console and uses just the first letter
String input = menuScan.next();
char inputChar = input.charAt(0);
// Runs it through a switch to execute the appropriate command
switch (inputChar) {
case 'a': loadFile();
break;
case 'b': stateSearch();
break;
case 'c': citySearch();
break;
case 'd': setCurrentCity();
break;
case 'e': showCurrentCity();
break;
case 'f': findClosestCities();
break;
case 'g': findShortestPath();
break;
case 'h': System.out.println("Quitting");
System.exit(0);
default: System.out.println("Unrecognized input. Please try again.");
}
}
|
57625bf4-9ee0-40ca-9cae-4ff08975b5c4
| 6
|
public static void main(String[] args)
{
System.out.println("Starting network example ...");
try
{
//////////////////////////////////////////
// First step: Initialize the GridSim package. It should be called
// before creating any entities. We can't run this example without
// initializing GridSim first. We will get run-time exception
// error.
int num_user = 2; // number of grid users
Calendar calendar = Calendar.getInstance();
// a flag that denotes whether to trace GridSim events or not.
boolean trace_flag = true;
// Initialize the GridSim package
System.out.println("Initializing GridSim package");
GridSim.init(num_user, calendar, trace_flag);
//////////////////////////////////////////
// Second step: Creates one or more GridResource entities
double baud_rate = 1000; // bits/sec
double propDelay = 10; // propagation delay in millisecond
int mtu = 1500; // max. transmission unit in byte
int i = 0;
// more resources can be created by
// setting totalResource to an appropriate value
int totalResource = 1;
ArrayList resList = new ArrayList(totalResource);
for (i = 0; i < totalResource; i++)
{
GridResource res = createGridResource("Res_"+i, baud_rate,
propDelay, mtu);
// add a resource into a list
resList.add(res);
}
//////////////////////////////////////////
// Third step: Creates one or more grid user entities
// number of Gridlets that will be sent to the resource
int totalGridlet = 5;
// create users
ArrayList userList = new ArrayList(num_user);
for (i = 0; i < num_user; i++)
{
// if trace_flag is set to "true", then this experiment will
// create User_i.csv where i = 0 ... (num_user-1)
NetUser user = new NetUser("User_"+i, totalGridlet, baud_rate,
propDelay, mtu, trace_flag);
// add a user into a list
userList.add(user);
}
//////////////////////////////////////////
// Fourth step: Builds the network topology among entities.
// In this example, the topology is:
// user(s) --1Mb/s-- r1 --10Mb/s-- r2 --1Mb/s-- GridResource(s)
// create the routers.
// If trace_flag is set to "true", then this experiment will create
// the following files (apart from sim_trace and sim_report):
// - router1_report.csv
// - router2_report.csv
Router r1 = new RIPRouter("router1", trace_flag); // router 1
Router r2 = new RIPRouter("router2", trace_flag); // router 2
// connect all user entities with r1 with 1Mb/s connection
// For each host, specify which PacketScheduler entity to use.
NetUser obj = null;
for (i = 0; i < userList.size(); i++)
{
// A First In First Out Scheduler is being used here.
// SCFQScheduler can be used for more fairness
FIFOScheduler userSched = new FIFOScheduler("NetUserSched_"+i);
obj = (NetUser) userList.get(i);
r1.attachHost(obj, userSched);
}
// connect all resource entities with r2 with 1Mb/s connection
// For each host, specify which PacketScheduler entity to use.
GridResource resObj = null;
for (i = 0; i < resList.size(); i++)
{
FIFOScheduler resSched = new FIFOScheduler("GridResSched_"+i);
resObj = (GridResource) resList.get(i);
r2.attachHost(resObj, resSched);
}
// then connect r1 to r2 with 10Mb/s connection
// For each host, specify which PacketScheduler entity to use.
baud_rate = 10000;
Link link = new SimpleLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched");
FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched");
// attach r2 to r1
r1.attachRouter(r2, link, r1Sched, r2Sched);
//////////////////////////////////////////
// Fifth step: Starts the simulation
GridSim.startGridSimulation();
//////////////////////////////////////////
// Final step: Prints the Gridlets when simulation is over
// also prints the routing table
r1.printRoutingTable();
r2.printRoutingTable();
GridletList glList = null;
for (i = 0; i < userList.size(); i++)
{
obj = (NetUser) userList.get(i);
glList = obj.getGridletList();
printGridletList(glList, obj.get_name(), false);
}
System.out.println("\nFinish network example ...");
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Unwanted errors happen");
}
}
|
cc92e8bf-0a1f-4e2d-8dd9-09320af99d4d
| 8
|
public void addRequiredParameters(OAuthAccessor accessor)
throws OAuthException, IOException, URISyntaxException {
final Map<String, String> pMap = OAuth.newMap(parameters);
if (pMap.get(OAuth.OAUTH_TOKEN) == null && accessor.accessToken != null) {
addParameter(OAuth.OAUTH_TOKEN, accessor.accessToken);
}
final OAuthConsumer consumer = accessor.consumer;
if (pMap.get(OAuth.OAUTH_CONSUMER_KEY) == null) {
addParameter(OAuth.OAUTH_CONSUMER_KEY, consumer.consumerKey);
}
String signatureMethod = pMap.get(OAuth.OAUTH_SIGNATURE_METHOD);
if (signatureMethod == null) {
signatureMethod = (String) consumer.getProperty(OAuth.OAUTH_SIGNATURE_METHOD);
if (signatureMethod == null) {
signatureMethod = OAuth.HMAC_SHA1;
}
addParameter(OAuth.OAUTH_SIGNATURE_METHOD, signatureMethod);
}
if (pMap.get(OAuth.OAUTH_TIMESTAMP) == null) {
addParameter(OAuth.OAUTH_TIMESTAMP, (System.currentTimeMillis() / 1000) + "");
}
if (pMap.get(OAuth.OAUTH_NONCE) == null) {
addParameter(OAuth.OAUTH_NONCE, System.nanoTime() + "");
}
if (pMap.get(OAuth.OAUTH_VERSION) == null) {
addParameter(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0);
}
this.sign(accessor);
}
|
8e9baddf-c0d8-4245-a88b-746ba6a605cb
| 0
|
@Basic
@Column(name = "POP_NOMBRE_PROVEEDOR")
public String getPopNombreProveedor() {
return popNombreProveedor;
}
|
4b8b6eb1-0ef6-4208-8eaa-0f782ec8013f
| 9
|
public static Keyword inequalitySpecialist(ControlFrame frame, Keyword lastmove) {
lastmove = lastmove;
{ Proposition proposition = frame.proposition;
Surrogate relation = ((Surrogate)(proposition.operator));
if (((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue()) {
{ Object old$ReversepolarityP$000 = Logic.$REVERSEPOLARITYp$.get();
try {
Native.setBooleanSpecial(Logic.$REVERSEPOLARITYp$, false);
if (relation == PlKernelKb.SGT_PL_KERNEL_KB_l) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_el, (proposition.arguments.theArray)[1], (proposition.arguments.theArray)[0]));
}
else if (relation == PlKernelKb.SGT_PL_KERNEL_KB_el) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_l, (proposition.arguments.theArray)[1], (proposition.arguments.theArray)[0]));
}
else if (relation == PlKernelKb.SGT_PL_KERNEL_KB_g) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_el, (proposition.arguments.theArray)[0], (proposition.arguments.theArray)[1]));
}
else if (relation == Logic.SGT_PL_KERNEL_KB_ge) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_l, (proposition.arguments.theArray)[0], (proposition.arguments.theArray)[1]));
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + relation + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
} finally {
Logic.$REVERSEPOLARITYp$.set(old$ReversepolarityP$000);
}
}
}
else {
if (relation == PlKernelKb.SGT_PL_KERNEL_KB_l) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_l, (proposition.arguments.theArray)[0], (proposition.arguments.theArray)[1]));
}
else if (relation == PlKernelKb.SGT_PL_KERNEL_KB_el) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_el, (proposition.arguments.theArray)[0], (proposition.arguments.theArray)[1]));
}
else if (relation == PlKernelKb.SGT_PL_KERNEL_KB_g) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_l, (proposition.arguments.theArray)[1], (proposition.arguments.theArray)[0]));
}
else if (relation == Logic.SGT_PL_KERNEL_KB_ge) {
return (PlKernelKb.lessSpecialistHelper(frame, PlKernelKb.SGT_PL_KERNEL_KB_el, (proposition.arguments.theArray)[1], (proposition.arguments.theArray)[0]));
}
else {
{ OutputStringStream stream001 = OutputStringStream.newOutputStringStream();
stream001.nativeStream.print("`" + relation + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace()));
}
}
}
}
}
|
5d416c6d-4471-48a5-b62e-489c8fb795ff
| 0
|
public Point2D getRelativeCenter()
{
return new Point2D.Double(getSideLength()/2.0, getSideLength()/2.0);
}
|
c5f46422-9000-4f73-818b-0d05d7e5293b
| 6
|
public PERangeList intersection(PERangeList listb) {
PERangeList rIts = new PERangeList();
if(getNumPE() == 0 || listb.getNumPE() == 0) {
return rIts;
}
sortRanges();
listb.sortRanges();
for(PERange rq : this.ranges) {
for(PERange ru : listb.ranges) {
// rq's end is already smaller than the start of the following ranges
if(rq.getEnd() < ru.getBegin()) {
break;
}
// No intersection has started yet because ru's end is still
// smaller than the start of rq, which means ru is still smaller
if(ru.getEnd() < rq.getBegin()) {
continue;
}
rIts.add(rq.intersection(ru));
}
}
return rIts;
}
|
3666fee1-f13d-493c-bc07-4f54bc6d44f2
| 5
|
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
CometEngine engine = CometContext.getInstance().getEngine();
if (COM1.equals(portName)) {
long totalMemory = Runtime.getRuntime().totalMemory();
System.out.println("totalMemory: " + totalMemory);
int randomValue = (int) (Math.random() * 1000);
System.out.println("randomValue: " + randomValue);
map.put(portName, "" + totalMemory + randomValue);
}
if (COM2.equals(portName)) {
long freeMemory = Runtime.getRuntime().freeMemory();
System.out.println("freeMemory: " + freeMemory);
int randomValue = (int) (Math.random() * 1000);
System.out.println(randomValue);
map.put(portName, "" + freeMemory + randomValue);
}
if (COM3.equals(portName)) {
long maxMemory = Runtime.getRuntime().maxMemory();
System.out.println("maxMemory: " + maxMemory);
int randomValue = (int) (Math.random() * 1000);
System.out.println(randomValue);
map.put(portName, "" + maxMemory + randomValue);
}
System.out.println("###: " + Runtime.getRuntime().freeMemory() / 1024);
JSONObject json = JSONObject.fromObject(map);
String jsonStr = json.toString();
System.out.println(jsonStr);
engine.sendToAll(CHANNEL, jsonStr);
// HealthDTO healthDto = new HealthDTO();
// long startup = System.currentTimeMillis();
// long totalMemory = Runtime.getRuntime().totalMemory();
// long freeMemory = Runtime.getRuntime().freeMemory();
// long maxMemory = Runtime.getRuntime().maxMemory();
// long usedMemory = totalMemory - freeMemory;
// Integer connectorCount = engine.getConnections().size();
// healthDto.setConnectorCount(connectorCount.toString());
// healthDto.setFreeMemory(freeMemory);
// healthDto.setMaxMemory(maxMemory);
// healthDto.setTotalMemory(totalMemory);
// healthDto.setUsedMemory(usedMemory);
// long dif = System.currentTimeMillis() - startup;
// long day_mill = 86400000;// 一天的毫秒数 60*60*1000*24
// long hour_mill = 3600000;// 一小时的毫秒数 60*60*1000
// Long day = dif / day_mill;
// Long hour = (dif % day_mill) / hour_mill;
// String str = day.toString() + "天 " + hour.toString() + "小时";
// healthDto.setStartup(str);
// System.out.println("freeMemory: " + healthDto.getFreeMemory());
// engine.sendToAll(CHANNEL, healthDto);
}
}
|
09406153-f4d7-49d8-a4cc-ccbbf91f3538
| 5
|
public static EasyDate smartParse(String date) {
if (date == null) {
throw new NullPointerException("指定的日期字符串不能为null");
}
int length = date.length(); // 字符串长度
String format = null;
switch (length) {
case 10:// 2012-01-02
format = DATE;
break;
case 19:// 2012-01-02 13:22:56
format = DATETIME;
break;
case 8:// 20120126
format = SHORT_DATE;
break;
case 6:// 201206
format = YM_DATE;
break;
default:
throw new IllegalArgumentException("智能转换日期字符串时无法找到对应的DateFormat.");
}
return parse(format, date);
}
|
5c44479e-5d42-49ef-9be8-76269652ad0f
| 4
|
public boolean hasConverged() {
if (x >= 0 && x <= MAX_X && y >= 0 && y <= MAX_Y) {
return true;
}
return false;
}
|
64fd283d-1171-4e52-9eb1-fa462f13da1e
| 6
|
private int binarySearchInArray(K key) {
int left = 0;
int right = entryList.size() - 1;
// Optimization: For the common case in which entries are added in
// ascending tag order, check the largest element in the array before
// doing a full binary search.
if (right >= 0) {
int cmp = key.compareTo(entryList.get(right).getKey());
if (cmp > 0) {
return -(right + 2); // Insert point is after "right".
} else if (cmp == 0) {
return right;
}
}
while (left <= right) {
int mid = (left + right) / 2;
int cmp = key.compareTo(entryList.get(mid).getKey());
if (cmp < 0) {
right = mid - 1;
} else if (cmp > 0) {
left = mid + 1;
} else {
return mid;
}
}
return -(left + 1);
}
|
51b584f9-aa71-461c-9c79-e7dc35fc3fdb
| 8
|
private void clearRows()
{
for (int i=0;i<board.length;i++)
{
boolean canRowClear=true;
for (int j=0;j<board[0].length;j++)
{
if (board[i][j]==0)
{
canRowClear=false;
}
}
if (canRowClear)
{
score+=10;
//clear row
for (int k=0;k<board[0].length;k++)
{
board[i][k]=0;
}
//shift other rows down
for (int k=i-1;k>=0;k--)
{
for (int m=0;m<board[0].length;m++)
{
board[k+1][m]=board[k][m];
}
}
//clear top row
for (int k=0;k<board[0].length;k++)
{
board[0][k]=0;
}
}
}
}
|
e54263ab-351e-4ba7-a01f-e0aa67800453
| 7
|
String getNextDataToken() throws Exception {
String str = peekToken();
if (str == null)
return null;
if (wasUnQuoted())
if (str.charAt(0) == '_' || str.startsWith("loop_")
|| str.startsWith("data_")
|| str.startsWith("stop_")
|| str.startsWith("global_"))
return null;
return tokenizer.getTokenPeeked();
}
|
55037c0a-05bb-4af4-af4e-0b381a66fbbb
| 8
|
public void deleteDuplicatesByGenes(List<Bin> newGenes) {
for(int i = 0; i < this.bins.size(); i++){
for(int j = 0; j < newGenes.size(); j++){
for(int n = 0; n < newGenes.get(j).getAll().size(); n++){
for(int m = 0; m < this.bins.get(i).getAll().size(); m++){
if(this.bins.get(i).getElement(m).getId() == newGenes.get(j).getElement(n).getId()){
this.bins.get(i).remove(m);
this.bins.get(i).markForDelete();
break;
}
}
}
}
}
List<Bin> newBins = new ArrayList<Bin>();
for(int i = 0; i < this.bins.size(); i++){
if(this.bins.get(i).toDelete()){
List<Element> elements = this.bins.get(i).getAll();
for(int k = 0; k < elements.size(); k++){
this.freeItems.add(elements.get(k));
}
} else {
newBins.add(this.bins.get(i));
}
}
this.bins = newBins;
}
|
c97a6ad4-fe94-43d2-8d18-ffc2288893c6
| 4
|
@SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = session.createQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getFirstResult();
} catch (NoResultException e) {
System.out.println("No result found for named query: " + namedQuery);
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}
|
1552eb03-9e92-4ad2-88d6-6e258f674caf
| 2
|
public boolean isOnEarth(){
if(jumpEnd){
if(jumpAnimation == 5){
jumpEnd = false;
jumpAnimation = 0;
} else {
jumpAnimation++;
}
return true;
} else {
return false;
}
}
|
ee9ad308-70e6-4abd-b6ee-4fd8b967edc5
| 2
|
static byte[] getFakedCookie(Session session){
synchronized(faked_cookie_hex_pool){
byte[] foo=(byte[])faked_cookie_hex_pool.get(session);
if(foo==null){
Random random=Session.random;
foo=new byte[16];
synchronized(random){
random.fill(foo, 0, 16);
}
/*
System.err.print("faked_cookie: ");
for(int i=0; i<foo.length; i++){
System.err.print(Integer.toHexString(foo[i]&0xff)+":");
}
System.err.println("");
*/
faked_cookie_pool.put(session, foo);
byte[] bar=new byte[32];
for(int i=0; i<16; i++){
bar[2*i]=table[(foo[i]>>>4)&0xf];
bar[2*i+1]=table[(foo[i])&0xf];
}
faked_cookie_hex_pool.put(session, bar);
foo=bar;
}
return foo;
}
}
|
3dcb2b9a-e13a-4a57-9d93-26a990fe7f11
| 6
|
private void checkWinner() {
boolean test = false;
if (test || m_test)
System.out.println("ConnectFour::checkWinner() - BEGIN");
for (int y = 0; y < GAME_HEIGHT; y++) {
for (int x = 0; x < GAME_WIDTH; x++) {
checkRight(x, y);
checkDown(x, y);
checkDiagonalUp(x, y);
checkDiagonalDown(x, y);
}
}
if (test || m_test)
System.out.println("ConnectFour::checkWinner() - END");
}
|
96cd3367-40a9-48ef-af15-c145a11d245e
| 3
|
public static BufferedImage resizeImage(BufferedImage image, double scale) {
if ((scale == 1.0) || (image == null)) {
return image;
}
int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image
.getType();
float width = image.getWidth();
float height = image.getHeight();
int newHeight = (int) Math.round(height * scale);
int newWidth = Math.round((width * newHeight) / height);
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight,
type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();
return resizedImage;
}
|
856c9e79-2c01-473c-b047-7738132a8219
| 1
|
public ArrayList viewMyBookingCheckin() {
ArrayList temp = new ArrayList();
Query q = em.createQuery("SELECT t from BookingEntity t");
for (Object o : q.getResultList()) {
BookingEntity p = (BookingEntity) o;
temp.add(sdf.format(p.getCheckinDate()));
System.out.println("aa"+sdf.format(p.getCheckinDate()));
}
return temp;
}
|
1f94dc28-8327-48b2-a74b-fc15521964b3
| 4
|
private void jButtonBekaeftBetalingActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonBekaeftBetalingActionPerformed
{//GEN-HEADEREND:event_jButtonBekaeftBetalingActionPerformed
if (jCheckBoxBetalt.isSelected())
{
for (int i = 0; i < control.getOrderlist().size(); i++)
{
if (jListStatusListe.getSelectedValue().toString().equals(control.getOrderlist().get(i).toString()))
{
control.getOrderlist().get(i).setState(1);
control.updateOrder(control.getOrderlist().get(i));
StatusListe.clear();
jTextOrdreInformationer.setText("");
jCheckBoxBetalt.setSelected(false);
for (int j = 0; j < control.getOrderlist().size(); j++)
{
StatusListe.addElement(control.getOrderlist().get(j).toString());
}
break;
}
}
}
}//GEN-LAST:event_jButtonBekaeftBetalingActionPerformed
|
fa75d76d-f0b2-4ea3-a8cf-6bc4e714677a
| 3
|
@Override
public void keyPressed(KeyEvent ke)
{
//synchronized(this)
//{
this.input = this.input.concat(Character.toString(ke.getKeyChar()));
if(ke.getKeyChar() == KeyEvent.VK_BACK_SPACE ) if(this.input.length()>=2)this.input= this.input.substring(0, this.input.length()-2);
if(ke.getKeyChar() ==KeyEvent.VK_ENTER)
{
System.out.println("Enter");
this.inputRecieved=true;
}
//}
}
|
21c83019-cb63-4eab-a859-89c6c8d24f64
| 1
|
private void storeEditData () {
int selRow = rosterTable.getSelectedRow();
if (selRow >= 0) {
Roster selRoster = MainWindow.rosterDB.getRosters().get(selRow);
selRoster.setFamilyName (familyNameField.getText());
selRoster.setGivenName (givenNameField.getText());
selRoster.setPhoneNumber(phoneNumberField.getText());
selRoster.setIsAspirant(isAspirantCheckBox.getState());
// sort roster list
MainWindow.rosterDB.sort();
// refresh roster list
refreshList();
}
}
|
c87f5031-3e3c-426a-8456-68309f2d240f
| 6
|
@Override
public void draw(Graphics2D drawScreen, int offsetX, int offsetY) {
totalVisibleEnities = 0;
clearMaps();
sortEntitiesToMap();
// At this point we will have a list of only visible sprites, and
// the map should contain the draw order required. Remember that not
// every key will match up with the required draw order!
for (DrawOrder drawOrder : drawOrders) {
// Because of the lazy initialization of keys/values
// visibleSprites.get(drawOrder) might actually be null
if (visibleSprites.containsKey(drawOrder)) {
for (RenderSystem.VisibleSprite visibleSprite : visibleSprites.get(drawOrder)) {
Spatial spatial = visibleSprite.spatialComponent;
BufferedImage drawImage = visibleSprite.drawComponent.getImage();
// If the spatial's location has changed we must investigate
// whether or not the rotation has also changed, if it is we
// shall apply the required affine transformation to the
// Draw component for re-caching
if (spatial.spatialChanged) {
if (spatial.previousSpatialWasNull || spatial.previousSpatial.getRotation() != spatial.getRotation()) {
AffineTransform tx = AffineTransform.getRotateInstance(spatial.getRotation(), spatial.width / 2, spatial.height / 2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Get the raw image and apply the transformation,
// then set its new graphic to the transformed image
visibleSprite.drawComponent.setImage(op.filter(visibleSprite.drawComponent.getRawImage(), null));
}
}
// Draw the required sprite
drawScreen.drawImage(drawImage,
(int) (spatial.x + offsetX - viewPort.getX()),
(int) (spatial.y + offsetY - viewPort.getY()),
null);
}
}
}
}
|
c1c70263-68b0-4b55-9636-71804790bd5b
| 8
|
private boolean r_factive() {
int among_var;
// (, line 132
// [, line 133
ket = cursor;
// substring, line 133
among_var = find_among_b(a_7, 2);
if (among_var == 0)
{
return false;
}
// ], line 133
bra = cursor;
// call R1, line 133
if (!r_R1())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 134
// call double, line 134
if (!r_double())
{
return false;
}
break;
case 2:
// (, line 135
// call double, line 135
if (!r_double())
{
return false;
}
break;
}
// delete, line 137
slice_del();
// call undouble, line 138
if (!r_undouble())
{
return false;
}
return true;
}
|
a016b6c3-d84d-4212-a671-3519ea4fee65
| 4
|
public boolean removeBlockFromRoulette(Block block) {
Set<Integer> tilesKeys = tilesLocations.keySet();
for(Integer key : tilesKeys) {
SerializableLocation blockLocation = new SerializableLocation(block.getLocation());
if(tilesLocations.get(key).contains(blockLocation)) {
tilesLocations.get(key).remove(blockLocation);
return true;
}
} Set<Integer> spinnersKeys = spinnersLocations.keySet();
for(Integer key : spinnersKeys) {
SerializableLocation blockLocation = new SerializableLocation(block.getLocation());
if(spinnersLocations.get(key).equals(blockLocation)) {
spinnersLocations.remove(key);
return true;
}
} return false;
}
|
1ec452a2-e37e-49e0-81d3-3a046f522b92
| 7
|
public static void back(int index, int cur) {
if (index >= list.length) {
if (cur > nBlacks) {
nBlacks = cur;
ans = color.clone();
}
return;
}
boolean neighBlack = false;
for (int i = 0; i < list[index].size() && !neighBlack; i++)
if (color[list[index].get(i)])
neighBlack = true;
if (!neighBlack && index != 0) {
color[index] = true;
back(index + 1, cur + 1);
color[index] = false;
}
back(index + 1, cur);
}
|
74c4df69-feee-4a6e-bbc2-b2d1e556fe5c
| 2
|
@Override
public void render() {
if(location.getWeaponID() == WeaponLocation.NO_WEAPON) {
super.render();
}
if(renderData) {
locData.render();
}
}
|
b0277cf9-5970-4ad7-8ff7-315e3e086577
| 8
|
private void initialize() {
frmGui = new JFrame();
//frmGui.setResizable(false);
frmGui.setTitle("guiTSP");
frmGui.setBounds(100, 100, 346, 786);
frmGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmGui.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel pnlInput = new JPanel();
frmGui.getContentPane().add(pnlInput, BorderLayout.NORTH);
pnlInput.setLayout(new GridLayout(0, 4, 0, 0));
JLabel lblCiclos = new JLabel("Ciclos:");
pnlInput.add(lblCiclos);
textField = new JTextField();
textField.setText("200");
pnlInput.add(textField);
textField.setColumns(10);
JLabel lblPoblacin = new JLabel("Población:");
pnlInput.add(lblPoblacin);
textField_1 = new JTextField();
textField_1.setText("50");
pnlInput.add(textField_1);
textField_1.setColumns(10);
JLabel lblCiudad = new JLabel("Ciudad:");
pnlInput.add(lblCiudad);
final JTextField txtIndiceCiudad = new JTextField();
txtIndiceCiudad.setText("21");
pnlInput.add(txtIndiceCiudad);
txtIndiceCiudad.setColumns(5);
JPanel pnlBtnResult = new JPanel();
frmGui.getContentPane().add(pnlBtnResult, BorderLayout.SOUTH);
pnlBtnResult.setLayout(new BorderLayout(0, 0));
JPanel pnlResult = new JPanel();
pnlBtnResult.add(pnlResult, BorderLayout.NORTH);
final JLabel lblResultado = new JLabel("");
pnlResult.add(lblResultado);
JPanel pnlBotones = new JPanel();
pnlBtnResult.add(pnlBotones, BorderLayout.SOUTH);
pnlBotones.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnEjecutarAlgGentico = new JButton("Ejecutar Alg. Genético");
pnlBotones.add(btnEjecutarAlgGentico);
btnEjecutarAlgGentico.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
GeneticoEst.CANT_CICLOS = Integer.valueOf(textField.getText());
GeneticoEst.CANT_POBLACION = Integer.valueOf(textField_1.getText());
GeneticoEst gen = new GeneticoEst();
Poblacion p = null;
for (int i = 0; i < GeneticoEst.CANT_CICLOS; i++) {
if (i == 0) {
p = gen.nuevaPoblacion();
//QUITADO p.processFitness();
} else {
p = gen.nuevaPoblacion(p);
//p.processFitness();
}
p.printPoblacion();
}
p.processFitness();
Cromosoma resultado = new Cromosoma();
resultado.setFitness(0);
for (Cromosoma c : p){
if (c.getFitness()>resultado.getFitness()){
resultado = c;
}
}
pnlMapa.dibujarRecorrido(resultado.getCiudades());
// pnlMapa.repaint();
lblResultado.setText("Ciudad Inicial: " + Constants.NOMBRES_PROVINCIAS[resultado.getCiudades()[0]]
+ " i: "+resultado.getCiudades()[0] + " y recorrido de " + resultado.getDistanciaRecorrido() + "km");
}
});
JButton btnEjecutarAlgHeurstico = new JButton(
"Ejecutar Alg. Heurístico");
btnEjecutarAlgHeurstico.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("done");
int mejorCiudad = -1;
int mejorRecorrido = -1;
for (int i = 0; i < Constants.CANTIDAD_PROVINCIAS; i++) {
HeuristicaFacu hf = new HeuristicaFacu();
hf.recorreCiudades(i);
if (mejorRecorrido < 0
|| mejorRecorrido > hf.getKmRecorridos()) {
mejorRecorrido = hf.getKmRecorridos();
mejorCiudad = i;
}
}
HeuristicaFacu hf = new HeuristicaFacu();
if(!txtIndiceCiudad.getText().isEmpty())
mejorCiudad= Integer.parseInt(txtIndiceCiudad.getText());
hf.recorreCiudades(mejorCiudad);
mejorRecorrido= hf.getKmRecorridos();
pnlMapa.dibujarRecorrido(hf.getRecorrido());
// pnlMapa.repaint();
lblResultado.setText("Ciudad Inicial: " + Constants.NOMBRES_PROVINCIAS[mejorCiudad]
+ " i: "+mejorCiudad + " y recorrido de " + mejorRecorrido + "km");
}
});
// btnEjecutarAlgHeurstico.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent arg0) {
//
// /*
// * int indice = hf.getRecorrido()[0];
// *
// *
// *
// * int x = Constants.COORENADAS_CIUDADES[indice].getX(); int y =
// * Constants.COORENADAS_CIUDADES[indice].getY();
// * pnlMapa.pintarInicio(x, y);
// */
//
//
// }
// });
pnlBotones.add(btnEjecutarAlgHeurstico);
ImageIcon imagen = new ImageIcon(IMG_PATH);
pnlMapa = new ImagePanel(imagen.getImage());
/*
* pnlMapa.addMouseMotionListener(new MouseMotionAdapter() {
*
* @Override public void mouseMoved(MouseEvent arg0) { try {
*
* System.out.println(arg0.getX()+ ":" + arg0.getY());
*
* }catch (Exception e){
*
*
*
* } } });
*/
frmGui.getContentPane().add(pnlMapa, BorderLayout.CENTER);
}
|
27b9535c-5a0f-45b2-b690-f3ddf68efa06
| 2
|
private void itmMnu_EncarregadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmMnu_EncarregadoActionPerformed
if ((usuarioLogado.getTipo().equals("Diretor")) || (usuarioLogado.getTipo().equals("Gerente"))) {
GerenciarEncarregadoForm gerenciarEncarregadoForm = null;
gerenciarEncarregadoForm = new GerenciarEncarregadoForm(usuarioLogado);
gerenciarEncarregadoForm.setVisible(true);
centralizaForm(gerenciarEncarregadoForm);
JDP1.add(gerenciarEncarregadoForm);
} else {
JOptionPane.showMessageDialog(null, "Você não possui previlégios para acessar \n "
+ "a Tela de Gestão de Encarregado!!!",
"Gestão de Encarregado", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_itmMnu_EncarregadoActionPerformed
|
9f7a828d-6d7b-4e32-a0af-d0f0aa1d763b
| 3
|
@Override
protected void checkAfterParse(Method method) throws DaoGenerateException {
super.checkAfterParse(method);
Class<?> returnType = method.getReturnType();
isReturnCollection = ClassHelper.isTypeCollection(returnType);
if (isReturnCollection && StringUtils.isEmpty(vkey)) {
throw new DaoGenerateException("方法[" + method + "]配置错误: 对于返回集合类型的方法,@Cache注解中必须包含");
}
}
|
fdb309a2-9e37-472a-a8e3-9570b1178467
| 1
|
public Map<String, Map<Integer, Map<String, Double>>> getAll()
throws FileNotFoundException, IOException {
for (String file : trainingFileString) {
getWordInClass(file);
}
return allMap;
}
|
b83d5c6e-0c0e-4991-b97d-6c6f4f90a3a0
| 2
|
private void processConnection() throws IOException
{
String message = "Connection successful";
sendData( message ); // send connection successful message
// enable enterField so server user can send messages
// setTextFieldEditable( true );
do // process messages sent from client
{
try // read message and display it
{
message = ( String ) input.readObject(); // read new message
System.out.println( "\n" + message ); // display message
} // end try
catch ( ClassNotFoundException classNotFoundException )
{
System.out.println( "\nUnknown object type received" );
} // end catch
} while ( !message.equals( "CLIENT>>> TERMINATE" ) );
} // end method processConnection
|
c32f4a37-f0bf-4a25-a929-8bb2e784b49a
| 0
|
public int getSteps() {
return steps;
}
|
0f3002d2-4716-468a-b47a-db9f6791dbe3
| 6
|
public void printOutput() throws Exception {
if (inFile==null) throw new Exception("class not initialized");
String sIn=this.inFile.readLine();
sIn=sIn.trim();
Integer iVal=new Integer(sIn);
System.out.println("Got3: [" + iVal + "]");
for (int i=1; i<=iVal.intValue(); ++i) {
boolean blThree=((i%3)==0);
boolean blFive=((i%5)==0);
if (blThree&&blFive)
System.out.println("Hop");
else if (blThree)
System.out.println("Hoppity");
else if (blFive)
System.out.println("Hophop");
}
}
|
b3d33665-fb90-41b3-9f05-b4ad73e921ce
| 1
|
public static String[] dataToStringArray(byte[][] data) {
String[] strings = new String[data.length];
for(int i = 0; i < data.length; i++) {
strings[i] = new String(data[i]); //.toString();
}
return strings;
}
|
026867b1-2223-49a3-8946-c967b799f2de
| 9
|
public void handleKeyboardEvent(int keycode){
availableMoves = gameboard.getAvailableMoves(workingTetromino, column, row);
//Gestion des mutateurs
switch(keycode) {
case KeyEvent.VK_UP:{
if(availableMoves.canRotateRight()) {
workingTetromino.rotateRight();
}
break;
}
case KeyEvent.VK_DOWN : {
if(availableMoves.canRotateLeft()) {
workingTetromino.rotateLeft();
}
break;
}
case KeyEvent.VK_RIGHT : {
if(availableMoves.canTranslateRight()) {
++column;
}
break;
}
case KeyEvent.VK_LEFT : {
if(availableMoves.canTranslateLeft()) {
--column;
}
break;
}
case KeyEvent.VK_SPACE : {
row = gameboard.drop(this);
break;
}
default:{}
}
}
|
71031de1-9f12-4e3f-98a7-65692f28c370
| 4
|
public static float getFloat() {
float x = 0.0F;
while (true) {
String str = readRealString();
if (str == null) {
errorMessage("Floating point number not found.",
"Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE);
}
else {
try {
x = Float.parseFloat(str);
}
catch (NumberFormatException e) {
errorMessage("Illegal floating point input, " + str + ".",
"Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE);
continue;
}
if (Float.isInfinite(x)) {
errorMessage("Floating point input outside of legal range, " + str + ".",
"Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE);
continue;
}
break;
}
}
inputErrorCount = 0;
return x;
}
|
9f1790a3-d4cb-4426-83ed-12f96c19ec34
| 0
|
public static void main(String[] args) {
Human human = new Human();
//human.name = "Slava";
human.setName("Sanya");
System.out.println(human.getName());
human.setAge(10);
//human.age = -345;
System.out.println(human.getAge());
}
|
df33c177-b21e-4153-9ee8-67129cdae9b0
| 9
|
public Projectile createNewProjectile(String name)
{
Projectile projectile = null;
if (name.equals("random"))
{
name = Helper.getWeightedRandomValue(this.weightedValues);
}
try
{
Class<?> projectileClass = Class.forName(name);
Constructor<?> constructor = projectileClass.getConstructor(new Class<?>[] {Board.class});
projectile = (Projectile) constructor.newInstance(this);
}
catch (NoSuchMethodException x)
{
System.out.println("NoSuchMethodException was catched from Board.java");
}
catch (ClassNotFoundException x)
{
System.out.println("ClassNotFoundException was catched from Board.java");
}
catch (InstantiationException x)
{
System.out.println("InstantiationException was catched from Board.java");
}
catch (IllegalAccessException x)
{
System.out.println("IllegalAccessException was catched from Board.java");
}
catch (InvocationTargetException x)
{
System.out.println("InvocationTargetException was catched from Board.java");
}
return projectile;
}
|
6e4d48c9-46a0-45ee-83a3-0d94a92b05fe
| 8
|
public void modelUpdate(final ModelEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
switch (e.getID()) {
case ModelEvent.SCRIPT_START:
if (disabledAtScript)
enableButton(false, e.getSource());
break;
case ModelEvent.SCRIPT_END:
if (disabledAtScript)
enableButton(true, e.getSource());
break;
case ModelEvent.MODEL_RUN:
if (disabledAtRun)
enableButton(false, e.getSource());
break;
case ModelEvent.MODEL_STOP:
if (disabledAtRun)
enableButton(true, e.getSource());
break;
}
}
});
}
|
8b62912a-09dc-4d68-bb40-7953fa74a306
| 7
|
public void initToNull() {
for (int z = 0; z < mapSizeZ; z++) {
for (int x = 0; x < mapSizeX; x++) {
for (int y = 0; y < mapSizeY; y++)
groundArray[z][x][y] = null;
}
}
for (int l = 0; l < anInt472; l++) {
for (int j1 = 0; j1 < cullingClusterPointer[l]; j1++)
cullingClusters[l][j1] = null;
cullingClusterPointer[l] = 0;
}
for (int k1 = 0; k1 < interactiveObjectCacheCurrentPos; k1++)
interactiveObjectCache[k1] = null;
interactiveObjectCacheCurrentPos = 0;
for (int l1 = 0; l1 < interactiveObjects.length; l1++)
interactiveObjects[l1] = null;
}
|
e2f0bd54-0733-49cb-9273-f3efee84370c
| 9
|
public static void ensureTokenizerBufferSize(TokenizerStreamState state, int currenttokenstart, int requiredspace) {
{ int size = state.bufferSize;
int newsize = size;
int end = ((state.end) % size);
int freespace = ((currenttokenstart == -1) ? size : (((end <= currenttokenstart) ? (currenttokenstart - end) : (currenttokenstart + (size - end)))));
char[] buffer = state.buffer;
char[] newbuffer = buffer;
while (freespace < requiredspace) {
freespace = freespace + newsize;
newsize = newsize * 2;
}
if (newsize > size) {
newbuffer = new char[newsize];
if (currenttokenstart < 0) {
state.cursor = 0;
state.end = newsize;
}
else if (end > currenttokenstart) {
{ int i = Stella.NULL_INTEGER;
int iter000 = currenttokenstart;
int upperBound000 = end - 1;
for (;iter000 <= upperBound000; iter000 = iter000 + 1) {
i = iter000;
newbuffer[i] = (char)(((char) (0x00ff & buffer[i])));
}
}
}
else {
{ int i = Stella.NULL_INTEGER;
int iter001 = currenttokenstart;
int upperBound001 = size - 1;
for (;iter001 <= upperBound001; iter001 = iter001 + 1) {
i = iter001;
newbuffer[i] = (char)(((char) (0x00ff & buffer[i])));
}
}
{ int i = Stella.NULL_INTEGER;
int iter002 = 0;
int upperBound002 = end - 1;
int j = Stella.NULL_INTEGER;
int iter003 = size;
for (;iter002 <= upperBound002; iter002 = iter002 + 1, iter003 = iter003 + 1) {
i = iter002;
j = iter003;
newbuffer[j] = (char)(((char) (0x00ff & buffer[i])));
}
}
state.end = size + end;
state.cursor = state.end;
}
state.buffer = newbuffer;
state.bufferSize = newsize;
}
}
}
|
33d0f0fc-8494-4838-a1b2-73dbf979baa9
| 8
|
private void qsort(Object[] items, Comparator comparator, int l, int r)
{
final int M = 4;
int i;
int j;
Object v;
if((r - l) > M)
{
i = (r + l) / 2;
if(comparator.compare(items[l], items[i]) > 0)
{
swap(items, l, i);
}
if(comparator.compare(items[l], items[r]) > 0)
{
swap(items, l, r);
}
if(comparator.compare(items[i], items[r]) > 0)
{
swap(items, i, r);
}
j = r - 1;
swap(items, i, j);
i = l;
v = items[j];
while(true)
{
while(comparator.compare(items[++i], v) < 0)
{
}
while(comparator.compare(items[--j], v) > 0)
{
}
if(j < i)
{
break;
}
swap(items, i, j);
}
swap(items, i, r - 1);
qsort(items, comparator, l, j);
qsort(items, comparator, i + 1, r);
}
}
|
bfd4e0cc-97fe-4763-bcbd-c77a5d57ca5c
| 5
|
public boolean saveAsRaw(String filename) throws Exception {
if (null == filename) {
throw new Exception("Filename must not be null");
}
// open the streams and send the height data to the file.
try {
FileOutputStream fos = new FileOutputStream(filename);
DataOutputStream dos = new DataOutputStream(fos);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
dos.writeFloat(getValueAtPoint(i, j));
}
}
fos.close();
dos.close();
} catch (FileNotFoundException e) {
Logger.getLogger(GenericTerrainMap.class.getName()).log(Level.WARNING, "Error opening file {0}", filename);
return false;
} catch (IOException e) {
Logger.getLogger(GenericTerrainMap.class.getName()).log(Level.WARNING, "Error writing to file {0}",
filename);
return false;
}
Logger.getLogger(GenericTerrainMap.class.getName()).log(Level.FINE, "Saved terrain to {0}", filename);
return true;
}
|
44a805aa-5622-4322-a322-7d3847d61952
| 9
|
private int getConstructorType(StructuredBlock body) {
/*
* A non static constructor must begin with a call to another
* constructor. Either to a constructor of the same class or to the
* super class
*/
InstructionBlock ib;
if (body instanceof InstructionBlock)
ib = (InstructionBlock) body;
else if (body instanceof SequentialBlock
&& (body.getSubBlocks()[0] instanceof InstructionBlock))
ib = (InstructionBlock) body.getSubBlocks()[0];
else
return 0;
Expression superExpr = ib.getInstruction().simplify();
if (!(superExpr instanceof InvokeOperator)
|| superExpr.getFreeOperandCount() != 0)
return 0;
InvokeOperator superInvoke = (InvokeOperator) superExpr;
if (!superInvoke.isConstructor() || !superInvoke.isSuperOrThis())
return 0;
Expression thisExpr = superInvoke.getSubExpressions()[0];
if (!isThis(thisExpr, clazzAnalyzer.getClazz()))
return 0;
if (superInvoke.isThis())
return 2;
else
return 1;
}
|
7009c8d5-8340-4833-8f0e-f067e8e89865
| 0
|
public int[] getData() {
return data;
}
|
85d88e53-9200-4a90-9c08-170b5238cae8
| 8
|
public void WGListWords(String sender, String login, String hostname, Command command) {
Game game = null;
User user = null;
if(command.arguments.length == 2) {
game = games.get(getServer() + " " + command.arguments[1]);
user = getUser(game, sender, login, hostname);
}
else if(command.arguments.length == 1) {
for(Game loopgame : games.values()) {
User loopuser = loopgame.getUser(sender, login, hostname);
if(loopuser != null) {
user = loopuser;
game = games.get(getServer() + " " + user.defaultchannel);
if(game != null) {
user = game.getUser(sender, login, hostname);
break;
}
}
}
if(game == null) {
sendMessage(sender, MSG_WANTDEFAULTCHANNEL);
sendMessage(sender, "Otherwise, use: !wglistwords <#channel>");
return;
}
if(user == null) {
tellNotRegistered(sender, null);
return;
}
}
else {
sendMessage(sender, "WGLISTWORDS usage: !wglistwords <#channel>");
sendMessage(sender, MSG_WANTDEFAULTCHANNEL);
return;
}
// We got all the needed data, continue
if(user == null) {
tellNotRegistered(sender, null);
}
else {
sendMessage(sender, user.listWords());
}
}
|
33b8b65f-7c49-4920-a364-bc19d1c50bfb
| 1
|
public static void run(Class serverClass) {
try {
executeInstance((NanoHTTPD) serverClass.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
|
2899e3e7-357d-4a48-af81-8e09b945fb8b
| 0
|
public Student(String name)
{
this.name = name;
}
|
936091a4-6f7b-4690-b426-b0436cda978c
| 8
|
public static boolean modifyRow (Object bean, String field) {
PreparedStatement stmt = null;
try{
if(bean instanceof Patient){
return modifyPatient((Patient)bean, stmt, field);
}
if(bean instanceof Employee){
return modifyEmployee((Employee)bean, stmt, field);
}
if(bean instanceof Drug){
return modifyDrug((Drug)bean, stmt, field);
}
if(bean instanceof Prescription){
return modifyPrescription((Prescription) bean, stmt, field);
}
if(bean instanceof Schedule){
return modifySchedule((Schedule)bean, stmt, field);
}
}catch(SQLException e){
System.out.println("SQLException within modifyRow()");
System.out.println(e);
}finally{
if(stmt != null)
try {
stmt.close();
} catch (SQLException e) {
System.out.println("unable to close stmt within modifyRow()");
e.printStackTrace();
}
}
return false;
}
|
d7ce04a6-5959-4d1c-8f4e-d9ee04c2d02b
| 2
|
public void setServerTypeClassName(String newClassName){
if(newClassName.equals(serverTypeClassName))
return;
if (ServerType.isValidServerTypeClassName(newClassName))
throw new IllegalArgumentException(INVALID_CLASSNAME);
serverTypeClassName = newClassName;
useNewModel();
}
|
7bd3d6ef-6d0a-42fd-ad5e-f47cb1783738
| 9
|
public void configForLanding(Object arg[]) {
text.setText("") ;
text.append("\nExpedition Settings:\n") ;
describePerk(0, "Site Type" , SITE_DESC ) ;
describePerk(1, "Funding Level", FUNDING_DESC) ;
describePerk(2, "Granted Title", gender == 1 ? TITLE_MALE : TITLE_FEMALE) ;
text.append("\n Colonists:") ;
int totalColonists = 0 ; for (int i : colonists) totalColonists += i ;
text.append(" ("+totalColonists+"/"+MAX_COLONISTS+")") ;
int i = 0 ; for (Background b : COLONIST_BACKGROUNDS) {
text.append("\n "+colonists[i++]+" ") ;
Call.add(" More", Colour.CYAN, this, "incColonists", text, b, 1) ;
Call.add(" Less", Colour.CYAN, this, "incColonists", text, b, -1) ;
text.append(" "+b.name) ;
}
text.append("\n Accompanying Household:") ;
text.append(" ("+advisors.size()+"/"+MAX_ADVISORS+")") ;
for (Background b : ADVISOR_BACKGROUNDS) {
final Colour c = advisors.includes(b) ? Colour.CYAN : null ;
Call.add("\n "+b.name, c, this, "setAdvisor", text, b) ;
}
boolean canBegin = true ;
if (perkSpent < MAX_PERKS) canBegin = false ;
if (totalColonists < MAX_COLONISTS) canBegin = false ;
if (advisors.size() < MAX_ADVISORS) canBegin = false ;
if (canBegin) {
text.append("\n\n (Sections complete)", Colour.LIGHT_GREY) ;
Call.add("\n Begin Game", this, "beginNewGame", text) ;
}
else {
text.append("\n\n (Please fill all sections)", Colour.LIGHT_GREY) ;
text.append("\n Begin Game", Colour.LIGHT_GREY) ;
}
Call.add("\n Go Back", this, "configForNew", text) ;
}
|
2bf29cb0-9662-4771-8c75-3ac3065d62db
| 0
|
public void setName(String name) {
this.name = name;
}
|
d3cda205-a8b7-491b-9a64-626d7e0214bc
| 3
|
private boolean createGridlets() {
int type = INTERACTIVE_JOBS;
int nodes = 1, runTime = -1;
long arrTime = -1;
arrivalInit(aarr, barr, anum, bnum, start, weights);
for (int i=0; i<numJobs; i++) {
long[] info = getNextArrival(type, weights, aarr, barr);
type = (int)info[0];
arrTime = info[1];
if(arrTime > workloadDuration) {
return true;
}
nodes = calcNumberOfNodes(serialProb[type] , pow2Prob[type],
uLow[type], uMed[type], uHi[type], uProb[type]);
runTime = (int)timeFromNodes(a1[type], b1[type], a2[type], b2[type],
pa[type], pb[type], nodes);
int len = runTime * rating; // calculate a job length for each PE
Gridlet gl = new Gridlet(i+1, len, size, size);
gl.setNumPE(nodes); // set the requested num of proc
// check the submit time
if (arrTime < 0) {
arrTime = 0;
}
WorkloadJob job = new WorkloadJob(gl, arrTime);
jobs.add(job);
}
return true;
}
|
29b49b71-f4b2-4693-a09c-68868ca5d43c
| 9
|
private void convertToArrAdj() {
// Log.print(Log.system, "Converting graph to ARR_ADJ");
switch (getState()) {
// ARR_INC -> ARR_ADJ
case ARR_INC:
clearGraph(States.ARR_ADJ);
for (int j = 0; j < M; j++) {
boolean isFirstFinded = false;
// First - отрицательное число, откуда ребро уходит, Second -
// положительное, туда ребро входит
int posFirst = 0;
int posSecond = 0;
for (int i = 0; i < N; i++) {
if (arr_inc[i][j] != 0) {
if (arr_inc[i][j] < 0)
posFirst = i;
else
posSecond = i;
if (!isFirstFinded) {
isFirstFinded = true;
} else {
arr_adj[posFirst][posSecond] = arr_inc[posSecond][j];
// arr_adj[i][posFirst] = arr_inc[i][j];
isFirstFinded = false;
}
}
}
}
break;
// LIST_ADJ -> ARR_ADJ
case LIST_ADJ:
clearGraph(States.ARR_ADJ);
for (int i = 0; i < N; i++) {
for (ListNode vertex : list_adj[i]) {
arr_adj[i][vertex.data] = vertex.weight;
}
}
break;
default:
break;
}
this.state = States.ARR_ADJ;
// After convert have to count edges.
countEdges();
}
|
d087ca83-593a-4174-8ec6-2f46bf0cde9c
| 8
|
private Color getColor(int col) {
switch (col) {
case BLACK:
return Color.BLACK;
case LIGHT_GRAY:
return Color.LIGHT_GRAY;
case RED:
return Color.RED;
case ORANGE:
return Color.ORANGE;
case YELLOW:
return Color.YELLOW;
case GREEN:
return Color.GREEN;
case BLUE:
return Color.BLUE;
case PINK:
return Color.PINK;
}
return null;
}
|
09d88278-6c83-4853-9219-d053b7e2866e
| 6
|
public void drawScreen(int par1, int par2, float par3)
{
this.func_41040_b(par1, par2, par3);
Tessellator var4 = Tessellator.instance;
short var5 = 274;
int var6 = this.width / 2 - var5 / 2;
int var7 = this.height + 50;
float var8 = -((float)this.updateCounter + par3) * this.field_41043_e;
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, var8, 0.0F);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("/title/mclogo.png"));
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.drawTexturedModalRect(var6, var7, 0, 0, 155, 44);
this.drawTexturedModalRect(var6 + 155, var7, 0, 45, 155, 44);
var4.setColorOpaque_I(16777215);
int var9 = var7 + 200;
int var10;
for (var10 = 0; var10 < this.lines.size(); ++var10)
{
if (var10 == this.lines.size() - 1)
{
float var11 = (float)var9 + var8 - (float)(this.height / 2 - 6);
if (var11 < 0.0F)
{
GL11.glTranslatef(0.0F, -var11, 0.0F);
}
}
if ((float)var9 + var8 + 12.0F + 8.0F > 0.0F && (float)var9 + var8 < (float)this.height)
{
String var12 = (String)this.lines.get(var10);
if (var12.startsWith("[C]"))
{
this.fontRenderer.drawStringWithShadow(var12.substring(3), var6 + (var5 - this.fontRenderer.getStringWidth(var12.substring(3))) / 2, var9, 16777215);
}
else
{
this.fontRenderer.fontRandom.setSeed((long)var10 * 4238972211L + (long)(this.updateCounter / 4));
this.fontRenderer.renderString(var12, var6 + 1, var9 + 1, 16777215, true);
this.fontRenderer.fontRandom.setSeed((long)var10 * 4238972211L + (long)(this.updateCounter / 4));
this.fontRenderer.renderString(var12, var6, var9, 16777215, false);
}
}
var9 += 12;
}
GL11.glPopMatrix();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.mc.renderEngine.getTexture("%blur%/misc/vignette.png"));
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_COLOR);
var4.startDrawingQuads();
var4.setColorRGBA_F(1.0F, 1.0F, 1.0F, 1.0F);
var10 = this.width;
int var13 = this.height;
var4.addVertexWithUV(0.0D, (double)var13, (double)this.zLevel, 0.0D, 1.0D);
var4.addVertexWithUV((double)var10, (double)var13, (double)this.zLevel, 1.0D, 1.0D);
var4.addVertexWithUV((double)var10, 0.0D, (double)this.zLevel, 1.0D, 0.0D);
var4.addVertexWithUV(0.0D, 0.0D, (double)this.zLevel, 0.0D, 0.0D);
var4.draw();
GL11.glDisable(GL11.GL_BLEND);
super.drawScreen(par1, par2, par3);
}
|
b6677298-337a-428a-ab75-c4740c746cda
| 5
|
public void cancelPieceForConnection(ManagedConnection mc, int piece){
Piece p = disseminatedPiecesToCompete.get(piece);
if(p!=null){
List<ManagedConnection> list = pieceToClients.get(p);
list.remove(mc);
if(list.size()==0){
//ok remove this from every where.
//This might be the only client that had the piece :-|
pieceToClients.remove(p);
disseminatedPiecesToCompete.remove(piece);
}
ConnectionWork cw = clientToPieceSet.get(mc);
cw.queued.remove(p);
Iterator<Request> itor = cw.blockLeft.iterator();
while(itor.hasNext()){
Request r = itor.next();
if(r.index==p.pieceIndex){
itor.remove();
}
}
if(mc.getConnectionState()==ConnectionState.connected){
mc.cancelPiece(p);
}
}
}
|
ed82bea0-3a8f-4c70-8cce-e7abc8d912c4
| 8
|
public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
}
|
61cc685c-6409-40c7-9396-b2e7dbf5b746
| 6
|
private boolean handleDamageBlocked(Player player, DamageCause type) {
if (WorldRegionsPlugin.getInstanceConfig().ENABLE_BLOCKED_DAMAGE && WGCommon.willFlagApply(player, WorldRegionsFlags.BLOCKED_DAMAGE)) {
// Disabled?
if (WGCommon.areRegionsDisabled(player.getWorld())) return true;
// Bypass?
if (!WGCommon.willFlagApply(player, WorldRegionsFlags.BLOCKED_DAMAGE)) return true;
// Get blocked
Object blocked = RegionUtil.getFlag(WorldRegionsFlags.BLOCKED_DAMAGE, player.getLocation());
if (blocked == null) return true;
// Check
DamageList list = (DamageList) blocked;
if (list.contains(type)) return false;
return true;
}
return true;
}
|
f0565308-029b-4d5e-b1a9-3dd3ce8baff2
| 5
|
public void back()
{
i++;
if(i>modtexts.length-1)
i=0;
modname = modtexts[i].getName();
boolean gef=false;
for(Modinfo prop: proposals)
if(prop.getName().equals(modname)) gef=true;
if(!gef)back();
headl.setText(modname);
headl2.setText(modname);
if(geladen)
laden();
else
neu=false;
}
|
f7a9f022-dfd8-431e-9234-4439d7c630a0
| 2
|
public void afficheTable(){
System.out.println("\nVoici la table de coordonnées [" + nombreColonne + "]["+ nombreRangee+ "]");
for(boolean[] temp : coordoneeJeu){
//System.out.print("Poura la rangée " + rangee);
for(boolean used : temp)
System.out.print(used+ " ");
System.out.println();
}
}
|
681dc473-ff74-4999-b7b6-d8fdc7eb358d
| 5
|
private void creerTriangle(final int position,final Case c) {
int num = 25-position;
Point p = new Point(0,0);
if(num<=6)
{
p = new Point(454-(num-1)*33,30);
}else if(num<=12)
{
p = new Point(392-173-(num-7)*33,30);
}else if(num<=18)
{
p = new Point(392-173+(num-18)*33,233);
}else if(num<=24)
{
p=new Point(0,0);
p = new Point(454+(num-24)*33,233);
}
CouleurCase couleur = (num%2!=0)?CouleurCase.BLANC:CouleurCase.NOIR;
TriangleCaseButton triangle = new TriangleCaseButton(c,couleur,(num >= 13));
triangle.setBounds(p.x, p.y,
triangle.getPreferredSize().width , triangle.getPreferredSize().height);
add(triangle);
casesButtons.put(c,triangle);
}
|
5abbab2c-4a2c-4be4-8881-7c246271000a
| 1
|
public static Entry[] mergeSort(Entry[] list) {
// Uses merge sort, and does not change the original array.
if(list.length == 1) {
return Arrays.copyOf(list, 1);
} else {
Entry[] list1 = Arrays.copyOfRange(list, list.length/2, list.length);
Entry[] list2 = Arrays.copyOfRange(list, 0, list.length/2);
return merge(mergeSort(list1), mergeSort(list2));
}
}
|
9a699981-8429-40d4-bc32-958a9ae0af6d
| 3
|
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
f = new JFrame("WiMAP");
JPanel p = new MainWindow();
f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
f.setContentPane(p);
f.setJMenuBar(createMenuBar());
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we)
{
String ObjButtons[] = {"Yes","No","Cancel"};
if (PaintPane.Mac.size() != 0)
{
int PromptResult = JOptionPane.showOptionDialog(null,"Save before exit?","",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
if(PromptResult==JOptionPane.NO_OPTION)
{
System.exit(0);
} else if(PromptResult==JOptionPane.YES_OPTION)
{////////////????????
save();
System.exit(0);
}
}
else
System.exit(0);
}
});
f.setVisible(true);
}
});
}
|
7c5677da-5d1c-40db-bd3d-6907af3f1a37
| 9
|
public boolean canMakeMove(Direction dir, Color [] [] placedBlocks) {
int XCoord, YCoord, Y = 0,X = 0;
switch (dir) {
case DOWN:
Y = 1;
break;
case UP:
Y = -1;
break;
case LEFT:
X = -1;
break;
case RIGHT:
X = 1;
}
for (Block block : getBlockList()){
YCoord = block.getYCoord()- getMovedY();
YCoord += Y;
XCoord = (int) (GameBoard.COLUMS / 2 + block.getXCoord() - Math.floor(getWidth() / 2) - getMovedX());
XCoord += X;
if (XCoord < 0 || XCoord >= 10 || YCoord > 23)
return false;
if (placedBlocks[YCoord][XCoord] != null)
return false;
}
return true;
}
|
cd9e64e5-347c-442b-a111-f31179c47698
| 1
|
private void drawGameElement(Graphics2D graphics, Element element,
Position position) {
Image image = findGameElementImage(element);
if (image != null) {
graphics.drawImage(image, position.xCoordinate,
position.yCoordinate, 40, 40, null);
}
}
|
0d9e9687-3d02-4113-82b4-bbb6e6e5f7d9
| 2
|
@Override
public boolean handleException(Throwable e, CommandBase command, CommandInvocation invocation)
{
for (ExceptionHandler handler : handlers)
{
if (handler.handleException(e, command, invocation))
{
return true;
}
}
return false;
}
|
bcf0df4b-d703-4263-b144-4ea7107977df
| 8
|
public void printStyles() {
ensureOut();
// First, copy the base css
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
ToHtml.class.getResourceAsStream("excelStyle.css")));
String line;
while ((line = in.readLine()) != null) {
out.format("%s%n", line);
}
} catch (IOException e) {
throw new IllegalStateException("Reading standard css", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
//noinspection ThrowFromFinallyBlock
throw new IllegalStateException("Reading standard css", e);
}
}
}
// now add css for each used style
Set<CellStyle> seen = new HashSet<CellStyle>();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
Row row = rows.next();
for (Cell cell : row) {
CellStyle style = cell.getCellStyle();
if (!seen.contains(style)) {
printStyle(style);
seen.add(style);
}
}
}
}
}
|
5210c466-1926-490c-8506-398fa4af5c41
| 5
|
public ListingPanel(String user, Item i) {
super();
ImagePanel picture = new ImagePanel(i.getImage(), 65, 65);
JLabel title = new JLabel(i.getTitle());
JLabel bid = new JLabel(i.getHighestBid().formatted());
JLabel time = new DynamicTimeLabel(i);
// Won/Lost messages
if (i.timeLeft() == 0) {
time = new JLabel("Ended.");
boolean isBidder = false;
Iterator<Bid> it = i.getBids().iterator();
while (!isBidder && it.hasNext()) {
isBidder = it.next().username.equals(user);
}
if (isBidder) {
if (i.getHighestBid().username.equals(user)) {
time = new JLabel("Won!");
time.setForeground(new Color(0, 100, 0));
} else {
time = new JLabel("Lost.");
time.setForeground(new Color(100, 0, 0));
}
}
}
GroupLayout listingLayout = new GroupLayout(this);
listingLayout.setHorizontalGroup(listingLayout.createSequentialGroup()
.addContainerGap()
.addComponent(picture)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(listingLayout.createParallelGroup()
.addComponent(title, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
.addComponent(bid, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
.addComponent(time, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
)
.addContainerGap()
);
listingLayout.setVerticalGroup(listingLayout.createSequentialGroup()
.addContainerGap()
.addGroup(listingLayout.createParallelGroup()
.addComponent(picture)
.addGroup(listingLayout.createSequentialGroup()
.addComponent(title)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(bid)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(time)
)
)
.addContainerGap()
);
this.setLayout(listingLayout);
this.setPreferredSize(new Dimension(250, 90));
this.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));
}
|
b10c5e20-0d3a-4b95-af65-81dda91a0cbf
| 9
|
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Utilizador ut = dados.get(rowIndex);
switch (columnIndex) {
case 0:
return ut.getNome();
case 1:
return ut.getEmail();
case 2:
return ut.getLogIn();
case 3:
//para poder representar Administradores
if (ut instanceof Administrador) {
return ((Administrador) ut).getMorada();
} else {
return "";
}
case 4:
//para poder representar Administradores
if (ut instanceof Administrador) {
return ((Administrador) ut).getTelefone();
} else {
return "";
}
case 5:
//para poder representar Administradores
if (ut instanceof Administrador) {
return((Administrador) ut).getDataNascimentoString();
} else {
return "";
}
default:
return "Error";
}
}
|
08771515-3e0c-413b-b060-745119bcdc4b
| 4
|
public int getSignID(final Location sign) throws SQLException, InvalidSignLocationException{
long time = 0;
plugin.getLoggerUtility().log("getting Sign!", LoggerUtility.Level.DEBUG);
time = System.nanoTime();
Statement st = null;
String sql;
ResultSet result;
try {
st = connector.getConnection().createStatement();
} catch (SQLException e) {
DatabaseTools.SQLErrorHandler(plugin, e);
}
sql = "SELECT ID from PaypassageSigns WHERE " + "Sign_X=" + sign.getBlockX() + " AND Sign_Y=" + sign.getBlockY() + " AND Sign_Z=" + sign.getBlockZ();
result = st.executeQuery(sql);
int id = -1;
try {
while (result.next() == true) {
id = result.getInt("ID");
}
connector.getConnection().commit();
st.close();
result.close();
} catch (SQLException e2) {
DatabaseTools.SQLErrorHandler(plugin, e2);
}
if(id == -1) {
throw new InvalidSignLocationException("No sign registered at " + sign.getBlockX() + " " + sign.getBlockY() + " " + sign.getBlockZ());
}
time = (System.nanoTime() - time) / 1000000;
plugin.getLoggerUtility().log("Finished in " + time + " ms!", LoggerUtility.Level.DEBUG);
return id;
}
|
993b3be7-1195-4cf3-8b6e-6d68bb09deb7
| 1
|
@Override
public void go(HasWidgets container) {
this.container = container;
if ("".equals(History.getToken())) {
History.newItem(HISTORY_TOKEN);
} else {
History.fireCurrentHistoryState();
}
}
|
2af4c349-17f0-4bc9-b1b0-824ebab284e7
| 9
|
private static void method232(int ai[], int ai1[], int ai2[], byte abyte0[], int i, int j, int k)
{
int l = 0;
for(int i1 = i; i1 <= j; i1++)
{
for(int l2 = 0; l2 < k; l2++)
if(abyte0[l2] == i1)
{
ai2[l] = l2;
l++;
}
}
for(int j1 = 0; j1 < 23; j1++)
ai1[j1] = 0;
for(int k1 = 0; k1 < k; k1++)
ai1[abyte0[k1] + 1]++;
for(int l1 = 1; l1 < 23; l1++)
ai1[l1] += ai1[l1 - 1];
for(int i2 = 0; i2 < 23; i2++)
ai[i2] = 0;
int i3 = 0;
for(int j2 = i; j2 <= j; j2++)
{
i3 += ai1[j2 + 1] - ai1[j2];
ai[j2] = i3 - 1;
i3 <<= 1;
}
for(int k2 = i + 1; k2 <= j; k2++)
ai1[k2] = (ai[k2 - 1] + 1 << 1) - ai1[k2];
}
|
ad71f994-0ccb-4ba8-8e89-c64fa920e0d8
| 8
|
public void printBoard() {
for(int y = 0; y < 9; y++) {
for(int x = 0; x < 9; x++) {
Player player;
if (attacker.getPieceTypeOnBoardAt(new Point(x, y)) > 0) player = attacker;
else player = defender;
String str = "";
Boolean existPiece = player.getPieceTypeOnBoardAt(new Point(x,y)) != Piece.NONE;
if (player instanceof AheadPlayer && existPiece) str += "+";
else if (player instanceof BehindPlayer && existPiece) str += "-";
if (!existPiece) str += "_";
System.out.print(str+player.getPieceOnBoardAt(new Point(x,y)).getName());
}
System.out.println();
}
}
|
cc98fb88-2692-4971-bc8e-7a3695a190a0
| 1
|
@Test
public void arithmeticInstr_testInvalidDestinationSourceRef() { //Checks instr. not created with invalid register ref.
try {
instr = new ArithmeticInstr(Opcode.DIV, 75, 2);
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
assertNull(instr);
}
|
92228eac-6e9c-4bb5-98c4-150e277d73a5
| 2
|
public static BufferedImage[][] split(BufferedImage source, int xSize, int ySize)
{
int xSlices = source.getWidth() / xSize;
int ySlices = source.getHeight() / ySize;
BufferedImage[][] newIm = new BufferedImage[xSlices][ySlices];
for(int x = 0;x < xSlices;x++)
{
for(int y = 0;y < ySlices;y++)
{
newIm[x][y] = new BufferedImage(xSize,ySize,BufferedImage.TYPE_INT_ARGB);
Graphics g = newIm[x][y].getGraphics();
g.drawImage(source, -x*xSize,-y*ySize,null);
g.dispose();
}
}
return newIm;
}
|
1bfa53d0-5b05-485d-b0e8-1ba958c3b4bc
| 5
|
public void runDay() {
for(int i=0; i<teller.length; i++)
teller[i] = new RoboTeller();
for(int i=0; i<teller.length; i++)
teller[i].start();
int done = 0;
while(done < teller.length)
try{teller[done].join();done++;} catch(InterruptedException e) {}
int finalCapital = 0;
for(int i=0; i<account.length; i++)
finalCapital += account[i].balance;
capital = finalCapital;
}
|
7ba613ce-2d1e-46c3-9db2-4f8ab53fc474
| 8
|
public void Process(int id){
switch(id){
case 102:ActivateImageSpace();
break;
case 141:BasicSpaceReasoning(-5,0);//左
break;
case 142:BasicSpaceReasoning(5, 0);//右
break;
case 143:BasicSpaceReasoning(0, -5);//上
break;
case 144:BasicSpaceReasoning(0, 5);//下
break;
case 145:BasicSpaceReasoning(0, -3);//下
break;
case 151:BasicMove(0,-3);
break;
case 199:{
GetRelationFromImageSpace();
// count++;//测试用
}
break;
}
}
|
4204ae40-2b48-4f0c-8589-a990ca2e860d
| 5
|
@Override
public void action() {
ACLMessage msg = myAgent.receive(msgFilter);
if (msg != null) {
if (msg.getConversationId() == null) {
logger.log(Level.WARNING, (teacherSymbol + ": ConversationId == null : sender: "
+ msg.getSender().getLocalName() + "; content: " + msg.getContent()));
return;
}
switch (msg.getConversationId()) {
case ScheduleReorganizationBehaviour.REORGANIZATION_BEGINNING:
sendProposal();
break;
case ScheduleReorganizationBehaviour.REORGANIZATION_REJECT_PROPOSAL:
rejectProposal();
break;
case ScheduleReorganizationBehaviour.REORGANIZATION_ACCEPT_PROPOSAL:
acceptProposal();
break;
default:
notUnderstandMessage(msg.getSender().getLocalName(), msg.getConversationId());
break;
}
} else {
block();
}
}
|
267831c1-3fdb-47d3-b0d2-71350bf0258c
| 6
|
public void setAdminUnitMasterListWithZero(
List<AdminUnit> adminUnitMasterListWithZero, AdminUnit foundMaster) {
List<AdminUnit> res = new ArrayList<AdminUnit>();
if (adminUnitMasterListWithZero == null) {
adminUnitMasterListWithZero = new ArrayList<AdminUnit>();
}
// create new AdminUnitType
AdminUnit withZero = new AdminUnit();
// set id to 0
withZero.setAdminUnitID(0);
// and name to "---"
withZero.setName("---");
// append it to list
res.add(withZero);
boolean masterPresent = false;
for (AdminUnit au : adminUnitMasterListWithZero) {
res.add(au);
if (au.getName().equals(foundMaster.getName())) {
masterPresent = true;
}
}
if (foundMaster != null) {
if(!masterPresent && foundMaster.getAdminUnitID() != 0)
res.add(foundMaster);
}
this.adminUnitMasterListWithZero = res;
}
|
aa4fd080-ab20-4763-bd98-9ee792ce0d18
| 7
|
private static <E extends Comparable<? super E>> List<LisNode<E>> lis(List<LisNode<E>> n)
{
List<LisNode<E>> pileTops = new ArrayList<>();
// Sort into piles
for (LisNode<E> node : n)
{
int i = Collections.binarySearch(pileTops, node);
if (i < 0)
{
i = ~i;
}
if (i != 0)
{
node.pointer = pileTops.get(i - 1);
}
if (i != pileTops.size())
{
pileTops.set(i, node);
}
else
{
pileTops.add(node);
}
}
// Extract LIS from nodes
List<LisNode<E>> result = new ArrayList<>();
for (LisNode<E> node = pileTops.isEmpty() ? null : pileTops.get(pileTops.size() - 1); node != null; node = node.pointer)
{
result.add(node);
}
Collections.reverse(result);
return result;
}
|
90db0f74-6c9c-4b34-befc-b81a006bdee3
| 9
|
private void createRivers(Map map) {
final Specification spec = map.getSpecification();
final TileImprovementType riverType
= spec.getTileImprovementType("model.improvement.river");
final int number = getApproximateLandCount()
/ mapOptions.getInteger("model.option.riverNumber");
int counter = 0;
HashMap<Position, River> riverMap = new HashMap<Position, River>();
List<River> rivers = new ArrayList<River>();
for (int i = 0; i < number; i++) {
nextTry: for (int tries = 0; tries < 100; tries++) {
Position position = getRandomLandPosition(map, random);
if (!map.getTile(position).getType()
.canHaveImprovement(riverType)) {
continue;
}
// check the river source/spring is not too close to the ocean
for (Tile neighborTile: map.getTile(position)
.getSurroundingTiles(2)) {
if (!neighborTile.isLand()) {
continue nextTry;
}
}
if (riverMap.get(position) == null) {
// no river here yet
ServerRegion riverRegion = new ServerRegion(map.getGame(),
"model.region.river" + i, Region.RegionType.RIVER,
map.getTile(position).getRegion());
riverRegion.setDiscoverable(true);
riverRegion.setClaimable(true);
River river = new River(map, riverMap, riverRegion, random);
if (river.flowFromSource(position)) {
logger.fine("Created new river with length "
+ river.getLength());
map.setRegion(riverRegion);
rivers.add(river);
counter++;
} else {
logger.fine("Failed to generate river.");
}
break;
}
}
}
logger.info("Created " + counter + " rivers of maximum " + number);
for (River river : rivers) {
ServerRegion region = river.getRegion();
int scoreValue = 0;
for (RiverSection section : river.getSections()) {
scoreValue += section.getSize();
}
scoreValue *= 2;
region.setScoreValue(scoreValue);
logger.fine("Created river region (length " + river.getLength()
+ ", score value " + scoreValue + ").");
}
}
|
12aeec49-6292-4453-8a14-2cf3bb6005df
| 2
|
public static boolean isFullMask(int itemID)
{
for (int i=0; i<fullMask.length; i++)
if (fullMask[i] == itemID)
return true;
return false;
}
|
8ff944ec-e425-48ac-a486-b65abac607db
| 0
|
public JobSchedulerBuilder withTriggerGroup( String triggerGroup )
{
this.triggerGroup = triggerGroup;
return this;
}
|
50d59f8f-3822-4301-9bee-d9dbf6da21bd
| 0
|
public void update(String str)
{
System.out.println(str);
}
|
eb254804-6fd5-4d75-a941-9d10e0f68743
| 4
|
private void printCardsOnHand() {
o(String.format(" Cards on your Hand: "));
Map<Integer, List<CardInterface>> cards = new HashMap<Integer, List<CardInterface>>();
for (int i = 0; i < Settings.getNationcount(); i++) {
cards.put(i, new ArrayList<CardInterface>());
}
for (CardInterface card : d.getCardsOnHand()) {
cards.get(card.getNation()).add(card);
}
for (int i = 0; i < Settings.getNationcount(); i++) {
StringBuilder sb = new StringBuilder();
List<CardInterface> al = cards.get(i);
Collections.sort(al);
sb.append(String.format(" %5s:", CardNames.getNationName(i)));
for (CardInterface card : al) {
sb.append(String.format(" %s", CardNames.getCardName(card.getValue())));
}
o(sb.toString());
}
o(String.format(" Trump is %s", CardNames.getNationName(d.getUIData().getTrumpIndex())));
}
|
ab856f68-d196-42f9-b69c-a42bac1fce89
| 8
|
public Location[] adjacentLocations(){
// Make a new arraylist
Location[] locations = new Location[(r == 0 || r == 3) ? 5 : 8];
int count = 0;
// Add locations that are in the grid
for (int i = r - 1; i < r + 2; i++) {
if (-1 < i && i < 4){
for (int j = -1; j < 2; j++){
// Don't add the same as this one
if (i != r || j != 0) {
locations[count++] = new Location(i, (j + t + 12) % 12);
}
}
}
}
// Return the new list
return locations;
}
|
5980d8bd-422a-45f8-af9d-83ee6f1d8925
| 9
|
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rotation == 1) {
g.drawLine(0, 100, 80, 100);
g.drawLine(120, 100, 200, 100);
g.drawLine(120, 78, 120, 122);
g.drawLine(80, 78, 80, 122);
g.drawLine(80, 78, 120, 100);
g.drawLine(80, 122, 120, 100);
g.drawLine(94, 81, 102, 65);
g.drawLine(102, 65, 102, 75);
g.drawLine(102, 65, 94, 71);
g.drawLine(104, 81, 112, 65);
g.drawLine(112, 65, 112, 75);
g.drawLine(112, 65, 104, 71);
}
if (rotation == 2) {
g.drawLine(100, 0, 100, 80);
g.drawLine(100, 120, 100, 200);
g.drawLine(78, 120, 122, 120);
g.drawLine(78, 80, 122, 80);
g.drawLine(78,80, 100, 120);
g.drawLine(122, 80, 100, 120);
g.drawLine(119, 94, 135, 102);
g.drawLine(135, 102, 125, 102);
g.drawLine(135, 102, 129, 94);
g.drawLine(119, 104, 135, 112);
g.drawLine(135, 112, 125, 112);
g.drawLine(135, 112, 129, 104);
}
if (rotation == 3) {
g.drawLine(0, 100, 80, 100);
g.drawLine(120, 100, 200, 100);
g.drawLine(120, 78, 120, 122);
g.drawLine(80, 78, 80, 122);
g.drawLine(120, 78, 80, 100);
g.drawLine(120, 122, 80, 100);
g.drawLine(106, 81, 98, 65);
g.drawLine(98, 65, 98, 75);
g.drawLine(98, 65, 106, 71);
g.drawLine(96, 81, 88, 65);
g.drawLine(88, 65, 88, 75);
g.drawLine(88, 65, 96, 71);
}
if (rotation == 4) {
g.drawLine(100, 0, 100, 80);
g.drawLine(100, 120, 100, 200);
g.drawLine(78, 120, 122, 120);
g.drawLine(78, 80, 122, 80);
g.drawLine(78, 120, 100, 80);
g.drawLine(122, 120, 100, 80);
g.drawLine(119, 106, 135, 98);
g.drawLine(135, 98, 125, 98);
g.drawLine(135, 98, 129, 106);
g.drawLine(119, 96, 135, 88);
g.drawLine(135, 88, 125, 88);
g.drawLine(135, 88, 129, 96);
}
if (rotation % 2 == 1) {
if (resistance!=0) {
g.drawString(resistance + "Ω", 85, 150);
}
}
if (rotation % 2 == 0) {
if (resistance!=0) {
g.drawString(resistance + "Ω", 35, 105);
}
}
if (getCurrent() != 0) {
g.drawOval(0, 0, ((int) (getCurrent()) * 10), ((int) (getCurrent()) * 10));
}
}
|
f9d6ec9c-d996-40ee-8850-e3b6702676a9
| 5
|
public void addCity(final String cityName, final int surveyInterval) {
final String transformedCityName = City.transformCityName(cityName);
final int cityId;
try {
cityId = cityParser.retrieveCityId(transformedCityName);
final City city = new City(transformedCityName, cityId, surveyInterval);
synchronized (mutex) {
if (cityMap.putIfAbsent(transformedCityName, city) == null) {
final WeatherMonitor monitor = new WeatherMonitor(city.getCityId(), cityName, this);
timerManager.scheduleWithFixedRate(monitor, city.getSurveyInterval(), cityName);
LOG.info("City " + transformedCityName + " is added");
} else {
LOG.info("City " + transformedCityName + " already presented in the list");
throw new IllegalArgumentException("City " + transformedCityName +
" already presented in the list");
}
}
} catch (ParserConfigurationException e) {
LOG.error(e.getMessage());
} catch (IOException e) {
LOG.error(e.getMessage());
} catch (SAXException e) {
LOG.error(e.getMessage());
} catch (XPathExpressionException e) {
LOG.error(e.getMessage());
}
}
|
ee4cfbd9-ddab-400b-9488-6fc468266d07
| 6
|
@Override
public String readLine() throws IOException {
final StringBuffer result = new StringBuffer();
try {
for (int value; true;) {
switch (value = this.readUnsignedByte()) {
case '\r':
final long cur = this.index();
if (this.readUnsignedByte() == '\n') return result.toString();
this.seek(cur);
case '\n':
return result.toString();
default:
result.append((char)value);
}
}
} catch (final EOFException cause) {
if (result.length() == 0) return null;
return result.toString();
}
}
|
b5f2e8c6-725a-48c6-b644-0fbdf10673c5
| 9
|
private static void distribute(final boolean[] higherPriorityCells, final DimensionInfo info, int toDistribute, final int[] widths) {
int stretches = 0;
for (int i = 0; i < info.getCellCount(); i++) {
if (higherPriorityCells[i]) {
stretches += info.getStretch(i);
}
}
{
final int toDistributeFrozen = toDistribute;
for (int i = 0; i < info.getCellCount(); i++) {
if (!higherPriorityCells[i]) {
continue;
}
final int addon = toDistributeFrozen * info.getStretch(i) / stretches;
widths[i] += addon;
toDistribute -= addon;
}
}
if (toDistribute != 0) {
for (int i = 0; i < info.getCellCount(); i++) {
if (!higherPriorityCells[i]) {
continue;
}
widths[i]++;
toDistribute--;
if (toDistribute == 0) {
break;
}
}
}
if (toDistribute != 0) {
throw new IllegalStateException("toDistribute = " + toDistribute);
}
}
|
aec83323-5c01-48ac-843c-000f70d9c0d1
| 0
|
@Override
public void onStringInput(String input) {
System.out.println("Your age is: "+ input);
}
|
48218d6c-c6b5-4746-92be-a2eb65c10c33
| 3
|
@SuppressWarnings("unchecked")
@Override
public B get(A a) {
B b = null;
try {
b = (B) getMethod.invoke(a, new Object[0]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return b;
}
|
ca983d83-d15e-4123-a980-c83b519730d8
| 8
|
@Override
public OmahaHiLoWorker build()
{
if (super.getRounds() <= 0) {
throw new IllegalStateException("The number of rounds must be a strictly positive number");
} else if (super.getProfiles() == null || super.getProfiles().size() < 2) {
throw new IllegalStateException("There need to be at least 2 players in every simulation.");
} else if (super.getUpdateInterval() <= 0 || 100 % super.getUpdateInterval() != 0) {
throw new IllegalStateException("Invalid update interval value");
} else if (super.getNotifiable() == null) {
throw new IllegalStateException("There needs to be a notifiable for this worker");
}
for (PlayerProfile profile : super.getProfiles()) {
if (profile == null) {
throw new NullPointerException();
}
}
return new OmahaHiLoWorker(this);
}
|
59264551-9835-4c23-84ef-be5c6d7fd13d
| 4
|
protected HashMap<String, Double> rankChild4StnByHybrid(_Stn stnObj,
_ParentDoc pDoc) {
HashMap<String, Double> childLikelihoodMap = new HashMap<String, Double>();
double smoothingMu = m_LM.m_smoothingMu;
for (_ChildDoc cDoc : pDoc.m_childDocs) {
double cDocLen = cDoc.getTotalDocLength();
_SparseFeature[] fv = cDoc.getSparse();
double stnLogLikelihood = 0;
double alphaDoc = smoothingMu / (smoothingMu + cDocLen);
_SparseFeature[] sv = stnObj.getFv();
for (_SparseFeature svWord : sv) {
double featureLikelihood = 0;
int wid = svWord.getIndex();
double stnVal = svWord.getValue();
int featureIndex = Utils.indexOf(fv, wid);
double docVal = 0;
if (featureIndex != -1) {
docVal = fv[featureIndex].getValue();
}
double LMLikelihood = (1 - alphaDoc) * docVal / (cDocLen);
LMLikelihood += alphaDoc * m_LM.getReferenceProb(wid);
double TMLikelihood = 0;
for (int k = 0; k < number_of_topics; k++) {
// double likelihoodPerTopic =
// topic_term_probabilty[k][wid];
// System.out.println("likelihoodPerTopic1-----\t"+likelihoodPerTopic);
//
// likelihoodPerTopic *= cDoc.m_topics[k];
// System.out.println("likelihoodPerTopic2-----\t"+likelihoodPerTopic);
TMLikelihood += (word_topic_sstat[k][wid] / m_sstat[k])
* (topicInDocProb(k, cDoc) / (d_alpha
* number_of_topics + cDocLen));
// TMLikelihood +=
// topic_term_probabilty[k][wid]*cDoc.m_topics[k];
// System.out.println("TMLikelihood\t"+TMLikelihood);
}
featureLikelihood = m_tau * LMLikelihood + (1 - m_tau)
* TMLikelihood;
// featureLikelihood = TMLikelihood;
featureLikelihood = Math.log(featureLikelihood);
stnLogLikelihood += stnVal * featureLikelihood;
}
childLikelihoodMap.put(cDoc.getName(), stnLogLikelihood);
}
return childLikelihoodMap;
}
|
3adaee89-1840-4346-aee4-2dd412722e20
| 3
|
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof BookModel) {
BookModel otherBook = (BookModel) other;
boolean isSameClass = this.getClass().equals(otherBook.getClass());
return (this.isbn == otherBook.isbn) && isSameClass;
}
return false;
}
|
0b6fe746-4872-4e72-b839-f31983ff9e24
| 0
|
public static void main(String[] args) {
double above = 0.7, below = 0.4;
float fabove = 0.7f, fbelow = 0.4f;
System.out.println("Math.round(above): " + Math.round(above));
System.out.println("Math.round(below): " + Math.round(below));
System.out.println("Math.round(fabove): " + Math.round(fabove));
System.out.println("Math.round(fbelow): " + Math.round(fbelow));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.