method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
36622588-ca1a-46fa-8ad1-f241f7a5eb5e
| 9
|
public void generate(int i, int j, int type, int ori){
if (type==0){
if (map[i][j] == suelo)
map[i][j] = obstacle0;
}else if (type==1){
if (ori == 0 && map[i][j] == suelo && map[i+1][j] == suelo){
map[i][j] = obstacle10;
map[i+1][j] = obstacle11;
}else if(ori == 1 && map[i][j] == suelo && map[i][j+1] == suelo){
map[i][j] = obstacle12;
map[i][j+1] = obstacle13;
}
}
}
|
c6d525f8-e91c-43a7-a4f4-8ab863888623
| 7
|
@Override
public void paintComponent(Graphics g)
{
g.clearRect(0, 0, getWidth(), getHeight());
for (int row = 0; row < board.getRows(); ++row)
{
for (int col = 0; col < board.getColumns(); ++col)
{
int r = board.getHeroLocation().getLocation().x;
int c = board.getHeroLocation().getLocation().y;
BufferedImage image = null;
try
{
if(r == row && c == col)
{
image = getHeroImage(board.getHeroDirection());
}
else
{
image = getImage(board.getCell(row, col));
}
}
catch (IOException e) {}
g.drawImage(image, col * cellSize, row * cellSize, cellSize, cellSize, null);
}
}
// draw grid
g.setColor(Color.WHITE);
for (int row = 0; row < board.getRows(); ++row)
{
for (int col = 0; col < board.getColumns(); ++col)
{
g.drawRect(col * cellSize, row * cellSize, cellSize, cellSize);
}
}
}
|
9aa808a7-0b9f-4e60-a7f8-764df3800713
| 3
|
@Override
public void update(Observable arg0, Object arg1) {
if(arg0.equals(model)){
while(tmodel.getRowCount() > 0){
tmodel.removeRow(0);
}
Vector<String> productVector;
Product p;
Iterator<fpt.com.Product> productIterator = model.iterator();
while(productIterator.hasNext()) {
productVector = new Vector<String>();
p = (model.Product)productIterator.next();
productVector.add(Long.toString(p.getId()));
productVector.add(p.getName());
productVector.add(Double.toString(p.getPrice()));
productVector.add(Integer.toString(p.getQuantity()));
productVector.add("0");
tmodel.addRow(productVector);
}
}
}
|
4abcaa31-ea14-40b3-a4a3-a5f29a0e8482
| 6
|
public void printShuffle(Graphics g) {
int q = 0;
int z = 250;
String cardName = null;
for (int i = 0; i < deck.length; i++) {
if (deck[i].cardValue == 0) {
cardName = "A" + deck[i].suit;
} else if (deck[i].cardValue == 11) {
cardName = "J" + deck[i].suit;
} else if (deck[i].cardValue == 12) {
cardName = "Q" + deck[i].suit;
} else if (deck[i].cardValue == 13) {
cardName = "K" + deck[i].suit;
} else {
cardName = deck[i].cardValue + deck[i].suit;
}
poster = new MoviePoster(cardName);
if (q > 1000) {
q = 0;
z += 75;
}
Rectangle b = new Rectangle(q, z, 50, 75);
poster.draw(g,b);
q += 50;
}
}
|
88a15afa-7331-42c6-9176-716feee48eee
| 5
|
@Override
public void initialize(URL location, ResourceBundle resources) {
final WebEngine engine = webViewAuth.getEngine();
try {
engine.load(Auth.getUrl(Constants.APP_ID, Auth.getSettings()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println("erorororoor ERROR!!!");
}
engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
@Override
public void handle(WebEvent<String> event) {
if (event.getSource() instanceof WebEngine){
WebEngine tmpEngine = (WebEngine) event.getSource();
String location = tmpEngine.getLocation();
if (location.startsWith(Auth.redirect_url) && location.contains("access_token")){
try {
URL url = new URL(location);
Map<String, String> map = BaseUtil.explodeQueryString(url.getRef());
new DBQuery().saveTokenID(map.get("access_token"), map.get("user_id"));
}catch (MalformedURLException e){
}
}
}
}
});
}
|
dc5d898a-28b1-4df4-bceb-faf31cbabc2d
| 5
|
@Override
public Boolean StartApplainceCycle(String said)
{
//TODO Auto-generated method stub
for (ArrayentBackEndCommunication app : _applainces)
{
if(app._applInstance.get_said()== said)
{
try
{
if(app._applInstance.get_isApplianceInitialized() && !app._applInstance.get_isCycleStarted())
{
app._applInstance.set_isCycleStarted(true);
app.AddStates(_states);
app.StartCycle();
return true;
}
}
catch(Exception exp)
{
exp.printStackTrace();
}
}
}
return false;
}
|
324b495c-981b-45ae-af70-b37eb1eda6e8
| 2
|
public int pickLvl()
{
int throwAway = (int)(Math.random()*4+baseLevel-2);
if(throwAway<5)
return 5;
else if(throwAway>100)
return 100;
else
return throwAway;
}
|
bc7d240a-6048-4a8a-ac9f-abdb0d7693e5
| 2
|
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
ImageData.getInstance().initialize();
categories = ImageData.getInstance().getCategories();
elements = ImageData.getInstance().getElements();
backgroundSheet = new SpriteSheet("res/anims/background/Light.png", 560, 420);
//airGlideSheet = new SpriteSheet("res/anims/")
data = new Image[(backgroundSheet.getHorizontalCount() * backgroundSheet.getVerticalCount())];
int x = 0, y = 0;
for (int i = 0; i < data.length; i++) {
if (x >= backgroundSheet.getHorizontalCount()) {
x = 0;
y++;
}
data[i] = backgroundSheet.getSprite(x, y);
x++;
}
background = new Animation(data, 100);
background.setAutoUpdate(true);
}
|
48f3e9af-af1c-4bc2-8356-1b18f84d4dc6
| 1
|
private void registerTasks(Environment environment) {
final Map<String, Task> beansOfType = applicationContext.getBeansOfType(Task.class);
for (String beanName : beansOfType.keySet()) {
Task task = beansOfType.get(beanName);
environment.admin().addTask(task);
logger.info("Registering task: " + task.getClass().getName());
}
}
|
578c31bf-11f4-4d38-a4c4-d2f9b4c944e9
| 2
|
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu3ActionPerformed
if (jRadioButtonMenuItem1.isSelected()) {
try {
byte[] encodeBase64Chunked = Base64.decodeBase64(jTextArea1.getText().getBytes("UTF-8"));
jTextArea1.setText(new String(encodeBase64Chunked));
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// try {
// byte[] encodeBase64Chunked = Base64.decodeBase64(Hex.decodeHex(jTextArea1.getText().toCharArray()));
// jTextArea1.setText(new String(encodeBase64Chunked));
// } catch (DecoderException ex) {
// Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}//GEN-LAST:event_jMenu3ActionPerformed
|
8ccd15f9-f5ca-4510-945d-5eb0c6bfd6a4
| 6
|
* @return Stella_Object
*/
public static Stella_Object unassert(Stella_Object proposition) {
{ Cons parsedprops = Logic.updateProposition(proposition, Logic.KWD_CONCEIVE);
Cons result = Stella.NIL;
if (parsedprops != null) {
{ Proposition prop = null;
Cons iter000 = parsedprops;
Cons collect000 = null;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
prop = ((Proposition)(iter000.value));
if (prop.kind == Logic.KWD_NOT) {
prop = ((Proposition)((prop.arguments.theArray)[0]));
}
Proposition.unassertProposition(prop);
if (collect000 == null) {
{
collect000 = Cons.cons(prop, Stella.NIL);
if (result == Stella.NIL) {
result = collect000;
}
else {
Cons.addConsToEndOfConsList(result, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(prop, Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
}
return (((result.length() > 1) ? result : result.value));
}
}
|
6ae1e0ed-1431-4052-97fc-17090d6cf765
| 9
|
@Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if((canBeUninvoked())&&(mob.location()!=null))
{
if((failed)||(!CMLib.flags().isSitting(mob))||(room==null)||(title==null)||(mob.location()!=room))
mob.tell(L("You are no longer squatting."));
else
if(title.getOwnerName().length()>0)
{
mob.tell(L("Your squat has succeeded. This property no longer belongs to @x1.",title.getOwnerName()));
title.setOwnerName("");
title.updateTitle();
title.updateLot(null);
}
else
{
mob.tell(L("Your squat has succeeded. This property now belongs to you."));
title.setOwnerName(mob.Name());
title.updateTitle();
title.updateLot(new XVector(mob.name()));
}
}
failed=false;
}
|
e345536f-30c2-4ad9-8390-b79407917c27
| 4
|
private void writeInputs(PrintWriter out) {
int curCycle = cycleOffset;
for (PlaybackOperation op : playback) {
for (Entry<Integer, Integer> input : op.getInputMap().entrySet()) {
boolean frameBoundary = curCycle + input.getKey() >= FRAME_CYCLES;
if (frameBoundary) {
curCycle -= FRAME_CYCLES;
while (curCycle + input.getKey() >= FRAME_CYCLES) {
writeInput(out, 0, true);
curCycle -= FRAME_CYCLES;
}
}
writeInput(out, input.getValue(), frameBoundary);
}
curCycle += op.getCycleCount();
}
}
|
8e07e01e-06b0-44e2-a987-94492fa25869
| 7
|
private void calculateMinRequiredNumber(GameDescription game){
ArrayList<SpriteData> allSprites = game.getAllSpriteData();
for(SpriteData sprite:allSprites){
if(!sprite.type.equals(resource) && checkIsCreate(sprite.name, game, allSprites)){
minRequiredNumber.put(sprite.name, 0);
}
else{
if(getAllInteractions(sprite.name, InteractionType.ALL, game).size() > 0 ||
spawnerTypes.contains(sprite.type)){
if(sprite.isSingleton){
minRequiredNumber.put(sprite.name, 1);
}
else{
minRequiredNumber.put(sprite.name, 2);
}
}
}
if(!minRequiredNumber.containsKey(sprite.name)){
minRequiredNumber.put(sprite.name, 0);
}
}
}
|
89d8e592-31a5-4563-9e28-f3d334089f4f
| 7
|
@Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
Campaign camp = (Campaign) session.get("campa");
Long campid = camp.getCampaignId();
// System.out.println("Camp is" + camp.toString());
// Long campl=Long.parseLong(camp.toString());
if (addimage == null && tileimage== null) {
CampaignCreative campcre = new CampaignCreative();
campcre.setCampaign(campid);
campcre.setStyleType(adtype);
campcre.setAddName(adname);
campcre.setAddUrl(url);
campcre.setDisplayUrl(displayurl);
campcre.setAddText(adtext);
getMyDao().getDbsession().save(campcre);
User user = (User) session.get("User");
setCamplist((List<Campaign>) myDao.getDbsession().createQuery("from Campaign").list());
Criteria crit = myDao.getDbsession().createCriteria(Campaign.class);
crit.add(Restrictions.like("user", user));
crit.setMaxResults(20);
setCamplist((List<Campaign>) crit.list());
addActionMessage("Campaign " + camp.getCampaignName() + " Successfully Created");
return "success";
} else if (addimage== null) {
CampaignCreative campcre = new CampaignCreative();
campcre.setCampaign(campid);
campcre.setStyleType(adtype);
campcre.setAddName(adname);
campcre.setAddUrl(url);
campcre.setDisplayUrl(displayurl);
campcre.setAddText(adtext);
byte[] tFile = new byte[(int) tileimage.length()];
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(tileimage);
fileInputStream.read(tFile);
fileInputStream.close();
campcre.setTileImage(tFile);
getMyDao().getDbsession().save(campcre);
User user = (User) session.get("User");
setCamplist((List<Campaign>) myDao.getDbsession().createQuery("from Campaign").list());
Criteria crit = myDao.getDbsession().createCriteria(Campaign.class);
crit.add(Restrictions.like("user", user));
crit.setMaxResults(20);
setCamplist((List<Campaign>) crit.list());
addActionMessage("Campaign " + camp.getCampaignName() + " Successfully Created");
return "success";
} else if (tileimage==null) {
CampaignCreative campcre = new CampaignCreative();
campcre.setCampaign(campid);
campcre.setStyleType(adtype);
campcre.setAddName(adname);
campcre.setAddUrl(url);
campcre.setDisplayUrl(displayurl);
campcre.setAddText(adtext);
byte[] aFile = new byte[(int) addimage.length()];
FileInputStream fileInputStream = new FileInputStream(addimage);
//convert file into array of bytes
fileInputStream.read(aFile);
campcre.setAddImage(aFile);
getMyDao().getDbsession().save(campcre);
User user = (User) session.get("User");
setCamplist((List<Campaign>) myDao.getDbsession().createQuery("from Campaign").list());
Criteria crit = myDao.getDbsession().createCriteria(Campaign.class);
crit.add(Restrictions.like("user", user));
crit.setMaxResults(20);
setCamplist((List<Campaign>) crit.list());
addActionMessage("Campaign " + camp.getCampaignName() + " Successfully Created");
return "success";
}
else{
CampaignCreative campcre = new CampaignCreative();
campcre.setCampaign(campid);
campcre.setStyleType(adtype);
campcre.setAddName(adname);
campcre.setAddUrl(url);
campcre.setDisplayUrl(displayurl);
campcre.setAddText(adtext);
byte[] aFile = new byte[(int) addimage.length()];
byte[] tFile = new byte[(int) tileimage.length()];
FileInputStream fileInputStream = new FileInputStream(addimage);
//convert file into array of bytes
fileInputStream.read(aFile);
campcre.setAddImage(aFile);
fileInputStream = new FileInputStream(tileimage);
fileInputStream.read(tFile);
fileInputStream.close();
campcre.setTileImage(tFile);
getMyDao().getDbsession().save(campcre);
User user = (User) session.get("User");
setCamplist((List<Campaign>) myDao.getDbsession().createQuery("from Campaign").list());
Criteria crit = myDao.getDbsession().createCriteria(Campaign.class);
crit.add(Restrictions.like("user", user));
crit.setMaxResults(20);
setCamplist((List<Campaign>) crit.list());
/*
* This code is used to retrieve the blob image from the database
* and store it on local system or any other specified location.
byte[] retadd = campcre.getAddImage();
FileOutputStream fos = new FileOutputStream("D:\\test.gif");
fos.write(retadd);
byte[] rettile = campcre.getTileImage();
fos = new FileOutputStream("D:\\test1.gif");
fos.write(rettile);
fos.close();
*/
addActionMessage("Campaign " + camp.getCampaignName() + " Successfully Created");
return "success";
}
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
}
|
9fcc3b6c-d4cc-4a88-afaf-0bd1a57b95a4
| 4
|
@Override
public void onDraw(Graphics G, int viewX, int viewY) {
if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300)
{
G.setColor(Color.gray);
G.fillRect((int)X-2-viewX, (int)Y-32-viewY, 4, 32);
G.setColor(Color.darkGray);
G.fillRect((int)X-16-viewX, (int)Y-4-viewY, 32, 4);
G.setColor(Color.lightGray);
G.fillArc((int)X-4-viewX, (int)Y-36-viewY-4, 8, 8, 0, 360);
G.setColor(Color.black);
G.drawRect((int)X-2-viewX, (int)Y-32-viewY, 4, 32);
G.drawRect((int)X-16-viewX, (int)Y-4-viewY, 32, 4);
G.drawArc((int)X-4-viewX, (int)Y-36-viewY-4, 8, 8, 0, 360);
G.setColor(Color.YELLOW);
int dir = r.nextInt(360), dis = 8+r.nextInt(16);
int xx = (int)X + (int)APPLET.lengthdir_x(dis,dir)-viewX, yy = (int)Y + (int)APPLET.lengthdir_y(dis, dir) - 34-viewY;
dir = r.nextInt(360); dis = 8+r.nextInt(16);
int xxx = xx + (int)APPLET.lengthdir_x(dis,dir), yyy = yy + (int)APPLET.lengthdir_y(dis, dir);
G.drawLine((int)X-viewX, (int)Y-34-viewY, xx, yy);
G.drawLine(xx, yy, xxx, yyy);
}
}
|
c2424b5e-7273-4d0c-b4dc-96fe774273e3
| 0
|
private SettingsManager() {
}
|
cb8c0cc8-c074-4612-9904-08c5ace25434
| 1
|
public static void triggerTraySelectionChanged() {
for (TraySelectionChangedListener listener : StorageUnitDisplayPanel.traySelectionChangedListeners) {
listener.onTraySelectionChanged();
}
}
|
4bf09bc2-5b7d-4c1a-8cfb-1031e2e46b8a
| 9
|
@SuppressWarnings("unchecked")
private static Number instantiateNumber(Class<? extends Number> cls,
String number) {
assert cls != null : "The class may not be null";
if (number == null || number.isEmpty()) {
return null;
}
try {
Constructor<Number> numberConstructor = (Constructor<Number>) cls
.getConstructor(String.class);
Number resnum = numberConstructor.newInstance(number);
return resnum;
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
|
3841b3d7-1f85-4dda-a4bd-78e16e192efe
| 9
|
private void checkErrors(JSONObject response) throws UniSenderMethodException, UniSenderInvalidResponseException{
if (response.has("error")){
try {
String errorMsg = response.getString("error");
String code = response.getString("code");
MethodExceptionCode mec = MethodExceptionCode.UNKNOWN;
if ("unspecified".equals(code)){
mec = MethodExceptionCode.UNSPECIFIED;
} else if ("invalid_api_key".equals(code)) {
mec = MethodExceptionCode.INVALID_API_KEY;
} else if ("access_denied".equals(code)) {
mec = MethodExceptionCode.ACCESS_DENIED;
} else if ("unknown_method".equals(code)) {
mec = MethodExceptionCode.UNKNOWN_METHOD;
} else if ("invalid_arg".equals(code)) {
mec = MethodExceptionCode.INVALID_ARG;
} else if ("not_enough_money".equals(code)) {
mec = MethodExceptionCode.NOT_ENOUGH_MONEY;
} else if ("too_many_double_optins".equals(code)) {
mec = MethodExceptionCode.TOO_MANY_DOUBLE_OPTINS;
}
throw new UniSenderMethodException(mec, errorMsg);
} catch (JSONException e) {
throw new UniSenderInvalidResponseException(e);
}
}
}
|
4f556617-6781-4f59-8c00-c567e92599f8
| 0
|
public void Close() {
this.pconnect.LogOut();
}
|
afc60e03-7f72-4b13-9224-3f1d9d279890
| 5
|
private void doPaintBucketNoDia(int x, int y, Color newCol, Color currentCol)
{
// make sure it's on the image
if (x > -1 && y > -1 && x < this.getDrawingWidth()
&& y < this.getDrawingHeight()
&& this.getPointColor(x, y).equals(currentCol))
{
this.drawPoint(x, y, newCol);
doPaintBucketNoDia(x - 1, y, newCol, currentCol);
doPaintBucketNoDia(x + 1, y, newCol, currentCol);
doPaintBucketNoDia(x, y - 1, newCol, currentCol);
doPaintBucketNoDia(x, y + 1, newCol, currentCol);
}
}
|
07bcea97-1931-4691-955b-2425b3e27408
| 9
|
private int getEarliestCarTime(Parking[] lots, MovingCar[] cars, int i, int dir) {
if (i < 0 || i >= lots.length || lots[i] == null) {
return Integer.MIN_VALUE;
}
if (!lots[i].isEmpty()) {
return lots[i].getFirst();
}
int lastBlock = dir == 1 ? nblocks[i] - 1 : 0;
for (int j = 0; j < cars.length; j++) {
if (cars[j].segment == i && cars[j].dir == dir && cars[j].block == lastBlock) {
return cars[j].startTime;
}
}
return Integer.MIN_VALUE;
}
|
162d49cc-fd41-4da4-a7a3-0471b8a41c18
| 6
|
@SuppressWarnings("LoopStatementThatDoesntLoop")
public <B, C> Trampoline<C> zipWith(final Trampoline<B> b, final F2<A, B, C> f) {
final Either<P1<Trampoline<A>>, A> ea = resume();
final Either<P1<Trampoline<B>>, B> eb = b.resume();
for (final P1<Trampoline<A>> x : ea.left()) {
for (final P1<Trampoline<B>> y : eb.left()) {
return suspend(x.bind(y, F2Functions.curry((ta, tb) -> suspend(P.<Trampoline<C>>lazy(u -> ta.zipWith(tb, f))))));
}
for (final B y : eb.right()) {
return suspend(x.map(ta -> ta.map(F2Functions.f(F2Functions.flip(f), y))));
}
}
for (final A x : ea.right()) {
for (final B y : eb.right()) {
return suspend(P.lazy(u -> pure(f.f(x, y))));
}
for (final P1<Trampoline<B>> y : eb.left()) {
return suspend(y.map(liftM2(F2Functions.curry(f)).f(pure(x))));
}
}
throw Bottom.error("Match error: Trampoline is neither done nor suspended.");
}
|
49c5ae53-1894-4908-8222-daf7ec242016
| 3
|
public static void Cliente_Apaga(String nome, InterfaceControlador ic_cliente){
/**Just a Scanner*/
Scanner sc = new Scanner(System.in);
System.out.println("\nDigite o nome do objeto a ser apagado");
nome = sc.next();
try
{
System.out.println("\nProcurando...\n");
ic_cliente.intControladorApaga(nome);
System.out.println("Objeto removido com sucesso\n");
}
catch (RemoteException e)
{
System.out.println("RemoteException");
e.printStackTrace();
return;
}
catch (NenhumServidorDisponivelException e)
{
System.out.println("NenhumServidorDisponivelException");
e.printStackTrace();
return;
}
catch (ObjetoNaoEncontradoException e)
{
System.out.println("Objeto Não encontrado\n");
return;
}
}
|
635a1762-9a64-4cf2-ab94-da7d53d2e080
| 6
|
private SocketChannel accept() {
Socket sock = null;
try {
sock = handle.socket().accept();
} catch (IOException e) {
return null;
}
if (!options.tcp_accept_filters.isEmpty ()) {
boolean matched = false;
for (TcpAddress.TcpAddressMask am : options.tcp_accept_filters) {
if (am.match_address (address.address())) {
matched = true;
break;
}
}
if (!matched) {
try {
sock.close();
} catch (IOException e) {
}
return null;
}
}
return sock.getChannel();
}
|
eec7f362-f7ee-4190-ae1e-658db4be0e9b
| 2
|
private void createButtonsMatrix() {
for (int i = 0; i < bMatrix.length; i++) {
for (int j = 0; j < bMatrix[0].length; j++) {
JButton button = new JButton();
button.setPreferredSize(new Dimension(50, 50));
bMatrix[i][j] = button;
}
}
}
|
30c89de9-1008-4f4b-9725-a2c103572470
| 8
|
public void visit_lload(final Instruction inst) {
final int index = ((LocalVariable) inst.operand()).index();
if (index + 2 > maxLocals) {
maxLocals = index + 2;
}
if (inst.useSlow()) {
if (index < 256) {
addOpcode(Opcode.opc_lload);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_lload);
addShort(index);
}
stackHeight++;
return;
}
switch (index) {
case 0:
addOpcode(Opcode.opc_lload_0);
break;
case 1:
addOpcode(Opcode.opc_lload_1);
break;
case 2:
addOpcode(Opcode.opc_lload_2);
break;
case 3:
addOpcode(Opcode.opc_lload_3);
break;
default:
if (index < 256) {
addOpcode(Opcode.opc_lload);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_lload);
addShort(index);
}
break;
}
stackHeight += 2;
}
|
d21ea39c-91b8-4f06-9fe0-64eec183530d
| 8
|
static int scoreRange(LeafCollector collector, DocIdSetIterator iterator, TwoPhaseIterator twoPhase,
Bits acceptDocs, int currentDoc, int end) throws IOException {
if (twoPhase == null) {
while (currentDoc < end) {
if (acceptDocs == null || acceptDocs.get(currentDoc)) {
collector.collect(currentDoc);
}
currentDoc = iterator.nextDoc();
}
return currentDoc;
} else {
final DocIdSetIterator approximation = twoPhase.approximation();
while (currentDoc < end) {
if ((acceptDocs == null || acceptDocs.get(currentDoc)) && twoPhase.matches()) {
collector.collect(currentDoc);
}
currentDoc = approximation.nextDoc();
}
return currentDoc;
}
}
|
62d5fa7c-d335-4ff2-acb9-d9ba7ac39c5b
| 1
|
public boolean more() throws JSONException {
this.next();
if (this.end()) {
return false;
}
this.back();
return true;
}
|
0af573ae-3ebe-4920-bdfd-332999b767c1
| 0
|
@FXML
private void handleSliderAction() {
threadField.setText(Double.toString((int) threadSlider.getValue()));
numThreads = (int)threadSlider.getValue();
System.out.println((int)threadSlider.getValue());
}
|
1a1acd0e-d8f1-4746-b982-d3143c00eaca
| 5
|
public void loadGameConfigValues() {
if (gameConfigValues.isEmpty()) {
try {
// config values were not loaded yet -> load it
Ini iniFile = new Ini(this.getClass().getResource("/" + LOTDConstants.INI_FILE_PATH_GAME_INI));
Section section = iniFile.get(LOTDConstants.INI_SECTION_GAME_INI_CONFIG_SECTION);
if (section != null) {
// and store its values in the gameConfigValues
for (Entry<String, String> entry : section.entrySet())
gameConfigValues.put(entry.getKey(), entry.getValue());
if (LOGGER.isDebugEnabled())
LOGGER.debug("Successfully loaded gameConfigValues");
} else
throw new Exception("Could not find section '" + LOTDConstants.INI_SECTION_GAME_INI_CONFIG_SECTION + "' within .ini file '" + LOTDConstants.INI_FILE_PATH_GAME_INI + "'");
} catch (Exception e) {
LOGGER.fatal("Error when trying to load gameConfigValues", e);
}
}
}
|
d3fbeeb8-5d03-4e74-9646-2252acae39bc
| 3
|
private boolean jj_3R_27()
{
if (jj_3R_30()) return true;
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_31()) { jj_scanpos = xsp; break; }
}
return false;
}
|
e95f7683-26fd-4017-afb9-89151bb013d9
| 9
|
public int compareTo( Object obj ) {
if( obj == null ) {
return( 1 );
}
else if( obj instanceof GenKbPhoneByUDescrIdxKey ) {
GenKbPhoneByUDescrIdxKey rhs = (GenKbPhoneByUDescrIdxKey)obj;
if( getRequiredContactId() < rhs.getRequiredContactId() ) {
return( -1 );
}
else if( getRequiredContactId() > rhs.getRequiredContactId() ) {
return( 1 );
}
{
int cmp = getRequiredDescription().compareTo( rhs.getRequiredDescription() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else if( obj instanceof GenKbPhoneBuff ) {
GenKbPhoneBuff rhs = (GenKbPhoneBuff)obj;
if( getRequiredContactId() < rhs.getRequiredContactId() ) {
return( -1 );
}
else if( getRequiredContactId() > rhs.getRequiredContactId() ) {
return( 1 );
}
{
int cmp = getRequiredDescription().compareTo( rhs.getRequiredDescription() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else {
throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(),
"compareTo",
"obj",
obj,
null );
}
}
|
5bbb1474-2410-4c40-a124-1a481355beb0
| 9
|
public boolean shouldExecute()
{
if (this.targetEntityClass == EntityPlayer.class)
{
if (this.theEntity instanceof EntityTameable && ((EntityTameable)this.theEntity).isTamed())
{
return false;
}
this.field_48240_d = this.theEntity.worldObj.getClosestPlayerToEntity(this.theEntity, (double)this.field_48241_e);
if (this.field_48240_d == null)
{
return false;
}
}
else
{
List var1 = this.theEntity.worldObj.getEntitiesWithinAABB(this.targetEntityClass, this.theEntity.boundingBox.expand((double)this.field_48241_e, 3.0D, (double)this.field_48241_e));
if (var1.size() == 0)
{
return false;
}
this.field_48240_d = (Entity)var1.get(0);
}
if (!this.theEntity.getEntitySenses().canSee(this.field_48240_d))
{
return false;
}
else
{
Vec3D var2 = RandomPositionGenerator.func_48623_b(this.theEntity, 16, 7, Vec3D.createVector(this.field_48240_d.posX, this.field_48240_d.posY, this.field_48240_d.posZ));
if (var2 == null)
{
return false;
}
else if (this.field_48240_d.getDistanceSq(var2.xCoord, var2.yCoord, var2.zCoord) < this.field_48240_d.getDistanceSqToEntity(this.theEntity))
{
return false;
}
else
{
this.field_48238_f = this.entityPathNavigate.getPathToXYZ(var2.xCoord, var2.yCoord, var2.zCoord);
return this.field_48238_f == null ? false : this.field_48238_f.func_48639_a(var2);
}
}
}
|
ab62515f-a827-44eb-9586-9b27df77bab7
| 4
|
public static void main(String[] args) {
// -------------------------Initialize Job Information------------------------------------
String startJobId = "job_201301191915_0001";
//String startJobId = "job_201212172252_0001";
//String jobName = "uservisits_aggre-pig-256MB";
//String jobName = "SampleWordCountWiki";
//String jobName = "BuildCompIndex-m36-r18";
//String jobName = "Wiki-m36-r18";
//String jobName = "BigTwitterInDegreeCount";
//String jobName = "big-uservisits_aggre-pig-256MB";
//String jobName = "BigTwitterBiDirectEdgeCount";
//String jobName = "BigTeraSort";
String jobName = "SampleTeraSort-1G";
//String jobName = "Big-uservisits_aggre-pig-50G";
//String baseDir = "/home/xulijie/MR-MEM/NewExperiments2/";
//String baseDir = "/home/xulijie/MR-MEM/NewExperiments3/";
//String baseDir = "/home/xulijie/MR-MEM/NewExperiments3/";
String baseDir = "/home/xulijie/MR-MEM/SampleExperiments/";
//String baseDir = "/home/xulijie/MR-MEM/BigExperiments/";
int reduceBase = 2;
boolean onlineEstimate = false;
String hostname = "master";
int iterateNum = 192;
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments/Wiki-m36-r18-256MB/estimatedJvmCost/";
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments/uservisits_aggre-pig-256MB/estimatedJvmCost/";
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments/TeraSort-256MB-m36-r18/estimatedJvmCost/";
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments2/BuildCompIndex-m36-r18-256MB/estimatedJvmCost/";
String outputDir = baseDir + jobName + "/estimatedJvmCost/";
boolean needMetrics = true; //going to analyze task counters/metrics/jvm?
int sampleMapperNum = 0; // only analyze the first sampleMapperNum mappers (0 means all the mappers)
int sampleReducerNum = 0; // only analyze the first sampleReducerNum reducers (0 means all the reducers)
boolean useRuntimeMaxJvmHeap = false; //since reducers' actual JVM heap is less than mapred.child.java.opts,
//this parameter determines whether to use the actual JVM heap to estimate
//--------------------------Setting ends------------------------------------
DecimalFormat nf = new DecimalFormat("0000");
for(int i = 0; i < iterateNum; i++) {
String prefix = startJobId.substring(0, startJobId.length() - 4);
int suffix = Integer.parseInt(startJobId.substring(startJobId.length() - 4));
String jobId = prefix + nf.format(suffix + i);
//--------------------------Profiling the run job-----------------------------
SerialBatchJobMemoryEstimator je = new SerialBatchJobMemoryEstimator();
boolean successful;
if(onlineEstimate == true)
successful = je.profile(hostname, jobId, needMetrics, sampleMapperNum, sampleReducerNum);
else
successful = je.profile(baseDir, jobName, "serialJob", jobId);
//--------------------------Profiling ends-----------------------------
//--------------------------Estimating Data Flow and Memory-----------------------------
if(successful == false) {
System.err.println("[" + jobId + "] is a failed job");
continue;
}
try {
je.batchEstimateDataAndMemory(useRuntimeMaxJvmHeap, outputDir + jobId, reduceBase);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//--------------------------Estimating ends-----------------------------
System.out.println("Finish estimating " + jobId);
}
}
|
68d73712-4bda-4653-8b0c-76b00c2a832d
| 3
|
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CommentPage commentPage = new CommentPage();
String text = request.getParameter("comment");
if (text == null || text.equals("")) {
commentPage.addComment(LocalTime.now().toString(), "<strong>No text found</strong>");
}
else {
db.addEntry(text);
List<CommentDB.Entry> list = db.getEntryList();
for (CommentDB.Entry i : list) {
commentPage.addComment(i.getTime(), i.getText());
}
}
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println(commentPage.getContent());
}
}
|
c716fb12-1c16-4048-bb98-8465a11bc1c6
| 9
|
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[50];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 0; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 50; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
jj_endpos = 0;
jj_rescan_token();
jj_add_error_token(0, 0);
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
|
0dc4bc43-89f2-475f-a6a4-2e0de05be06a
| 7
|
public TaskListClientView getTasksForDate(String dateKey) {
PersistenceManager pm = getPersistenceManager();
TaskListClientView result = null;
try {
Query q = pm.newQuery(DateBoundTasks.class, "dateString == ds");
q.declareParameters("java.lang.String ds");
List<DateBoundTasks> tasks = (List<DateBoundTasks>) q.execute(dateKey);
if (tasks.size() == 0 || tasks.get(0).getTaskTitle().length == 0)
return null;
DateBoundTasks taskInPersistantView = tasks.get(0);
int taskListLength = Math.max(Math.max(
taskInPersistantView.getTaskDescription().length,
taskInPersistantView.getTaskTitle().length), Math.max(
taskInPersistantView.getIsComplete().length,
taskInPersistantView.getTaskOwner().length));
SingleTaskClientView[] clientTasks = new SingleTaskClientView[taskListLength];
for (int i=0; i<taskListLength; i++) {
clientTasks[i] = new SingleTaskClientView(
taskInPersistantView.getTaskTitle().length > i ? taskInPersistantView.getTaskTitle()[i] : ("TITLE MISSING # " + i),
taskInPersistantView.getTaskDescription().length > i ? taskInPersistantView.getTaskDescription()[i] : "none",
taskInPersistantView.getTaskOwner().length > i ? taskInPersistantView.getTaskOwner()[i] : "Bobby",
taskInPersistantView.getIsComplete().length > i ? taskInPersistantView.getIsComplete()[i] : false);
}
result = new TaskListClientView(dateKey, clientTasks);
//To restore data integrity, re-save loaded list with the defaults applied
saveTaskList(result);
} finally {
pm.close();
}
return result;
}
|
d2520465-adca-4c0b-8d21-0b6a3514ebf5
| 6
|
public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
|
423d7bdd-2329-4431-b5dc-6bf696cc33a8
| 6
|
public void initialise() {
switch( network.type ) {
case GENERAL: initialiseGeneral();
break;
case RANDOM:
initialiseRandom();
break;
case LINE: initialiseLine();
break;
case STAR: initialiseStar();
break;
case RING: initialiseRing();
break;
case GRID: initialiseGrid();
break;
}
}
|
227da016-5e2b-4609-aeca-9f56f8fef38f
| 9
|
private void recursive_move(int count)
{
if(max_backup_files == 0)
{
File file= new File(log_file_path + log_file_name + log_file_ending);
file.delete();
return;
}
if (count == max_backup_files)
return;
File file_from;
File file_to;
if (count == 0)
file_from = new File(log_file_path + log_file_name + log_file_ending);
else
{
if(count < 10)
file_from = new File(log_file_path + log_file_backup
+ log_file_ending
+ ".00" + new Integer(count).toString());
else if(count < 100)
file_from = new File(log_file_path + log_file_backup
+ log_file_ending
+ ".0" + new Integer(count).toString());
else
file_from = new File(log_file_path + log_file_backup
+ "." + new Integer(count).toString()
+ log_file_ending);
}
if(count < 9)
file_to = new File(log_file_path + log_file_backup
+ log_file_ending
+ ".00" + new Integer(count + 1).toString());
else if(count < 99)
file_to = new File(log_file_path + log_file_backup
+ log_file_ending
+ ".0" + new Integer(count + 1).toString());
else
file_to = new File(log_file_path + log_file_backup
+ log_file_ending
+ "." + new Integer(count + 1).toString());
log(4, log_key, "recursive move call with count: "
+ new Integer(count).toString() + "\n");
if(file_to.exists())
recursive_move(count + 1);
log(4, log_key, "moving file:", file_from.getAbsolutePath(), "\n");
log(4, log_key, " to:", file_to.getAbsolutePath(), "\n");
if(!file_from.renameTo(file_to))
{
System.out.print(
"\n\n" +
"ERROR: could not move logfiles.\n" +
"DETAILED ERROR:\n" +
" was not able to rotate the logfiles, maybe path wrong/not created?\n\n"
);
Main.exit();
}
}
|
cedcdf44-3d5b-4465-9dab-b0aab9fa40e9
| 7
|
private boolean closeToOthers(Point p, int size) {
int xmin = p.x - 1;
int xmax = p.x + size;
int ymin = p.y - 1;
int ymax = p.y + size;
if (xmin < 0) // In case the coordinates are negative
xmin = 0;
if (ymin < 0)
ymin = 0;
for (int i = xmin; i <= xmax; i++)
for (int j = ymin; j <= ymax; j++)
if (wm.isAreaTree(i, j) || wm.isAreaGold(i, j) || wm.isAreaBuilding(i, j)) {
return true;
}
//System.out.println("return false");
return false;
}
|
da6e71cb-86cc-498f-ab48-90560513b38d
| 2
|
void fillRandom(double[][] map) {
for (int i = 0; i < map.length; i++) {
double[] row = map[i];
for (int j = 0; j < row.length; j++) {
map[i][j] = 1024*Math.random();
}
}
}
|
6810de2b-7617-43e3-8db3-926bcceb034e
| 9
|
private final int jjStopStringLiteralDfa_0(int pos, long active0)
{
switch (pos)
{
case 0:
if ((active0 & 0x2e00L) != 0L)
{
jjmatchedKind = 15;
return 5;
}
return -1;
case 1:
if ((active0 & 0x2e00L) != 0L)
{
jjmatchedKind = 15;
jjmatchedPos = 1;
return 5;
}
return -1;
case 2:
if ((active0 & 0xc00L) != 0L)
return 5;
if ((active0 & 0x2200L) != 0L)
{
jjmatchedKind = 15;
jjmatchedPos = 2;
return 5;
}
return -1;
case 3:
if ((active0 & 0x2200L) != 0L)
return 5;
return -1;
default :
return -1;
}
}
|
cd672c20-7cc3-41d5-8745-17fb3cd92bdd
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Triangle other = (Triangle) obj;
if (i != other.i)
return false;
if (j != other.j)
return false;
if (k != other.k)
return false;
if (normalVector == null) {
if (other.normalVector != null)
return false;
} else if (!normalVector.equals(other.normalVector))
return false;
return true;
}
|
d4e220ad-0fdb-4254-8361-46d4f4f2e2fb
| 2
|
public void clearAll() {
for (ArrayList<Key> keyList : keys.values()) {
for (Key key : keyList) {
key.clear();
}
}
}
|
f29d8239-a1f1-4c03-a67a-08724f98f8bc
| 6
|
@Override
public void mouseUp(MouseEvent e, int x, int y) {
Position p = GfxConstants.getPositionFromXY(x, y);
if (p.getRow() >= 0 && p.getRow() < GameConstants.WORLDSIZE
&& p.getColumn() >= 0
&& p.getColumn() < GameConstants.WORLDSIZE) {
// check if a tile was clicked
Unit u = game.getUnitAt(p);
City c = game.getCityAt(p);
game.setTileFocus(p);
if (u == null && c == null) {
}
}
}
|
89580c35-d3e9-45ab-a2b4-bce595a776da
| 1
|
public static void addCreature(Creature cr)
{
if(cr.id > 0)
pool.add(cr.id, cr);
else
{
pool.add(cr);
cr.id = pool.indexOf(cr);
}
}
|
9e97b155-364a-41d5-bef1-5d905dfff9fd
| 6
|
@Test
public void testGetWaitingQueues() throws Exception {
PreparedStatement ps = _connection.prepareStatement("INSERT INTO message (sender, receiver, queue) VALUES (1,2,3)");
for (int i = 0; i < 4; i++) { ps.execute(); }
ps = _connection.prepareStatement("INSERT INTO message (sender, receiver, queue) VALUES (1,2,4)");
for (int i = 0; i < 4; i++) { ps.execute(); }
ps = _connection.prepareStatement("INSERT INTO message (sender, receiver, queue) VALUES (1,3,4)");
for (int i = 0; i < 4; i++) { ps.execute(); }
List<Integer> res = _dao.getWaitingQueues(2);
assertTrue("Retrieved queues not waiting.", (res.get(0) == 3 && res.get(1) == 4) || (res.get(0) == 4 && res.get(1) == 3));
}
|
616ff9d7-3b41-47dd-b25d-388bf4088541
| 7
|
public static void main(String[] args) throws IOException {
Path destination = Paths.get("src/main/java/com/dodosoft/dpm");
Files.list(SOURCE).forEach(chapterDir -> {
if (Files.isDirectory(chapterDir) == false) {
return;
}
final String chapterPackageName = toPackageName(chapterDir.getFileName().toString());
final Path chapterDestinationDir = destination.resolve(chapterPackageName);
if (Files.exists(chapterDestinationDir)) {
return;
}
try {
Files.list(chapterDir).forEach(sampleDir -> {
if (Files.isDirectory(sampleDir) == false) {
return;
}
final String samplePackageName = toPackageName(sampleDir.getFileName().toString());
final Path sampleDestinationDir = chapterDestinationDir.resolve(samplePackageName);
if (Files.exists(sampleDestinationDir) == false) {
try {
Files.createDirectories(sampleDestinationDir);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
copyPackage("com.dodosoft.dpm." + chapterPackageName, sampleDir, sampleDestinationDir);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(sampleDestinationDir);
});
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
|
029e95e1-6659-42f9-9ed0-a2521918c1ed
| 6
|
public void Update(GameTime gameTime)
{
if (lifeTimer == -1)
{
lifeTimer = gameTime.GetRuntime() + maxLife;
}
mPosition.PlusEquals(mVelocity.Times(new Vector2(1)));
mVelocity.DividedByEquals(new Vector2(1.05f));
sparkSizeFactor /= 1.05f;
float lifeDifference = lifeTimer - gameTime.GetRuntime();
if (lifeDifference < 0)
{
Destroy();
}
else
{
lifePercentage = lifeDifference / maxLife;
}
color.SetEqual(originalColor.Times(lifePercentage));
if (mPosition.X < -5 || mPosition.X > GameProperties.SizeX() + 5 || mPosition.Y < -5 || mPosition.Y > GameProperties.SizeY() + 5)
{
Destroy();
}
}
|
7acf039b-5f6f-45fe-a040-087c83364160
| 1
|
public boolean ModificarPropiedad(Propiedad p){
if (p!=null) {
cx.Modificar(p);
return true;
}else {
return false;
}
}
|
bfc0cc72-a0d1-4638-b3e0-3d7a294ebf7f
| 7
|
public int read(int width) throws IOException {
if (width == 0) {
return 0;
}
if (width < 0 || width > 32) {
throw new IOException("Bad read width.");
}
int result = 0;
while (width > 0) {
if (this.available == 0) {
this.unread = this.in.read();
if (this.unread < 0) {
throw new IOException("Attempt to read past end.");
}
this.available = 8;
}
int take = width;
if (take > this.available) {
take = this.available;
}
result |= ((this.unread >>> (this.available - take)) & mask[take])
<< (width - take);
this.nrBits += take;
this.available -= take;
width -= take;
}
return result;
}
|
62bdfb4e-d52e-40d4-b9e3-f072abc72409
| 0
|
public static PermWriter getProject() {
return instance;
}
|
207da254-c2bc-44bc-ad22-7a03016664ce
| 2
|
public boolean checkShapeDate(long fechaDesde, long fechaHasta){
return (fechaAlta >= fechaDesde && fechaAlta < fechaHasta && fechaBaja >= fechaHasta);
}
|
71a690ce-5843-48c9-8c69-fa96fecd41e5
| 3
|
public void paint(Graphics g) {
for (int y = 0; y < 7; y++) {
for (int x = 0; x < 7; x++) {
if (this.chrArray[y][x] == -16711936) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.LIGHT_GRAY);
}
g.fillRect((x * 50 + 10), (y * 50 + 30), 40, 40);
}
}
}
|
c523eb70-baf6-472d-bcaa-05d7880acdda
| 2
|
public List<ValidateException> validateYear(int yearOfBirth) {
List<ValidateException> validateExceptionList = new LinkedList<>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
int currentYear = calendar.get(Calendar.YEAR);
if ((yearOfBirth < 1582) || (yearOfBirth > (currentYear - 18))) {
String exMsg = "entered wrong year of birth";
validateExceptionList.add(new ValidateException(String.format("You %s!", exMsg)));
logger.warn("User {} - {}. Min year = 1582. Max year = {}", exMsg, yearOfBirth, (currentYear -18));
}
return validateExceptionList;
}
|
dac9bc43-6ad2-4192-853c-b99891a57ff5
| 3
|
public void pickUpWeapon(Weapon w){
for(int i = 0; i<3 ; i++){
if(weapons[i] == activeWeapon){
if(w != null){
weapons[i] = w;
activeWeapon = w;
}else{
weapons[i] = WeaponFactory.createPlayerDefaultWeapon();
activeWeapon = weapons[i];
}
}
}
}
|
58516eca-8677-4065-808f-708f5bde34da
| 8
|
public boolean fValidateTrackDetails(WebElement trackItem,String detail)
{
if(detail.equalsIgnoreCase("title")){
WebElement title = objCommon.getChildObject(trackItem, txtTrackTitle);
if(title==null) return false;
//get text
String txtDetail = title.getAttribute("text").trim();
//check text
if(txtDetail.isEmpty()){
Reporter.fnWriteToHtmlOutput("Verify track has " + detail, "Track should have some " + detail, detail + " is empty", "Fail");
return false;
}
Reporter.fnWriteToHtmlOutput("Verify track has " + detail, "Track should have some " + detail, detail + " is " + txtDetail, "Pass");
//return true;
}
else if(detail.equalsIgnoreCase("artist")){
WebElement artist = objCommon.getChildObject(trackItem, txtArtistName);
if(artist==null) return false;
//get text
String txtDetail = artist.getAttribute("text").trim();
//check text
if(txtDetail.isEmpty()){
Reporter.fnWriteToHtmlOutput("Verify track has " + detail, "Track should have some " + detail, detail + " is empty", "Fail");
return false;
}
Reporter.fnWriteToHtmlOutput("Verify track has " + detail, "Track should have some " + detail, detail + " is " + txtDetail, "Pass");
//return true;
}
else if(detail.equalsIgnoreCase("icon")){
WebElement icon = objCommon.getChildObject(trackItem, imgIcon);
if(icon==null) return false;
Reporter.fnWriteToHtmlOutput("Verify icon", "Image should be displayed", "Image displayed", "Pass");
}
return true;
}
|
f3f58560-b7ee-4490-8ce1-f5c2a86dc4ce
| 1
|
private void checkPos() {
if ( pos == line.length() ) {
pos = -1;
}
}
|
09fbcf5c-8912-4a40-b42b-af854a8a799e
| 1
|
public Shader() {
program = glCreateProgram();
uniforms = new HashMap<String, Integer>();
if (program == 0) {
System.err
.println("engine.graphics.Shader creation failed: Could not find valid memory location in constructor");
System.exit(1);
}
}
|
3dfa6f79-29ba-48dc-a2c3-b9b7d3eab26a
| 3
|
public BufferedImage getImage(){
if(!running){
return images.get(0);
}else{
long curTime = (System.currentTimeMillis() - startTime) % totalTime ;
for(int i=0; i<times.size(); i++){
if(curTime - times.get(i) <= 0){
return images.get(i);
}else{
curTime -= times.get(i);
}
}
}
return images.get(images.size()-1);
}
|
61d35f39-6ffc-45d6-b389-71e6ba99fdb9
| 9
|
public boolean ramasserObjet(Objet o)
{
if(o instanceof Arme)
{
Arme a = (Arme) o;
if(a.getCategorieArme() == this.typeArme && a.getLevel() > this.arme.getLevel())
{
this.arme = a;
if(a.getLevel() == 1)
this.ptMana = this.ptManaMax = 120; // bâton de l'érudit
else
this.ptMana = this.ptManaMax = 150; // baguette de sureau
return true;
}
}
else if(o instanceof PotionVie)
{
PotionVie pv = (PotionVie) o;
if(this.ptVieMax > this.ptVie) // si p a perdu de la vie
{
pv.soignerVie(this); // soigner p
return true;
}
}
else if(o instanceof Sort)
{
Sort s = (Sort) o;
if(s.getCoutMana() > this.sort.getCoutMana())
{
this.sort = s;
return true;
}
}
else
{
PotionMana pm = (PotionMana) o;
if(this.ptManaMax > this.ptMana)
{
pm.soignerMana(this);
return true;
}
}
return false;
}
|
909f12d3-b91a-4e87-99ca-f805318809d9
| 0
|
protected int processHeader (byte[] header)
{
// TBD
// if (Outliner.DEBUG)
// System.out.println ("\tStan_Debug:\tPdbReaderWriter:processHeader"); }
return SUCCESS ;
} // end protected method processRecord
|
4ef92d9f-a384-4106-9379-be4cb596dabd
| 3
|
private void createUser() {
String name = JOptionPane.showInputDialog("Name");
String cpr = JOptionPane.showInputDialog("CPR (ddmmyy-MRRG)");
JPasswordField nPass = new JPasswordField();
JPasswordField qPass = new JPasswordField();
JOptionPane.showConfirmDialog(null, nPass, "Enter password", 0);
JOptionPane.showConfirmDialog(null, qPass, "Enter password again", 0);
if(Arrays.equals(nPass.getPassword(), qPass.getPassword())) {
try {
if(opr.createOperator(name, cpr, nPass.getPassword()))
textArea.append("[" + getDate() + "] User with name: " + name + " has been added.\n");
}
catch (DALException e) {
e.printStackTrace();
}
}
}
|
09a71694-57a2-48e0-8cde-3b8de9f58b09
| 0
|
public String getHudsonBuildNumber()
{
return getManifestMainAttribute(
new Attributes.Name("Hudson-Build-Number"), "unknown"
);
}
|
3215ace1-df8c-4745-83b0-55f55edd527d
| 8
|
private static double[][] calculateCovarianceMatrix(int userID, double[][] usersForUserMovies) {
double[][] covMatr = new double[UserMovieRatings.get(userID).size()][UserMovieRatings.get(userID).size()];
int movie1Index = 0;
for (Integer movie1ID : UserMovieRatings.get(userID).keySet()) {
int movie2Index = 0;
for (Integer movie2ID : UserMovieRatings.get(userID).keySet()) {
int N = 0;
double sum = 0;
if (movie1Index <= movie2Index) {
for (int user = 0; user < usersForUserMovies.length; user++) {
if (usersForUserMovies[user][movie1Index] != 0 && usersForUserMovies[user][movie2Index] != 0) {
sum += (usersForUserMovies[user][movie1Index] - averageMovieRatings.get(movie1ID))
* (usersForUserMovies[user][movie2Index] - averageMovieRatings.get(movie2ID));
N++;
}
}
if (N == 1) {
// TODO: Handle properly
N++;
}
covMatr[movie1Index][movie2Index] = (sum / (N - 1));
covMatr[movie2Index][movie1Index] = (sum / (N - 1));
// Add constant to diagonal so there won't be problems with
// singular matrices
if (movie1Index == movie2Index) {
covMatr[movie1Index][movie1Index] += 1;
}
userStatEnum += N;
userStatDenom++;
}
movie2Index++;
}
movie1Index++;
}
return covMatr;
}
|
5afa7af4-2c43-408f-a852-da6ef8697dab
| 6
|
public void testConstructor_int_int_int() throws Throwable {
TimeOfDay test = new TimeOfDay(10, 20, 30);
assertEquals(ISO_UTC, test.getChronology());
assertEquals(10, test.getHourOfDay());
assertEquals(20, test.getMinuteOfHour());
assertEquals(30, test.getSecondOfMinute());
assertEquals(0, test.getMillisOfSecond());
try {
new TimeOfDay(-1, 20, 30);
fail();
} catch (IllegalArgumentException ex) {}
try {
new TimeOfDay(24, 20, 30);
fail();
} catch (IllegalArgumentException ex) {}
try {
new TimeOfDay(10, -1, 30);
fail();
} catch (IllegalArgumentException ex) {}
try {
new TimeOfDay(10, 60, 30);
fail();
} catch (IllegalArgumentException ex) {}
try {
new TimeOfDay(10, 20, -1);
fail();
} catch (IllegalArgumentException ex) {}
try {
new TimeOfDay(10, 20, 60);
fail();
} catch (IllegalArgumentException ex) {}
}
|
2ccb6e80-6e1a-4790-92ce-882c09db209d
| 2
|
public Object getComponent() throws Exception {
URLClassLoader loader = getClassLoader();
Class c = null;
if (classname == null) {
// return getGeneratedComponent(loader);
// classname = getGeneratedComponent(loader);
c = getGeneratedComponent(loader);
} else {
try {
c = loader.loadClass(getComponentClassName(classname));
} catch (ClassNotFoundException E) {
throw new IllegalArgumentException(
"Component/Model not found '" + classname + "'");
}
}
return c.newInstance();
}
|
ab664c6f-e5e8-4a11-b3a0-47a4e7ca4c88
| 8
|
@Override
public Ptg calculatePtg( Ptg[] parsething )
{
Object o = null;
Formula f = ((Formula) getParentRec());
if( f.isSharedFormula() )
{
o = FormulaCalculator.calculateFormula( f.shared.instantiate( f ) );
}
else
{
Object r = null;
if( f.getInternalRecords().size() > 0 )
{
r = f.getInternalRecords().get( 0 );
}
else
{ // it's part of an array formula but not the parent
r = getParentRec().getSheet().getArrayFormula( getReferent() );
}
if( r instanceof Array )
{
Array arr = (Array) r;
o = arr.getValue( this );
}
else if( r instanceof StringRec )
{
o = ((StringRec) r).getStringVal();
}
else // should never happen
{
throw new UnsupportedOperationException( "Expected records parsing Formula were not present" );
}
}
Ptg p = null;
// conversion isn't necessary
// try{
if( o instanceof Integer )
{
return new PtgInt( (Integer) o );
}
// Double d = new Double(o.toString());
if( o instanceof Double )
{
return new PtgNumber( (Double) o );
}
//p = new PtgNumber(d.doubleValue());
// }catch(NumberFormatException e){
if( o.toString().equalsIgnoreCase( "true" ) || o.toString().equalsIgnoreCase( "false" ) )
{
p = new PtgBool( o.toString().equalsIgnoreCase( "true" ) );
}
else
{
p = new PtgStr( o.toString() );
}
// }
return p;
}
|
09d86a43-52e5-4521-bde3-d71bf22ce80d
| 4
|
private int getCurrentPage(String command, String pageParam) {
int currentPage = 0;
int page = 0;
if (pageParam != null) {
page = Integer.valueOf(pageParam).intValue();
}
if (command == null) {
currentPage = 1;
} else {
currentPage = page;
if (COMMAND_NEXT.equals(command)) {
currentPage++;
} else if (COMMAND_PREVIOUS.equals(command)) {
currentPage--;
}
}
return currentPage;
}
|
ddaa0226-8d2e-4e74-a605-cd7136c7a9f5
| 6
|
@Override
public Integer deleteNames(String... names) {
if (names == null || names.length == 0) {
throw new IllegalArgumentException("names must have at least one entry");
}
String query = "DELETE FROM `" + playerNamesTable + "` WHERE `name` ";
if (names.length == 1) {
query += "= ?";
} else {
// IN ('supaham', 'thatkid', 'thatotherkid')
query += "IN (";
for (String name : names) {
query += "'" + name + "',";
}
query = query.substring(0, query.length() - 1) + ")";
}
try (PreparedStatement insertStmt = this.connection.prepareStatement(query)) {
if (names.length == 1) {
insertStmt.setString(1, names[0]);
}
return insertStmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
|
043b88b5-24e7-4339-bf1d-7ff9db09d525
| 4
|
public Main() {
readConfig();
//下载文档
filedown = new FileDownload();
for(int i=0;i<HOSTSLIB.length;i++){
filedown.DownloadFile(HOSTSLIB[i], SAVEFILES[i]);
}
System.out.println("FileDownLoad OK");
//对下载的文档进行处理
updatetimecheck=new UpdateTimeCheck();
if(updatetimecheck.needUpdate()){
System.out.println("--------updating----------");
textProcess=new TextProcessForWebPage();
textProcess.ProcessText(Main.SAVEFILES[0], 0);
// textProcess.ProcessVidGithub(Main.SAVEFILES[2]);
textProcess.ProcessText(Main.SAVEFILES[1], 1);
textProcess.ProcessViaKeywords(Main.SAVEFILES[2]);
// PushOtherHosts.pushOtherHosts(OTHERHOSTS);
System.out.println("Change local hosts successfully.");
ftp = new FtpFileTransmit();
if (ftp.connect(FTPPATH, ADDR, PORT, USERNAME, PASSWORD)) {
System.out.println("Ftp connect successful.");
try {
ftp.upload(new File("hosts"));
} catch (Exception e) {
e.printStackTrace();
}
}
//如果有更新,且更新成功了,发送邮件
new SendMail(UpdateTimeCheck.DETAILTIME,userName,userKey,destMailAdress);
System.out.println("-----Update Successfully------");
}
}
|
74c23c15-f994-4bf8-94f4-ac3ea5a889cf
| 0
|
public int getWidth() {
return anim.getImage().getWidth(null);
}
|
b287349e-a788-4c19-bddb-bcd089a3066d
| 3
|
public synchronized boolean setItem(FieldItem item, Position position) {
if (insideBounds(position) && this.getItemType(position) == ' ' && !isPositioned(item)) {
field[position.getX()][position.getY()] = item;
return true;
}
return false;
}
|
855a4053-84a0-4b8e-8b5a-1f10830372ab
| 9
|
public void tokenize(String line) {
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String[] metadata = token.split("/");
if (metadata.length > 2) {
String POS = null;
if (metadata[1].indexOf(":") > 0){
POS = metadata[1].substring(0, metadata[1].indexOf(":"));
} else {
POS = metadata[1];
}
String word = metadata[0];
String base = metadata[2];
if (!word.startsWith("__")
&& !word.equals("")
&& Arrays.asList(pos).contains(POS)
&& !stopwords.getList().contains(word)
&& !stopwords.getList().contains(base)){
tokens.add(new Token(word, base, POS));
if (!occurrences.containsKey(base)){
occurrences.put(base, 1);
} else {
occurrences.put(base, occurrences.get(base) + 1);
}
}
}
}
// tokens.add(new Token("ENDLINE", "ENDLINE", "ENDLINE"));
}
|
6e84a418-ced5-424e-adea-c705555ae57e
| 4
|
private void drawCoordinates(java.awt.event.MouseEvent evt)
{
int length=graph_screen.getWidth();
int height=graph_screen.getHeight();
xmin=Double.parseDouble(Xmin.getText());
xmax=Double.parseDouble(Xmax.getText());
ymin=Double.parseDouble(Ymin.getText());
ymax=Double.parseDouble(Ymax.getText());
double xRange=(xmax-xmin);double yRange=(ymax-ymin);
Graphics2D g2D = (Graphics2D) graph_screen.getGraphics();
//get mouse position
int mouse_x = evt.getX();
int mouse_y = evt.getY();
//determine graph coordinates
String graph_x=Double.toString(xmin+((1.0*mouse_x/length)*xRange));
String graph_y=Double.toString(ymax-((1.0*mouse_y/height)*yRange));
if(graph_x.indexOf('.')!=-1&&graph_x.length()>graph_x.indexOf('.')+3)
graph_x=graph_x.substring(0,graph_x.indexOf('.')+3);
if(graph_y.indexOf('.')!=-1&&graph_y.length()>graph_y.indexOf('.')+3)
graph_y=graph_y.substring(0,graph_y.indexOf('.')+3);
//draw coordinates
g2D.setColor(graphColor);
g2D.fillRect(1,1,coords.length()*6,14);
coords="Coordinates: ("+graph_x+","+graph_y+")";
g2D.fillRect(1,1,coords.length()*6,14);
g2D.setColor(Color.black);
//set font to that of a button, in this case the Radian radio button
g2D.setFont(Radian.getFont());
g2D.drawString(coords,2,12);
}
|
e558ca43-ddf8-4b05-b1a1-1096662246ff
| 5
|
protected char[][] build_ct(String v_key,int pos)
{
int row=v_key.length();
char[][] result=new char[row][26];
for(int i=0;i<row;i++)
{
result[i][pos]=v_key.charAt(i);
}
for(int i=0;i<row;i++)
{
for(int j=1;j<26;j++)
{
int cur_pos=pos+j;
if(cur_pos>=26)
{
cur_pos-=26;
}
char cur_c=(char)(result[i][pos]+j);
if(cur_c>'Z')
{
cur_c=(char)(cur_c-26);
}
result[i][cur_pos]=cur_c;
}
}
return result;
}
|
784eac02-d407-48cd-977e-67fc75ff1e1c
| 1
|
public static int qdepth() {
int ret = 0;
for (Loader l = loader; l != null; l = l.next)
ret += l.queue.size();
return (ret);
}
|
50b95754-50b3-4fe1-82ff-db2fccae4e31
| 1
|
@Override
public void actionPerformed(ActionEvent e) {
if (getGraphics() != null)
paint(getGraphics());
}
|
65a1e5c5-cfb1-4b33-918e-32f6e0a40263
| 1
|
@Override
protected void generateFrameData(ResizingByteBuffer bb)
throws FileNotFoundException, IOException {
if(this.rawFrameContents!=null) {
bb.put(this.rawFrameContents);
}
}
|
664b9d96-a77f-4e30-bff5-5034c533b522
| 7
|
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
m = new int[10];
m2 = new int[10];
while ((line = in.readLine()) != null && line.length() != 0) {
if (line.trim().equals("end"))
break;
String name = line;
initialAmountOn = 0;
for (int i = 0; i < 10; i++) {
line = in.readLine();
m[i] = 0;
for (int j = 0; j < 10; j++)
if (line.charAt(j) == 'O') {
m[i] |= 1 << j;
initialAmountOn++;
}
}
minSteps = Integer.MAX_VALUE;
count(0, initialAmountOn);
back(0, initialAmountOn, 0);
out.append(name + " ");
if (minSteps == Integer.MAX_VALUE)
out.append("-1\n");
else
out.append(minSteps + "\n");
}
System.out.print(out);
}
|
4594e3de-a28b-4a06-b188-843f133869a7
| 6
|
public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7)
{
if (par3World.isRemote)
{
return true;
}
else
{
int var8 = par3World.getBlockId(par4, par5, par6);
par4 += Facing.offsetsXForSide[par7];
par5 += Facing.offsetsYForSide[par7];
par6 += Facing.offsetsZForSide[par7];
double var9 = 0.0D;
if (par7 == 1 && var8 == Block.fence.blockID || var8 == Block.netherFence.blockID)
{
var9 = 0.5D;
}
if (func_48440_a(par3World, par1ItemStack.getItemDamage(), (double)par4 + 0.5D, (double)par5 + var9, (double)par6 + 0.5D) && !par2EntityPlayer.capabilities.isCreativeMode)
{
--par1ItemStack.stackSize;
}
return true;
}
}
|
e14dd259-475e-42e2-bd76-72e15c0cea8a
| 2
|
public void m4t1() {
synchronized (this) {
int i = 5;
while (i-- > 0) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}
}
|
a4b252ae-0f41-4010-b09c-2cb03fb1841f
| 4
|
public static void changeDate(int rentTransID, String dateIn, String dateOut) {
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE RentTransactions SET date_out = ?, date_in = ? WHERE rent_trans_id = ?");
stmnt.setString(1, dateIn);
stmnt.setString(2, dateOut);
stmnt.setInt(3, rentTransID);
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}
catch(SQLException e){
System.out.println("Update fail: " + e);
}
}
|
b5d6c5cd-c7b8-44da-b07a-cb254489795f
| 2
|
public double removeCharge(double request) {
if (request <= 0.0)
return 0.0;
if (charge >= request) {
charge -= request;
lastTickDraw += request;
return request;
}
double ret = charge;
charge = 0.0;
lastTickDraw += ret;
return ret;
}
|
96fef355-7e42-445c-bae3-2309a74e7d8b
| 4
|
@Override
public PlayerLeftMessage LeaveServer(int playerID) {
Player player = _state.TryGetPlayer(playerID);
if (player == null)
return MessageCreator.CreatePlayerLeftMessage(new LinkedList<>(), null, null, null);
List<Integer> idsToUpdate = new LinkedList<>(_state.Lobby.GetPlayerIDs());
List<MapChange> map = null;
Game gameToSend = null;
if (player.PlayerStatus != PlayerStatus.InLobby && player.PlayerStatus != PlayerStatus.Undefined) {
ServerGame game = _state.TryGetGameByPlayerId(playerID);
if (game != null)
{
PlayerLeftGameMessage message = LeaveGame(playerID);
map = message.Map;
gameToSend = message.Game;
idsToUpdate = new LinkedList<>(message.PlayerIDsToUpdate);
}
}
_state.Lobby.RemovePlayer(player);
_state.Players.remove(player);
PlayerMapper.Remove(player);
idsToUpdate.remove(player);
return MessageCreator.CreatePlayerLeftMessage(idsToUpdate, player, gameToSend,map);
}
|
0ee4552b-f77f-494a-a2d1-b1199398de69
| 7
|
public static int[] getLCP(char s[], int[] sufAr){
int n = s.length, i, j, l = 0;
int invSufAr[] = new int[n];
for(i=0; i<n; ++i) invSufAr[sufAr[i]] = i;
int lcp[] = new int[n];
for(i=0; i<n; ++i){
j = invSufAr[i];
if(j>0) while(sufAr[j]+l<n && sufAr[j-1]+l<n && s[sufAr[j]+l]==s[sufAr[j-1]+l]) ++l;
lcp[j] = l;
--l; if(l<0) l = 0;
}
return lcp;
}
|
78f4a402-2baf-4166-b37e-3a5e267698bc
| 9
|
protected void processNodeOutgoing(TreeNode node)
{
mxIGraphModel model = graph.getModel();
TreeNode child = node.child;
Object parentCell = node.cell;
int childCount = 0;
List<WeightedCellSorter> sortedCells = new ArrayList<WeightedCellSorter>();
while (child != null)
{
childCount++;
double sortingCriterion = child.x;
if (this.horizontal)
{
sortingCriterion = child.y;
}
sortedCells.add(new WeightedCellSorter(child,
(int) sortingCriterion));
child = child.next;
}
WeightedCellSorter[] sortedCellsArray = sortedCells
.toArray(new WeightedCellSorter[sortedCells.size()]);
Arrays.sort(sortedCellsArray);
double availableWidth = node.width;
double requiredWidth = (childCount + 1) * prefHozEdgeSep;
// Add a buffer on the edges of the vertex if the edge count allows
if (availableWidth > requiredWidth + (2 * prefHozEdgeSep))
{
availableWidth -= 2 * prefHozEdgeSep;
}
double edgeSpacing = availableWidth / childCount;
double currentXOffset = edgeSpacing / 2.0;
if (availableWidth > requiredWidth + (2 * prefHozEdgeSep))
{
currentXOffset += prefHozEdgeSep;
}
double currentYOffset = minEdgeJetty - prefVertEdgeOff;
double maxYOffset = 0;
mxRectangle parentBounds = getVertexBounds(parentCell);
child = node.child;
for (int j = 0; j < sortedCellsArray.length; j++)
{
Object childCell = sortedCellsArray[j].cell.cell;
mxRectangle childBounds = getVertexBounds(childCell);
Object[] edges = mxGraphModel.getEdgesBetween(model, parentCell,
childCell);
List<mxPoint> newPoints = new ArrayList<mxPoint>(3);
double x = 0;
double y = 0;
for (int i = 0; i < edges.length; i++)
{
if (this.horizontal)
{
// Use opposite co-ords, calculation was done for
//
x = parentBounds.getX() + parentBounds.getWidth();
y = parentBounds.getY() + currentXOffset;
newPoints.add(new mxPoint(x, y));
x = parentBounds.getX() + parentBounds.getWidth()
+ currentYOffset;
newPoints.add(new mxPoint(x, y));
y = childBounds.getY() + childBounds.getHeight() / 2.0;
newPoints.add(new mxPoint(x, y));
setEdgePoints(edges[i], newPoints);
}
else
{
x = parentBounds.getX() + currentXOffset;
y = parentBounds.getY() + parentBounds.getHeight();
newPoints.add(new mxPoint(x, y));
y = parentBounds.getY() + parentBounds.getHeight()
+ currentYOffset;
newPoints.add(new mxPoint(x, y));
x = childBounds.getX() + childBounds.getWidth() / 2.0;
newPoints.add(new mxPoint(x, y));
setEdgePoints(edges[i], newPoints);
}
}
if (j < childCount / 2.0f)
{
currentYOffset += prefVertEdgeOff;
}
else if (j > childCount / 2.0f)
{
currentYOffset -= prefVertEdgeOff;
}
// Ignore the case if equals, this means the second of 2
// jettys with the same y (even number of edges)
// pos[k * 2] = currentX;
currentXOffset += edgeSpacing;
// pos[k * 2 + 1] = currentYOffset;
maxYOffset = Math.max(maxYOffset, currentYOffset);
}
}
|
e4b8ffac-8fe4-487d-ad76-6ac9e2d52f34
| 2
|
public static boolean isPublicStaticFinal(Field field) {
int modifiers = field.getModifiers();
return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier
.isFinal(modifiers));
}
|
f1904eb6-ae70-421c-91f5-0fc4b2e052ab
| 3
|
public String toString(){
StringBuffer result = new StringBuffer();
for(Map.Entry<String, Integer> e : addressMap.entrySet()){
result.append(e.getKey());
result.append(" : ");
result.append(e.getValue());
result.append("\n");
}
result.append("\n");
for(Map.Entry<String, Descriptor> e : descriptorMap.entrySet()){
result.append(e.getKey());
result.append(" : ");
result.append(e.getValue());
result.append("\n");
}
result.append("\n");
result.append("\n");
result.append("currentAddress: " + currentAddress + "\n");
if(parentTable != null){
result.append("-----------------------------------------\n\n");
//Parent Table Rekursion wenn Verweise auf untertabellen.
//result.append("parentTable: \n" + parentTable + "\n");
}
return result.toString();
}
|
c4cdd1cf-a651-4d42-ab5d-c51844c9808b
| 5
|
public Sound(String fileName) {
// specify the sound to play
// (assuming the sound can be played by the audio system)
// from a wave File
try {
File file = new File(fileName);
if (file.exists()) {
AudioInputStream sound = AudioSystem.getAudioInputStream(file);
// load the sound into memory (a Clip)
clip = AudioSystem.getClip();
clip.open(sound);
}
else {
throw new RuntimeException("Sound: file not found: " + fileName);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Malformed URL: " + e);
}
catch (UnsupportedAudioFileException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Unsupported Audio File: " + e);
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Input/Output Error: " + e);
}
catch (LineUnavailableException e) {
e.printStackTrace();
throw new RuntimeException("Sound: Line Unavailable Exception Error: " + e);
}
// play, stop, loop the sound clip
}
|
3a41562d-07e0-4c72-bf0d-74efd9ae5795
| 8
|
public static void main( String [ ] args )
{
QuadraticProbingHashTable<String> H = new QuadraticProbingHashTable<>( );
long startTime = System.currentTimeMillis( );
final int NUMS = 2000000;
final int GAP = 37;
System.out.println( "Checking... (no more output means success)" );
for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS )
H.insert( ""+i );
for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS )
if( H.insert( ""+i ) )
System.out.println( "OOPS!!! " + i );
for( int i = 1; i < NUMS; i+= 2 )
H.remove( ""+i );
for( int i = 2; i < NUMS; i+=2 )
if( !H.contains( ""+i ) )
System.out.println( "Find fails " + i );
for( int i = 1; i < NUMS; i+=2 )
{
if( H.contains( ""+i ) )
System.out.println( "OOPS!!! " + i );
}
long endTime = System.currentTimeMillis( );
System.out.println( "Elapsed time: " + (endTime - startTime) );
System.out.println( "H size is: " + H.size( ) );
System.out.println( "Array size is: " + H.capacity( ) );
}
|
ea8444f8-362a-4943-9263-191c7da29fa8
| 9
|
private int clearExecList(int totalPE)
{
int removeSoFar = 0; // number of PEs removed so far
ResGridlet obj = null;
// first, remove unreserved Gridlets
int i = 0;
while ( i < gridletInExecList_.size() )
{
obj = (ResGridlet) gridletInExecList_.get(i);
if (removeSoFar <= totalPE && !obj.hasReserved())
{
obj.setGridletStatus(Gridlet.QUEUED);
gridletInExecList_.remove(i);
gridletQueueList_.add(obj);
super.resource_.setStatusPE(PE.FREE, obj.getMachineID(),
obj.getPEID());
removeSoFar++;
continue;
}
i++;
}
// if enough, then exit
if (removeSoFar == totalPE) {
return removeSoFar;
}
// if still not enough, then remove Gridlets that are running longer
long currentTime = super.getCurrentTime();
long finishTime = 0;
// searching through the loop again
i = 0;
while ( i < gridletInExecList_.size() )
{
// exit the loop if there are enough space already
if (removeSoFar > totalPE) {
break;
}
obj = (ResGridlet) gridletInExecList_.get(i);
// look for AR Gridlets that are running longer than estimated
if (removeSoFar <= totalPE && obj.hasReserved())
{
finishTime = obj.getStartTime()+(obj.getDurationTime()*MILLI_SEC);
if (finishTime <= currentTime)
{
obj.setGridletStatus(Gridlet.QUEUED);
gridletInExecList_.remove(i);
gridletQueueList_.add(obj);
super.resource_.setStatusPE(PE.FREE, obj.getMachineID(),
obj.getPEID());
removeSoFar++;
continue;
}
}
i++;
} // end for
return removeSoFar;
}
|
a1359354-88ac-4f43-9ab5-9a73a006815d
| 5
|
private ModuleLoader() {
super(null);
final String className = this.getClass().getCanonicalName()
.replace('.', '/')
+ ".class";
final URL url = Main.class.getClassLoader().getResource(className);
if (url.getProtocol().equals("file")) {
final Path classPath = Path.getPath(url);
this.jar = false;
this.workingDirectory = classPath.getParent().getParent();
} else if (url.getProtocol().equals("jar")) {
this.jar = true;
this.workingDirectory = Path.getPath(url);
} else {
this.jar = false;
this.workingDirectory = null;
}
@SuppressWarnings("hiding")
final String[] cp = System.getProperty("java.class.path").split(
FileSystem.type == FileSystem.OSType.WINDOWS ? ";" : ":");
this.cp = new Path[Math.max(1, cp.length)];
if (cp.length == 0) {
this.cp[0] = this.workingDirectory;
} else {
final Path path = Path.getPath(System.getProperty("user.dir")
.split("\\" + FileSystem.getFileSeparator()));
for (int i = 0; i < cp.length; i++) {
final String[] cpPath = cp[i].split("\\"
+ FileSystem.getFileSeparator());
this.cp[i] = path.resolve(cpPath);
}
}
this.modulePath = StartupContainer.getDatadirectory();
}
|
40b3de7a-2984-48de-bfe3-9a39f70873b1
| 5
|
public Enumeration<Node> getSortedNodeEnumeration(boolean backToFront){
if(!Configuration.draw3DGraphNodesInProperOrder) {
return flatList.elements();
}
PositionTransformation t3d = Main.getRuntime().getTransformator();
int actualVersionNumber = t3d.getVersionNumber();
if((lastVersionNumber != actualVersionNumber)||(flatListChanged)){
//the transformation has changed. Need to resort the array.
lastVersionNumber = actualVersionNumber;
flatListChanged = false;
sortedNodeArray = flatList.toArray(sortedNodeArray);
sortedNodeArraySize = flatList.size();
if(sortedNodeArraySize > 1) {
if(myDepthComparator == null) {
myDepthComparator = new DepthComparator();
}
Arrays.sort(sortedNodeArray, 0, sortedNodeArraySize, myDepthComparator);
}
}
return new ArrayEnumeration(backToFront);
}
|
973a1031-d2cc-4a63-8b76-9ad945e9d911
| 8
|
public List<? extends Object> loadRelated (Class type, Object... relationAndRelated) {
Transaction transaction = _manager.currentTransaction ();
StringBuilder criteria = new StringBuilder ("");
List<? extends Object> results;
Query query;
String relation;
Object related;
boolean first = true;
for (int index = 0; index < relationAndRelated.length - 1; index += 2) {
relation = relationAndRelated[index].toString ();
related = relationAndRelated[index + 1];
if (relation != null && related != null) {
if (!first) {
criteria.append (" && ");
}
// DEFINITELY WRONG: append (related)
criteria.append (relation).append (" == s").append (index).
append (" && s").append (index).append (" == '").append (related).append ("'");
first = false;
}
}
try {
transaction.begin ();
query = _manager.newQuery (type.getName (), criteria);
results = (List<? extends Object>) query.execute ();
transaction.commit ();
} finally {
if (transaction.isActive ()) {
transaction.rollback ();
}
_manager.close ();
}
return results;
}
|
413c11d8-f435-404f-a4cd-da70f5fd0cb4
| 2
|
String getRawURI(URL url) {
String uri = url.getPath();
if (url.getQuery() != null && url.getQuery().length() != 0) {
uri += "?" + url.getQuery();
}
return uri;
}
|
55924c45-0446-40ef-95ac-35a2b0a33cf4
| 8
|
BulkScorer optionalBulkScorer(LeafReaderContext context) throws IOException {
List<BulkScorer> optional = new ArrayList<BulkScorer>();
Iterator<BooleanClause> cIter = query.iterator();
for (Weight w : weights) {
BooleanClause c = cIter.next();
if (c.getOccur() != Occur.SHOULD) {
continue;
}
BulkScorer subScorer = w.bulkScorer(context);
if (subScorer != null) {
optional.add(subScorer);
}
}
if (optional.size() == 0) {
return null;
}
if (query.getMinimumNumberShouldMatch() > optional.size()) {
return null;
}
if (optional.size() == 1) {
BulkScorer opt = optional.get(0);
if (!disableCoord && maxCoord > 1) {
return new BooleanTopLevelScorers.BoostedBulkScorer(opt, coord(1, maxCoord));
} else {
return opt;
}
}
return new BooleanScorer(this, disableCoord, maxCoord, optional, Math.max(1, query.getMinimumNumberShouldMatch()), needsScores);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.