method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
7a3e03ae-17dd-4838-a6aa-912a429e6d60
| 7
|
private final void encode(final ByteArrayBuffer fb, final char c) {
if (c < 0x80) {
fb.append((byte) c);
} else if (c < 0x800) {
fb.append((byte) (0xc0 | c >> 6));
fb.append((byte) (0x80 | c & 0x3f));
} else if(c < 0xD800){
fb.append((byte) (0xe0 | c >> 12));
fb.append((byte) (0x80 | c >> 6 & 0x3f));
fb.append((byte) (0x80 | c & 0x3f));
} else if(c < 0xE000){
fb.append((byte) 0x3F);
} else if (c < 0x10000) {
fb.append((byte) (0xe0 | c >> 12));
fb.append((byte) (0x80 | c >> 6 & 0x3f));
fb.append((byte) (0x80 | c & 0x3f));
} else if (c < 0x200000) {
fb.append((byte) (0xf0 | c >> 18));
fb.append((byte) (0x80 | c >> 12));
fb.append((byte) (0x80 | c >> 6 & 0x3f));
fb.append((byte) (0x80 | c & 0x3f));
} else if (c < 0x4000000) {
fb.append((byte) (0xf8 | c >> 24));
fb.append((byte) (0x80 | c >> 18));
fb.append((byte) (0x80 | c >> 12));
fb.append((byte) (0x80 | c >> 6 & 0x3f));
fb.append((byte) (0x80 | c & 0x3f));
} else {
fb.append((byte) (0xfc | c >> 30));
fb.append((byte) (0x80 | c >> 24));
fb.append((byte) (0x80 | c >> 18));
fb.append((byte) (0x80 | c >> 12));
fb.append((byte) (0x80 | c >> 6 & 0x3f));
fb.append((byte) (0x80 | c & 0x3f));
}
}
|
9f7d7d35-2925-421f-bae2-189e3be92334
| 2
|
@Override
public String toString() {
StringBuffer info = new StringBuffer();
info.append("Layer Name :: ").append(getName()).append("\n");
info.append("logical Queue : ").append(logicalQueue).append("\n");
info.append("Draw List : ").append(drawableList);
// Output drawable
info.append(drawableList.size() > 0 ? drawableList.size() + " drawable game components added :: " : "No current game drawable components added").append("\n");
for (IDrawable obj : drawableList)
info.append(Helpers.concat(obj.toString(), "\n"));
return info.toString();
}
|
1bf6b2c5-c9a2-440c-8d7b-e65666134ed0
| 9
|
private void load() {
String packageName = "Exercises";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ArrayList<String> names = new ArrayList<String>();
URL packageURL = classLoader.getResource(packageName);
if (packageURL != null) {
File folder = new File(packageURL.getFile().replaceAll("%20", " "));
File[] files = folder.listFiles();
String entryName;
if (files != null) {
for (File actual : files) {
entryName = actual.getName();
if (!ignore.contains(entryName) && !actual.isDirectory()) {
entryName = entryName.substring(0, entryName.lastIndexOf('.'));
names.add(entryName);
}
}
for (String s : names) {
try {
add((IExercise) Class.forName("Exercises." + s).newInstance());
} catch (ClassNotFoundException e) {
pl("Class not found.");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} else {
pl("\"files\" is null! Please add some class files for the launcher to work.");
System.exit(0);
}
} else {
pl("packageURL is null! Aborting!");
System.exit(1);
}
}
|
28262f04-54e5-43f2-8941-7d367ac45fdc
| 8
|
public void adjustRGB(int adjustmentR, int adjustmentG, int adjustmentB) {
for (int pixel = 0; pixel < pixels.length; pixel++) {
int originalColour = pixels[pixel];
if (originalColour != 0) {
int red = originalColour >> 16 & 0xff;
red += adjustmentR;
if (red < 1)
red = 1;
else if (red > 255)
red = 255;
int green = originalColour >> 8 & 0xff;
green += adjustmentG;
if (green < 1)
green = 1;
else if (green > 255)
green = 255;
int blue = originalColour & 0xff;
blue += adjustmentB;
if (blue < 1)
blue = 1;
else if (blue > 255)
blue = 255;
pixels[pixel] = (red << 16) + (green << 8) + blue;
}
}
}
|
2c3fda60-03ca-4bed-afd7-a946b275adc9
| 2
|
private void reloadMode(ModeEnum myMode) {
String[] modes = comboMode.getItems();
String label = myMode.getLabel();
for (int index = 0; index < modes.length; index++) {
if (label.equals(modes[index])) {
comboMode.select(index);
break;
}
}
}
|
b758f8d0-fa2a-4183-84fb-1da7e7c4678b
| 8
|
private void dessineCamembert(Noeud n, Graphics g,
HashMap<String, Color[]> historique, DrawStrategy strategy,
Color couleur_demande) {
// on dessine le noeud de destination
// differement selon la strategie defini
if (strategy == DrawStrategy.LAST_WIN) {
// Si la strategy est LAST_WIN, il suffit
// de dessiner le noeud dans la couleur
// de la derniere plage horaire (donc c)
dessineNoeud(n, g, couleur_demande);
} else if (strategy == DrawStrategy.FIRST_WIN) {
// Si la strategy est FIRST_WIN...
// On ne dessine le noeud que si c'est
// la premi�re fois qu'on le parcours
// En pratique, on verifie qu'il n'est pas dans
// la liste des noeuds de passage parcourus
if (!historique.containsKey(n.toString())) {
// et s'il n'y est pas,
dessineNoeud(n, g, couleur_demande);
Color[] couleurs = { couleur_demande };// on le dessine
// et on l'ajoute a la liste des noeuds de passage parcourus
historique.put(n.toString(), couleurs);
}
} else {
// Si la strategy est BOTH_WIN ou proportionnate,
// On regarde si le noeud a deja ete dessine
if (historique.containsKey(n.toString())) {
// Si oui,
Color[] couleurs = historique.get(n.toString());
boolean deja_peinte = false;
if (strategy == DrawStrategy.BOTH_WIN) {
// et que la strategy est BOTH_WIN,
// on regarde si le noeud a deja ete parcourus par
// un trajet de la m�me plage horaire
for (Color coul : couleurs) {
if (coul == couleur_demande) {
deja_peinte = true;
break;
}
}
}
if (!deja_peinte) {
// Si non, on ajoute la couleur de la plage horaire actuel
Color[] couleurs2 = new Color[couleurs.length + 1];
System.arraycopy(couleurs, 0, couleurs2, 0, couleurs.length);
couleurs2[couleurs.length] = couleur_demande;
// puis on dessine le point
dessineNoeud(n, g, couleurs2);
historique.put(n.toString(), couleurs2);
}
/*
* Remarque : Pour la strategy PROPORTIONATE, on ne verifie
* jamais is un point a �t� parcourus par un trajet de la m�me
* plage horaire. Par consequent plus un point est parcourus
* dans un meme plage horaire, plus il sera dessine dans la
* couleur de cette plage horaire (sa part de camembert
* augmente)
*/
} else {
// Enfin, si le noeud n'a jamais ete dessine
dessineNoeud(n, g, couleur_demande);// on le dessine une
// premiere fois
Color[] couleurs = { couleur_demande };
// puis on met � jour la liste des noeuds deja dessine
historique.put(n.toString(), couleurs);
}
}
}
|
1c80639c-a53e-4f09-9adf-b30defbaf271
| 1
|
public int getInt() {
String textv = ((TextEntry)wdg()).text;
try{
Integer ival = Integer.parseInt(textv);
return ival.intValue();
}
catch(NumberFormatException e){
return 0;
}
}
|
c51e1771-bade-4d42-8f71-1656da87e1ca
| 4
|
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new IllegalArgumentException("half width must be nonnegative");
if (halfHeight < 0) throw new IllegalArgumentException("half height must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
|
cf7b31c0-8a9b-4d9a-aca8-c9b699cc38ef
| 0
|
public String execute() {
return "SUCCESS";
}
|
0fd78d60-cf48-4617-9c17-b8bbf5da04f3
| 1
|
public Connection(Socket socket) throws java.io.IOException{
this.socket = socket;
if (socket!=null) {
setInputStream(socket.getInputStream());
setOutputStream(socket.getOutputStream());
}
}
|
ffebafd1-a58c-471f-acf4-3980a11c1c14
| 1
|
protected static String processEmphasis(String text) {
String[] arr = text.split("\\|");
if (arr.length == 2) {
return "<span class=\"emphasis\">" + arr[1] + "</span>";
}
return "<span class=\"emphasis\">" + arr[1] + "</span><span class=\"afterEmphasis\">" + arr[2] + "</span>";
}
|
1412117d-5251-487e-a8ff-c15bc1e74ba7
| 7
|
Power(String name, int properties, String imgFile, String helpInfo) {
this.name = name ;
this.helpInfo = helpInfo ;
this.buttonTex = Texture.loadTexture(IMG_DIR+imgFile) ;
this.properties = properties ;
}
|
f7d65c75-a994-432d-8924-a09bbbc0afa3
| 2
|
public int swapOddAndEvenBit(int origNum){
int resultNum = 0;
//make a new Num with origNum shift right by 1;
System.out.println("origNum="+origNum);
int shiftedNum = origNum >> 1;
System.out.println("shiftedRight="+shiftedNum);
//XOR origNum and shiftedNum, then bit 0 would be XOR of bit(0,1), bit 1 =XOR(1,2), etc...
int newNum = shiftedNum ^ origNum;
System.out.println("XOR="+newNum);
//just need to check even bits, as bit 0 = (0,1), bit 2 = (2,3), etc. Odd bits are not useful in this case
//if even bits is 0 , meaning those two bits are same, nothing needs to be done; Otherwise, change the original bit to its oppsite.
for(int i=0;i<31;i+=2){ //increase i by 2 to avoid checking odd number bits
if((newNum & (1 << i)) > 0){
//modify origNum at bit i and i+1 to its opposite, coz newNum[i]= XOR(orig[i],orig[i+1]);
resultNum = this.revertBitAtPos(origNum,i);
resultNum = this.revertBitAtPos(resultNum,i+1);
}
}
return resultNum;
}
|
40173fdd-ac99-4087-8f94-c1f61be45047
| 2
|
public boolean hasIntArg() {
try{
String s = peek();
if(s.isEmpty()) {
return false;
} else {
Integer.valueOf(s);
}
} catch(NumberFormatException e) {
return false;
}
return true;
}
|
5679a89f-b89c-4b20-aeb3-32349f37af4c
| 5
|
public IVPNumber divide(IVPNumber number, Context context, DataFactory factory, HashMap map) {
IVPNumber result = factory.createIVPNumber();
map.put(result.getUniqueID(), result);
if(getValueType().equals(IVPValue.INTEGER_TYPE) && number.getValueType().equals(IVPValue.INTEGER_TYPE)){
int resultInt = context.getInt(getUniqueID()) / context.getInt(number.getUniqueID());
result.setValueType(IVPValue.INTEGER_TYPE);
context.addInt(result.getUniqueID(), resultInt);
}else{
double resultDouble = 0.0;
if(getValueType().equals(IVPValue.DOUBLE_TYPE) && number.getValueType().equals(IVPValue.DOUBLE_TYPE)){
resultDouble = context.getDouble(getUniqueID()) / context.getDouble(number.getUniqueID());
result.setValueType(IVPValue.DOUBLE_TYPE);
}else{
if(getValueType().equals(IVPValue.DOUBLE_TYPE)){
resultDouble = context.getDouble(getUniqueID()) / context.getInt(number.getUniqueID());
}else{
resultDouble = context.getInt(getUniqueID()) / context.getDouble(number.getUniqueID());
}
}
result.setValueType(IVPValue.DOUBLE_TYPE);
context.addDouble(result.getUniqueID(), resultDouble);
}
return result;
}
|
a73de40c-c2b0-4c51-bc32-2c386d5ae234
| 8
|
public static Direction flip_x_dir(Direction d) {
switch (d) {
case NW:
return NE;
case W:
return E;
case SW:
return SE;
case N:
return N;
case S:
return S;
case NE:
return NW;
case E:
return W;
case SE:
return SW;
}
assert false : "should not happen";
return NW;
}
|
a71719eb-26b1-4401-a0b6-de9e429103e5
| 9
|
public void copyAsRtf() {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
if (selStart==selEnd) {
return;
}
// Make sure there is a system clipboard, and that we can write
// to it.
SecurityManager sm = System.getSecurityManager();
if (sm!=null) {
try {
sm.checkSystemClipboardAccess();
} catch (SecurityException se) {
UIManager.getLookAndFeel().provideErrorFeedback(null);
return;
}
}
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
// Create the RTF selection.
RtfGenerator gen = getRTFGenerator();
Token tokenList = getTokenListFor(selStart, selEnd);
for (Token t=tokenList; t!=null; t=t.getNextToken()) {
if (t.isPaintable()) {
if (t.textCount==1 && t.text[t.textOffset]=='\n') {
gen.appendNewline();
}
else {
Font font = getFontForTokenType(t.type);
Color bg = getBackgroundForToken(t);
boolean underline = getUnderlineForToken(t);
// Small optimization - don't print fg color if this
// is a whitespace color. Saves on RTF size.
if (t.isWhitespace()) {
gen.appendToDocNoFG(t.getLexeme(), font, bg, underline);
}
else {
Color fg = getForegroundForToken(t);
gen.appendToDoc(t.getLexeme(), font, fg, bg, underline);
}
}
}
}
// Set the system clipboard contents to the RTF selection.
RtfTransferable contents = new RtfTransferable(gen.getRtf().getBytes());
//System.out.println("*** " + new String(gen.getRtf().getBytes()));
try {
cb.setContents(contents, null);
} catch (IllegalStateException ise) {
UIManager.getLookAndFeel().provideErrorFeedback(null);
return;
}
}
|
facea919-7019-457f-872d-83247034e744
| 0
|
public void setCode_sec(String code_sec) {
this.code_sec = code_sec;
}
|
91f385a2-0659-4b27-96fd-d26b460c83ec
| 4
|
@Override
public void mouseReleased(MouseEvent event) {
if (mSortColumn != null) {
if (mSortColumn == mOwner.overColumn(event.getX())) {
if (mOwner.isUserSortable()) {
boolean sortAscending = mSortColumn.isSortAscending();
if (mSortColumn.getSortSequence() != -1) {
sortAscending = !sortAscending;
}
mOwner.setSort(mSortColumn, sortAscending, event.isShiftDown());
}
}
mSortColumn = null;
} else {
mOwner.mouseReleased(event);
}
}
|
28de82e6-ce74-42c0-87c5-698fc9ce6404
| 3
|
public boolean contains(Point p) {
Point p0 = this.getXY();
int s2 = this.getParent().getConnectorSize() / 2;
return (p.x >= p0.x - s2 && p.x <= p0.x + s2 && p.y >= p0.y - s2 && p.y <= p0.y
+ s2);
}
|
98180723-8690-4259-912d-a8d0f10f86cd
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PresentacionDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PresentacionDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PresentacionDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PresentacionDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PresentacionDocente().setVisible(true);
}
});
}
|
837cffbd-f5c2-485b-b00e-f82a0ebc24a0
| 2
|
public static void add(Record rec, User user, int score) throws SQLException
{
if (rec != null && user != null)
{
String sql = "INSERT INTO score_history (record_id,user_id,score_date,score_value) VALUES (?,?,now(),?)";
PreparedStatement ps = Connect.getConnection().getPreparedStatement(sql.toString());
ps.setInt(1, rec.getNumber());
ps.setInt(2, user.getID());
ps.setInt(3, score);
ps.execute();
ps.close();
// Update the record to ranked
rec.save();
}
}
|
0f234f0e-d82f-4891-8caf-00a49e82540f
| 6
|
public Boolean isWellFormed(String strParentheses) {
if (strParentheses == null) {
return false;
}
// Idea is to have two counters, one for open parentheses '{' and one
// for close '}'
// Read one character at a time and increment one of the counters
// If any given point of time count of close parentheses is greater than
// the open one, return false
// If at the end both counters are equal, return true
int openParenCounter = 0;
int closeParenCounter = 0;
for (int i = 0; i < strParentheses.length(); i++) {
char x = strParentheses.charAt(i);
if (x == '{')
openParenCounter++;
else if (x == '}')
closeParenCounter++;
if (closeParenCounter > openParenCounter) {
return false;
}
}
if (openParenCounter == closeParenCounter)
return true;
else
return false;
}
|
9086f705-f385-4b23-bf41-58d30bc2c8e1
| 4
|
protected Batch <String> descOngoingUpgrades() {
final Batch <String> desc = new Batch <String> () ;
if (upgrades == null) return desc ;
for (int i = 0 ; i < upgrades.length ; i++) {
if (upgrades[i] == null || upgradeStates[i] == STATE_INTACT) continue ;
desc.add(upgrades[i].name+" ("+STATE_DESC[upgradeStates[i]]+")") ;
}
return desc ;
}
|
d4025667-3bb4-4be6-bd83-0c36291f08b1
| 9
|
* @param mes the messsage
*/
private void handleMONOPOLYPICK(StringConnection c, MonopolyPick mes)
{
if (c != null)
{
Game ga = gameList.getGameData(mes.getGame());
if (ga != null)
{
ga.takeMonitor();
try
{
final String gaName = ga.getName();
if (checkTurn(c, ga))
{
if (ga.canDoMonopolyAction())
{
int[] monoPicks = ga.doMonopolyAction(mes.getResource());
recordGameEvent(mes, mes.getGame(), mes.toCmd());
final String monoPlayerName = (String) c.getData();
final String resName
= " " + ResourceConstants.resName(mes.getResource()) + ".";
String message = monoPlayerName + " monopolized" + resName;
gameList.takeMonitorForGame(gaName);
messageToGameExcept(gaName, c, new GameTextMsg(gaName, SERVERNAME, message), false);
/**
* just send all the player's resource counts for the
* monopolized resource
*/
for (int i = 0; i < ga.maxPlayers; i++)
{
/**
* Note: This only works if PlayerElement.CLAY == ResourceConstants.CLAY
*/
messageToGameWithMon(gaName, new PlayerElement(gaName, i, PlayerElement.SET, mes.getResource(), ga.getPlayer(i).getResources().getAmount(mes.getResource())));
}
gameList.releaseMonitorForGame(gaName);
/**
* now that monitor is released, notify the
* victim(s) of resource amounts taken,
* and tell the player how many they won.
*/
int monoTotal = 0;
for (int i = 0; i < ga.maxPlayers; i++)
{
int picked = monoPicks[i];
if (picked == 0)
continue;
monoTotal += picked;
String viName = ga.getPlayer(i).getName();
StringConnection viCon = getConnection(viName);
if (viCon != null)
messageToPlayer(viCon, gaName,
monoPlayerName + "'s Monopoly took your " + picked + resName);
}
messageToPlayer(c, gaName, "You monopolized " + monoTotal + resName);
sendGameState(ga);
}
else
{
messageToPlayer(c, gaName, "You can't do a Monopoly pick now.");
}
}
else
{
messageToPlayer(c, gaName, "It's not your turn.");
}
}
catch (Exception e)
{
D.ebugPrintln("Exception caught - " + e);
e.printStackTrace();
}
ga.releaseMonitor();
}
}
}
|
470cfd2b-7987-434b-9af3-4a73c38c0320
| 1
|
public static void renderButton(Graphics g, Rectangle r, String s)
{
if(r.contains(Main.mse))
{
g.drawImage(Button2, r.x, r.y, r.width, r.height, null);
}
else
{
g.drawImage(Button1, r.x, r.y, r.width, r.height, null);
}
g.setFont(new Font(Font.SANS_SERIF, (int)(r.height/1.75), (int)(r.height/1.75)));
g.drawString(s, r.x + (r.width/6), (int) (r.y+(r.height/1.25)));
}
|
9b4b02d9-9afd-4f7f-bfb4-dad937b634bd
| 4
|
public void setAttribute(String asName, String asVal, boolean abMultiAttr) {
if (UtilityMethods.isValidString(asName) && UtilityMethods.isValidString(asName)) {
if (abMultiAttr) {
getAttrList().add(new Attribute(asName, asVal));
} else {
Attribute laAttr = getAttribute(asName);
if (laAttr != null) {
laAttr.setVal(asVal);
} else {
getAttrList().add(new Attribute(asName, asVal));
}
}
}
}
|
99b929e4-4dd9-46a6-a374-aac0ff89b71b
| 2
|
public static void main(String[] args) {
ShopifyService service = new ShopifyService();
String url ="https://0f99730e50a2493463d263f6f6003622:1a27610dee9600dd8366bf76d90b5589@shopatmyspace.myshopify.com/admin/customers.json";
try{
final HttpClientContext context = HttpClientContext.create();
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = client.execute(get,context);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while((line= br.readLine())!=null){
service.save(new JSONObject(line));
}
}catch(Exception e){
e.printStackTrace();
}
}
|
f314c567-6052-4692-8570-c7224a7bf6c4
| 7
|
protected void landingOn(PlayerClass pPlayer)
{
this.victim = pPlayer;
if(this.owned == true && this.currentOwner == pPlayer && ownsAllColours() == true) // If you own your own property, you can upgrade.
{
buyMenu();
}
if(this.owned == false && pPlayer.account.getBalance() >= this.buyPrice) // If not owned, you can buy the property
{
buyProperty(this.colour);
}
if(this.owned == true && this.currentOwner != pPlayer) // if owned and you don't own the place
{
enemyTerritory();
}
}
|
73b7e22c-9a01-4f46-84dc-540e953644b2
| 1
|
@Override
public void setSelected( Selection selection ) {
super.setSelected( selection );
connection.updateSelection();
ItemSelectionEvent event = new ItemSelectionEvent( connection, selection );
for( ItemSelectionListener listener : listeners()){
listener.itemSelectionChanged( event );
}
}
|
4e4120ae-3f81-47c4-a2b5-8522e39a136c
| 1
|
private String options() {
String options = "";
int commandNumber = 1;
for (Command command : commands){
options += commandNumber++ + ") " + command.name() + "\n";
}
return options;
}
|
895d03d1-8d6c-4775-b1e3-a2861d4fb126
| 7
|
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
StringBuilder sb = new StringBuilder();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
|
f138dae7-a103-4dd1-97c2-5337adce98de
| 3
|
@Override
public String toString() {
String result = "[";
int i = 0;
while (i < capacity) {
if (queue[i] != null) {
result += queue[i] + ", ";
}
i++;
}
if (result.length() > 2) {
result = result.substring(0, result.length() - 2);
}
result += "]";
return result;
}
|
51085705-3e2d-44c0-8a49-543792b1ab2c
| 0
|
public static void createIcons() {
// Create a buffered image from the is not property image.
Image isNotPropertyImage = ICON_IS_NOT_PROPERTY.getImage();
BufferedImage isNotImage = new BufferedImage(TRUE_WIDTH, BUTTON_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D gIsNotImage = isNotImage.createGraphics();
gIsNotImage.drawImage(isNotPropertyImage,0,0,Outliner.outliner);
// Create a buffered image from the is property image.
Image isPropertyImage = ICON_IS_PROPERTY.getImage();
BufferedImage isImage = new BufferedImage(TRUE_WIDTH, BUTTON_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D gIsImage = isImage.createGraphics();
gIsImage.drawImage(isPropertyImage,0,0,Outliner.outliner);
// Lighten color to inherited versions
RGBImageFilter lightenFilter = ImageFilters.getLightenFilter(0x00cccccc);
FilteredImageSource isNotPropertyInheritedSource = new FilteredImageSource(isNotImage.getSource(), lightenFilter);
FilteredImageSource isPropertyInheritedSource = new FilteredImageSource(isImage.getSource(), lightenFilter);
Image isNotPropertyInheritedImage = Outliner.outliner.createImage(isNotPropertyInheritedSource);
Image isPropertyInheritedImage = Outliner.outliner.createImage(isPropertyInheritedSource);
ICON_IS_NOT_PROPERTY_INHERITED = new ImageIcon(isNotPropertyInheritedImage);
ICON_IS_PROPERTY_INHERITED = new ImageIcon(isPropertyInheritedImage);
}
|
5af581de-0ee6-4724-ad72-325713f39cf0
| 3
|
private final static long getDays(long year) {
final Long entry = Time.daysSince1970.get(year);
if (entry != null) {
return entry;
}
long days = 0;
for (long y = 1970; y < year; ++y) {
final boolean leap = isLeap(y);
if (leap) {
days += 366;
} else {
days += 365;
}
}
Time.daysSince1970.put(year, days);
return days;
}
|
de50b2b7-6185-4c7e-bbab-e36c9b2862cd
| 5
|
protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
CoderResult result;
while (true) {
// output buffered data
if (buf.hasRemaining()) {
result = super.decodeLoop(buf,out);
// stop if out of output space or error
if (buf.hasRemaining() || result.isError())
return result;
}
// process new data into buffer
buf.clear();
result = unpack(in, buf);
buf.flip();
if (!buf.hasRemaining())
return result;
unpackedCount += buf.remaining();
}
}
|
1ae1b861-0067-4208-8eb0-afc193c315ac
| 8
|
protected void pasteBufferedComponent(int x, int y) {
if (pasteBuffer instanceof ImageComponent) {
ImageComponent ic = null;
try {
ic = new ImageComponent(((ImageComponent) pasteBuffer).toString());
} catch (Exception e) {
e.printStackTrace();
return;
}
ic.setLocation(x, y);
addLayeredComponent(ic);
} else if (pasteBuffer instanceof TextBoxComponent) {
TextBoxComponent t = new TextBoxComponent((TextBoxComponent) pasteBuffer);
t.setLocation(x, y);
if (t.isCallOut())
t.setCallOutLocation(x - 10, y - 10);
addLayeredComponent(t);
} else if (pasteBuffer instanceof LineComponent) {
LineComponent l = new LineComponent((LineComponent) pasteBuffer);
l.setLocation(x, y);
addLayeredComponent(l);
} else if (pasteBuffer instanceof RectangleComponent) {
RectangleComponent r = new RectangleComponent((RectangleComponent) pasteBuffer);
r.setLocation(x, y);
addLayeredComponent(r);
} else if (pasteBuffer instanceof EllipseComponent) {
EllipseComponent e = new EllipseComponent((EllipseComponent) pasteBuffer);
e.setLocation(x, y);
addLayeredComponent(e);
} else if (pasteBuffer instanceof TriangleComponent) {
TriangleComponent t = new TriangleComponent((TriangleComponent) pasteBuffer);
t.setLocation(x, y);
addLayeredComponent(t);
}
}
|
b1066bce-4809-4f9d-813a-b92df8ef1efb
| 7
|
public void actionPerformed(ActionEvent e) {
this.setCmd(e.getActionCommand());
if (isCmd("debugmode")) {
if (this.getInfo().chckbxDebug.isSelected()) {
this.getCore().settings.set(this.getCore().showDebug, "true");
} else {
this.getCore().settings.set(this.getCore().showDebug, "false");
}
} else if (isCmd("debugoncmd")) {
if (this.getInfo().chckbxShowGuiWhen.isSelected()) {
this.getCore().settings.set(this.getCore().showGui, "true");
} else {
this.getCore().settings.set(this.getCore().showGui, "false");
}
} else if (isCmd("save")) {
this.getCore().settings.save();
} else if (isCmd("save_e")) {
this.getCore().settings.save();
this.getInfo().dispose();
} else if (isCmd("cancel")) {
this.getInfo().dispose();
}
}
|
513f4f65-6434-4eba-91ae-bed3151d9248
| 6
|
public void loadMapFromFile(File selFile) {
BufferedReader csvReader = null;
try {
csvReader = new BufferedReader(new FileReader(selFile));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
int fieldCount = 0;
int lineCount = 0;
String[] csvFields = null;
String[] header = null;
String curLine;
String patternStr = ",";
boolean loadCities = true;
try {
while ((curLine = csvReader.readLine()) != null) {
csvFields = curLine.split(patternStr);
fieldCount = csvFields.length;
if (fieldCount == 1) {
loadCities = false;
} else {
lineCount++;
if (loadCities) {
cities.add(deblank(csvFields));
processCoords(csvFields);
} else {
roads.add(deblank(csvFields));
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
try {
csvReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
|
79373180-1bbf-436d-900c-4dfe86cc32b5
| 3
|
@Override
public double getWidth() {
double width = 0;
double x = getX();
double temp = 0;
ModelSubset[] subs = getAnimatedModel().getSubsets();
for (int i = 0; i < subs.length; i++) {
for (int j = 0; j < subs[i].getVertices().length; j++) {
temp = subs[i].getVertices()[j].getX() - x;
Math.abs(temp);
if (temp > width) {
width = temp;
}
}
}
return width;
}
|
4aca28bc-f034-49d9-9a95-cc8b607039a8
| 9
|
private synchronized IndexReader doReopenNoWriter(final boolean openReadOnly, IndexCommit commit) throws CorruptIndexException, IOException {
if (commit == null) {
if (hasChanges) {
// We have changes, which means we are not readOnly:
assert readOnly == false;
// and we hold the write lock:
assert writeLock != null;
// so no other writer holds the write lock, which
// means no changes could have been done to the index:
assert isCurrent();
if (openReadOnly) {
return clone(openReadOnly);
} else {
return this;
}
} else if (isCurrent()) {
if (openReadOnly != readOnly) {
// Just fallback to clone
return clone(openReadOnly);
} else {
return this;
}
}
} else {
if (directory != commit.getDirectory())
throw new IOException("the specified commit does not match the specified Directory");
if (segmentInfos != null && commit.getSegmentsFileName().equals(segmentInfos.getCurrentSegmentFileName())) {
if (readOnly != openReadOnly) {
// Just fallback to clone
return clone(openReadOnly);
} else {
return this;
}
}
}
return (IndexReader) new SegmentInfos.FindSegmentsFile(directory) {
@Override
protected Object doBody(String segmentFileName) throws CorruptIndexException, IOException {
SegmentInfos infos = new SegmentInfos();
infos.read(directory, segmentFileName);
return doReopen(infos, false, openReadOnly);
}
}.run(commit);
}
|
fbc4991e-a46e-4333-a266-56e9a860bf4d
| 3
|
public synchronized void write(Transaction ta, int pageId, String data) {
incrementLSN();
// write the data to a file
// one file for each page
// LSN also into the file for redoing
log(ta.getTaId(), LogType.WRITE, pageId, data);
Page page = new Page(pageId, logSequenceNumber, data, ta);
buffer.put(pageId, page);
System.out.println("Buffer Size: " + buffer.size());
if (buffer.size() > 5)
{
Object[] allValues = buffer.values().toArray();
for (int i = 0; i < allValues.length; i++)
{
Page currentPage = (Page) allValues[i];
if (currentPage.checkForCommit())
{
savePage(currentPage);
buffer.remove(currentPage.getPageId());
}
}
}
}
|
ebc6b748-d7db-4205-9e33-2f3048325340
| 4
|
private static void insertionSort(int[] arr) {
if(arr.length < 2) return;
int firstUnsortedNum;//第一个未排序的数,我们认为arr[0]已经排好序,因而从arr[1]开始
for(int i=1; i<arr.length; i++){
firstUnsortedNum = arr[i];
int j = i - 1;
while(j>=0 && firstUnsortedNum < arr[j]){//和已排好序的数进行比较,从最后一个已排序数开始
arr[j+1] = arr[j];
j--;
}
arr[j+1] = firstUnsortedNum;
}
}
|
7ff55b88-0c2f-4619-b87b-e1d00c4b111f
| 1
|
public boolean supprimerLocation(int numero){
System.out.println("ModeleLocations::supprimerLocation()") ;
Location location = rechercherLocation(numero) ;
if(location != null){
location.getVehicule().setSituation(Vehicule.DISPONIBLE) ;
this.locations.remove(location) ;
return true ;
}
else {
return false ;
}
}
|
c6cac3f0-4740-4fb2-8fbd-85f26b10997f
| 4
|
public boolean connect (String IP, boolean scan)
{
try
{
if(scan){
socket = findServer();
if(socket == null){
jTextField2.setText("Status: No Server Found");
return false;
}
}
else{
socket = new Socket();
socket.connect (new InetSocketAddress (IP, PORT), 10);
}
}
catch (Exception e)
{
System.out.println ("Error connectiong to server:" + e);
return false;
}
System.out.println ("Connection accepted " +
socket.getInetAddress () + ":" +
socket.getPort ());
/* Creating both Data Stream */
try
{
Sinput = new ObjectInputStream (socket.getInputStream ());
Soutput = new ObjectOutputStream (socket.getOutputStream ());
}
catch (IOException e)
{
System.out.println ("Exception creating new Input/output Streams: " + e);
return false;
}
connected = true;
return true;
}
|
e3874f75-1b2a-4c8d-9acb-7d2a4b1365a9
| 4
|
public void newProject() throws IOException {
boolean canceled = false;
if (isChanged) {
Object[] options = { Tools.getLocalizedString("YES"),
Tools.getLocalizedString("NO") };
JFrame frame = new JFrame();
int n = JOptionPane.showOptionDialog(frame,
Tools.getLocalizedString("EXIT_DIALOGUE"),
"KS Boolean Expression", JOptionPane.YES_NO_OPTION,
JOptionPane.YES_NO_OPTION, null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
save();
if (isChanged)
canceled = true;
}
}
if (!canceled) {
algebricForm();
fileName = null;
isChanged = false;
}
}
|
910d6710-a77b-45e1-8196-9fef66e7a27a
| 8
|
@Override
public void e(float sideMot, float forMot) {
if (this.passenger == null || !(this.passenger instanceof EntityHuman)) {
super.e(sideMot, forMot);
this.W = 0.5F; // Make sure the entity can walk over half slabs,
// instead of jumping
return;
}
EntityHuman human = (EntityHuman) this.passenger;
if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) {
// Same as before
super.e(sideMot, forMot);
this.W = 0.5F;
return;
}
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
// Set the entity's pitch, yaw, head rotation etc.
this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166
this.aO = this.aM = this.yaw;
this.W = 1.0F; // The custom entity will now automatically climb up 1
// high blocks
sideMot = ((EntityLiving) this.passenger).bd * 0.5F;
forMot = ((EntityLiving) this.passenger).be;
if (forMot <= 0.0F) {
forMot *= 0.25F; // Make backwards slower
}
sideMot *= 0.75F; // Also make sideways slower
float speed = 0.35F; // 0.2 is the default entity speed. I made it
// slightly faster so that riding is better than
// walking
this.i(speed); // Apply the speed
super.e(sideMot, forMot); // Apply the motion to the entity
try {
Field jump = null;
jump = EntityLiving.class.getDeclaredField("bc");
jump.setAccessible(true);
if (jump != null && this.onGround) { // Wouldn't want it jumping
// while
// on the ground would we?
if (jump.getBoolean(this.passenger)) {
double jumpHeight = 0.5D;
this.motY = jumpHeight; // Used all the time in NMS for
// entity jumping
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
e44139b1-d455-4bb6-80ba-3d4490556bfe
| 8
|
public static Coordinates readMoveFromKeyboard() {
Coordinates result = null;
while (result == null) {
System.out.print(">");
String str = null;
int row = 0, column = 0;
BufferedReader d = new BufferedReader(new InputStreamReader(
System.in));
// String einlesen
try {
str = d.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// gelesenen String sezieren
str.trim();
str = str.toLowerCase();
// falls der Zug "passen" bedeutet, beende Schleife (gib 'null'
// zurück)
if (str.equals(PASSEN)) {
System.out.println("Zug 'PASSEN' wurde ausgewaehlt.");
break;
}
if (str.length() != 2) {
System.out.println("Ungueltige Eingabe: mehr als 2 Zeichen.");
continue;
}
// ist das erste Zeichen eine Ziffer zwischen 0..8?
row = (int) (str.charAt(0)) - (int) '0';
// Zeilen 0 und 9 sind ungueltig
if (row < 1 || row > 8) {
System.out.println("Ungueltige Eingabe: die Zeilennummer muss "
+ "zwischen 1 und 8 liegen.");
continue;
}
// ist das zweite Zeichen ein Buchstabe zwischen a..h?
column = (int) (str.charAt(1)) - (int) 'a' + 1;
if (column < 1 || column > 8) {
System.out.println("Ungueltige Eingabe: die Spaltenummer muss "
+ "zwischen A und H liegen.");
continue;
}
result = new Coordinates(row, column);
}
return result;
} // end readMoveFromKeyboard()
|
1662f0a0-cfd4-4a85-87db-ca10a9456774
| 8
|
public int getValue() {
int status = 0;
status |= (negative ? 0x80 : 0);
status |= (overflow ? 0x40 : 0);
status |= (memory_access ? 0x20 : 0);
status |= (index_register ? 0x10 : 0);
status |= (decimal_mode ? 0x8 : 0);
status |= (irq_disable ? 0x4 : 0);
status |= (zero ? 0x2 : 0);
status |= (carry ? 0x1 : 0);
return status;
}
|
fa95ea04-88a0-49b7-b798-51a4e780e4b1
| 7
|
protected void actionPerformed(GuiButton par1GuiButton)
{
if (!par1GuiButton.enabled)
{
return;
}
if (par1GuiButton.id == 2)
{
String s = getSaveName(selectedWorld);
if (s != null)
{
deleting = true;
GuiYesNo guiyesno = func_74061_a(this, s, selectedWorld);
mc.displayGuiScreen(guiyesno);
}
}
else if (par1GuiButton.id == 1)
{
selectWorld(selectedWorld);
}
else if (par1GuiButton.id == 3)
{
mc.displayGuiScreen(new GuiCreateWorld(this));
}
else if (par1GuiButton.id == 6)
{
mc.displayGuiScreen(new GuiRenameWorld(this, getSaveFileName(selectedWorld)));
}
else if (par1GuiButton.id == 0)
{
mc.displayGuiScreen(parentScreen);
}
else
{
worldSlotContainer.actionPerformed(par1GuiButton);
}
}
|
69b7a037-e1df-4355-8f3e-5ccf6cca1287
| 8
|
private static boolean
classMatcher(REGlobalData gData, RECharSet charSet, char ch)
{
if (!charSet.converted) {
processCharSet(gData, charSet);
}
int byteIndex = ch / 8;
if (charSet.sense) {
if ((charSet.length == 0) ||
( (ch > charSet.length)
|| ((charSet.bits[byteIndex] & (1 << (ch & 0x7))) == 0) ))
return false;
} else {
if (! ((charSet.length == 0) ||
( (ch > charSet.length)
|| ((charSet.bits[byteIndex] & (1 << (ch & 0x7))) == 0) )))
return false;
}
return true;
}
|
a7d0a3c0-03ab-4e60-bbe6-3e94cbdad0ba
| 1
|
@Override
public boolean getUserExists(String username) {
boolean userExists = false;
// Find an user record in the entity bean User, passing a primary key of
// username.
User user = emgr.find(entity.User.class, username);
// Determine whether the user exists
if (user != null) {
userExists = true;
}
return userExists;
}
|
f5fe895c-5323-4ecc-8694-a3b84527ef91
| 8
|
public boolean equals(Object passedObj)
{
//Checks if the object exists
if (passedObj == null)
{
return false;
}
//Checks to ensure the class is an instance of this class
if(!(passedObj instanceof MyAllTypesSecond))
{
return false;
}
if(passedObj == this)
{
return true;
}
MyAllTypesSecond cls = (MyAllTypesSecond)passedObj;
if((this.myCharS == cls.getMyCharS()) &&
(this.myIntS == cls.getMyIntS()) &&
(this.myStringS.equals(cls.getMyStringS())) &&
(this.myFloatS == cls.getMyFloatS()) &&
(this.myShortS == cls.getMyShortS()))
{
return true;
}
return false;
}
|
6ef39d8e-fd96-47f8-b93b-4ed4e981085f
| 8
|
@Override
public ArrayList<seed> move(ArrayList<Pair> initTreelist, double initWidth, double initLength, double initS) {
treelist = initTreelist;
width = initWidth;
length = initLength;
s = initS;
seedgraph = new SeedGraph(initTreelist, initWidth, initLength, initS);
boards = new Boards(seedgraph);
ArrayList<seed> hexAlternatingNW = boards.getHexagonalNWBoard();
ArrayList<seed> hexAlternatingNE = boards.getHexagonalNEBoard();
ArrayList<seed> hexAlternatingSW = boards.getHexagonalSWBoard();
ArrayList<seed> hexAlternatingSE = boards.getHexagonalSEBoard();
ArrayList<seed> gridAlternatingNW = boards.getAlternatingNWBoard();
ArrayList<seed> gridAlternatingNE = boards.getAlternatingNEBoard();
ArrayList<seed> gridAlternatingSW = boards.getAlternatingSWBoard();
ArrayList<seed> gridAlternatingSE = boards.getAlternatingSEBoard();
double scoreHexAlternatingNW = seedgraph.calculateScore(hexAlternatingNW);
double scoreHexAlternatingNE = seedgraph.calculateScore(hexAlternatingNE);
double scoreHexAlternatingSW = seedgraph.calculateScore(hexAlternatingSW);
double scoreHexAlternatingSE = seedgraph.calculateScore(hexAlternatingSE);
double scoreGridAlternatingNW = seedgraph.calculateScore(gridAlternatingNW);
double scoreGridAlternatingNE = seedgraph.calculateScore(gridAlternatingNE);
double scoreGridAlternatingSW = seedgraph.calculateScore(gridAlternatingSW);
double scoreGridAlternatingSE = seedgraph.calculateScore(gridAlternatingSE);
double maxScore = Double.MIN_VALUE;
// check alternating scores
if (scoreHexAlternatingNW > maxScore) {
seedlist = hexAlternatingNW;
maxScore = scoreHexAlternatingNW;
}
if (scoreHexAlternatingNE > maxScore) {
seedlist = hexAlternatingNE;
maxScore = scoreHexAlternatingNE;
}
if (scoreHexAlternatingSW > maxScore) {
seedlist = hexAlternatingSW;
maxScore = scoreHexAlternatingSW;
}
if (scoreHexAlternatingSE > maxScore) {
seedlist = hexAlternatingSE;
maxScore = scoreHexAlternatingSE;
}
// check grid scores
if (scoreGridAlternatingNW > maxScore) {
seedlist = gridAlternatingNW;
maxScore = scoreGridAlternatingNW;
}
if (scoreGridAlternatingNE > maxScore) {
seedlist = gridAlternatingNE;
maxScore = scoreGridAlternatingNE;
}
if (scoreGridAlternatingSW > maxScore) {
seedlist = gridAlternatingSW;
maxScore = scoreGridAlternatingSW;
}
if (scoreGridAlternatingSE > maxScore) {
seedlist = gridAlternatingSE;
maxScore = scoreGridAlternatingSE;
}
System.out.println("maxScore = " + maxScore);
System.out.printf("seedlist size is %d\n", seedlist.size());
System.out.printf("score is %f\n", maxScore);
return seedlist;
}
|
81fddb52-bc3c-4c7a-94ad-e1b29a9ea1ed
| 5
|
@Override
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof OCPTelno)) {
return false;
}
OCPTelno other = (OCPTelno) obj;
if (!Arrays.equals(mTelno, other.mTelno)) {
return false;
}
if (mTypePlan != other.mTypePlan) {
return false;
}
return true;
}
|
7b8af52e-15a2-49ef-81a4-ae274a6bb584
| 9
|
public void refreshGameControl() {
// mortgageOption
gamecontrol.optionPanel.removeAll();
int y=50;
if (showThrowDiceBtn) {
// Insert dice button
JButton copy = choices.get(0);
copy.setSize(gamecontrol.optionPanel.getWidth(),50);
copy.setLocation(0,y*3);
gamecontrol.optionPanel.add(copy);
}
if (showJailThrowDiceBtn) {
// Insert prison/jail dice button
JButton copy = choices.get(3);
copy.setSize(gamecontrol.optionPanel.getWidth(),50);
copy.setLocation(0,y*3);
gamecontrol.optionPanel.add(copy);
}
if (showJailPayBailBtn) {
// Insert pay jail bail button
JButton copy = choices.get(4);
copy.setSize(gamecontrol.optionPanel.getWidth(),50);
copy.setLocation(0,y);
gamecontrol.optionPanel.add(copy);
}
if (showMortgageBtn) {
// Insert mortage btn
JButton copy = choices.get(1);
copy.setSize(gamecontrol.optionPanel.getWidth(),50);
copy.setLocation(0,y*0);
gamecontrol.optionPanel.add(copy);
}
if (showJailFreeCardBtn) {
// Insert jail free card button
JButton copy = choices.get(5);
copy.setSize(gamecontrol.optionPanel.getWidth(),50);
copy.setLocation(0,y*2);
gamecontrol.optionPanel.add(copy);
}
if (showNextPlayerBtn) {
// Insert next player btn
JButton copy = choices.get(2);
copy.setSize(gamecontrol.optionPanel.getWidth(),50);
copy.setLocation(0,y*3);
gamecontrol.optionPanel.add(copy);
}
DefaultTableModel model = (DefaultTableModel)gamecontrol.jTable1.getModel();
int count=0;
while (model.getRowCount()>0) {
model.removeRow(0);
count++;
}
if (count>0) model.fireTableRowsInserted(0,count-1);
for (Player player : Game.players) {
model.addRow(new Object[]{player.Name,player.GetMoney(),player.GetOutCard});
}
model.fireTableRowsInserted(0,Game.players.size());
gamecontrol.optionPanel.updateUI();
gamecontrol.updateList();
}
|
2f0c54f9-445b-46eb-a4b6-0cba1b54e486
| 4
|
public static void main(String[] args) {
// -------------------------Initialize Job Information------------------------------------
/*********************************Big Experiments*********************************/
//String startJobId = "job_201301181454_0001";
//String jobName = "Big-uservisits_aggre-pig-50G";
//String startJobId = "job_201301232026_0001";
//String jobName = "BigBuildInvertedIndex";
//String startJobId = "job_201301132344_0001";
//String jobName = "BigTeraSort-36GB";
//String startJobId = "job_201301111138_0001";
//String jobName = "BigTwitterBiDirectEdgeCount";
//String startJobId = "job_201301081033_0001";
//String jobName = "BigTwitterInDegreeCount";
//String startJobId = "job_201301072049_0001";
//String jobName = "BigWiki-m36-r18";
//String baseDir = "/home/xulijie/MR-MEM/BigExperiments/";
//Boolean hasSplitFile = true;
//int newRNBase = 9;
//int iterateNum = 192;
/*********************************Big Experiments*********************************/
/*********************************Sample Experiments*********************************/
//String startJobId = "job_201301211121_0001";
//String jobName = "SampleBuildInvertedIndex-1G";
//String startJobId = "job_201301191915_0001";
//String jobName = "SampleTeraSort-1G";
//String startJobId = "job_201301252338_0001";
//String jobName = "SampleTwitterBiDirectEdgeCount";
//String startJobId = "job_201301281455_0001";
//String jobName = "SampleTwitterInDegreeCount";
//String startJobId = "job_201301222028_0001";
//String jobName = "SampleUservisits-1G";
String startJobId = "job_201301192319_0001";
String jobName = "SampleWikiWordCount-1G";
String baseDir = "/home/xulijie/MR-MEM/SampleExperiments/";
Boolean hasSplitFile = true;
int newRNBase = 2;
int iterateNum = 192;
/*********************************Sample Experiments*********************************/
int[] splitMBs = {64, 128, 256};
boolean outputDetailedDataflow = false;
String outputDir = baseDir + jobName + "/estimatedDM/";
//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-----------------------------
SelfDataAndMemoryEstimator je = new SelfDataAndMemoryEstimator();
boolean successful;
successful = je.profile(baseDir, jobName, "serialJob", jobId);
//--------------------------Profiling ends-----------------------------
if(splitMap.isEmpty())
computeSplitMap(splitMBs, je.job.getJobConfiguration(), baseDir + jobName, hasSplitFile);
//--------------------------Estimating Data Flow and Memory-----------------------------
if(successful == false) {
System.err.println("[" + jobId + "] is a failed job");
continue;
}
try {
je.batchEstimateDataAndMemory(useRuntimeMaxJvmHeap, outputDir + jobId, newRNBase, outputDetailedDataflow);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//--------------------------Estimating ends-----------------------------
System.out.println("Finish estimating " + jobId);
}
}
|
523aee3c-fe35-48b7-a5e9-a405f46e400c
| 0
|
public Pelaaja() {
super(0, 0);
xNopeus = 0;
xSuunta = 0;
isoHyppy = 0;
putoamiskiihtyvyysPerFrame = 1;
terminaalinopeus = 50;
/**
* Nopeudeksi määritetään terminaalinopeus, koska jos pelaaja alottaa
* ilmasta, haluamme sen putoavan täysiiiiiii
*/
yNopeus = terminaalinopeus;
hahmonKorkeus = 32;
}
|
222447de-8b1c-4b9c-9482-1c94ff9254a1
| 5
|
String getHelpText() {
boolean letters = ((characters & LETTERS) == LETTERS);
boolean digits = ((characters & DIGITS) == DIGITS);
boolean ascii = ((characters & SYMBOL) == SYMBOL);
return "Allowed characters:"
+ (letters ? " letters" : " ")
+ (digits ? " digits" : " ")
+ (ascii ? " ascii" : " ")
+ " \nminimum length: "
+ minLength
+ " maximum length: "
+ maxLength
+ (minValue != -1 ? " \nminimum value: " + minValue
+ " maximum value: " + maxValue : "")
+ (requiredNumOfSemi != -1 ? ",\n " + (requiredNumOfSemi + 1) + " \';\' separated fields" : "");
}
|
66ca09ec-4920-4724-be0c-d19fff406f20
| 3
|
public void addPart3(Statement statement, String line) {
String counterPartyAccount = line.substring(10, 44).trim();
CounterParty counterParty = new CounterParty();
if (!counterPartyAccount.trim().equals("")) {
BankAccount bankAccount = new BankAccount(counterPartyAccount);
bankAccount.setBic(counterPartyBic);
String counterPartyCurrency = line.substring(44, 47).trim();
bankAccount.setCurrency(counterPartyCurrency);
counterParty.addAccount(bankAccount);
}
String counterPartyName = line.substring(47, 82).trim();
counterParty.setName(counterPartyName.toUpperCase().trim());
statement.setCounterParty(counterParty);
try {
counterParties.addBusinessObject(counterParty);
} catch (EmptyNameException e) {
System.err.println("The Name of the CounterParty cannot be empty");
} catch (DuplicateNameException e) {
System.err.println("The Name of the CounterParty already exists");
}
}
|
b0fa7e63-c246-486d-8bfe-56cbd318bae6
| 0
|
private void jCheckBoxComptesRendusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxComptesRendusActionPerformed
//Récupération de la méthode contrôleur 'afficherComptesRendus'
this.getCtrlM().afficherComptesRendus();
}//GEN-LAST:event_jCheckBoxComptesRendusActionPerformed
|
a6c83954-0a0f-4749-a62e-ad67d092203a
| 3
|
private void addUniform(String uniformName, String uniformType, HashMap<String, ArrayList<GLSLStruct>> structs) {
boolean addThis = true;
ArrayList<GLSLStruct> structComponents = structs.get(uniformType);
if (structComponents != null) {
addThis = false;
for (GLSLStruct struct : structComponents) {
addUniform(uniformName + "." + struct.name, struct.type, structs);
}
}
if (!addThis)
return;
int uniformLocation = glGetUniformLocation(resource.getProgram(), uniformName);
resource.getUniforms().put(uniformName, uniformLocation);
}
|
93d8f225-7921-49c1-993c-cca9d24f1b81
| 5
|
public ArrayList<String> getRequirementString() {
ArrayList<String> requirements = new ArrayList<String>();
if(!item1.equals("None")) {
requirements.add(item1 + ":" + item1Qty);
}
if(!item2.equals("None")) {
requirements.add(item2 + ":" + item2Qty);
}
if(!item3.equals("None")) {
requirements.add(item3 + ":" + item3Qty);
}
if(!item4.equals("None")) {
requirements.add(item4 + ":" + item4Qty);
}
if(!workBench.equals("None")) {
requirements.add(workBench + ":0");
}
return requirements;
}
|
50741af9-961a-4a5b-bce9-548176788f1d
| 4
|
public List<Disciplina> getDisciplinasPreferidasComNivel(
int nivelPreferencia) throws PreferenciaInvalidaException {
switch (nivelPreferencia) {
case 1:
return this.listaDisciplinasP1;
case 2:
return this.listaDisciplinasP2;
case 3:
return this.listaDisciplinasP3;
case 4:
return this.listaDisciplinasNP;
default:
throw new PreferenciaInvalidaException(
"Retorna Preferencia ERRO!!!");
}
}
|
52f77931-822f-4d2a-9fef-456fe787bfd9
| 6
|
public void update(Contestant c) throws InvalidFieldException {
if (c.getFirstName() != null) {
setFirstName(c.getFirstName());
}
if (c.getLastName() != null) {
setLastName(c.getLastName());
}
if (c.getID() != null) {
setID(c.getID());
}
if (c.getPicture() != null) {
setPicture(c.getPicture());
}
if (c.getTribe() != null) {
setTribe(c.getTribe());
}
if (c.isCastOff()) {
setCastDate(c.getCastDate());
}
}
|
68839666-94bd-4162-85de-a0184bef2628
| 4
|
public static boolean deleteFile(Path file) {
boolean ret = false;
if ((file != null) && Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
try {
if (file.toFile().canWrite()) {
Files.delete(file);
}
ret = !Files.exists(file, LinkOption.NOFOLLOW_LINKS);
} catch (IOException e) {
IllegalStateException ise = new IllegalStateException("An IO exception occured while deleting file '" + file + "'");
Main.handleUnhandableProblem(ise);
}
}
return ret;
}
|
ad16acce-c1cd-405a-a912-cdf3083057d9
| 1
|
public TroubleInputStream(InputStream in, Filter[] filters) {
super(in);
this.filters = filters;
hasFilters = filters != null && filters.length > 0;
}
|
1e212232-d269-40a5-b465-6730b9b4d3b4
| 4
|
public void makeDeclaration(Set done) {
super.makeDeclaration(done);
/*
* Normally we have to declare our exceptionLocal. This is automatically
* done in dumpSource.
*
* If we are unlucky the exceptionLocal is used outside of this block.
* In that case we do a transformation.
*/
if (exceptionLocal != null) {
if (declare.contains(exceptionLocal))
declare.remove(exceptionLocal);
else {
LocalInfo dummyLocal = new LocalInfo();
Expression store = new StoreInstruction(new LocalStoreOperator(
exceptionLocal.getType(), exceptionLocal))
.addOperand(new LocalLoadOperator(dummyLocal.getType(),
null, dummyLocal));
InstructionBlock ib = new InstructionBlock(store);
ib.setFlowBlock(flowBlock);
ib.appendBlock(catchBlock);
catchBlock = ib;
exceptionLocal = dummyLocal;
String localName = dummyLocal.guessName();
Iterator doneIter = done.iterator();
while (doneIter.hasNext()) {
Declarable previous = (Declarable) doneIter.next();
if (localName.equals(previous.getName())) {
/* A name conflict happened. */
dummyLocal.makeNameUnique();
break;
}
}
}
}
}
|
51d38dfa-adf9-4414-827c-090c4ffd6083
| 1
|
public Main() {
movingObjects = new LinkedList<MovingObject>();
units = new LinkedList<Unit>();
units.add(new Summoner(50, 50));
units.add(new Summoner(100, 100));
units.add(new Collector(200, 50));
units.add(new Collector(200, 100));
buildings = new LinkedList<Building>();
buildings.add(new ManaAltar(100, 100));
buildings.add(new ManaAltar(400, 200));
animatedObjects = new LinkedList<AnimatedObject>();
trees = new LinkedList<Tree>();
trees.add(new Tree(200, 200, SpriteLoader.loadAnimationFile("tree1")));
trees.add(new Tree(250, 250, SpriteLoader.loadAnimationFile("tree1")));
trees.add(new Tree(150, 250, SpriteLoader.loadAnimationFile("tree1")));
manaCrystals = new LinkedList<ManaCrystal>();
manaCrystals.add(new ManaCrystal(600, 100, SpriteLoader.loadAnimationFile("crystal")));
clickableObjects = new LinkedList<ClickableObject>();
for(Building building : buildings) {
clickableObjects.add(building);
}
selectionManager = new SelectionManager();
//selection = new LinkedList<ClickableObject>();
map = new Map("map1");
initializeGUI();
}
|
c06391b8-5bd3-410e-870a-7fe977211b0b
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ProcessManager other = (ProcessManager) obj;
if (rootProcess == null) {
if (other.rootProcess != null) {
return false;
}
} else if (!rootProcess.equals(other.rootProcess)) {
return false;
}
return true;
}
|
e76385bc-f7ae-456d-b48d-81edd9f0bef6
| 9
|
boolean validWallSet(boolean[][] w) {
// copy array
boolean[][] c;
c = new boolean[w.length][w[0].length];
for (int i=0; i<w.length; i++) {
for (int j=0; j<w[0].length; j++) c[i][j] = w[i][j];
}
// fill all 8-connected neighbours of the first empty
// square.
boolean found = false;
search: for (int i=0; i<c.length; i++) {
for (int j=0; j<c[0].length; j++) {
if (!c[i][j]) {
// found empty square, fill neighbours
fillNeighbours(c, i, j);
found = true;
break search;
}
}
}
if (!found) return false;
// check if any empty squares remain
for (int i=0; i<c.length; i++) {
for (int j=0; j<c[0].length; j++) if (!c[i][j]) return false;
}
return true;
}
|
7ade89d1-bcf0-4026-ad57-5bebbed4dd89
| 5
|
private ArrayList<Language> sortProbability(double[] prob) {
ArrayList<Language> list = new ArrayList<Language>();
for(int j=0;j<prob.length;++j) {
double p = prob[j];
if (p > PROB_THRESHOLD) {
for (int i = 0; i <= list.size(); ++i) {
if (i == list.size() || list.get(i).prob < p) {
list.add(i, new Language(langlist.get(j), p));
break;
}
}
}
}
return list;
}
|
5ab89615-32d4-4962-a55b-d30658d281f2
| 6
|
public void handleControl(ucEvent e){
if(e.getSource() == castor.source){
switch(e.getCommand()){
case 3: setMouseAction("Mirsel"); prisec = true; mirrefflag[1] = 0; break;
case 4: mirrefflag[1] = 1; prisec = true; setMouseAction("Mirsel");break;
}
}
if(e.getSource() == pollux.source){
switch(e.getCommand()){
case 3: setMouseAction("Mirsel"); prisec = false; mirrefflag[1] = 0; break;
case 4: mirrefflag[1] = 1; prisec = false; setMouseAction("Mirsel");break;
}
}
}
|
1b8bf7ce-2a5d-49f1-b886-39b22094fd92
| 1
|
public static void toggleMoveableInheritanceText(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
toggleMoveableInheritanceForSingleNode(currentNode, undoable);
if (!undoable.isEmpty()) {
undoable.setName("Toggle Moveability Inheritance for Node");
tree.getDocument().getUndoQueue().add(undoable);
}
// Redraw
layout.draw(currentNode, OutlineLayoutManager.TEXT);
}
|
d05750b9-fdec-4f8d-978a-f13f76a232d3
| 9
|
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Function1 function1 = new Function1();
Function2 function2 = new Function2();
Function3 function3 = new Function3();
Function4 function4 = new Function4();
Function5 function5 = new Function5();
Function6 function6 = new Function6();
Function7 function7 = new Function7();
// Create a 7-element AbstractCalculateFunction array
AbstractCalculateFunction[] functions = new AbstractCalculateFunction[7];
// Initialize the array with function1~7
functions[0] = function1;
functions[1] = function2;
functions[2] = function3;
functions[3] = function4;
functions[4] = function5;
functions[5] = function6;
functions[6] = function7;
// Simply explain the program
System.out.println("This is a program that calculates several functions.");
System.out.println("The Functions are respectively:");
// Display the details of the functions
for(AbstractCalculateFunction function: functions)
System.out.println(function); // Invokes toString method
System.out.println("===================================================");
int toContinue = 1; // To continue or not (1: to continue, others: not to continue)
double x; // The value of x
int f; // Which function? (e.g. f = 1 stands for the Function1.)
while (toContinue == 1) {
System.out.print("Enter the value of x: "); // Prompt the user to enter the value of x
x = input.nextDouble();
System.out.print("Choose a function: (Enter number 1 to 7): "); // Prompt the user to choose a function
f = input.nextInt();
// Display the answer
switch(f) {
case 1: System.out.printf("f(x) = %.2f\n", function1.f(x)); break;
case 2: System.out.printf("f(x) = %.2f\n", function2.f(x)); break;
case 3: System.out.printf("f(x) = %.2f\n", function3.f(x)); break;
case 4: System.out.printf("f(x) = %.2f\n", function4.f(x)); break;
case 5: System.out.printf("f(x) = %.2f\n", function5.f(x)); break;
case 6: System.out.printf("f(x) = %.2f\n", function6.f(x)); break;
case 7: System.out.printf("f(x) = %.2f\n", function7.f(x)); break;
default: System.out.println("Invalid Input."); // If the function chosen does not exist
}
// Ask the user whether or not to calculate another x or another function
System.out.print("Again? (Enter 1 to calculate functions again and others to exit): ");
toContinue = input.nextInt();
}
input.close(); // Close the input
}
|
e1d441e4-2564-4160-a0f8-b0bcfb320941
| 8
|
private void drawMarking(Graphics2D g2) {
float yMarkingHeight = (getSize().height - (topMargin + bottomMargin)) / (float)yMarkCount;
int baseLineIndex = yMarkCount / 2;
int startY = topMargin;
double delta = (plotMaxY - plotMinY) / yMarkCount;
g2.setFont(fontLabel);
FontMetrics fm = g2.getFontMetrics();
for (int i = 0; i <= yMarkCount; i++) {
startY = Math.round(topMargin + i * yMarkingHeight);
DrawUtil.drawLine(g2, i == 0 || i == baseLineIndex || i == yMarkCount? baseLineColor : lineColor,
leftMargin, startY, getSize().width - rightMargin, startY);
double mark = plotMaxY - i * delta;
String markStr = markingDf.format(mark);
int markLen = fm.stringWidth(markStr);
g2.setColor(baseLineColor);
g2.drawString(markStr, getSize().width / 2 - markLen, startY);
}
float xMarkingWidth = (getSize().width - (leftMargin + rightMargin)) / (float)xMarkCount;
int startX = 0;
baseLineIndex = xMarkCount / 2;
delta = (plotMaxX - plotMinX) / xMarkCount;
for (int i = 0; i <= xMarkCount; i++) {
startX = Math.round(leftMargin + i * xMarkingWidth);
DrawUtil.drawLine(g2, i == 0 || i == baseLineIndex || i == xMarkCount? baseLineColor : lineColor,
startX, topMargin, startX, getSize().height - bottomMargin);
double mark = plotMinX + i * delta;
String markStr = markingDf.format(mark);
int markLen = fm.stringWidth(markStr);
g2.setColor(baseLineColor);
g2.drawString(markStr, startX - markLen / 2, getSize().height / 2 + fm.getHeight());
}
}
|
1ab75878-6b56-40de-9f82-75592e738976
| 9
|
public boolean checkHypergeometricParams(int k, int N, int D, int n) {
if ((k < 0) || (N < 0) || (D < 0) || (n < 0)) return false;
/* Change of variables
* drawn not drawn | total
* defective a = k b = D - k | D
* nondefective c = n - k d = N + k - n - D | N - D
* --------------------------------+----------
* total n N - n | N
*/
int a, b, c, d;
a = k;
b = D - k;
c = n - k;
d = N + k - n - D;
// Check values
if ((a < 0) || (b < 0) || (c < 0) || (d < 0) || (N < 0)) return false;
return true;
}
|
b638c0d9-ca1f-4d09-a44a-afbe4b199c84
| 8
|
protected void drawRadarPoly(Graphics2D g2,
Rectangle2D plotArea,
Point2D centre,
PlotRenderingInfo info,
int series, int catCount,
double headH, double headW) {
Polygon polygon = new Polygon();
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
// plot the data...
for (int cat = 0; cat < catCount; cat++) {
Number dataValue = getPlotValue(series, cat);
if (dataValue != null) {
double value = dataValue.doubleValue();
if (value >= 0) { // draw the polygon series...
// Finds our starting angle from the centre for this axis
double angle = getStartAngle()
+ (getDirection().getFactor() * cat * 360 / catCount);
// The following angle calc will ensure there isn't a top
// vertical axis - this may be useful if you don't want any
// given criteria to 'appear' move important than the
// others..
// + (getDirection().getFactor()
// * (cat + 0.5) * 360 / catCount);
// find the point at the appropriate distance end point
// along the axis/angle identified above and add it to the
// polygon
Point2D point = getWebPoint(plotArea, angle,
value / this.maxValue);
polygon.addPoint((int) point.getX(), (int) point.getY());
// put an elipse at the point being plotted..
Paint paint = getSeriesPaint(series);
Paint outlinePaint = getSeriesOutlinePaint(series);
Stroke outlineStroke = getSeriesOutlineStroke(series);
Ellipse2D head = new Ellipse2D.Double(point.getX()
- headW / 2, point.getY() - headH / 2, headW,
headH);
g2.setPaint(paint);
g2.fill(head);
g2.setStroke(outlineStroke);
g2.setPaint(outlinePaint);
g2.draw(head);
if (entities != null) {
String tip = null;
if (this.toolTipGenerator != null) {
tip = this.toolTipGenerator.generateToolTip(
this.dataset, series, cat);
}
String url = null;
if (this.urlGenerator != null) {
url = this.urlGenerator.generateURL(this.dataset,
series, cat);
}
Shape area = new Rectangle((int) (point.getX() - headW),
(int) (point.getY() - headH),
(int) (headW * 2), (int) (headH * 2));
CategoryItemEntity entity = new CategoryItemEntity(
area, tip, url, this.dataset, series,
this.dataset.getColumnKey(cat), cat);
entities.add(entity);
}
}
}
}
// Plot the polygon
Paint paint = getSeriesPaint(series);
g2.setPaint(paint);
g2.setStroke(getSeriesOutlineStroke(series));
g2.draw(polygon);
// Lastly, fill the web polygon if this is required
if (this.webFilled) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
0.1f));
g2.fill(polygon);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
}
}
|
d40656c3-94d3-4c5d-900d-e8a332f9f91c
| 8
|
public static String colorizeParameter5(int param) {
String color = "";
if(param <= 15) color = "red";
if(param > 15 && param <= 30) color = "yellow";
if(param > 30 && param <= 70) color = "green";
if(param > 70 && param <= 85) color = "purple";
if(param > 85) color = "cyan";
return "<span class = '" + color + "'>" + param + "</span>";
}
|
16a1f1cb-e4dd-4353-82a0-e91bab0086a2
| 7
|
protected void onDeathUpdate()
{
++this.deathTime;
if (this.deathTime == 20)
{
int var1;
if (!this.worldObj.isRemote && (this.recentlyHit > 0 || this.isPlayer()) && !this.isChild())
{
var1 = this.getExperiencePoints(this.attackingPlayer);
while (var1 > 0)
{
int var2 = EntityXPOrb.getXPSplit(var1);
var1 -= var2;
this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, var2));
}
}
this.onEntityDeath();
this.setDead();
for (var1 = 0; var1 < 20; ++var1)
{
double var8 = this.rand.nextGaussian() * 0.02D;
double var4 = this.rand.nextGaussian() * 0.02D;
double var6 = this.rand.nextGaussian() * 0.02D;
this.worldObj.spawnParticle("explode", this.posX + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, this.posY + (double)(this.rand.nextFloat() * this.height), this.posZ + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, var8, var4, var6);
}
}
}
|
60d86b2e-69de-4456-a2a4-ba5bc3d146dd
| 4
|
public void testCaddie (Connection conn) throws IOException, BDException {
if (session.getAttribute("config") == null) {
char d = BDRequetes.getTypeCaddie(conn);
if (d == 'P'){
BDRequetes.checkCaddieLifetime(conn);
session.setAttribute("config", "P");
}
else {
int d2 = BDRequetes.getCaddieLifetime(conn);
if (d2 == -1){
CaddieVirtuel.vider();
}
else if (d2 > 0){
CaddieVirtuel.checkDate(d2);
}
session.setAttribute("config", "V");
}
}
}
|
d76ec4ac-bb1e-4af2-ab8b-0598a4d68218
| 4
|
private UrlSource() {
this.urlList = new LinkedList<>();
try (
InputStream urlStream = this.getClass().getResourceAsStream("URLSET.txt");
BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlStream));) {
String url;
while (true) {
url = urlReader.readLine();
if (url == null) {
break;
}
if (!url.isEmpty()) {
this.urlList.add(url);
}
}
} catch (IOException ex) {
Logger.getLogger(DictionarySource.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
c0b1575c-e1c3-4e76-a686-5fb6ea31ad4e
| 6
|
public static ArrayList<Point> graham(ArrayList<Point> points) {
ArrayList<Point> bestPoints = new ArrayList<Point>();
Point tP = points.get(closestPoint(points));
points.remove(closestPoint(points));
sort(points, tP);
points.add(0, tP);
ArrayList<Point> uniqArray = new ArrayList<Point>();
for (Point p : points) {
uniqArray.add(p);
}
int index = 2;
while (index < uniqArray.size()) {
if (myCompare(uniqArray.get(0), uniqArray.get(index), uniqArray.get(index - 1)) == 0) {
if ((new Vector(uniqArray.get(0), uniqArray.get(index))).getSize() >
(new Vector(uniqArray.get(0), uniqArray.get(index - 1))).getSize()) {
uniqArray.remove(index - 1);
} else {
uniqArray.remove(index);
}
} else {
index++;
}
}
bestPoints.add(uniqArray.get(0));
bestPoints.add(uniqArray.get(1));
for (int i = 2; i < uniqArray.size(); i++) {
while (Vector.mulVectors(new Vector(bestPoints.get(bestPoints.size() - 1), bestPoints.get(bestPoints.size() - 2)),
new Vector(bestPoints.get(bestPoints.size() - 1), uniqArray.get(i))) > 0) {
bestPoints.remove(bestPoints.size() - 1);
}
bestPoints.add(uniqArray.get(i));
}
return bestPoints;
}
|
53aa08e4-9efe-441e-a0a4-a87b50b50328
| 5
|
public void determinecounter(int grade) {
switch (grade / 10) {
case 10:
case 9:
acount++;
break;
case 8:
bcount++;
break;
case 7:
ccount++;
break;
case 6:
dcount++;
break;
default:
fcount++;
break;
}
}
|
51412763-5864-4a9d-9661-db7456b8e4f5
| 3
|
@Override
public void parse() throws IllegalArgumentException
{
try
{
setEncoding(Encoding.getEncoding(buffer[0]));
}
catch (IllegalArgumentException ex)
{ // ignore the bad value and set it to ISO-8859-1 so we can continue parsing the tag
setEncoding(Encoding.ISO_8859_1);
}
nullTerminatorIndex = getNextNullTerminator(1, Encoding.ISO_8859_1.getCharacterSet());
String pricesString = new String(buffer, 1, nullTerminatorIndex-1, Encoding.ISO_8859_1.getCharacterSet()).trim();
String[] pricesArray = pricesString.split("/");
Vector<Price> prices = new Vector<Price>();
for(String price : pricesArray)
prices.add(new Price(Currency.getCurrency(price.substring(0,3)), price.substring(3)));
nullTerminatorIndex++;
setValidUntil(new String(buffer, nullTerminatorIndex, VALID_UNTIL_DATE_SIZE, Encoding.ISO_8859_1.getCharacterSet()).trim());
nullTerminatorIndex += VALID_UNTIL_DATE_SIZE;
nextNullTerminatorIndex = getNextNullTerminator(nullTerminatorIndex, Encoding.ISO_8859_1.getCharacterSet());
contactURL = new String(buffer, nullTerminatorIndex, nextNullTerminatorIndex - nullTerminatorIndex, Encoding.ISO_8859_1.getCharacterSet()).trim();
nullTerminatorIndex = nextNullTerminatorIndex + 1;
try
{
setReceivedAs(ReceivedType.getReceivedType(buffer[nullTerminatorIndex]));
}
catch (IllegalArgumentException ex)
{ // ignore the bad value and set it to other so we can continue parsing the tag
setReceivedAs(ReceivedType.OTHER);
}
nullTerminatorIndex++;
nextNullTerminatorIndex = getNextNullTerminator(nullTerminatorIndex, encoding.getCharacterSet());
seller = new String(buffer, nullTerminatorIndex, nextNullTerminatorIndex-nullTerminatorIndex, encoding.getCharacterSet()).trim();
nullTerminatorIndex += nextNullTerminatorIndex + encoding.getNumBytesInNullTerminator();
nextNullTerminatorIndex = getNextNullTerminator(nullTerminatorIndex, encoding.getCharacterSet());
description = new String(buffer, nullTerminatorIndex, nextNullTerminatorIndex-nullTerminatorIndex, encoding.getCharacterSet()).trim();
nullTerminatorIndex += nextNullTerminatorIndex + encoding.getNumBytesInNullTerminator();
nextNullTerminatorIndex = getNextNullTerminator(nullTerminatorIndex, Encoding.ISO_8859_1.getCharacterSet());
pictureMimeType = new String(buffer, nullTerminatorIndex, nextNullTerminatorIndex-nullTerminatorIndex, Encoding.ISO_8859_1.getCharacterSet()).trim();
nullTerminatorIndex += nextNullTerminatorIndex + 1;
sellerLogo = new byte[buffer.length - nullTerminatorIndex];
System.arraycopy(buffer, nullTerminatorIndex, sellerLogo, 0, sellerLogo.length);
dirty = false; // we just read in the frame info, so the frame body's internal byte buffer is up to date
}
|
97642b45-3629-4e1b-be55-5e318b396f23
| 9
|
@Test
public void testConstructor_IllegalArgumentException() {
boolean exceptionThrown = false;
try {
new PaymentResponse(null, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 256, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, null, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.FAILURE, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "", "seller", Currency.BTC, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", null, Currency.BTC, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", null, 12, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 0, System.currentTimeMillis());
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
try {
new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 12, 0);
} catch (IllegalArgumentException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
exceptionThrown = false;
}
|
d5fba127-5a1f-4ce1-861b-dc4d754f92c9
| 9
|
public static Direction getReversed(Direction d) {
switch (d) {
case DOWN:
return UP;
case DOWNLEFT:
return UPRIGHT;
case DOWNRIGHT:
return UPLEFT;
case LEFT:
return RIGHT;
case RIGHT:
return LEFT;
case UP:
return DOWN;
case UPLEFT:
return DOWNRIGHT;
case UPRIGHT:
return DOWNLEFT;
case MIDDLE:
return MIDDLE;
default:
return MIDDLE;
}
}
|
7b95564e-03aa-4858-97e7-e47ef5c7b1a9
| 9
|
static public Calendar interpret(String value)
{
if(igpp.util.Text.isEmpty(value)) return null;
if(value.indexOf("-") != -1) return parse(value, CONVENTION); // Treat as convention format
// Intrept unitized values
Calendar time = getNow();
String[] part = value.split(" ", 2);
if(part.length < 2) return null; // No units
int step = 0;
try {
step = Integer.parseInt(part[0]);
} catch(Exception e) { // Bad number format
return null;
}
part[1] = part[1].toLowerCase();
if(part[1].startsWith("second")) time.add(Calendar.SECOND, -step);
if(part[1].startsWith("minute")) time.add(Calendar.MINUTE, -step);
if(part[1].startsWith("day")) time.add(Calendar.DAY_OF_YEAR, -step);
if(part[1].startsWith("month")) time.add(Calendar.MONTH, -step);
if(part[1].startsWith("year")) time.add(Calendar.YEAR, -step);
return time;
}
|
ed574aaf-cf32-43b7-8068-ebf6da87fb5d
| 7
|
public JPopupMenu getMenu() {
if (elm == null) {
return null;
}
if (elm instanceof TransistorElm) {
scopeIbMenuItem.setState(value == VAL_IB);
scopeIcMenuItem.setState(value == VAL_IC);
scopeIeMenuItem.setState(value == VAL_IE);
scopeVbeMenuItem.setState(value == VAL_VBE);
scopeVbcMenuItem.setState(value == VAL_VBC);
scopeVceMenuItem.setState(value == VAL_VCE && ivalue != VAL_IC);
scopeVceIcMenuItem.setState(value == VAL_VCE && ivalue == VAL_IC);
return transScopeMenu;
} else {
scopeVMenuItem.setState(showV && value == 0);
scopeIMenuItem.setState(showI && value == 0);
scopeMaxMenuItem.setState(showMax);
scopeMinMenuItem.setState(showMin);
scopeFreqMenuItem.setState(showFreq);
scopePowerMenuItem.setState(value == VAL_POWER);
scopeVIMenuItem.setState(plot2d && !plotXY);
scopeXYMenuItem.setState(plotXY);
scopeSelectYMenuItem.setEnabled(plotXY);
scopeResistMenuItem.setState(value == VAL_R);
scopeResistMenuItem.setEnabled(elm instanceof MemristorElm);
return scopeMenu;
}
}
|
5433b381-1ada-4486-b9bb-baf143779a60
| 7
|
@SuppressWarnings("unchecked")
public boolean equals(Object o){
if(o == null) return false;
if(o.getClass() == getClass()){
ShareableHashSet<V> other = (ShareableHashSet<V>) o;
if(other.currentHashCode != currentHashCode) return false;
if(other.size() != size()) return false;
if(isEmpty()) return true; // No need to check if the sets are empty.
Iterator<V> otherIterator = other.iterator();
while(otherIterator.hasNext()){
if(!contains(otherIterator.next())) return false;
}
return true;
}
return false;
}
|
f5582f0d-9617-4649-88ea-a00758b841b9
| 0
|
@Override
public String getColumnName(int column) {
return this.columnNames[column];
}
|
c8cef589-8400-4be6-a8fc-fa1891e8d289
| 6
|
public static long[] getPrimeSmallerThanK(int k, boolean print) {
long[] primes = new long[k];
primes[0] = 2;
int currPrimeCount = 1;
for(int i=3;i<=k;i+=2) { // even number cannot be prime
boolean isPrime = true;
long sqrt = (long) Math.sqrt(i);
for(int j=0; j<currPrimeCount && primes[j]<=sqrt; j++) {
if (i % primes[j] == 0) { // test the prime, to see if the prime is the factor of i
isPrime = false;
break;
}
}
if (isPrime) {
primes[currPrimeCount++] = i;
}
}
primes = Arrays.copyOf(primes, currPrimeCount);
if(print) {
System.out.print("First primes which are smaller than " + k + " are: ");
System.out.print(Arrays.toString(primes));
System.out.println();
}
return primes;
}
|
5935e12c-9daa-4721-9286-79e06c850c65
| 3
|
public long getAllPopulation() {
long returnedPopulation = 0;
for (AstronomicalObject astronomicalObject : elements) {
if ((astronomicalObject.getClass() == InhabitedPlanet.class) || (astronomicalObject.getClass() == NaturalSatellite.class)) {
returnedPopulation += astronomicalObject.getPopulation();
}
}
return returnedPopulation;
}
|
24a88075-b357-4b77-a242-b887ac80239f
| 5
|
@SuppressWarnings("unchecked")
@Test public void fuzzyTest() {
final Random rng = new Random(42);
for(int n = 0; n < 1000; n++) {
for(int k = 0; k < 100; k++) {
final int l = rng.nextInt(n + 1), r = n - l;
A a1 = emptyArray(), b1 = emptyArray();
final ArrayList<Integer> a2 = new ArrayList<>(l), b2 = new ArrayList<>(r);
for(int i = 0; i < l; i++) {
final int pos = rng.nextInt(i + 1);
a1 = (A) a1.insertBefore(pos, i);
a2.add(pos, i);
}
for(int i = 0; i < r; i++) {
final int pos = rng.nextInt(i + 1);
b1 = (A) b1.insertBefore(pos, l + i);
b2.add(pos, l + i);
}
a1 = (A) a1.concat(b1);
checkInvariants(a1);
a2.addAll(b2);
assertEquals(n, a1.size());
assertEquals(n, a2.size());
final Iterator<Integer> it1 = a1.iterator(), it2 = a2.iterator();
while(it1.hasNext()) {
assertTrue(it2.hasNext());
final int i1 = it1.next(), i2 = it2.next();
assertEquals(i2, i1);
}
assertFalse(it2.hasNext());
}
}
}
|
415d3fc5-0254-4257-8302-d9ef3f5e5a50
| 1
|
void initTranstoForm()
{
textInput.setText(getCommaStringFromArrayList(sim.getAlphabetFromTransitions()));
AutoCompleteComboBoxModel acm = new AutoCompleteComboBoxModel();
ArrayList<String> t = new ArrayList<String>();
t.add("[same state]");
Dfa d = getdFAMainWin().getDfaSim().getDfa();
for (int i=0;i<d.getStates().size();i++)
{
t.add(d.getStates().get(i).getState_Properties().getName());
}
acm.setList(t);
jComboChooseState.setModel(acm);
}
|
08e10af8-12ea-4e87-8635-0936c63ded31
| 1
|
private boolean cellIsFree(int x, int y){
if(field[x][y] == DEFAULT_CELL_VALUE){
return true;
} else {
return false;
}
}
|
97906470-42aa-4806-921d-eeb9aaf91eb3
| 3
|
public Labyrinth(int height, int width) {
try {
caseArray = new Case[height][width];
for (int a = 0; a < height; a++) {
for (int b = 0; b < width; b++) {
caseArray[a][b] = new Case(a, b);
}
}
cells = height * width;
this.generate();
} catch (Exception e) {
System.out.println("Unknown Error !");
}
}
|
8bdb23e8-01c1-488e-a0ee-5e7d93054e75
| 8
|
private static int checkTypeSignature(final String signature, int pos) {
// TypeSignature:
// Z | C | B | S | I | F | J | D | FieldTypeSignature
switch (getChar(signature, pos)) {
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
case 'F':
case 'J':
case 'D':
return pos + 1;
default:
return checkFieldTypeSignature(signature, pos);
}
}
|
346d9703-8f54-479a-9f72-2b9636ca5b52
| 7
|
public void loadFile(String path) throws IOException {
String thisLine; // variable to read each line.
BufferedReader myInput = null;
try {
FileInputStream fin = new FileInputStream(new File(path));
myInput = new BufferedReader(new InputStreamReader(fin));
// for each line until the end of the file
while ((thisLine = myInput.readLine()) != null) {
// if the line is not a comment, is not empty or is not other
// kind of metadata
if (thisLine.isEmpty() == false &&
thisLine.charAt(0) != '#' && thisLine.charAt(0) != '%'
&& thisLine.charAt(0) != '@') {
// split this line according to spaces and process the line
addSequence(thisLine.split(" "));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (myInput != null) {
myInput.close();
}
}
}
|
9bc9f9f6-255f-46b9-ab29-3584e1278466
| 2
|
@Override
protected void decode(ChannelHandlerContext chc, ByteBuf buf, List<Object> out) throws Exception {
byte id = buf.readByte();
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
Class<? extends Packet> clazz = Packet.packetIdMap.get(id);
if (clazz == null) {
throw new RuntimeException("Encountered illegal packet type: " + id);
}
Method decoder = clazz.getMethod("decode", byte[].class);
Packet packet = (Packet) decoder.invoke(null, (Object) data);
out.add(packet);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.